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