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