]> git.lizzy.rs Git - minetest.git/blob - src/map.h
e049588713fcaacff9b32745a72d1a0c09b4b682
[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 "mapblock.h"
30 #include "mapnode.h"
31 #include "constants.h"
32 #include "voxel.h"
33 #include "modifiedstate.h"
34 #include "util/container.h"
35 #include "util/metricsbackend.h"
36 #include "util/numeric.h"
37 #include "nodetimer.h"
38 #include "map_settings_manager.h"
39 #include "debug.h"
40
41 class Settings;
42 class MapDatabase;
43 class ClientMap;
44 class MapSector;
45 class ServerMapSector;
46 class MapBlock;
47 class NodeMetadata;
48 class IGameDef;
49 class IRollbackManager;
50 class EmergeManager;
51 class MetricsBackend;
52 class ServerEnvironment;
53 struct BlockMakeData;
54
55 /*
56         MapEditEvent
57 */
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         // Sets the event's position and marks the block as modified.
83         void setPositionModified(v3s16 pos)
84         {
85                 p = pos;
86                 modified_blocks.insert(getNodeBlockPos(pos));
87         }
88
89         VoxelArea getArea() const
90         {
91                 switch(type){
92                 case MEET_ADDNODE:
93                 case MEET_REMOVENODE:
94                 case MEET_SWAPNODE:
95                 case MEET_BLOCK_NODE_METADATA_CHANGED:
96                         return VoxelArea(p);
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(IGameDef *gamedef);
125         virtual ~Map();
126         DISABLE_CLASS_COPY(Map);
127
128         /*
129                 Drop (client) or delete (server) the map.
130         */
131         virtual void drop()
132         {
133                 delete this;
134         }
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
146         /*
147                 This is overloaded by ClientMap and ServerMap to allow
148                 their differing fetch methods.
149         */
150         virtual MapSector * emergeSector(v2s16 p){ return NULL; }
151
152         // Returns InvalidPositionException if not found
153         MapBlock * getBlockNoCreate(v3s16 p);
154         // Returns NULL if not found
155         MapBlock * getBlockNoCreateNoEx(v3s16 p);
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, s32 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                 Utilities
263         */
264
265         // Iterates through all nodes in the area in an unspecified order.
266         // The given callback takes the position as its first argument and the node
267         // as its second. If it returns false, forEachNodeInArea returns early.
268         template<typename F>
269         void forEachNodeInArea(v3s16 minp, v3s16 maxp, F func)
270         {
271                 v3s16 bpmin = getNodeBlockPos(minp);
272                 v3s16 bpmax = getNodeBlockPos(maxp);
273                 for (s16 bz = bpmin.Z; bz <= bpmax.Z; bz++)
274                 for (s16 bx = bpmin.X; bx <= bpmax.X; bx++)
275                 for (s16 by = bpmin.Y; by <= bpmax.Y; by++) {
276                         // y is iterated innermost to make use of the sector cache.
277                         v3s16 bp(bx, by, bz);
278                         MapBlock *block = getBlockNoCreateNoEx(bp);
279                         v3s16 basep = bp * MAP_BLOCKSIZE;
280                         s16 minx_block = rangelim(minp.X - basep.X, 0, MAP_BLOCKSIZE - 1);
281                         s16 miny_block = rangelim(minp.Y - basep.Y, 0, MAP_BLOCKSIZE - 1);
282                         s16 minz_block = rangelim(minp.Z - basep.Z, 0, MAP_BLOCKSIZE - 1);
283                         s16 maxx_block = rangelim(maxp.X - basep.X, 0, MAP_BLOCKSIZE - 1);
284                         s16 maxy_block = rangelim(maxp.Y - basep.Y, 0, MAP_BLOCKSIZE - 1);
285                         s16 maxz_block = rangelim(maxp.Z - basep.Z, 0, MAP_BLOCKSIZE - 1);
286                         for (s16 z_block = minz_block; z_block <= maxz_block; z_block++)
287                         for (s16 y_block = miny_block; y_block <= maxy_block; y_block++)
288                         for (s16 x_block = minx_block; x_block <= maxx_block; x_block++) {
289                                 v3s16 p = basep + v3s16(x_block, y_block, z_block);
290                                 MapNode n = block ?
291                                                 block->getNodeNoCheck(x_block, y_block, z_block) :
292                                                 MapNode(CONTENT_IGNORE);
293                                 if (!func(p, n))
294                                         return;
295                         }
296                 }
297         }
298
299         bool isBlockOccluded(MapBlock *block, v3s16 cam_pos_nodes);
300 protected:
301         IGameDef *m_gamedef;
302
303         std::set<MapEventReceiver*> m_event_receivers;
304
305         std::unordered_map<v2s16, MapSector*> m_sectors;
306
307         // Be sure to set this to NULL when the cached sector is deleted
308         MapSector *m_sector_cache = nullptr;
309         v2s16 m_sector_cache_p;
310
311         // This stores the properties of the nodes on the map.
312         const NodeDefManager *m_nodedef;
313
314         // Can be implemented by child class
315         virtual void reportMetrics(u64 save_time_us, u32 saved_blocks, u32 all_blocks) {}
316
317         bool determineAdditionalOcclusionCheck(const v3s16 &pos_camera,
318                 const core::aabbox3d<s16> &block_bounds, v3s16 &check);
319         bool isOccluded(const v3s16 &pos_camera, const v3s16 &pos_target,
320                 float step, float stepfac, float start_offset, float end_offset,
321                 u32 needed_count);
322 };
323
324 /*
325         ServerMap
326
327         This is the only map class that is able to generate map.
328 */
329
330 class ServerMap : public Map
331 {
332 public:
333         /*
334                 savedir: directory to which map data should be saved
335         */
336         ServerMap(const std::string &savedir, IGameDef *gamedef, EmergeManager *emerge, MetricsBackend *mb);
337         ~ServerMap();
338
339         /*
340                 Get a sector from somewhere.
341                 - Check memory
342                 - Check disk (doesn't load blocks)
343                 - Create blank one
344         */
345         MapSector *createSector(v2s16 p);
346
347         /*
348                 Blocks are generated by using these and makeBlock().
349         */
350         bool blockpos_over_mapgen_limit(v3s16 p);
351         bool initBlockMake(v3s16 blockpos, BlockMakeData *data);
352         void finishBlockMake(BlockMakeData *data,
353                 std::map<v3s16, MapBlock*> *changed_blocks);
354
355         /*
356                 Get a block from somewhere.
357                 - Memory
358                 - Create blank
359         */
360         MapBlock *createBlock(v3s16 p);
361
362         /*
363                 Forcefully get a block from somewhere.
364                 - Memory
365                 - Load from disk
366                 - Create blank filled with CONTENT_IGNORE
367
368         */
369         MapBlock *emergeBlock(v3s16 p, bool create_blank=true) override;
370
371         /*
372                 Try to get a block.
373                 If it does not exist in memory, add it to the emerge queue.
374                 - Memory
375                 - Emerge Queue (deferred disk or generate)
376         */
377         MapBlock *getBlockOrEmerge(v3s16 p3d);
378
379         bool isBlockInQueue(v3s16 pos);
380
381         void addNodeAndUpdate(v3s16 p, MapNode n,
382                         std::map<v3s16, MapBlock*> &modified_blocks,
383                         bool remove_metadata) override;
384
385         /*
386                 Database functions
387         */
388         static MapDatabase *createDatabase(const std::string &name, const std::string &savedir, Settings &conf);
389
390         // Call these before and after saving of blocks
391         void beginSave() override;
392         void endSave() override;
393
394         void save(ModifiedState save_level) override;
395         void listAllLoadableBlocks(std::vector<v3s16> &dst);
396         void listAllLoadedBlocks(std::vector<v3s16> &dst);
397
398         MapgenParams *getMapgenParams();
399
400         bool saveBlock(MapBlock *block) override;
401         static bool saveBlock(MapBlock *block, MapDatabase *db, int compression_level = -1);
402         MapBlock* loadBlock(v3s16 p);
403         // Database version
404         void loadBlock(std::string *blob, v3s16 p3d, MapSector *sector, bool save_after_load=false);
405
406         bool deleteBlock(v3s16 blockpos) override;
407
408         void updateVManip(v3s16 pos);
409
410         // For debug printing
411         void PrintInfo(std::ostream &out) override;
412
413         bool isSavingEnabled(){ return m_map_saving_enabled; }
414
415         u64 getSeed();
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         void transformLiquids(std::map<v3s16, MapBlock*> & modified_blocks,
428                         ServerEnvironment *env);
429
430         void transforming_liquid_add(v3s16 p);
431
432         MapSettingsManager settings_mgr;
433
434 protected:
435
436         void reportMetrics(u64 save_time_us, u32 saved_blocks, u32 all_blocks) override;
437
438 private:
439         friend class LuaVoxelManip;
440
441         // Emerge manager
442         EmergeManager *m_emerge;
443
444         std::string m_savedir;
445         bool m_map_saving_enabled;
446
447         int m_map_compression_level;
448
449         std::set<v3s16> m_chunks_in_progress;
450
451         // Queued transforming water nodes
452         UniqueQueue<v3s16> m_transforming_liquid;
453         f32 m_transforming_liquid_loop_count_multiplier = 1.0f;
454         u32 m_unprocessed_count = 0;
455         u64 m_inc_trending_up_start_time = 0; // milliseconds
456         bool m_queue_size_timer_started = false;
457
458         /*
459                 Metadata is re-written on disk only if this is true.
460                 This is reset to false when written on disk.
461         */
462         bool m_map_metadata_changed = true;
463         MapDatabase *dbase = nullptr;
464         MapDatabase *dbase_ro = nullptr;
465
466         // Map metrics
467         MetricGaugePtr m_loaded_blocks_gauge;
468         MetricCounterPtr m_save_time_counter;
469         MetricCounterPtr m_save_count_counter;
470 };
471
472
473 #define VMANIP_BLOCK_DATA_INEXIST     1
474 #define VMANIP_BLOCK_CONTAINS_CIGNORE 2
475
476 class MMVManip : public VoxelManipulator
477 {
478 public:
479         MMVManip(Map *map);
480         virtual ~MMVManip() = default;
481
482         virtual void clear()
483         {
484                 VoxelManipulator::clear();
485                 m_loaded_blocks.clear();
486         }
487
488         void initialEmerge(v3s16 blockpos_min, v3s16 blockpos_max,
489                 bool load_if_inexistent = true);
490
491         // This is much faster with big chunks of generated data
492         void blitBackAll(std::map<v3s16, MapBlock*> * modified_blocks,
493                 bool overwrite_generated = true);
494
495         /*
496                 Creates a copy of this VManip including contents, the copy will not be
497                 associated with a Map.
498         */
499         MMVManip *clone() const;
500
501         // Reassociates a copied VManip to a map
502         void reparent(Map *map);
503
504         // Is it impossible to call initialEmerge / blitBackAll?
505         inline bool isOrphan() const { return !m_map; }
506
507         bool m_is_dirty = false;
508
509 protected:
510         MMVManip() {};
511
512         // may be null
513         Map *m_map = nullptr;
514         /*
515                 key = blockpos
516                 value = flags describing the block
517         */
518         std::map<v3s16, u8> m_loaded_blocks;
519 };