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