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