]> git.lizzy.rs Git - dragonfireclient.git/blob - src/map.h
Add more error checking to l_register_ore
[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 #ifndef MAP_HEADER
21 #define MAP_HEADER
22
23 #include <jmutex.h>
24 #include <jmutexautolock.h>
25 #include <jthread.h>
26 #include <iostream>
27 #include <sstream>
28 #include <set>
29 #include <map>
30 #include <list>
31
32 #include "irrlichttypes_bloated.h"
33 #include "mapnode.h"
34 #include "constants.h"
35 #include "voxel.h"
36 #include "mapgen.h" //for BlockMakeData and EmergeManager
37 #include "modifiedstate.h"
38 #include "util/container.h"
39 #include "nodetimer.h"
40
41 extern "C" {
42         #include "sqlite3.h"
43 }
44
45 class ClientMap;
46 class MapSector;
47 class ServerMapSector;
48 class MapBlock;
49 class NodeMetadata;
50 class IGameDef;
51 class IRollbackReportSink;
52 class EmergeManager;
53 struct BlockMakeData;
54
55
56 /*
57         MapEditEvent
58 */
59
60 #define MAPTYPE_BASE 0
61 #define MAPTYPE_SERVER 1
62 #define MAPTYPE_CLIENT 2
63
64 enum MapEditEventType{
65         // Node added (changed from air or something else to something)
66         MEET_ADDNODE,
67         // Node removed (changed to air)
68         MEET_REMOVENODE,
69         // Node metadata of block changed (not knowing which node exactly)
70         // p stores block coordinate
71         MEET_BLOCK_NODE_METADATA_CHANGED,
72         // Anything else (modified_blocks are set unsent)
73         MEET_OTHER
74 };
75
76 struct MapEditEvent
77 {
78         MapEditEventType type;
79         v3s16 p;
80         MapNode n;
81         std::set<v3s16> modified_blocks;
82         u16 already_known_by_peer;
83
84         MapEditEvent():
85                 type(MEET_OTHER),
86                 already_known_by_peer(0)
87         {
88         }
89
90         MapEditEvent * clone()
91         {
92                 MapEditEvent *event = new MapEditEvent();
93                 event->type = type;
94                 event->p = p;
95                 event->n = n;
96                 event->modified_blocks = modified_blocks;
97                 return event;
98         }
99
100         VoxelArea getArea()
101         {
102                 switch(type){
103                 case MEET_ADDNODE:
104                         return VoxelArea(p);
105                 case MEET_REMOVENODE:
106                         return VoxelArea(p);
107                 case MEET_BLOCK_NODE_METADATA_CHANGED:
108                 {
109                         v3s16 np1 = p*MAP_BLOCKSIZE;
110                         v3s16 np2 = np1 + v3s16(1,1,1)*MAP_BLOCKSIZE - v3s16(1,1,1);
111                         return VoxelArea(np1, np2);
112                 }
113                 case MEET_OTHER:
114                 {
115                         VoxelArea a;
116                         for(std::set<v3s16>::iterator
117                                         i = modified_blocks.begin();
118                                         i != modified_blocks.end(); ++i)
119                         {
120                                 v3s16 p = *i;
121                                 v3s16 np1 = p*MAP_BLOCKSIZE;
122                                 v3s16 np2 = np1 + v3s16(1,1,1)*MAP_BLOCKSIZE - v3s16(1,1,1);
123                                 a.addPoint(np1);
124                                 a.addPoint(np2);
125                         }
126                         return a;
127                 }
128                 }
129                 return VoxelArea();
130         }
131 };
132
133 class MapEventReceiver
134 {
135 public:
136         // event shall be deleted by caller after the call.
137         virtual void onMapEditEvent(MapEditEvent *event) = 0;
138 };
139
140 class Map /*: public NodeContainer*/
141 {
142 public:
143
144         Map(std::ostream &dout, IGameDef *gamedef);
145         virtual ~Map();
146
147         /*virtual u16 nodeContainerId() const
148         {
149                 return NODECONTAINER_ID_MAP;
150         }*/
151
152         virtual s32 mapType() const
153         {
154                 return MAPTYPE_BASE;
155         }
156
157         /*
158                 Drop (client) or delete (server) the map.
159         */
160         virtual void drop()
161         {
162                 delete this;
163         }
164
165         void addEventReceiver(MapEventReceiver *event_receiver);
166         void removeEventReceiver(MapEventReceiver *event_receiver);
167         // event shall be deleted by caller after the call.
168         void dispatchEvent(MapEditEvent *event);
169
170         // On failure returns NULL
171         MapSector * getSectorNoGenerateNoExNoLock(v2s16 p2d);
172         // Same as the above (there exists no lock anymore)
173         MapSector * getSectorNoGenerateNoEx(v2s16 p2d);
174         // On failure throws InvalidPositionException
175         MapSector * getSectorNoGenerate(v2s16 p2d);
176         // Gets an existing sector or creates an empty one
177         //MapSector * getSectorCreate(v2s16 p2d);
178
179         /*
180                 This is overloaded by ClientMap and ServerMap to allow
181                 their differing fetch methods.
182         */
183         virtual MapSector * emergeSector(v2s16 p){ return NULL; }
184         virtual MapSector * emergeSector(v2s16 p,
185                         std::map<v3s16, MapBlock*> &changed_blocks){ return NULL; }
186
187         // Returns InvalidPositionException if not found
188         MapBlock * getBlockNoCreate(v3s16 p);
189         // Returns NULL if not found
190         MapBlock * getBlockNoCreateNoEx(v3s16 p);
191
192         /* Server overrides */
193         virtual MapBlock * emergeBlock(v3s16 p, bool allow_generate=true)
194         { return getBlockNoCreateNoEx(p); }
195
196         // Returns InvalidPositionException if not found
197         bool isNodeUnderground(v3s16 p);
198
199         bool isValidPosition(v3s16 p);
200
201         // throws InvalidPositionException if not found
202         MapNode getNode(v3s16 p);
203
204         // throws InvalidPositionException if not found
205         void setNode(v3s16 p, MapNode & n);
206
207         // Returns a CONTENT_IGNORE node if not found
208         MapNode getNodeNoEx(v3s16 p);
209
210         void unspreadLight(enum LightBank bank,
211                         std::map<v3s16, u8> & from_nodes,
212                         std::set<v3s16> & light_sources,
213                         std::map<v3s16, MapBlock*> & modified_blocks);
214
215         void unLightNeighbors(enum LightBank bank,
216                         v3s16 pos, u8 lightwas,
217                         std::set<v3s16> & light_sources,
218                         std::map<v3s16, MapBlock*> & modified_blocks);
219
220         void spreadLight(enum LightBank bank,
221                         std::set<v3s16> & from_nodes,
222                         std::map<v3s16, MapBlock*> & modified_blocks);
223
224         void lightNeighbors(enum LightBank bank,
225                         v3s16 pos,
226                         std::map<v3s16, MapBlock*> & modified_blocks);
227
228         v3s16 getBrightestNeighbour(enum LightBank bank, v3s16 p);
229
230         s16 propagateSunlight(v3s16 start,
231                         std::map<v3s16, MapBlock*> & modified_blocks);
232
233         void updateLighting(enum LightBank bank,
234                         std::map<v3s16, MapBlock*>  & a_blocks,
235                         std::map<v3s16, MapBlock*> & modified_blocks);
236
237         void updateLighting(std::map<v3s16, MapBlock*>  & a_blocks,
238                         std::map<v3s16, MapBlock*> & modified_blocks);
239
240         /*
241                 These handle lighting but not faces.
242         */
243         void addNodeAndUpdate(v3s16 p, MapNode n,
244                         std::map<v3s16, MapBlock*> &modified_blocks);
245         void removeNodeAndUpdate(v3s16 p,
246                         std::map<v3s16, MapBlock*> &modified_blocks);
247
248         /*
249                 Wrappers for the latter ones.
250                 These emit events.
251                 Return true if succeeded, false if not.
252         */
253         bool addNodeWithEvent(v3s16 p, MapNode n);
254         bool removeNodeWithEvent(v3s16 p);
255
256         /*
257                 Takes the blocks at the edges into account
258         */
259         bool getDayNightDiff(v3s16 blockpos);
260
261         //core::aabbox3d<s16> getDisplayedBlockArea();
262
263         //bool updateChangedVisibleArea();
264
265         // Call these before and after saving of many blocks
266         virtual void beginSave() {return;};
267         virtual void endSave() {return;};
268
269         virtual void save(ModifiedState save_level){assert(0);};
270
271         // Server implements this.
272         // Client leaves it as no-op.
273         virtual void saveBlock(MapBlock *block){};
274
275         /*
276                 Updates usage timers and unloads unused blocks and sectors.
277                 Saves modified blocks before unloading on MAPTYPE_SERVER.
278         */
279         void timerUpdate(float dtime, float unload_timeout,
280                         std::list<v3s16> *unloaded_blocks=NULL);
281
282         // Deletes sectors and their blocks from memory
283         // Takes cache into account
284         // If deleted sector is in sector cache, clears cache
285         void deleteSectors(std::list<v2s16> &list);
286
287 #if 0
288         /*
289                 Unload unused data
290                 = flush changed to disk and delete from memory, if usage timer of
291                   block is more than timeout
292         */
293         void unloadUnusedData(float timeout,
294                         core::list<v3s16> *deleted_blocks=NULL);
295 #endif
296
297         // For debug printing. Prints "Map: ", "ServerMap: " or "ClientMap: "
298         virtual void PrintInfo(std::ostream &out);
299
300         void transformLiquids(std::map<v3s16, MapBlock*> & modified_blocks);
301         void transformLiquidsFinite(std::map<v3s16, MapBlock*> & modified_blocks);
302
303         /*
304                 Node metadata
305                 These are basically coordinate wrappers to MapBlock
306         */
307
308         NodeMetadata* getNodeMetadata(v3s16 p);
309         void setNodeMetadata(v3s16 p, NodeMetadata *meta);
310         void removeNodeMetadata(v3s16 p);
311
312         /*
313                 Node Timers
314                 These are basically coordinate wrappers to MapBlock
315         */
316
317         NodeTimer getNodeTimer(v3s16 p);
318         void setNodeTimer(v3s16 p, NodeTimer t);
319         void removeNodeTimer(v3s16 p);
320
321         /*
322                 Misc.
323         */
324         std::map<v2s16, MapSector*> *getSectorsPtr(){return &m_sectors;}
325
326         /*
327                 Variables
328         */
329
330         void transforming_liquid_add(v3s16 p);
331         s32 transforming_liquid_size();
332
333 protected:
334
335         std::ostream &m_dout; // A bit deprecated, could be removed
336
337         IGameDef *m_gamedef;
338
339         std::set<MapEventReceiver*> m_event_receivers;
340
341         std::map<v2s16, MapSector*> m_sectors;
342
343         // Be sure to set this to NULL when the cached sector is deleted
344         MapSector *m_sector_cache;
345         v2s16 m_sector_cache_p;
346
347         // Queued transforming water nodes
348         UniqueQueue<v3s16> m_transforming_liquid;
349 };
350
351 /*
352         ServerMap
353
354         This is the only map class that is able to generate map.
355 */
356
357 class ServerMap : public Map
358 {
359 public:
360         /*
361                 savedir: directory to which map data should be saved
362         */
363         ServerMap(std::string savedir, IGameDef *gamedef, EmergeManager *emerge);
364         ~ServerMap();
365
366         s32 mapType() const
367         {
368                 return MAPTYPE_SERVER;
369         }
370
371         /*
372                 Get a sector from somewhere.
373                 - Check memory
374                 - Check disk (doesn't load blocks)
375                 - Create blank one
376         */
377         ServerMapSector * createSector(v2s16 p);
378
379         /*
380                 Blocks are generated by using these and makeBlock().
381         */
382         bool initBlockMake(BlockMakeData *data, v3s16 blockpos);
383         MapBlock *finishBlockMake(BlockMakeData *data,
384                         std::map<v3s16, MapBlock*> &changed_blocks);
385
386         /*
387                 Get a block from somewhere.
388                 - Memory
389                 - Create blank
390         */
391         MapBlock * createBlock(v3s16 p);
392
393         /*
394                 Forcefully get a block from somewhere.
395                 - Memory
396                 - Load from disk
397                 - Create blank filled with CONTENT_IGNORE
398
399         */
400         MapBlock * emergeBlock(v3s16 p, bool create_blank=true);
401
402         // Helper for placing objects on ground level
403         s16 findGroundLevel(v2s16 p2d);
404
405         /*
406                 Misc. helper functions for fiddling with directory and file
407                 names when saving
408         */
409         void createDirs(std::string path);
410         // returns something like "map/sectors/xxxxxxxx"
411         std::string getSectorDir(v2s16 pos, int layout = 2);
412         // dirname: final directory name
413         v2s16 getSectorPos(std::string dirname);
414         v3s16 getBlockPos(std::string sectordir, std::string blockfile);
415         static std::string getBlockFilename(v3s16 p);
416
417         /*
418                 Database functions
419         */
420         // Create the database structure
421         void createDatabase();
422         // Verify we can read/write to the database
423         void verifyDatabase();
424         // Get an integer suitable for a block
425         static sqlite3_int64 getBlockAsInteger(const v3s16 pos);
426         static v3s16 getIntegerAsBlock(sqlite3_int64 i);
427
428         // Returns true if the database file does not exist
429         bool loadFromFolders();
430
431         // Call these before and after saving of blocks
432         void beginSave();
433         void endSave();
434
435         void save(ModifiedState save_level);
436         //void loadAll();
437         void listAllLoadableBlocks(std::list<v3s16> &dst);
438         // Saves map seed and possibly other stuff
439         void saveMapMeta();
440         void loadMapMeta();
441
442         /*void saveChunkMeta();
443         void loadChunkMeta();*/
444
445         // The sector mutex should be locked when calling most of these
446
447         // This only saves sector-specific data such as the heightmap
448         // (no MapBlocks)
449         // DEPRECATED? Sectors have no metadata anymore.
450         void saveSectorMeta(ServerMapSector *sector);
451         MapSector* loadSectorMeta(std::string dirname, bool save_after_load);
452         bool loadSectorMeta(v2s16 p2d);
453
454         // Full load of a sector including all blocks.
455         // returns true on success, false on failure.
456         bool loadSectorFull(v2s16 p2d);
457         // If sector is not found in memory, try to load it from disk.
458         // Returns true if sector now resides in memory
459         //bool deFlushSector(v2s16 p2d);
460
461         void saveBlock(MapBlock *block);
462         // This will generate a sector with getSector if not found.
463         void loadBlock(std::string sectordir, std::string blockfile, MapSector *sector, bool save_after_load=false);
464         MapBlock* loadBlock(v3s16 p);
465         // Database version
466         void loadBlock(std::string *blob, v3s16 p3d, MapSector *sector, bool save_after_load=false);
467
468         // For debug printing
469         virtual void PrintInfo(std::ostream &out);
470
471         bool isSavingEnabled(){ return m_map_saving_enabled; }
472
473         u64 getSeed(){ return m_seed; }
474
475         MapgenParams *getMapgenParams(){ return m_mgparams; }
476
477         // Parameters fed to the Mapgen
478         MapgenParams *m_mgparams;
479 private:
480         // Seed used for all kinds of randomness in generation
481         u64 m_seed;
482         
483         // Emerge manager
484         EmergeManager *m_emerge;
485
486         std::string m_savedir;
487         bool m_map_saving_enabled;
488
489 #if 0
490         // Chunk size in MapSectors
491         // If 0, chunks are disabled.
492         s16 m_chunksize;
493         // Chunks
494         core::map<v2s16, MapChunk*> m_chunks;
495 #endif
496
497         /*
498                 Metadata is re-written on disk only if this is true.
499                 This is reset to false when written on disk.
500         */
501         bool m_map_metadata_changed;
502
503         /*
504                 SQLite database and statements
505         */
506         sqlite3 *m_database;
507         sqlite3_stmt *m_database_read;
508         sqlite3_stmt *m_database_write;
509         sqlite3_stmt *m_database_list;
510 };
511
512 #define VMANIP_BLOCK_DATA_INEXIST     1
513 #define VMANIP_BLOCK_CONTAINS_CIGNORE 2
514
515 class MapVoxelManipulator : public VoxelManipulator
516 {
517 public:
518         MapVoxelManipulator(Map *map);
519         virtual ~MapVoxelManipulator();
520
521         virtual void clear()
522         {
523                 VoxelManipulator::clear();
524                 m_loaded_blocks.clear();
525         }
526
527         virtual void emerge(VoxelArea a, s32 caller_id=-1);
528
529         void blitBack(std::map<v3s16, MapBlock*> & modified_blocks);
530
531 protected:
532         Map *m_map;
533         /*
534                 key = blockpos
535                 value = flags describing the block
536         */
537         std::map<v3s16, u8> m_loaded_blocks;
538 };
539
540 class ManualMapVoxelManipulator : public MapVoxelManipulator
541 {
542 public:
543         ManualMapVoxelManipulator(Map *map);
544         virtual ~ManualMapVoxelManipulator();
545
546         void setMap(Map *map)
547         {m_map = map;}
548
549         virtual void emerge(VoxelArea a, s32 caller_id=-1);
550
551         void initialEmerge(v3s16 blockpos_min, v3s16 blockpos_max);
552
553         // This is much faster with big chunks of generated data
554         void blitBackAll(std::map<v3s16, MapBlock*> * modified_blocks);
555
556 protected:
557         bool m_create_area;
558 };
559
560 #endif
561