]> git.lizzy.rs Git - dragonfireclient.git/blob - src/environment.h
Replace pause and message menu by formspec ones
[dragonfireclient.git] / src / environment.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 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 <list>
35 #include <map>
36 #include "irr_v3d.h"
37 #include "activeobject.h"
38 #include "util/numeric.h"
39 #include "mapnode.h"
40 #include "mapblock.h"
41
42 class ServerEnvironment;
43 class ActiveBlockModifier;
44 class ServerActiveObject;
45 class ITextureSource;
46 class IGameDef;
47 class Map;
48 class ServerMap;
49 class ClientMap;
50 class GameScripting;
51 class Player;
52
53 class Environment
54 {
55 public:
56         // Environment will delete the map passed to the constructor
57         Environment();
58         virtual ~Environment();
59
60         /*
61                 Step everything in environment.
62                 - Move players
63                 - Step mobs
64                 - Run timers of map
65         */
66         virtual void step(f32 dtime) = 0;
67
68         virtual Map & getMap() = 0;
69
70         virtual void addPlayer(Player *player);
71         void removePlayer(u16 peer_id);
72         Player * getPlayer(u16 peer_id);
73         Player * getPlayer(const char *name);
74         Player * getRandomConnectedPlayer();
75         Player * getNearestConnectedPlayer(v3f pos);
76         std::list<Player*> getPlayers();
77         std::list<Player*> getPlayers(bool ignore_disconnected);
78         
79         u32 getDayNightRatio();
80
81         // 0-23999
82         virtual void setTimeOfDay(u32 time)
83         {
84                 m_time_of_day = time;
85                 m_time_of_day_f = (float)time / 24000.0;
86         }
87
88         u32 getTimeOfDay()
89         { return m_time_of_day; }
90
91         float getTimeOfDayF()
92         { return m_time_of_day_f; }
93
94         void stepTimeOfDay(float dtime);
95
96         void setTimeOfDaySpeed(float speed)
97         { m_time_of_day_speed = speed; }
98         
99         float getTimeOfDaySpeed()
100         { return m_time_of_day_speed; }
101
102         void setDayNightRatioOverride(bool enable, u32 value)
103         {
104                 m_enable_day_night_ratio_override = enable;
105                 m_day_night_ratio_override = value;
106         }
107
108 protected:
109         // peer_ids in here should be unique, except that there may be many 0s
110         std::list<Player*> m_players;
111         // Time of day in milli-hours (0-23999); determines day and night
112         u32 m_time_of_day;
113         // Time of day in 0...1
114         float m_time_of_day_f;
115         float m_time_of_day_speed;
116         // Used to buffer dtime for adding to m_time_of_day
117         float m_time_counter;
118         // Overriding the day-night ratio is useful for custom sky visuals
119         bool m_enable_day_night_ratio_override;
120         u32 m_day_night_ratio_override;
121 };
122
123 /*
124         Active block modifier interface.
125
126         These are fed into ServerEnvironment at initialization time;
127         ServerEnvironment handles deleting them.
128 */
129
130 class ActiveBlockModifier
131 {
132 public:
133         ActiveBlockModifier(){};
134         virtual ~ActiveBlockModifier(){};
135         
136         // Set of contents to trigger on
137         virtual std::set<std::string> getTriggerContents()=0;
138         // Set of required neighbors (trigger doesn't happen if none are found)
139         // Empty = do not check neighbors
140         virtual std::set<std::string> getRequiredNeighbors()
141         { return std::set<std::string>(); }
142         // Trigger interval in seconds
143         virtual float getTriggerInterval() = 0;
144         // Random chance of (1 / return value), 0 is disallowed
145         virtual u32 getTriggerChance() = 0;
146         // This is called usually at interval for 1/chance of the nodes
147         virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){};
148         virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
149                         u32 active_object_count, u32 active_object_count_wider){};
150 };
151
152 struct ABMWithState
153 {
154         ActiveBlockModifier *abm;
155         float timer;
156
157         ABMWithState(ActiveBlockModifier *abm_);
158 };
159
160 /*
161         List of active blocks, used by ServerEnvironment
162 */
163
164 class ActiveBlockList
165 {
166 public:
167         void update(std::list<v3s16> &active_positions,
168                         s16 radius,
169                         std::set<v3s16> &blocks_removed,
170                         std::set<v3s16> &blocks_added);
171
172         bool contains(v3s16 p){
173                 return (m_list.find(p) != m_list.end());
174         }
175
176         void clear(){
177                 m_list.clear();
178         }
179
180         std::set<v3s16> m_list;
181         std::set<v3s16> m_forceloaded_list;
182
183 private:
184 };
185
186 /*
187         The server-side environment.
188
189         This is not thread-safe. Server uses an environment mutex.
190 */
191
192 class ServerEnvironment : public Environment
193 {
194 public:
195         ServerEnvironment(ServerMap *map, GameScripting *scriptIface,
196                         IGameDef *gamedef);
197         ~ServerEnvironment();
198
199         Map & getMap();
200
201         ServerMap & getServerMap();
202
203         //TODO find way to remove this fct!
204         GameScripting* getScriptIface()
205                 { return m_script; }
206
207         IGameDef *getGameDef()
208                 { return m_gamedef; }
209
210         float getSendRecommendedInterval()
211                 { return m_recommended_send_interval; }
212
213         /*
214                 Save players
215         */
216         void serializePlayers(const std::string &savedir);
217         void deSerializePlayers(const std::string &savedir);
218
219         /*
220                 Save and load time of day and game timer
221         */
222         void saveMeta(const std::string &savedir);
223         void loadMeta(const std::string &savedir);
224
225         /*
226                 External ActiveObject interface
227                 -------------------------------------------
228         */
229
230         ServerActiveObject* getActiveObject(u16 id);
231
232         /*
233                 Add an active object to the environment.
234                 Environment handles deletion of object.
235                 Object may be deleted by environment immediately.
236                 If id of object is 0, assigns a free id to it.
237                 Returns the id of the object.
238                 Returns 0 if not added and thus deleted.
239         */
240         u16 addActiveObject(ServerActiveObject *object);
241         
242         /*
243                 Add an active object as a static object to the corresponding
244                 MapBlock.
245                 Caller allocates memory, ServerEnvironment frees memory.
246                 Return value: true if succeeded, false if failed.
247                 (note:  not used, pending removal from engine)
248         */
249         //bool addActiveObjectAsStatic(ServerActiveObject *object);
250         
251         /*
252                 Find out what new objects have been added to
253                 inside a radius around a position
254         */
255         void getAddedActiveObjects(v3s16 pos, s16 radius,
256                         std::set<u16> &current_objects,
257                         std::set<u16> &added_objects);
258
259         /*
260                 Find out what new objects have been removed from
261                 inside a radius around a position
262         */
263         void getRemovedActiveObjects(v3s16 pos, s16 radius,
264                         std::set<u16> &current_objects,
265                         std::set<u16> &removed_objects);
266         
267         /*
268                 Get the next message emitted by some active object.
269                 Returns a message with id=0 if no messages are available.
270         */
271         ActiveObjectMessage getActiveObjectMessage();
272
273         /*
274                 Activate objects and dynamically modify for the dtime determined
275                 from timestamp and additional_dtime
276         */
277         void activateBlock(MapBlock *block, u32 additional_dtime=0);
278
279         /*
280                 ActiveBlockModifiers
281                 -------------------------------------------
282         */
283
284         void addActiveBlockModifier(ActiveBlockModifier *abm);
285
286         /*
287                 Other stuff
288                 -------------------------------------------
289         */
290
291         // Script-aware node setters
292         bool setNode(v3s16 p, const MapNode &n);
293         bool removeNode(v3s16 p);
294         bool swapNode(v3s16 p, const MapNode &n);
295         
296         // Find all active objects inside a radius around a point
297         std::set<u16> getObjectsInsideRadius(v3f pos, float radius);
298         
299         // Clear all objects, loading and going through every MapBlock
300         void clearAllObjects();
301         
302         // This makes stuff happen
303         void step(f32 dtime);
304         
305         //check if there's a line of sight between two positions
306         bool line_of_sight(v3f pos1, v3f pos2, float stepsize=1.0, v3s16 *p=NULL);
307
308         u32 getGameTime() { return m_game_time; }
309
310         void reportMaxLagEstimate(float f) { m_max_lag_estimate = f; }
311         float getMaxLagEstimate() { return m_max_lag_estimate; }
312         
313         // is weather active in this environment?
314         bool m_use_weather;
315         
316         std::set<v3s16>* getForceloadedBlocks() { return &m_active_blocks.m_forceloaded_list; };
317         
318 private:
319
320         /*
321                 Internal ActiveObject interface
322                 -------------------------------------------
323         */
324
325         /*
326                 Add an active object to the environment.
327
328                 Called by addActiveObject.
329
330                 Object may be deleted by environment immediately.
331                 If id of object is 0, assigns a free id to it.
332                 Returns the id of the object.
333                 Returns 0 if not added and thus deleted.
334         */
335         u16 addActiveObjectRaw(ServerActiveObject *object, bool set_changed, u32 dtime_s);
336         
337         /*
338                 Remove all objects that satisfy (m_removed && m_known_by_count==0)
339         */
340         void removeRemovedObjects();
341         
342         /*
343                 Convert stored objects from block to active
344         */
345         void activateObjects(MapBlock *block, u32 dtime_s);
346         
347         /*
348                 Convert objects that are not in active blocks to static.
349
350                 If m_known_by_count != 0, active object is not deleted, but static
351                 data is still updated.
352
353                 If force_delete is set, active object is deleted nevertheless. It
354                 shall only be set so in the destructor of the environment.
355         */
356         void deactivateFarObjects(bool force_delete);
357
358         /*
359                 Member variables
360         */
361         
362         // The map
363         ServerMap *m_map;
364         // Lua state
365         GameScripting* m_script;
366         // Game definition
367         IGameDef *m_gamedef;
368         // Active object list
369         std::map<u16, ServerActiveObject*> m_active_objects;
370         // Outgoing network message buffer for active objects
371         std::list<ActiveObjectMessage> m_active_object_messages;
372         // Some timers
373         float m_random_spawn_timer; // used for experimental code
374         float m_send_recommended_timer;
375         IntervalLimiter m_object_management_interval;
376         // List of active blocks
377         ActiveBlockList m_active_blocks;
378         IntervalLimiter m_active_blocks_management_interval;
379         IntervalLimiter m_active_block_modifier_interval;
380         IntervalLimiter m_active_blocks_nodemetadata_interval;
381         int m_active_block_interval_overload_skip;
382         // Time from the beginning of the game in seconds.
383         // Incremented in step().
384         u32 m_game_time;
385         // A helper variable for incrementing the latter
386         float m_game_time_fraction_counter;
387         std::list<ABMWithState> m_abms;
388         // An interval for generally sending object positions and stuff
389         float m_recommended_send_interval;
390         // Estimate for general maximum lag as determined by server.
391         // Can raise to high values like 15s with eg. map generation mods.
392         float m_max_lag_estimate;
393 };
394
395 #ifndef SERVER
396
397 #include "clientobject.h"
398 class ClientSimpleObject;
399
400 /*
401         The client-side environment.
402
403         This is not thread-safe.
404         Must be called from main (irrlicht) thread (uses the SceneManager)
405         Client uses an environment mutex.
406 */
407
408 enum ClientEnvEventType
409 {
410         CEE_NONE,
411         CEE_PLAYER_DAMAGE,
412         CEE_PLAYER_BREATH
413 };
414
415 struct ClientEnvEvent
416 {
417         ClientEnvEventType type;
418         union {
419                 struct{
420                 } none;
421                 struct{
422                         u8 amount;
423                         bool send_to_server;
424                 } player_damage;
425                 struct{
426                         u16 amount;
427                 } player_breath;
428         };
429 };
430
431 class ClientEnvironment : public Environment
432 {
433 public:
434         ClientEnvironment(ClientMap *map, scene::ISceneManager *smgr,
435                         ITextureSource *texturesource, IGameDef *gamedef,
436                         IrrlichtDevice *device);
437         ~ClientEnvironment();
438
439         Map & getMap();
440         ClientMap & getClientMap();
441
442         IGameDef *getGameDef()
443         { return m_gamedef; }
444
445         void step(f32 dtime);
446
447         virtual void addPlayer(Player *player);
448         LocalPlayer * getLocalPlayer();
449         
450         /*
451                 ClientSimpleObjects
452         */
453
454         void addSimpleObject(ClientSimpleObject *simple);
455
456         /*
457                 ActiveObjects
458         */
459         
460         ClientActiveObject* getActiveObject(u16 id);
461
462         /*
463                 Adds an active object to the environment.
464                 Environment handles deletion of object.
465                 Object may be deleted by environment immediately.
466                 If id of object is 0, assigns a free id to it.
467                 Returns the id of the object.
468                 Returns 0 if not added and thus deleted.
469         */
470         u16 addActiveObject(ClientActiveObject *object);
471
472         void addActiveObject(u16 id, u8 type, const std::string &init_data);
473         void removeActiveObject(u16 id);
474
475         void processActiveObjectMessage(u16 id, const std::string &data);
476
477         /*
478                 Callbacks for activeobjects
479         */
480
481         void damageLocalPlayer(u8 damage, bool handle_hp=true);
482         void updateLocalPlayerBreath(u16 breath);
483
484         /*
485                 Client likes to call these
486         */
487         
488         // Get all nearby objects
489         void getActiveObjects(v3f origin, f32 max_d,
490                         std::vector<DistanceSortedActiveObject> &dest);
491         
492         // Get event from queue. CEE_NONE is returned if queue is empty.
493         ClientEnvEvent getClientEvent();
494
495         std::vector<core::vector2d<int> > attachment_list; // X is child ID, Y is parent ID
496
497         std::list<std::string> getPlayerNames()
498         { return m_player_names; }
499         void addPlayerName(std::string name)
500         { m_player_names.push_back(name); }
501         void removePlayerName(std::string name)
502         { m_player_names.remove(name); }
503         void updateCameraOffset(v3s16 camera_offset)
504         { m_camera_offset = camera_offset; }
505         v3s16 getCameraOffset()
506         { return m_camera_offset; }
507         
508 private:
509         ClientMap *m_map;
510         scene::ISceneManager *m_smgr;
511         ITextureSource *m_texturesource;
512         IGameDef *m_gamedef;
513         IrrlichtDevice *m_irr;
514         std::map<u16, ClientActiveObject*> m_active_objects;
515         std::list<ClientSimpleObject*> m_simple_objects;
516         std::list<ClientEnvEvent> m_client_event_queue;
517         IntervalLimiter m_active_object_light_update_interval;
518         IntervalLimiter m_lava_hurt_interval;
519         IntervalLimiter m_drowning_interval;
520         IntervalLimiter m_breathing_interval;
521         std::list<std::string> m_player_names;
522         v3s16 m_camera_offset;
523 };
524
525 #endif
526
527 #endif
528