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