]> git.lizzy.rs Git - dragonfireclient.git/blob - src/mapblock.h
Huge LBM lookup performance improvement on mapblock loading (#7195)
[dragonfireclient.git] / src / mapblock.h
1 /*
2 Minetest
3 Copyright (C) 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 <set>
23 #include "irr_v3d.h"
24 #include "mapnode.h"
25 #include "exceptions.h"
26 #include "constants.h"
27 #include "staticobject.h"
28 #include "nodemetadata.h"
29 #include "nodetimer.h"
30 #include "modifiedstate.h"
31 #include "util/numeric.h" // getContainerPos
32 #include "settings.h"
33 #include "mapgen/mapgen.h"
34
35 class Map;
36 class NodeMetadataList;
37 class IGameDef;
38 class MapBlockMesh;
39 class VoxelManipulator;
40
41 #define BLOCK_TIMESTAMP_UNDEFINED 0xffffffff
42
43 ////
44 //// MapBlock modified reason flags
45 ////
46
47 #define MOD_REASON_INITIAL                   (1 << 0)
48 #define MOD_REASON_REALLOCATE                (1 << 1)
49 #define MOD_REASON_SET_IS_UNDERGROUND        (1 << 2)
50 #define MOD_REASON_SET_LIGHTING_COMPLETE     (1 << 3)
51 #define MOD_REASON_SET_GENERATED             (1 << 4)
52 #define MOD_REASON_SET_NODE                  (1 << 5)
53 #define MOD_REASON_SET_NODE_NO_CHECK         (1 << 6)
54 #define MOD_REASON_SET_TIMESTAMP             (1 << 7)
55 #define MOD_REASON_REPORT_META_CHANGE        (1 << 8)
56 #define MOD_REASON_CLEAR_ALL_OBJECTS         (1 << 9)
57 #define MOD_REASON_BLOCK_EXPIRED             (1 << 10)
58 #define MOD_REASON_ADD_ACTIVE_OBJECT_RAW     (1 << 11)
59 #define MOD_REASON_REMOVE_OBJECTS_REMOVE     (1 << 12)
60 #define MOD_REASON_REMOVE_OBJECTS_DEACTIVATE (1 << 13)
61 #define MOD_REASON_TOO_MANY_OBJECTS          (1 << 14)
62 #define MOD_REASON_STATIC_DATA_ADDED         (1 << 15)
63 #define MOD_REASON_STATIC_DATA_REMOVED       (1 << 16)
64 #define MOD_REASON_STATIC_DATA_CHANGED       (1 << 17)
65 #define MOD_REASON_EXPIRE_DAYNIGHTDIFF       (1 << 18)
66 #define MOD_REASON_VMANIP                    (1 << 19)
67 #define MOD_REASON_UNKNOWN                   (1 << 20)
68
69 ////
70 //// MapBlock itself
71 ////
72
73 class MapBlock
74 {
75 public:
76         MapBlock(Map *parent, v3s16 pos, IGameDef *gamedef, bool dummy=false);
77         ~MapBlock();
78
79         /*virtual u16 nodeContainerId() const
80         {
81                 return NODECONTAINER_ID_MAPBLOCK;
82         }*/
83
84         Map * getParent()
85         {
86                 return m_parent;
87         }
88
89         void reallocate()
90         {
91                 delete[] data;
92                 data = new MapNode[nodecount];
93                 for (u32 i = 0; i < nodecount; i++)
94                         data[i] = MapNode(CONTENT_IGNORE);
95
96                 raiseModified(MOD_STATE_WRITE_NEEDED, MOD_REASON_REALLOCATE);
97         }
98
99         MapNode* getData()
100         {
101                 return data;
102         }
103
104         ////
105         //// Modification tracking methods
106         ////
107         void raiseModified(u32 mod, u32 reason=MOD_REASON_UNKNOWN)
108         {
109                 if (mod > m_modified) {
110                         m_modified = mod;
111                         m_modified_reason = reason;
112                         if (m_modified >= MOD_STATE_WRITE_AT_UNLOAD)
113                                 m_disk_timestamp = m_timestamp;
114                 } else if (mod == m_modified) {
115                         m_modified_reason |= reason;
116                 }
117         }
118
119         inline u32 getModified()
120         {
121                 return m_modified;
122         }
123
124         inline u32 getModifiedReason()
125         {
126                 return m_modified_reason;
127         }
128
129         std::string getModifiedReasonString();
130
131         inline void resetModified()
132         {
133                 m_modified = MOD_STATE_CLEAN;
134                 m_modified_reason = 0;
135         }
136
137         ////
138         //// Flags
139         ////
140
141         inline bool isDummy()
142         {
143                 return !data;
144         }
145
146         inline void unDummify()
147         {
148                 assert(isDummy()); // Pre-condition
149                 reallocate();
150         }
151
152         // is_underground getter/setter
153         inline bool getIsUnderground()
154         {
155                 return is_underground;
156         }
157
158         inline void setIsUnderground(bool a_is_underground)
159         {
160                 is_underground = a_is_underground;
161                 raiseModified(MOD_STATE_WRITE_NEEDED, MOD_REASON_SET_IS_UNDERGROUND);
162         }
163
164         inline void setLightingComplete(u16 newflags)
165         {
166                 if (newflags != m_lighting_complete) {
167                         m_lighting_complete = newflags;
168                         raiseModified(MOD_STATE_WRITE_NEEDED, MOD_REASON_SET_LIGHTING_COMPLETE);
169                 }
170         }
171
172         inline u16 getLightingComplete()
173         {
174                 return m_lighting_complete;
175         }
176
177         inline void setLightingComplete(LightBank bank, u8 direction,
178                 bool is_complete)
179         {
180                 assert(direction >= 0 && direction <= 5);
181                 if (bank == LIGHTBANK_NIGHT) {
182                         direction += 6;
183                 }
184                 u16 newflags = m_lighting_complete;
185                 if (is_complete) {
186                         newflags |= 1 << direction;
187                 } else {
188                         newflags &= ~(1 << direction);
189                 }
190                 setLightingComplete(newflags);
191         }
192
193         inline bool isLightingComplete(LightBank bank, u8 direction)
194         {
195                 assert(direction >= 0 && direction <= 5);
196                 if (bank == LIGHTBANK_NIGHT) {
197                         direction += 6;
198                 }
199                 return (m_lighting_complete & (1 << direction)) != 0;
200         }
201
202         inline bool isGenerated()
203         {
204                 return m_generated;
205         }
206
207         inline void setGenerated(bool b)
208         {
209                 if (b != m_generated) {
210                         raiseModified(MOD_STATE_WRITE_NEEDED, MOD_REASON_SET_GENERATED);
211                         m_generated = b;
212                 }
213         }
214
215         ////
216         //// Position stuff
217         ////
218
219         inline v3s16 getPos()
220         {
221                 return m_pos;
222         }
223
224         inline v3s16 getPosRelative()
225         {
226                 return m_pos_relative;
227         }
228
229         inline core::aabbox3d<s16> getBox()
230         {
231                 return core::aabbox3d<s16>(getPosRelative(),
232                                 getPosRelative()
233                                 + v3s16(MAP_BLOCKSIZE, MAP_BLOCKSIZE, MAP_BLOCKSIZE)
234                                 - v3s16(1,1,1));
235         }
236
237         ////
238         //// Regular MapNode get-setters
239         ////
240
241         inline bool isValidPosition(s16 x, s16 y, s16 z)
242         {
243                 return data
244                         && x >= 0 && x < MAP_BLOCKSIZE
245                         && y >= 0 && y < MAP_BLOCKSIZE
246                         && z >= 0 && z < MAP_BLOCKSIZE;
247         }
248
249         inline bool isValidPosition(v3s16 p)
250         {
251                 return isValidPosition(p.X, p.Y, p.Z);
252         }
253
254         inline MapNode getNode(s16 x, s16 y, s16 z, bool *valid_position)
255         {
256                 *valid_position = isValidPosition(x, y, z);
257
258                 if (!*valid_position)
259                         return {CONTENT_IGNORE};
260
261                 return data[z * zstride + y * ystride + x];
262         }
263
264         inline MapNode getNode(v3s16 p, bool *valid_position)
265         {
266                 return getNode(p.X, p.Y, p.Z, valid_position);
267         }
268
269         inline MapNode getNodeNoEx(v3s16 p)
270         {
271                 bool is_valid;
272                 return getNode(p.X, p.Y, p.Z, &is_valid);
273         }
274
275         inline void setNode(s16 x, s16 y, s16 z, MapNode & n)
276         {
277                 if (!isValidPosition(x, y, z))
278                         throw InvalidPositionException();
279
280                 data[z * zstride + y * ystride + x] = n;
281                 raiseModified(MOD_STATE_WRITE_NEEDED, MOD_REASON_SET_NODE);
282         }
283
284         inline void setNode(v3s16 p, MapNode & n)
285         {
286                 setNode(p.X, p.Y, p.Z, n);
287         }
288
289         ////
290         //// Non-checking variants of the above
291         ////
292
293         inline MapNode getNodeNoCheck(s16 x, s16 y, s16 z, bool *valid_position)
294         {
295                 *valid_position = data != nullptr;
296                 if (!*valid_position)
297                         return {CONTENT_IGNORE};
298
299                 return data[z * zstride + y * ystride + x];
300         }
301
302         inline MapNode getNodeNoCheck(v3s16 p, bool *valid_position)
303         {
304                 return getNodeNoCheck(p.X, p.Y, p.Z, valid_position);
305         }
306
307         ////
308         //// Non-checking, unsafe variants of the above
309         //// MapBlock must be loaded by another function in the same scope/function
310         //// Caller must ensure that this is not a dummy block (by calling isDummy())
311         ////
312
313         inline const MapNode &getNodeUnsafe(s16 x, s16 y, s16 z)
314         {
315                 return data[z * zstride + y * ystride + x];
316         }
317
318         inline const MapNode &getNodeUnsafe(v3s16 &p)
319         {
320                 return getNodeUnsafe(p.X, p.Y, p.Z);
321         }
322
323         inline void setNodeNoCheck(s16 x, s16 y, s16 z, MapNode & n)
324         {
325                 if (!data)
326                         throw InvalidPositionException();
327
328                 data[z * zstride + y * ystride + x] = n;
329                 raiseModified(MOD_STATE_WRITE_NEEDED, MOD_REASON_SET_NODE_NO_CHECK);
330         }
331
332         inline void setNodeNoCheck(v3s16 p, MapNode & n)
333         {
334                 setNodeNoCheck(p.X, p.Y, p.Z, n);
335         }
336
337         // These functions consult the parent container if the position
338         // is not valid on this MapBlock.
339         bool isValidPositionParent(v3s16 p);
340         MapNode getNodeParent(v3s16 p, bool *is_valid_position = NULL);
341         void setNodeParent(v3s16 p, MapNode & n);
342
343         inline void drawbox(s16 x0, s16 y0, s16 z0, s16 w, s16 h, s16 d, MapNode node)
344         {
345                 for (u16 z = 0; z < d; z++)
346                 for (u16 y = 0; y < h; y++)
347                 for (u16 x = 0; x < w; x++)
348                         setNode(x0 + x, y0 + y, z0 + z, node);
349         }
350
351         // Copies data to VoxelManipulator to getPosRelative()
352         void copyTo(VoxelManipulator &dst);
353
354         // Copies data from VoxelManipulator getPosRelative()
355         void copyFrom(VoxelManipulator &dst);
356
357         // Update day-night lighting difference flag.
358         // Sets m_day_night_differs to appropriate value.
359         // These methods don't care about neighboring blocks.
360         void actuallyUpdateDayNightDiff();
361
362         // Call this to schedule what the previous function does to be done
363         // when the value is actually needed.
364         void expireDayNightDiff();
365
366         inline bool getDayNightDiff()
367         {
368                 if (m_day_night_differs_expired)
369                         actuallyUpdateDayNightDiff();
370                 return m_day_night_differs;
371         }
372
373         ////
374         //// Miscellaneous stuff
375         ////
376
377         /*
378                 Tries to measure ground level.
379                 Return value:
380                         -1 = only air
381                         -2 = only ground
382                         -3 = random fail
383                         0...MAP_BLOCKSIZE-1 = ground level
384         */
385         s16 getGroundLevel(v2s16 p2d);
386
387         ////
388         //// Timestamp (see m_timestamp)
389         ////
390
391         // NOTE: BLOCK_TIMESTAMP_UNDEFINED=0xffffffff means there is no timestamp.
392
393         inline void setTimestamp(u32 time)
394         {
395                 m_timestamp = time;
396                 raiseModified(MOD_STATE_WRITE_AT_UNLOAD, MOD_REASON_SET_TIMESTAMP);
397         }
398
399         inline void setTimestampNoChangedFlag(u32 time)
400         {
401                 m_timestamp = time;
402         }
403
404         inline u32 getTimestamp()
405         {
406                 return m_timestamp;
407         }
408
409         inline u32 getDiskTimestamp()
410         {
411                 return m_disk_timestamp;
412         }
413
414         ////
415         //// Usage timer (see m_usage_timer)
416         ////
417
418         inline void resetUsageTimer()
419         {
420                 m_usage_timer = 0;
421         }
422
423         inline void incrementUsageTimer(float dtime)
424         {
425                 m_usage_timer += dtime;
426         }
427
428         inline float getUsageTimer()
429         {
430                 return m_usage_timer;
431         }
432
433         ////
434         //// Reference counting (see m_refcount)
435         ////
436
437         inline void refGrab()
438         {
439                 m_refcount++;
440         }
441
442         inline void refDrop()
443         {
444                 m_refcount--;
445         }
446
447         inline int refGet()
448         {
449                 return m_refcount;
450         }
451
452         ////
453         //// Node Timers
454         ////
455
456         inline NodeTimer getNodeTimer(const v3s16 &p)
457         {
458                 return m_node_timers.get(p);
459         }
460
461         inline void removeNodeTimer(const v3s16 &p)
462         {
463                 m_node_timers.remove(p);
464         }
465
466         inline void setNodeTimer(const NodeTimer &t)
467         {
468                 m_node_timers.set(t);
469         }
470
471         inline void clearNodeTimers()
472         {
473                 m_node_timers.clear();
474         }
475
476         ////
477         //// Serialization
478         ///
479
480         // These don't write or read version by itself
481         // Set disk to true for on-disk format, false for over-the-network format
482         // Precondition: version >= SER_FMT_VER_LOWEST_WRITE
483         void serialize(std::ostream &os, u8 version, bool disk);
484         // If disk == true: In addition to doing other things, will add
485         // unknown blocks from id-name mapping to wndef
486         void deSerialize(std::istream &is, u8 version, bool disk);
487
488         void serializeNetworkSpecific(std::ostream &os);
489         void deSerializeNetworkSpecific(std::istream &is);
490 private:
491         /*
492                 Private methods
493         */
494
495         void deSerialize_pre22(std::istream &is, u8 version, bool disk);
496
497         /*
498                 Used only internally, because changes can't be tracked
499         */
500
501         inline MapNode &getNodeRef(s16 x, s16 y, s16 z)
502         {
503                 if (!isValidPosition(x, y, z))
504                         throw InvalidPositionException();
505
506                 return data[z * zstride + y * ystride + x];
507         }
508
509         inline MapNode &getNodeRef(v3s16 &p)
510         {
511                 return getNodeRef(p.X, p.Y, p.Z);
512         }
513
514 public:
515         /*
516                 Public member variables
517         */
518
519 #ifndef SERVER // Only on client
520         MapBlockMesh *mesh = nullptr;
521 #endif
522
523         NodeMetadataList m_node_metadata;
524         NodeTimerList m_node_timers;
525         StaticObjectList m_static_objects;
526
527         static const u32 ystride = MAP_BLOCKSIZE;
528         static const u32 zstride = MAP_BLOCKSIZE * MAP_BLOCKSIZE;
529
530         static const u32 nodecount = MAP_BLOCKSIZE * MAP_BLOCKSIZE * MAP_BLOCKSIZE;
531
532 private:
533         /*
534                 Private member variables
535         */
536
537         // NOTE: Lots of things rely on this being the Map
538         Map *m_parent;
539         // Position in blocks on parent
540         v3s16 m_pos;
541
542         /* This is the precalculated m_pos_relative value
543         * This caches the value, improving performance by removing 3 s16 multiplications
544         * at runtime on each getPosRelative call
545         * For a 5 minutes runtime with valgrind this removes 3 * 19M s16 multiplications
546         * The gain can be estimated in Release Build to 3 * 100M multiply operations for 5 mins
547         */
548         v3s16 m_pos_relative;
549
550         IGameDef *m_gamedef;
551
552         /*
553                 If NULL, block is a dummy block.
554                 Dummy blocks are used for caching not-found-on-disk blocks.
555         */
556         MapNode *data = nullptr;
557
558         /*
559                 - On the server, this is used for telling whether the
560                   block has been modified from the one on disk.
561                 - On the client, this is used for nothing.
562         */
563         u32 m_modified = MOD_STATE_WRITE_NEEDED;
564         u32 m_modified_reason = MOD_REASON_INITIAL;
565
566         /*
567                 When propagating sunlight and the above block doesn't exist,
568                 sunlight is assumed if this is false.
569
570                 In practice this is set to true if the block is completely
571                 undeground with nothing visible above the ground except
572                 caves.
573         */
574         bool is_underground = false;
575
576         /*!
577          * Each bit indicates if light spreading was finished
578          * in a direction. (Because the neighbor could also be unloaded.)
579          * Bits (most significant first):
580          * nothing,  nothing,  nothing,  nothing,
581          * night X-, night Y-, night Z-, night Z+, night Y+, night X+,
582          * day X-,   day Y-,   day Z-,   day Z+,   day Y+,   day X+.
583         */
584         u16 m_lighting_complete = 0xFFFF;
585
586         // Whether day and night lighting differs
587         bool m_day_night_differs = false;
588         bool m_day_night_differs_expired = true;
589
590         bool m_generated = false;
591
592         /*
593                 When block is removed from active blocks, this is set to gametime.
594                 Value BLOCK_TIMESTAMP_UNDEFINED=0xffffffff means there is no timestamp.
595         */
596         u32 m_timestamp = BLOCK_TIMESTAMP_UNDEFINED;
597         // The on-disk (or to-be on-disk) timestamp value
598         u32 m_disk_timestamp = BLOCK_TIMESTAMP_UNDEFINED;
599
600         /*
601                 When the block is accessed, this is set to 0.
602                 Map will unload the block when this reaches a timeout.
603         */
604         float m_usage_timer = 0;
605
606         /*
607                 Reference count; currently used for determining if this block is in
608                 the list of blocks to be drawn.
609         */
610         int m_refcount = 0;
611 };
612
613 typedef std::vector<MapBlock*> MapBlockVect;
614
615 inline bool objectpos_over_limit(v3f p)
616 {
617         const float max_limit_bs = MAX_MAP_GENERATION_LIMIT * BS;
618         return p.X < -max_limit_bs ||
619                 p.X >  max_limit_bs ||
620                 p.Y < -max_limit_bs ||
621                 p.Y >  max_limit_bs ||
622                 p.Z < -max_limit_bs ||
623                 p.Z >  max_limit_bs;
624 }
625
626 inline bool blockpos_over_max_limit(v3s16 p)
627 {
628         const s16 max_limit_bp = MAX_MAP_GENERATION_LIMIT / MAP_BLOCKSIZE;
629         return p.X < -max_limit_bp ||
630                 p.X >  max_limit_bp ||
631                 p.Y < -max_limit_bp ||
632                 p.Y >  max_limit_bp ||
633                 p.Z < -max_limit_bp ||
634                 p.Z >  max_limit_bp;
635 }
636
637 /*
638         Returns the position of the block where the node is located
639 */
640 inline v3s16 getNodeBlockPos(const v3s16 &p)
641 {
642         return getContainerPos(p, MAP_BLOCKSIZE);
643 }
644
645 inline void getNodeBlockPosWithOffset(const v3s16 &p, v3s16 &block, v3s16 &offset)
646 {
647         getContainerPosWithOffset(p, MAP_BLOCKSIZE, block, offset);
648 }
649
650 /*
651         Get a quick string to describe what a block actually contains
652 */
653 std::string analyze_block(MapBlock *block);