9817d590d125ca48785692a1165efb1d1651424a
[oweals/minetest.git] / src / player.cpp
1 /*
2 Minetest-c55
3 Copyright (C) 2010 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 /*
21 (c) 2010 Perttu Ahola <celeron55@gmail.com>
22 */
23
24 #include "player.h"
25 #include "map.h"
26 #include "connection.h"
27 #include "constants.h"
28 #include "utility.h"
29
30 Player::Player():
31         touching_ground(false),
32         in_water(false),
33         peer_id(PEER_ID_INEXISTENT),
34         m_speed(0,0,0),
35         m_position(0,0,0)
36 {
37         updateName("<not set>");
38         resetInventory();
39 }
40
41 Player::~Player()
42 {
43 }
44
45 void Player::resetInventory()
46 {
47         inventory.clear();
48         inventory.addList("main", PLAYER_INVENTORY_SIZE);
49         inventory.addList("craft", 9);
50         inventory.addList("craftresult", 1);
51 }
52
53 // Y direction is ignored
54 void Player::accelerate(v3f target_speed, f32 max_increase)
55 {
56         v3f d_wanted = target_speed - m_speed;
57         d_wanted.Y = 0;
58         f32 dl_wanted = d_wanted.getLength();
59         f32 dl = dl_wanted;
60         if(dl > max_increase)
61                 dl = max_increase;
62         
63         v3f d = d_wanted.normalize() * dl;
64
65         m_speed.X += d.X;
66         m_speed.Z += d.Z;
67         //m_speed += d;
68
69 #if 0 // old code
70         if(m_speed.X < target_speed.X - max_increase)
71                 m_speed.X += max_increase;
72         else if(m_speed.X > target_speed.X + max_increase)
73                 m_speed.X -= max_increase;
74         else if(m_speed.X < target_speed.X)
75                 m_speed.X = target_speed.X;
76         else if(m_speed.X > target_speed.X)
77                 m_speed.X = target_speed.X;
78
79         if(m_speed.Z < target_speed.Z - max_increase)
80                 m_speed.Z += max_increase;
81         else if(m_speed.Z > target_speed.Z + max_increase)
82                 m_speed.Z -= max_increase;
83         else if(m_speed.Z < target_speed.Z)
84                 m_speed.Z = target_speed.Z;
85         else if(m_speed.Z > target_speed.Z)
86                 m_speed.Z = target_speed.Z;
87 #endif
88 }
89
90 void Player::serialize(std::ostream &os)
91 {
92         // Utilize a Settings object for storing values
93         Settings args;
94         args.setS32("version", 1);
95         args.set("name", m_name);
96         args.setFloat("pitch", m_pitch);
97         args.setFloat("yaw", m_yaw);
98         args.setV3F("position", m_position);
99
100         args.writeLines(os);
101
102         os<<"PlayerArgsEnd\n";
103
104         inventory.serialize(os);
105 }
106
107 void Player::deSerialize(std::istream &is)
108 {
109         Settings args;
110         
111         for(;;)
112         {
113                 if(is.eof())
114                         throw SerializationError
115                                         ("Player::deSerialize(): PlayerArgsEnd not found");
116                 std::string line;
117                 std::getline(is, line);
118                 std::string trimmedline = trim(line);
119                 if(trimmedline == "PlayerArgsEnd")
120                         break;
121                 args.parseConfigLine(line);
122         }
123
124         //args.getS32("version");
125         std::string name = args.get("name");
126         updateName(name.c_str());
127         m_pitch = args.getFloat("pitch");
128         m_yaw = args.getFloat("yaw");
129         m_position = args.getV3F("position");
130
131         inventory.deSerialize(is);
132 }
133
134 /*
135         RemotePlayer
136 */
137
138 #ifndef SERVER
139
140 RemotePlayer::RemotePlayer(
141                 scene::ISceneNode* parent,
142                 IrrlichtDevice *device,
143                 s32 id):
144         scene::ISceneNode(parent, (device==NULL)?NULL:device->getSceneManager(), id),
145         m_text(NULL)
146 {
147         m_box = core::aabbox3d<f32>(-BS/2,0,-BS/2,BS/2,BS*2,BS/2);
148
149         if(parent != NULL && device != NULL)
150         {
151                 // ISceneNode stores a member called SceneManager
152                 scene::ISceneManager* mgr = SceneManager;
153                 video::IVideoDriver* driver = mgr->getVideoDriver();
154                 gui::IGUIEnvironment* gui = device->getGUIEnvironment();
155
156                 // Add a text node for showing the name
157                 wchar_t wname[1] = {0};
158                 m_text = mgr->addTextSceneNode(gui->getBuiltInFont(),
159                                 wname, video::SColor(255,255,255,255), this);
160                 m_text->setPosition(v3f(0, (f32)BS*2.1, 0));
161
162                 // Attach a simple mesh to the player for showing an image
163                 scene::SMesh *mesh = new scene::SMesh();
164                 { // Front
165                 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
166                 video::SColor c(255,255,255,255);
167                 video::S3DVertex vertices[4] =
168                 {
169                         video::S3DVertex(-BS/2,0,0, 0,0,0, c, 0,1),
170                         video::S3DVertex(BS/2,0,0, 0,0,0, c, 1,1),
171                         video::S3DVertex(BS/2,BS*2,0, 0,0,0, c, 1,0),
172                         video::S3DVertex(-BS/2,BS*2,0, 0,0,0, c, 0,0),
173                 };
174                 u16 indices[] = {0,1,2,2,3,0};
175                 buf->append(vertices, 4, indices, 6);
176                 // Set material
177                 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
178                 //buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
179                 buf->getMaterial().setTexture(0, driver->getTexture(porting::getDataPath("player.png").c_str()));
180                 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
181                 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
182                 //buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
183                 buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
184                 // Add to mesh
185                 mesh->addMeshBuffer(buf);
186                 buf->drop();
187                 }
188                 { // Back
189                 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
190                 video::SColor c(255,255,255,255);
191                 video::S3DVertex vertices[4] =
192                 {
193                         video::S3DVertex(BS/2,0,0, 0,0,0, c, 1,1),
194                         video::S3DVertex(-BS/2,0,0, 0,0,0, c, 0,1),
195                         video::S3DVertex(-BS/2,BS*2,0, 0,0,0, c, 0,0),
196                         video::S3DVertex(BS/2,BS*2,0, 0,0,0, c, 1,0),
197                 };
198                 u16 indices[] = {0,1,2,2,3,0};
199                 buf->append(vertices, 4, indices, 6);
200                 // Set material
201                 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
202                 //buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
203                 buf->getMaterial().setTexture(0, driver->getTexture(porting::getDataPath("player_back.png").c_str()));
204                 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
205                 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
206                 buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
207                 // Add to mesh
208                 mesh->addMeshBuffer(buf);
209                 buf->drop();
210                 }
211                 m_node = mgr->addMeshSceneNode(mesh, this);
212                 mesh->drop();
213                 m_node->setPosition(v3f(0,0,0));
214         }
215 }
216
217 RemotePlayer::~RemotePlayer()
218 {
219         if(SceneManager != NULL)
220                 ISceneNode::remove();
221 }
222
223 void RemotePlayer::updateName(const char *name)
224 {
225         Player::updateName(name);
226         if(m_text != NULL)
227         {
228                 wchar_t wname[PLAYERNAME_SIZE];
229                 mbstowcs(wname, m_name, strlen(m_name)+1);
230                 m_text->setText(wname);
231         }
232 }
233
234 void RemotePlayer::move(f32 dtime, Map &map)
235 {
236         m_pos_animation_time_counter += dtime;
237         m_pos_animation_counter += dtime;
238         v3f movevector = m_position - m_oldpos;
239         f32 moveratio;
240         if(m_pos_animation_time < 0.001)
241                 moveratio = 1.0;
242         else
243                 moveratio = m_pos_animation_counter / m_pos_animation_time;
244         if(moveratio > 1.5)
245                 moveratio = 1.5;
246         m_showpos = m_oldpos + movevector * moveratio;
247         
248         ISceneNode::setPosition(m_showpos);
249 }
250
251 #endif
252
253 #ifndef SERVER
254 /*
255         LocalPlayer
256 */
257
258 LocalPlayer::LocalPlayer()
259 {
260 }
261
262 LocalPlayer::~LocalPlayer()
263 {
264 }
265
266 void LocalPlayer::move(f32 dtime, Map &map)
267 {
268         v3f position = getPosition();
269         v3f oldpos = position;
270         v3s16 oldpos_i = floatToInt(oldpos);
271
272         /*std::cout<<"oldpos_i=("<<oldpos_i.X<<","<<oldpos_i.Y<<","
273                         <<oldpos_i.Z<<")"<<std::endl;*/
274
275         position += m_speed * dtime;
276
277         bool free_move = g_settings.getBool("free_move");
278         bool terrain_viewer = g_settings.getBool("terrain_viewer");
279         
280         // Skip collision detection if player is non-local or
281         // a special movement mode is used
282         if(isLocal() == false || free_move || terrain_viewer)
283         {
284                 setPosition(position);
285                 return;
286         }
287
288         /*
289                 Collision detection
290         */
291
292         v3s16 pos_i = floatToInt(position);
293         
294         /*
295                 Check if player is in water
296         */
297         try{
298                 if(in_water)
299                 {
300                         v3s16 pp = floatToInt(position + v3f(0,0,0));
301                         in_water = content_liquid(map.getNode(pp).d);
302                 }
303                 else
304                 {
305                         v3s16 pp = floatToInt(position + v3f(0,BS/2,0));
306                         in_water = content_liquid(map.getNode(pp).d);
307                 }
308         }
309         catch(InvalidPositionException &e)
310         {
311                 in_water = false;
312         }
313
314         // The frame length is limited to the player going 0.1*BS per call
315         f32 d = (float)BS * 0.15;
316
317 #define PLAYER_RADIUS (BS*0.3)
318 #define PLAYER_HEIGHT (BS*1.7)
319
320         core::aabbox3d<f32> playerbox(
321                 position.X - PLAYER_RADIUS,
322                 position.Y - 0.0,
323                 position.Z - PLAYER_RADIUS,
324                 position.X + PLAYER_RADIUS,
325                 position.Y + PLAYER_HEIGHT,
326                 position.Z + PLAYER_RADIUS
327         );
328         core::aabbox3d<f32> playerbox_old(
329                 oldpos.X - PLAYER_RADIUS,
330                 oldpos.Y - 0.0,
331                 oldpos.Z - PLAYER_RADIUS,
332                 oldpos.X + PLAYER_RADIUS,
333                 oldpos.Y + PLAYER_HEIGHT,
334                 oldpos.Z + PLAYER_RADIUS
335         );
336
337         //hilightboxes.push_back(playerbox);
338
339         touching_ground = false;
340         
341         /*std::cout<<"Checking collisions for ("
342                         <<oldpos_i.X<<","<<oldpos_i.Y<<","<<oldpos_i.Z
343                         <<") -> ("
344                         <<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z
345                         <<"):"<<std::endl;*/
346
347         for(s16 y = oldpos_i.Y - 1; y <= oldpos_i.Y + 2; y++){
348                 for(s16 z = oldpos_i.Z - 1; z <= oldpos_i.Z + 1; z++){
349                         for(s16 x = oldpos_i.X - 1; x <= oldpos_i.X + 1; x++){
350                                 try{
351                                         if(content_walkable(map.getNode(v3s16(x,y,z)).d) == false){
352                                                 continue;
353                                         }
354                                 }
355                                 catch(InvalidPositionException &e)
356                                 {
357                                         // Doing nothing here will block the player from
358                                         // walking over map borders
359                                 }
360
361                                 core::aabbox3d<f32> nodebox = Map::getNodeBox(
362                                                 v3s16(x,y,z));
363                                 
364                                 // See if the player is touching ground
365                                 if(
366                                                 fabs(nodebox.MaxEdge.Y-playerbox.MinEdge.Y) < d
367                                                 && nodebox.MaxEdge.X-d > playerbox.MinEdge.X
368                                                 && nodebox.MinEdge.X+d < playerbox.MaxEdge.X
369                                                 && nodebox.MaxEdge.Z-d > playerbox.MinEdge.Z
370                                                 && nodebox.MinEdge.Z+d < playerbox.MaxEdge.Z
371                                 ){
372                                         touching_ground = true;
373                                 }
374                                 
375                                 if(playerbox.intersectsWithBox(nodebox))
376                                 {
377                                 
378         v3f dirs[3] = {
379                 v3f(0,0,1), // back
380                 v3f(0,1,0), // top
381                 v3f(1,0,0), // right
382         };
383         for(u16 i=0; i<3; i++)
384         {
385                 f32 nodemax = nodebox.MaxEdge.dotProduct(dirs[i]);
386                 f32 nodemin = nodebox.MinEdge.dotProduct(dirs[i]);
387                 f32 playermax = playerbox.MaxEdge.dotProduct(dirs[i]);
388                 f32 playermin = playerbox.MinEdge.dotProduct(dirs[i]);
389                 f32 playermax_old = playerbox_old.MaxEdge.dotProduct(dirs[i]);
390                 f32 playermin_old = playerbox_old.MinEdge.dotProduct(dirs[i]);
391
392                 bool main_edge_collides = 
393                         ((nodemax > playermin && nodemax <= playermin_old + d
394                                 && m_speed.dotProduct(dirs[i]) < 0)
395                         ||
396                         (nodemin < playermax && nodemin >= playermax_old - d
397                                 && m_speed.dotProduct(dirs[i]) > 0));
398
399                 bool other_edges_collide = true;
400                 for(u16 j=0; j<3; j++)
401                 {
402                         if(j == i)
403                                 continue;
404                         f32 nodemax = nodebox.MaxEdge.dotProduct(dirs[j]);
405                         f32 nodemin = nodebox.MinEdge.dotProduct(dirs[j]);
406                         f32 playermax = playerbox.MaxEdge.dotProduct(dirs[j]);
407                         f32 playermin = playerbox.MinEdge.dotProduct(dirs[j]);
408                         if(!(nodemax - d > playermin && nodemin + d < playermax))
409                         {
410                                 other_edges_collide = false;
411                                 break;
412                         }
413                 }
414                 
415                 if(main_edge_collides && other_edges_collide)
416                 {
417                         m_speed -= m_speed.dotProduct(dirs[i]) * dirs[i];
418                         position -= position.dotProduct(dirs[i]) * dirs[i];
419                         position += oldpos.dotProduct(dirs[i]) * dirs[i];
420                 }
421         
422         }
423                                 } // if(playerbox.intersectsWithBox(nodebox))
424                         } // for x
425                 } // for z
426         } // for y
427
428         setPosition(position);
429 }
430
431 void LocalPlayer::applyControl(float dtime)
432 {
433         // Clear stuff
434         swimming_up = false;
435
436         // Random constants
437 #define WALK_ACCELERATION (4.0 * BS)
438 #define WALKSPEED_MAX (4.0 * BS)
439         f32 walk_acceleration = WALK_ACCELERATION;
440         f32 walkspeed_max = WALKSPEED_MAX;
441         
442         setPitch(control.pitch);
443         setYaw(control.yaw);
444         
445         v3f move_direction = v3f(0,0,1);
446         move_direction.rotateXZBy(getYaw());
447         
448         v3f speed = v3f(0,0,0);
449
450         bool free_move = g_settings.getBool("free_move");
451         bool fast_move = g_settings.getBool("fast_move");
452         bool continuous_forward = g_settings.getBool("continuous_forward");
453
454         if(free_move)
455         {
456                 v3f speed = getSpeed();
457                 speed.Y = 0;
458                 setSpeed(speed);
459         }
460
461         // Whether superspeed mode is used or not
462         bool superspeed = false;
463         
464         // If free movement and fast movement, always move fast
465         if(free_move && fast_move)
466                 superspeed = true;
467         
468         // Auxiliary button 1 (E)
469         if(control.aux1)
470         {
471                 if(free_move)
472                 {
473                         // In free movement mode, aux1 descends
474                         v3f speed = getSpeed();
475                         if(fast_move)
476                                 speed.Y = -20*BS;
477                         else
478                                 speed.Y = -walkspeed_max;
479                         setSpeed(speed);
480                 }
481                 else
482                 {
483                         // If not free movement but fast is allowed, aux1 is
484                         // "Turbo button"
485                         if(fast_move)
486                                 superspeed = true;
487                 }
488         }
489
490         if(continuous_forward)
491                 speed += move_direction;
492
493         if(control.up)
494         {
495                 if(continuous_forward)
496                         superspeed = true;
497                 else
498                         speed += move_direction;
499         }
500         if(control.down)
501         {
502                 speed -= move_direction;
503         }
504         if(control.left)
505         {
506                 speed += move_direction.crossProduct(v3f(0,1,0));
507         }
508         if(control.right)
509         {
510                 speed += move_direction.crossProduct(v3f(0,-1,0));
511         }
512         if(control.jump)
513         {
514                 if(free_move)
515                 {
516                         v3f speed = getSpeed();
517                         if(fast_move)
518                                 speed.Y = 20*BS;
519                         else
520                                 speed.Y = walkspeed_max;
521                         setSpeed(speed);
522                 }
523                 else if(touching_ground)
524                 {
525                         v3f speed = getSpeed();
526                         speed.Y = 6.5*BS;
527                         setSpeed(speed);
528                 }
529                 else if(in_water)
530                 {
531                         v3f speed = getSpeed();
532                         speed.Y = 2.0*BS;
533                         setSpeed(speed);
534                         swimming_up = true;
535                 }
536         }
537
538         // The speed of the player (Y is ignored)
539         if(superspeed)
540                 speed = speed.normalize() * walkspeed_max * 5;
541         else
542                 speed = speed.normalize() * walkspeed_max;
543         
544         f32 inc = walk_acceleration * BS * dtime;
545         
546         // Faster acceleration if fast and free movement
547         if(free_move && fast_move)
548                 inc = walk_acceleration * BS * dtime * 10;
549         
550         // Accelerate to target speed with maximum increment
551         accelerate(speed, inc);
552 }
553 #endif
554