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