Protect Player::hud from concurrent modifications
[oweals/minetest.git] / src / player.cpp
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 #include "player.h"
21
22 #include <fstream>
23 #include "util/numeric.h"
24 #include "hud.h"
25 #include "constants.h"
26 #include "gamedef.h"
27 #include "settings.h"
28 #include "content_sao.h"
29 #include "filesys.h"
30 #include "log.h"
31 #include "porting.h"  // strlcpy
32
33
34 Player::Player(IGameDef *gamedef, const char *name):
35         touching_ground(false),
36         in_liquid(false),
37         in_liquid_stable(false),
38         liquid_viscosity(0),
39         is_climbing(false),
40         swimming_vertical(false),
41         camera_barely_in_ceiling(false),
42         inventory(gamedef->idef()),
43         hp(PLAYER_MAX_HP),
44         hurt_tilt_timer(0),
45         hurt_tilt_strength(0),
46         peer_id(PEER_ID_INEXISTENT),
47         keyPressed(0),
48 // protected
49         m_gamedef(gamedef),
50         m_breath(PLAYER_MAX_BREATH),
51         m_pitch(0),
52         m_yaw(0),
53         m_speed(0,0,0),
54         m_position(0,0,0),
55         m_collisionbox(-BS*0.30,0.0,-BS*0.30,BS*0.30,BS*1.75,BS*0.30),
56         m_dirty(false)
57 {
58         strlcpy(m_name, name, PLAYERNAME_SIZE);
59
60         inventory.clear();
61         inventory.addList("main", PLAYER_INVENTORY_SIZE);
62         InventoryList *craft = inventory.addList("craft", 9);
63         craft->setWidth(3);
64         inventory.addList("craftpreview", 1);
65         inventory.addList("craftresult", 1);
66         inventory.setModified(false);
67
68         // Can be redefined via Lua
69         inventory_formspec = "size[8,7.5]"
70                 //"image[1,0.6;1,2;player.png]"
71                 "list[current_player;main;0,3.5;8,4;]"
72                 "list[current_player;craft;3,0;3,3;]"
73                 "list[current_player;craftpreview;7,1;1,1;]";
74
75         // Initialize movement settings at default values, so movement can work if the server fails to send them
76         movement_acceleration_default   = 3    * BS;
77         movement_acceleration_air       = 2    * BS;
78         movement_acceleration_fast      = 10   * BS;
79         movement_speed_walk             = 4    * BS;
80         movement_speed_crouch           = 1.35 * BS;
81         movement_speed_fast             = 20   * BS;
82         movement_speed_climb            = 2    * BS;
83         movement_speed_jump             = 6.5  * BS;
84         movement_liquid_fluidity        = 1    * BS;
85         movement_liquid_fluidity_smooth = 0.5  * BS;
86         movement_liquid_sink            = 10   * BS;
87         movement_gravity                = 9.81 * BS;
88
89         // Movement overrides are multipliers and must be 1 by default
90         physics_override_speed        = 1;
91         physics_override_jump         = 1;
92         physics_override_gravity      = 1;
93         physics_override_sneak        = true;
94         physics_override_sneak_glitch = true;
95
96         hud_flags = HUD_FLAG_HOTBAR_VISIBLE | HUD_FLAG_HEALTHBAR_VISIBLE |
97                          HUD_FLAG_CROSSHAIR_VISIBLE | HUD_FLAG_WIELDITEM_VISIBLE |
98                          HUD_FLAG_BREATHBAR_VISIBLE;
99
100         hud_hotbar_itemcount = HUD_HOTBAR_ITEMCOUNT_DEFAULT;
101 }
102
103 Player::~Player()
104 {
105         clearHud();
106 }
107
108 // Horizontal acceleration (X and Z), Y direction is ignored
109 void Player::accelerateHorizontal(v3f target_speed, f32 max_increase)
110 {
111         if(max_increase == 0)
112                 return;
113
114         v3f d_wanted = target_speed - m_speed;
115         d_wanted.Y = 0;
116         f32 dl = d_wanted.getLength();
117         if(dl > max_increase)
118                 dl = max_increase;
119         
120         v3f d = d_wanted.normalize() * dl;
121
122         m_speed.X += d.X;
123         m_speed.Z += d.Z;
124
125 #if 0 // old code
126         if(m_speed.X < target_speed.X - max_increase)
127                 m_speed.X += max_increase;
128         else if(m_speed.X > target_speed.X + max_increase)
129                 m_speed.X -= max_increase;
130         else if(m_speed.X < target_speed.X)
131                 m_speed.X = target_speed.X;
132         else if(m_speed.X > target_speed.X)
133                 m_speed.X = target_speed.X;
134
135         if(m_speed.Z < target_speed.Z - max_increase)
136                 m_speed.Z += max_increase;
137         else if(m_speed.Z > target_speed.Z + max_increase)
138                 m_speed.Z -= max_increase;
139         else if(m_speed.Z < target_speed.Z)
140                 m_speed.Z = target_speed.Z;
141         else if(m_speed.Z > target_speed.Z)
142                 m_speed.Z = target_speed.Z;
143 #endif
144 }
145
146 // Vertical acceleration (Y), X and Z directions are ignored
147 void Player::accelerateVertical(v3f target_speed, f32 max_increase)
148 {
149         if(max_increase == 0)
150                 return;
151
152         f32 d_wanted = target_speed.Y - m_speed.Y;
153         if(d_wanted > max_increase)
154                 d_wanted = max_increase;
155         else if(d_wanted < -max_increase)
156                 d_wanted = -max_increase;
157
158         m_speed.Y += d_wanted;
159
160 #if 0 // old code
161         if(m_speed.Y < target_speed.Y - max_increase)
162                 m_speed.Y += max_increase;
163         else if(m_speed.Y > target_speed.Y + max_increase)
164                 m_speed.Y -= max_increase;
165         else if(m_speed.Y < target_speed.Y)
166                 m_speed.Y = target_speed.Y;
167         else if(m_speed.Y > target_speed.Y)
168                 m_speed.Y = target_speed.Y;
169 #endif
170 }
171
172 v3s16 Player::getLightPosition() const
173 {
174         return floatToInt(m_position + v3f(0,BS+BS/2,0), BS);
175 }
176
177 void Player::serialize(std::ostream &os)
178 {
179         // Utilize a Settings object for storing values
180         Settings args;
181         args.setS32("version", 1);
182         args.set("name", m_name);
183         //args.set("password", m_password);
184         args.setFloat("pitch", m_pitch);
185         args.setFloat("yaw", m_yaw);
186         args.setV3F("position", m_position);
187         args.setS32("hp", hp);
188         args.setS32("breath", m_breath);
189
190         args.writeLines(os);
191
192         os<<"PlayerArgsEnd\n";
193
194         inventory.serialize(os);
195 }
196
197 void Player::deSerialize(std::istream &is, std::string playername)
198 {
199         Settings args;
200
201         if (!args.parseConfigLines(is, "PlayerArgsEnd")) {
202                 throw SerializationError("PlayerArgsEnd of player " +
203                                 playername + " not found!");
204         }
205
206         m_dirty = true;
207         //args.getS32("version"); // Version field value not used
208         std::string name = args.get("name");
209         strlcpy(m_name, name.c_str(), PLAYERNAME_SIZE);
210         setPitch(args.getFloat("pitch"));
211         setYaw(args.getFloat("yaw"));
212         setPosition(args.getV3F("position"));
213         try{
214                 hp = args.getS32("hp");
215         }catch(SettingNotFoundException &e) {
216                 hp = PLAYER_MAX_HP;
217         }
218         try{
219                 m_breath = args.getS32("breath");
220         }catch(SettingNotFoundException &e) {
221                 m_breath = PLAYER_MAX_BREATH;
222         }
223
224         inventory.deSerialize(is);
225
226         if(inventory.getList("craftpreview") == NULL) {
227                 // Convert players without craftpreview
228                 inventory.addList("craftpreview", 1);
229
230                 bool craftresult_is_preview = true;
231                 if(args.exists("craftresult_is_preview"))
232                         craftresult_is_preview = args.getBool("craftresult_is_preview");
233                 if(craftresult_is_preview)
234                 {
235                         // Clear craftresult
236                         inventory.getList("craftresult")->changeItem(0, ItemStack());
237                 }
238         }
239 }
240
241 u32 Player::addHud(HudElement *toadd)
242 {
243         JMutexAutoLock lock(m_mutex);
244         u32 id = getFreeHudID();
245
246         if (id < hud.size())
247                 hud[id] = toadd;
248         else
249                 hud.push_back(toadd);
250
251         return id;
252 }
253
254 HudElement* Player::getHud(u32 id)
255 {
256         JMutexAutoLock lock(m_mutex);
257
258         if (id < hud.size())
259                 return hud[id];
260
261         return NULL;
262 }
263
264 HudElement* Player::removeHud(u32 id)
265 {
266         JMutexAutoLock lock(m_mutex);
267
268         HudElement* retval = NULL;
269         if (id < hud.size()) {
270                 retval = hud[id];
271                 hud[id] = NULL;
272         }
273         return retval;
274 }
275
276 void Player::clearHud()
277 {
278         JMutexAutoLock lock(m_mutex);
279
280         while(!hud.empty()) {
281                 delete hud.back();
282                 hud.pop_back();
283         }
284 }
285
286
287 void RemotePlayer::save(std::string savedir)
288 {
289         /*
290          * We have to open all possible player files in the players directory
291          * and check their player names because some file systems are not
292          * case-sensitive and player names are case-sensitive.
293          */
294
295         // A player to deserialize files into to check their names
296         RemotePlayer testplayer(m_gamedef, "");
297
298         savedir += DIR_DELIM;
299         std::string path = savedir + m_name;
300         for (u32 i = 0; i < PLAYER_FILE_ALTERNATE_TRIES; i++) {
301                 if (!fs::PathExists(path)) {
302                         // Open file and serialize
303                         std::ostringstream ss(std::ios_base::binary);
304                         serialize(ss);
305                         if (!fs::safeWriteToFile(path, ss.str())) {
306                                 infostream << "Failed to write " << path << std::endl;
307                         }
308                         setModified(false);
309                         return;
310                 }
311                 // Open file and deserialize
312                 std::ifstream is(path.c_str(), std::ios_base::binary);
313                 if (!is.good()) {
314                         infostream << "Failed to open " << path << std::endl;
315                         return;
316                 }
317                 testplayer.deSerialize(is, path);
318                 is.close();
319                 if (strcmp(testplayer.getName(), m_name) == 0) {
320                         // Open file and serialize
321                         std::ostringstream ss(std::ios_base::binary);
322                         serialize(ss);
323                         if (!fs::safeWriteToFile(path, ss.str())) {
324                                 infostream << "Failed to write " << path << std::endl;
325                         }
326                         setModified(false);
327                         return;
328                 }
329                 path = savedir + m_name + itos(i);
330         }
331
332         infostream << "Didn't find free file for player " << m_name << std::endl;
333         return;
334 }
335
336 /*
337         RemotePlayer
338 */
339 void RemotePlayer::setPosition(const v3f &position)
340 {
341         Player::setPosition(position);
342         if(m_sao)
343                 m_sao->setBasePosition(position);
344 }
345