583f35e0be3acb4f1e9e7a7c9905413b0ad2aab7
[oweals/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 #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 changed
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         bool is_private_change = false;
79
80         MapEditEvent() = default;
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                 event->is_private_change = is_private_change;
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 * getSectorNoGenerateNoLock(v2s16 p2d);
159         // Same as the above (there exists no lock anymore)
160         MapSector * getSectorNoGenerate(v2s16 p2d);
161         // Gets an existing sector or creates an empty one
162         //MapSector * getSectorCreate(v2s16 p2d);
163
164         /*
165                 This is overloaded by ClientMap and ServerMap to allow
166                 their differing fetch methods.
167         */
168         virtual MapSector * emergeSector(v2s16 p){ return NULL; }
169
170         // Returns InvalidPositionException if not found
171         MapBlock * getBlockNoCreate(v3s16 p);
172         // Returns NULL if not found
173         MapBlock * getBlockNoCreateNoEx(v3s16 p);
174
175         /* Server overrides */
176         virtual MapBlock * emergeBlock(v3s16 p, bool create_blank=true)
177         { return getBlockNoCreateNoEx(p); }
178
179         inline const NodeDefManager * getNodeDefManager() { return m_nodedef; }
180
181         // Returns InvalidPositionException if not found
182         bool isNodeUnderground(v3s16 p);
183
184         bool isValidPosition(v3s16 p);
185
186         // throws InvalidPositionException if not found
187         void setNode(v3s16 p, MapNode & n);
188
189         // Returns a CONTENT_IGNORE node if not found
190         // If is_valid_position is not NULL then this will be set to true if the
191         // position is valid, otherwise false
192         MapNode getNode(v3s16 p, bool *is_valid_position = NULL);
193
194         /*
195                 These handle lighting but not faces.
196         */
197         void addNodeAndUpdate(v3s16 p, MapNode n,
198                         std::map<v3s16, MapBlock*> &modified_blocks,
199                         bool remove_metadata = true);
200         void removeNodeAndUpdate(v3s16 p,
201                         std::map<v3s16, MapBlock*> &modified_blocks);
202
203         /*
204                 Wrappers for the latter ones.
205                 These emit events.
206                 Return true if succeeded, false if not.
207         */
208         bool addNodeWithEvent(v3s16 p, MapNode n, bool remove_metadata = true);
209         bool removeNodeWithEvent(v3s16 p);
210
211         // Call these before and after saving of many blocks
212         virtual void beginSave() {}
213         virtual void endSave() {}
214
215         virtual void save(ModifiedState save_level) { FATAL_ERROR("FIXME"); }
216
217         // Server implements these.
218         // Client leaves them as no-op.
219         virtual bool saveBlock(MapBlock *block) { return false; }
220         virtual bool deleteBlock(v3s16 blockpos) { return false; }
221
222         /*
223                 Updates usage timers and unloads unused blocks and sectors.
224                 Saves modified blocks before unloading on MAPTYPE_SERVER.
225         */
226         void timerUpdate(float dtime, float unload_timeout, u32 max_loaded_blocks,
227                         std::vector<v3s16> *unloaded_blocks=NULL);
228
229         /*
230                 Unloads all blocks with a zero refCount().
231                 Saves modified blocks before unloading on MAPTYPE_SERVER.
232         */
233         void unloadUnreferencedBlocks(std::vector<v3s16> *unloaded_blocks=NULL);
234
235         // Deletes sectors and their blocks from memory
236         // Takes cache into account
237         // If deleted sector is in sector cache, clears cache
238         void deleteSectors(std::vector<v2s16> &list);
239
240         // For debug printing. Prints "Map: ", "ServerMap: " or "ClientMap: "
241         virtual void PrintInfo(std::ostream &out);
242
243         void transformLiquids(std::map<v3s16, MapBlock*> & modified_blocks,
244                         ServerEnvironment *env);
245
246         /*
247                 Node metadata
248                 These are basically coordinate wrappers to MapBlock
249         */
250
251         std::vector<v3s16> findNodesWithMetadata(v3s16 p1, v3s16 p2);
252         NodeMetadata *getNodeMetadata(v3s16 p);
253
254         /**
255          * Sets metadata for a node.
256          * This method sets the metadata for a given node.
257          * On success, it returns @c true and the object pointed to
258          * by @p meta is then managed by the system and should
259          * not be deleted by the caller.
260          *
261          * In case of failure, the method returns @c false and the
262          * caller is still responsible for deleting the object!
263          *
264          * @param p node coordinates
265          * @param meta pointer to @c NodeMetadata object
266          * @return @c true on success, false on failure
267          */
268         bool setNodeMetadata(v3s16 p, NodeMetadata *meta);
269         void removeNodeMetadata(v3s16 p);
270
271         /*
272                 Node Timers
273                 These are basically coordinate wrappers to MapBlock
274         */
275
276         NodeTimer getNodeTimer(v3s16 p);
277         void setNodeTimer(const NodeTimer &t);
278         void removeNodeTimer(v3s16 p);
279
280         /*
281                 Misc.
282         */
283         std::map<v2s16, MapSector*> *getSectorsPtr(){return &m_sectors;}
284
285         /*
286                 Variables
287         */
288
289         void transforming_liquid_add(v3s16 p);
290
291         bool isBlockOccluded(MapBlock *block, v3s16 cam_pos_nodes);
292 protected:
293         friend class LuaVoxelManip;
294
295         std::ostream &m_dout; // A bit deprecated, could be removed
296
297         IGameDef *m_gamedef;
298
299         std::set<MapEventReceiver*> m_event_receivers;
300
301         std::map<v2s16, MapSector*> m_sectors;
302
303         // Be sure to set this to NULL when the cached sector is deleted
304         MapSector *m_sector_cache = nullptr;
305         v2s16 m_sector_cache_p;
306
307         // Queued transforming water nodes
308         UniqueQueue<v3s16> m_transforming_liquid;
309
310         // This stores the properties of the nodes on the map.
311         const NodeDefManager *m_nodedef;
312
313         bool isOccluded(v3s16 p0, v3s16 p1, float step, float stepfac,
314                         float start_off, float end_off, u32 needed_count);
315
316 private:
317         f32 m_transforming_liquid_loop_count_multiplier = 1.0f;
318         u32 m_unprocessed_count = 0;
319         u64 m_inc_trending_up_start_time = 0; // milliseconds
320         bool m_queue_size_timer_started = false;
321 };
322
323 /*
324         ServerMap
325
326         This is the only map class that is able to generate map.
327 */
328
329 class ServerMap : public Map
330 {
331 public:
332         /*
333                 savedir: directory to which map data should be saved
334         */
335         ServerMap(const std::string &savedir, IGameDef *gamedef, EmergeManager *emerge);
336         ~ServerMap();
337
338         s32 mapType() const
339         {
340                 return MAPTYPE_SERVER;
341         }
342
343         /*
344                 Get a sector from somewhere.
345                 - Check memory
346                 - Check disk (doesn't load blocks)
347                 - Create blank one
348         */
349         MapSector *createSector(v2s16 p);
350
351         /*
352                 Blocks are generated by using these and makeBlock().
353         */
354         bool blockpos_over_mapgen_limit(v3s16 p);
355         bool initBlockMake(v3s16 blockpos, BlockMakeData *data);
356         void finishBlockMake(BlockMakeData *data,
357                 std::map<v3s16, MapBlock*> *changed_blocks);
358
359         /*
360                 Get a block from somewhere.
361                 - Memory
362                 - Create blank
363         */
364         MapBlock *createBlock(v3s16 p);
365
366         /*
367                 Forcefully get a block from somewhere.
368                 - Memory
369                 - Load from disk
370                 - Create blank filled with CONTENT_IGNORE
371
372         */
373         MapBlock *emergeBlock(v3s16 p, bool create_blank=true);
374
375         /*
376                 Try to get a block.
377                 If it does not exist in memory, add it to the emerge queue.
378                 - Memory
379                 - Emerge Queue (deferred disk or generate)
380         */
381         MapBlock *getBlockOrEmerge(v3s16 p3d);
382
383         // Helper for placing objects on ground level
384         s16 findGroundLevel(v2s16 p2d);
385
386         /*
387                 Misc. helper functions for fiddling with directory and file
388                 names when saving
389         */
390         void createDirs(const std::string &path);
391         // returns something like "map/sectors/xxxxxxxx"
392         std::string getSectorDir(v2s16 pos, int layout = 2);
393         // dirname: final directory name
394         v2s16 getSectorPos(const std::string &dirname);
395         v3s16 getBlockPos(const std::string &sectordir, const std::string &blockfile);
396         static std::string getBlockFilename(v3s16 p);
397
398         /*
399                 Database functions
400         */
401         static MapDatabase *createDatabase(const std::string &name, const std::string &savedir, Settings &conf);
402
403         // Returns true if the database file does not exist
404         bool loadFromFolders();
405
406         // Call these before and after saving of blocks
407         void beginSave();
408         void endSave();
409
410         void save(ModifiedState save_level);
411         void listAllLoadableBlocks(std::vector<v3s16> &dst);
412         void listAllLoadedBlocks(std::vector<v3s16> &dst);
413
414         MapgenParams *getMapgenParams();
415
416         bool saveBlock(MapBlock *block);
417         static bool saveBlock(MapBlock *block, MapDatabase *db);
418         // This will generate a sector with getSector if not found.
419         void loadBlock(const std::string &sectordir, const std::string &blockfile,
420                         MapSector *sector, bool save_after_load=false);
421         MapBlock* loadBlock(v3s16 p);
422         // Database version
423         void loadBlock(std::string *blob, v3s16 p3d, MapSector *sector, bool save_after_load=false);
424
425         bool deleteBlock(v3s16 blockpos);
426
427         void updateVManip(v3s16 pos);
428
429         // For debug printing
430         virtual void PrintInfo(std::ostream &out);
431
432         bool isSavingEnabled(){ return m_map_saving_enabled; }
433
434         u64 getSeed();
435         s16 getWaterLevel();
436
437         /*!
438          * Fixes lighting in one map block.
439          * May modify other blocks as well, as light can spread
440          * out of the specified block.
441          * Returns false if the block is not generated (so nothing
442          * changed), true otherwise.
443          */
444         bool repairBlockLight(v3s16 blockpos,
445                 std::map<v3s16, MapBlock *> *modified_blocks);
446
447         MapSettingsManager settings_mgr;
448
449 private:
450         // Emerge manager
451         EmergeManager *m_emerge;
452
453         std::string m_savedir;
454         bool m_map_saving_enabled;
455
456 #if 0
457         // Chunk size in MapSectors
458         // If 0, chunks are disabled.
459         s16 m_chunksize;
460         // Chunks
461         core::map<v2s16, MapChunk*> m_chunks;
462 #endif
463
464         /*
465                 Metadata is re-written on disk only if this is true.
466                 This is reset to false when written on disk.
467         */
468         bool m_map_metadata_changed = true;
469         MapDatabase *dbase = nullptr;
470         MapDatabase *dbase_ro = nullptr;
471 };
472
473
474 #define VMANIP_BLOCK_DATA_INEXIST     1
475 #define VMANIP_BLOCK_CONTAINS_CIGNORE 2
476
477 class MMVManip : public VoxelManipulator
478 {
479 public:
480         MMVManip(Map *map);
481         virtual ~MMVManip() = default;
482
483         virtual void clear()
484         {
485                 VoxelManipulator::clear();
486                 m_loaded_blocks.clear();
487         }
488
489         void initialEmerge(v3s16 blockpos_min, v3s16 blockpos_max,
490                 bool load_if_inexistent = true);
491
492         // This is much faster with big chunks of generated data
493         void blitBackAll(std::map<v3s16, MapBlock*> * modified_blocks,
494                 bool overwrite_generated = true);
495
496         bool m_is_dirty = false;
497
498 protected:
499         Map *m_map;
500         /*
501                 key = blockpos
502                 value = flags describing the block
503         */
504         std::map<v3s16, u8> m_loaded_blocks;
505 };