beb49885c558bed51858189a5daba427fbb089a3
[oweals/minetest.git] / src / environment.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 General Public License as published by
7 the Free Software Foundation; either version 2 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 General Public License for more details.
14
15 You should have received a copy of the GNU 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 ENVIRONMENT_HEADER
21 #define ENVIRONMENT_HEADER
22
23 /*
24         This class is the game's environment.
25         It contains:
26         - The map
27         - Players
28         - Other objects
29         - The current time in the game
30         - etc.
31 */
32
33 #include <set>
34 #include "common_irrlicht.h"
35 #include "player.h"
36 #include "map.h"
37 #include <ostream>
38 #include "utility.h"
39 #include "activeobject.h"
40
41 class Server;
42 class ActiveBlockModifier;
43 class ServerActiveObject;
44 typedef struct lua_State lua_State;
45 class ITextureSource;
46 class IGameDef;
47
48 class Environment
49 {
50 public:
51         // Environment will delete the map passed to the constructor
52         Environment();
53         virtual ~Environment();
54
55         /*
56                 Step everything in environment.
57                 - Move players
58                 - Step mobs
59                 - Run timers of map
60         */
61         virtual void step(f32 dtime) = 0;
62
63         virtual Map & getMap() = 0;
64
65         virtual void addPlayer(Player *player);
66         void removePlayer(u16 peer_id);
67         Player * getPlayer(u16 peer_id);
68         Player * getPlayer(const char *name);
69         Player * getRandomConnectedPlayer();
70         Player * getNearestConnectedPlayer(v3f pos);
71         core::list<Player*> getPlayers();
72         core::list<Player*> getPlayers(bool ignore_disconnected);
73         void printPlayers(std::ostream &o);
74         
75         //void setDayNightRatio(u32 r);
76         u32 getDayNightRatio();
77         
78         // 0-23999
79         virtual void setTimeOfDay(u32 time)
80         {
81                 m_time_of_day = time;
82         }
83
84         u32 getTimeOfDay()
85         {
86                 return m_time_of_day;
87         }
88
89 protected:
90         // peer_ids in here should be unique, except that there may be many 0s
91         core::list<Player*> m_players;
92         // Brightness
93         //u32 m_daynight_ratio;
94         // Time of day in milli-hours (0-23999); determines day and night
95         u32 m_time_of_day;
96 };
97
98 /*
99         Active block modifier interface.
100
101         These are fed into ServerEnvironment at initialization time;
102         ServerEnvironment handles deleting them.
103 */
104
105 class ActiveBlockModifier
106 {
107 public:
108         ActiveBlockModifier(){};
109         virtual ~ActiveBlockModifier(){};
110         
111         // Set of contents to trigger on
112         virtual std::set<std::string> getTriggerContents()=0;
113         // Set of required neighbors (trigger doesn't happen if none are found)
114         // Empty = do not check neighbors
115         virtual std::set<std::string> getRequiredNeighbors()
116         { return std::set<std::string>(); }
117         // Trigger interval in seconds
118         virtual float getTriggerInterval() = 0;
119         // Random chance of (1 / return value), 0 is disallowed
120         virtual u32 getTriggerChance() = 0;
121         // This is called usually at interval for 1/chance of the nodes
122         virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){};
123         virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
124                         u32 active_object_count, u32 active_object_count_wider){};
125 };
126
127 struct ABMWithState
128 {
129         ActiveBlockModifier *abm;
130         float timer;
131
132         ABMWithState(ActiveBlockModifier *abm_);
133 };
134
135 /*
136         List of active blocks, used by ServerEnvironment
137 */
138
139 class ActiveBlockList
140 {
141 public:
142         void update(core::list<v3s16> &active_positions,
143                         s16 radius,
144                         core::map<v3s16, bool> &blocks_removed,
145                         core::map<v3s16, bool> &blocks_added);
146
147         bool contains(v3s16 p){
148                 return (m_list.find(p) != NULL);
149         }
150
151         void clear(){
152                 m_list.clear();
153         }
154
155         core::map<v3s16, bool> m_list;
156
157 private:
158 };
159
160 class IBackgroundBlockEmerger
161 {
162 public:
163         virtual void queueBlockEmerge(v3s16 blockpos, bool allow_generate)=0;
164 };
165
166 /*
167         The server-side environment.
168
169         This is not thread-safe. Server uses an environment mutex.
170 */
171
172 class ServerEnvironment : public Environment
173 {
174 public:
175         ServerEnvironment(ServerMap *map, lua_State *L, IGameDef *gamedef,
176                         IBackgroundBlockEmerger *emerger);
177         ~ServerEnvironment();
178
179         Map & getMap()
180                 { return *m_map; }
181
182         ServerMap & getServerMap()
183                 { return *m_map; }
184
185         lua_State* getLua()
186                 { return m_lua; }
187
188         IGameDef *getGameDef()
189                 { return m_gamedef; }
190
191         float getSendRecommendedInterval()
192         {
193                 return 0.10;
194         }
195
196         /*
197                 Save players
198         */
199         void serializePlayers(const std::string &savedir);
200         void deSerializePlayers(const std::string &savedir);
201
202         /*
203                 Save and load time of day and game timer
204         */
205         void saveMeta(const std::string &savedir);
206         void loadMeta(const std::string &savedir);
207
208         /*
209                 External ActiveObject interface
210                 -------------------------------------------
211         */
212
213         ServerActiveObject* getActiveObject(u16 id);
214
215         /*
216                 Add an active object to the environment.
217                 Environment handles deletion of object.
218                 Object may be deleted by environment immediately.
219                 If id of object is 0, assigns a free id to it.
220                 Returns the id of the object.
221                 Returns 0 if not added and thus deleted.
222         */
223         u16 addActiveObject(ServerActiveObject *object);
224         
225         /*
226                 Add an active object as a static object to the corresponding
227                 MapBlock.
228                 Caller allocates memory, ServerEnvironment frees memory.
229                 Return value: true if succeeded, false if failed.
230         */
231         bool addActiveObjectAsStatic(ServerActiveObject *object);
232         
233         /*
234                 Find out what new objects have been added to
235                 inside a radius around a position
236         */
237         void getAddedActiveObjects(v3s16 pos, s16 radius,
238                         core::map<u16, bool> &current_objects,
239                         core::map<u16, bool> &added_objects);
240
241         /*
242                 Find out what new objects have been removed from
243                 inside a radius around a position
244         */
245         void getRemovedActiveObjects(v3s16 pos, s16 radius,
246                         core::map<u16, bool> &current_objects,
247                         core::map<u16, bool> &removed_objects);
248         
249         /*
250                 Get the next message emitted by some active object.
251                 Returns a message with id=0 if no messages are available.
252         */
253         ActiveObjectMessage getActiveObjectMessage();
254
255         /*
256                 Activate objects and dynamically modify for the dtime determined
257                 from timestamp and additional_dtime
258         */
259         void activateBlock(MapBlock *block, u32 additional_dtime=0);
260
261         /*
262                 ActiveBlockModifiers
263                 -------------------------------------------
264         */
265
266         void addActiveBlockModifier(ActiveBlockModifier *abm);
267
268         /*
269                 Other stuff
270                 -------------------------------------------
271         */
272         
273         // Find all active objects inside a radius around a point
274         std::set<u16> getObjectsInsideRadius(v3f pos, float radius);
275         
276         // Clear all objects, loading and going through every MapBlock
277         void clearAllObjects();
278         
279         // This makes stuff happen
280         void step(f32 dtime);
281         
282 private:
283
284         /*
285                 Internal ActiveObject interface
286                 -------------------------------------------
287         */
288
289         /*
290                 Add an active object to the environment.
291
292                 Called by addActiveObject.
293
294                 Object may be deleted by environment immediately.
295                 If id of object is 0, assigns a free id to it.
296                 Returns the id of the object.
297                 Returns 0 if not added and thus deleted.
298         */
299         u16 addActiveObjectRaw(ServerActiveObject *object, bool set_changed);
300         
301         /*
302                 Remove all objects that satisfy (m_removed && m_known_by_count==0)
303         */
304         void removeRemovedObjects();
305         
306         /*
307                 Convert stored objects from block to active
308         */
309         void activateObjects(MapBlock *block);
310         
311         /*
312                 Convert objects that are not in active blocks to static.
313
314                 If m_known_by_count != 0, active object is not deleted, but static
315                 data is still updated.
316
317                 If force_delete is set, active object is deleted nevertheless. It
318                 shall only be set so in the destructor of the environment.
319         */
320         void deactivateFarObjects(bool force_delete);
321
322         /*
323                 Member variables
324         */
325         
326         // The map
327         ServerMap *m_map;
328         // Lua state
329         lua_State *m_lua;
330         // Game definition
331         IGameDef *m_gamedef;
332         // Background block emerger (the server, in practice)
333         IBackgroundBlockEmerger *m_emerger;
334         // Active object list
335         core::map<u16, ServerActiveObject*> m_active_objects;
336         // Outgoing network message buffer for active objects
337         Queue<ActiveObjectMessage> m_active_object_messages;
338         // Some timers
339         float m_random_spawn_timer; // used for experimental code
340         float m_send_recommended_timer;
341         IntervalLimiter m_object_management_interval;
342         // List of active blocks
343         ActiveBlockList m_active_blocks;
344         IntervalLimiter m_active_blocks_management_interval;
345         IntervalLimiter m_active_block_modifier_interval;
346         IntervalLimiter m_active_blocks_nodemetadata_interval;
347         // Time from the beginning of the game in seconds.
348         // Incremented in step().
349         u32 m_game_time;
350         // A helper variable for incrementing the latter
351         float m_game_time_fraction_counter;
352         core::list<ABMWithState> m_abms;
353 };
354
355 #ifndef SERVER
356
357 #include "clientobject.h"
358
359 /*
360         The client-side environment.
361
362         This is not thread-safe.
363         Must be called from main (irrlicht) thread (uses the SceneManager)
364         Client uses an environment mutex.
365 */
366
367 enum ClientEnvEventType
368 {
369         CEE_NONE,
370         CEE_PLAYER_DAMAGE
371 };
372
373 struct ClientEnvEvent
374 {
375         ClientEnvEventType type;
376         union {
377                 struct{
378                 } none;
379                 struct{
380                         u8 amount;
381                         bool send_to_server;
382                 } player_damage;
383         };
384 };
385
386 class ClientEnvironment : public Environment
387 {
388 public:
389         ClientEnvironment(ClientMap *map, scene::ISceneManager *smgr,
390                         ITextureSource *texturesource, IGameDef *gamedef,
391                         IrrlichtDevice *device);
392         ~ClientEnvironment();
393
394         Map & getMap()
395         { return *m_map; }
396
397         ClientMap & getClientMap()
398         { return *m_map; }
399
400         IGameDef *getGameDef()
401         { return m_gamedef; }
402
403         void step(f32 dtime);
404
405         virtual void addPlayer(Player *player);
406         LocalPlayer * getLocalPlayer();
407         
408         // Slightly deprecated
409         void updateMeshes(v3s16 blockpos);
410         void expireMeshes(bool only_daynight_diffed);
411
412         void setTimeOfDay(u32 time)
413         {
414                 u32 old_dr = getDayNightRatio();
415
416                 Environment::setTimeOfDay(time);
417
418                 if(getDayNightRatio() != old_dr)
419                 {
420                         /*infostream<<"ClientEnvironment: DayNightRatio changed"
421                                         <<" -> expiring meshes"<<std::endl;*/
422                         expireMeshes(true);
423                 }
424         }
425
426         /*
427                 ActiveObjects
428         */
429         
430         ClientActiveObject* getActiveObject(u16 id);
431
432         /*
433                 Adds an active object to the environment.
434                 Environment handles deletion of object.
435                 Object may be deleted by environment immediately.
436                 If id of object is 0, assigns a free id to it.
437                 Returns the id of the object.
438                 Returns 0 if not added and thus deleted.
439         */
440         u16 addActiveObject(ClientActiveObject *object);
441
442         void addActiveObject(u16 id, u8 type, const std::string &init_data);
443         void removeActiveObject(u16 id);
444
445         void processActiveObjectMessage(u16 id, const std::string &data);
446
447         /*
448                 Callbacks for activeobjects
449         */
450
451         void damageLocalPlayer(u8 damage, bool handle_hp=true);
452
453         /*
454                 Client likes to call these
455         */
456         
457         // Get all nearby objects
458         void getActiveObjects(v3f origin, f32 max_d,
459                         core::array<DistanceSortedActiveObject> &dest);
460         
461         // Get event from queue. CEE_NONE is returned if queue is empty.
462         ClientEnvEvent getClientEvent();
463         
464 private:
465         ClientMap *m_map;
466         scene::ISceneManager *m_smgr;
467         ITextureSource *m_texturesource;
468         IGameDef *m_gamedef;
469         IrrlichtDevice *m_irr;
470         core::map<u16, ClientActiveObject*> m_active_objects;
471         Queue<ClientEnvEvent> m_client_event_queue;
472         IntervalLimiter m_active_object_light_update_interval;
473         IntervalLimiter m_lava_hurt_interval;
474 };
475
476 #endif
477
478 #endif
479