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