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