3 Copyright (C) 2010-2011 celeron55, Perttu Ahola <celeron55@gmail.com>
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.
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.
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.
22 #include "connection.h"
23 #include "constants.h"
28 touching_ground(false),
30 in_water_stable(false),
32 craftresult_is_preview(true),
34 peer_id(PEER_ID_INEXISTENT),
40 updateName("<not set>");
48 void Player::resetInventory()
51 inventory.addList("main", PLAYER_INVENTORY_SIZE);
52 inventory.addList("craft", 9);
53 inventory.addList("craftresult", 1);
56 // Y direction is ignored
57 void Player::accelerate(v3f target_speed, f32 max_increase)
59 v3f d_wanted = target_speed - m_speed;
61 f32 dl_wanted = d_wanted.getLength();
66 v3f d = d_wanted.normalize() * dl;
73 if(m_speed.X < target_speed.X - max_increase)
74 m_speed.X += max_increase;
75 else if(m_speed.X > target_speed.X + max_increase)
76 m_speed.X -= max_increase;
77 else if(m_speed.X < target_speed.X)
78 m_speed.X = target_speed.X;
79 else if(m_speed.X > target_speed.X)
80 m_speed.X = target_speed.X;
82 if(m_speed.Z < target_speed.Z - max_increase)
83 m_speed.Z += max_increase;
84 else if(m_speed.Z > target_speed.Z + max_increase)
85 m_speed.Z -= max_increase;
86 else if(m_speed.Z < target_speed.Z)
87 m_speed.Z = target_speed.Z;
88 else if(m_speed.Z > target_speed.Z)
89 m_speed.Z = target_speed.Z;
93 void Player::serialize(std::ostream &os)
95 // Utilize a Settings object for storing values
97 args.setS32("version", 1);
98 args.set("name", m_name);
99 //args.set("password", m_password);
100 args.setFloat("pitch", m_pitch);
101 args.setFloat("yaw", m_yaw);
102 args.setV3F("position", m_position);
103 args.setBool("craftresult_is_preview", craftresult_is_preview);
104 args.setS32("hp", hp);
108 os<<"PlayerArgsEnd\n";
110 inventory.serialize(os);
113 void Player::deSerialize(std::istream &is)
120 throw SerializationError
121 ("Player::deSerialize(): PlayerArgsEnd not found");
123 std::getline(is, line);
124 std::string trimmedline = trim(line);
125 if(trimmedline == "PlayerArgsEnd")
127 args.parseConfigLine(line);
130 //args.getS32("version");
131 std::string name = args.get("name");
132 updateName(name.c_str());
133 /*std::string password = "";
134 if(args.exists("password"))
135 password = args.get("password");
136 updatePassword(password.c_str());*/
137 m_pitch = args.getFloat("pitch");
138 m_yaw = args.getFloat("yaw");
139 m_position = args.getV3F("position");
141 craftresult_is_preview = args.getBool("craftresult_is_preview");
142 }catch(SettingNotFoundException &e){
143 craftresult_is_preview = true;
146 hp = args.getS32("hp");
147 }catch(SettingNotFoundException &e){
151 std::string sprivs = args.get("privs");
158 std::istringstream ss(sprivs);
161 }catch(SettingNotFoundException &e){
162 privs = PRIV_DEFAULT;
165 inventory.deSerialize(is);
174 RemotePlayer::RemotePlayer(
175 scene::ISceneNode* parent,
176 IrrlichtDevice *device,
178 scene::ISceneNode(parent, (device==NULL)?NULL:device->getSceneManager(), id),
181 m_box = core::aabbox3d<f32>(-BS/2,0,-BS/2,BS/2,BS*2,BS/2);
183 if(parent != NULL && device != NULL)
185 // ISceneNode stores a member called SceneManager
186 scene::ISceneManager* mgr = SceneManager;
187 video::IVideoDriver* driver = mgr->getVideoDriver();
188 gui::IGUIEnvironment* gui = device->getGUIEnvironment();
190 // Add a text node for showing the name
191 wchar_t wname[1] = {0};
192 m_text = mgr->addTextSceneNode(gui->getBuiltInFont(),
193 wname, video::SColor(255,255,255,255), this);
194 m_text->setPosition(v3f(0, (f32)BS*2.1, 0));
196 // Attach a simple mesh to the player for showing an image
197 scene::SMesh *mesh = new scene::SMesh();
199 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
200 video::SColor c(255,255,255,255);
201 video::S3DVertex vertices[4] =
203 video::S3DVertex(-BS/2,0,0, 0,0,0, c, 0,1),
204 video::S3DVertex(BS/2,0,0, 0,0,0, c, 1,1),
205 video::S3DVertex(BS/2,BS*2,0, 0,0,0, c, 1,0),
206 video::S3DVertex(-BS/2,BS*2,0, 0,0,0, c, 0,0),
208 u16 indices[] = {0,1,2,2,3,0};
209 buf->append(vertices, 4, indices, 6);
211 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
212 //buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
213 buf->getMaterial().setTexture(0, driver->getTexture(getTexturePath("player.png").c_str()));
214 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
215 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
216 //buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
217 buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
219 mesh->addMeshBuffer(buf);
223 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
224 video::SColor c(255,255,255,255);
225 video::S3DVertex vertices[4] =
227 video::S3DVertex(BS/2,0,0, 0,0,0, c, 1,1),
228 video::S3DVertex(-BS/2,0,0, 0,0,0, c, 0,1),
229 video::S3DVertex(-BS/2,BS*2,0, 0,0,0, c, 0,0),
230 video::S3DVertex(BS/2,BS*2,0, 0,0,0, c, 1,0),
232 u16 indices[] = {0,1,2,2,3,0};
233 buf->append(vertices, 4, indices, 6);
235 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
236 //buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
237 buf->getMaterial().setTexture(0, driver->getTexture(getTexturePath("player_back.png").c_str()));
238 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
239 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
240 buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
242 mesh->addMeshBuffer(buf);
245 m_node = mgr->addMeshSceneNode(mesh, this);
247 m_node->setPosition(v3f(0,0,0));
251 RemotePlayer::~RemotePlayer()
253 if(SceneManager != NULL)
254 ISceneNode::remove();
257 void RemotePlayer::updateName(const char *name)
259 Player::updateName(name);
262 wchar_t wname[PLAYERNAME_SIZE];
263 mbstowcs(wname, m_name, strlen(m_name)+1);
264 m_text->setText(wname);
268 void RemotePlayer::move(f32 dtime, Map &map, f32 pos_max_d)
270 m_pos_animation_time_counter += dtime;
271 m_pos_animation_counter += dtime;
272 v3f movevector = m_position - m_oldpos;
274 if(m_pos_animation_time < 0.001)
277 moveratio = m_pos_animation_counter / m_pos_animation_time;
280 m_showpos = m_oldpos + movevector * moveratio;
282 ISceneNode::setPosition(m_showpos);
292 LocalPlayer::LocalPlayer():
293 m_sneak_node(32767,32767,32767),
294 m_sneak_node_exists(false)
296 // Initialize hp to 0, so that no hearts will be shown if server
297 // doesn't support health points
301 LocalPlayer::~LocalPlayer()
305 void LocalPlayer::move(f32 dtime, Map &map, f32 pos_max_d,
306 core::list<CollisionInfo> *collision_info)
308 v3f position = getPosition();
309 v3f oldpos = position;
310 v3s16 oldpos_i = floatToInt(oldpos, BS);
312 /*std::cout<<"oldpos_i=("<<oldpos_i.X<<","<<oldpos_i.Y<<","
313 <<oldpos_i.Z<<")"<<std::endl;*/
316 Calculate new position
318 position += m_speed * dtime;
320 // Skip collision detection if a special movement mode is used
321 bool free_move = g_settings.getBool("free_move");
324 setPosition(position);
332 // Player position in nodes
333 v3s16 pos_i = floatToInt(position, BS);
336 Check if player is in water (the oscillating value)
339 // If in water, the threshold of coming out is at higher y
342 v3s16 pp = floatToInt(position + v3f(0,BS*0.1,0), BS);
343 in_water = content_liquid(map.getNode(pp).d);
345 // If not in water, the threshold of going in is at lower y
348 v3s16 pp = floatToInt(position + v3f(0,BS*0.5,0), BS);
349 in_water = content_liquid(map.getNode(pp).d);
352 catch(InvalidPositionException &e)
358 Check if player is in water (the stable value)
361 v3s16 pp = floatToInt(position + v3f(0,0,0), BS);
362 in_water_stable = content_liquid(map.getNode(pp).d);
364 catch(InvalidPositionException &e)
366 in_water_stable = false;
370 Collision uncertainty radius
371 Make it a bit larger than the maximum distance of movement
373 //f32 d = pos_max_d * 1.1;
374 // A fairly large value in here makes moving smoother
377 // This should always apply, otherwise there are glitches
378 assert(d > pos_max_d);
380 float player_radius = BS*0.35;
381 float player_height = BS*1.7;
383 // Maximum distance over border for sneaking
384 f32 sneak_max = BS*0.4;
387 If sneaking, player has larger collision radius to keep from
391 player_radius = sneak_max + d*1.1;*/
394 If sneaking, keep in range from the last walked node and don't
397 if(control.sneak && m_sneak_node_exists)
399 f32 maxd = 0.5*BS + sneak_max;
400 v3f lwn_f = intToFloat(m_sneak_node, BS);
401 position.X = rangelim(position.X, lwn_f.X-maxd, lwn_f.X+maxd);
402 position.Z = rangelim(position.Z, lwn_f.Z-maxd, lwn_f.Z+maxd);
404 f32 min_y = lwn_f.Y + 0.5*BS;
405 if(position.Y < min_y)
414 Calculate player collision box (new and old)
416 core::aabbox3d<f32> playerbox(
417 position.X - player_radius,
419 position.Z - player_radius,
420 position.X + player_radius,
421 position.Y + player_height,
422 position.Z + player_radius
424 core::aabbox3d<f32> playerbox_old(
425 oldpos.X - player_radius,
427 oldpos.Z - player_radius,
428 oldpos.X + player_radius,
429 oldpos.Y + player_height,
430 oldpos.Z + player_radius
434 If the player's feet touch the topside of any node, this is
437 Player is allowed to jump when this is true.
439 touching_ground = false;
441 /*std::cout<<"Checking collisions for ("
442 <<oldpos_i.X<<","<<oldpos_i.Y<<","<<oldpos_i.Z
444 <<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z
448 Go through every node around the player
450 for(s16 y = oldpos_i.Y - 1; y <= oldpos_i.Y + 2; y++)
451 for(s16 z = oldpos_i.Z - 1; z <= oldpos_i.Z + 1; z++)
452 for(s16 x = oldpos_i.X - 1; x <= oldpos_i.X + 1; x++)
455 // Player collides into walkable nodes
456 if(content_walkable(map.getNode(v3s16(x,y,z)).d) == false)
459 catch(InvalidPositionException &e)
461 // Doing nothing here will block the player from
462 // walking over map borders
465 core::aabbox3d<f32> nodebox = getNodeBox(v3s16(x,y,z), BS);
468 See if the player is touching ground.
470 Player touches ground if player's minimum Y is near node's
471 maximum Y and player's X-Z-area overlaps with the node's
474 Use 0.15*BS so that it is easier to get on a node.
477 //fabs(nodebox.MaxEdge.Y-playerbox.MinEdge.Y) < d
478 fabs(nodebox.MaxEdge.Y-playerbox.MinEdge.Y) < 0.15*BS
479 && nodebox.MaxEdge.X-d > playerbox.MinEdge.X
480 && nodebox.MinEdge.X+d < playerbox.MaxEdge.X
481 && nodebox.MaxEdge.Z-d > playerbox.MinEdge.Z
482 && nodebox.MinEdge.Z+d < playerbox.MaxEdge.Z
484 touching_ground = true;
487 // If player doesn't intersect with node, ignore node.
488 if(playerbox.intersectsWithBox(nodebox) == false)
492 Go through every axis
495 v3f(0,0,1), // back-front
496 v3f(0,1,0), // top-bottom
497 v3f(1,0,0), // right-left
499 for(u16 i=0; i<3; i++)
502 Calculate values along the axis
504 f32 nodemax = nodebox.MaxEdge.dotProduct(dirs[i]);
505 f32 nodemin = nodebox.MinEdge.dotProduct(dirs[i]);
506 f32 playermax = playerbox.MaxEdge.dotProduct(dirs[i]);
507 f32 playermin = playerbox.MinEdge.dotProduct(dirs[i]);
508 f32 playermax_old = playerbox_old.MaxEdge.dotProduct(dirs[i]);
509 f32 playermin_old = playerbox_old.MinEdge.dotProduct(dirs[i]);
512 Check collision for the axis.
513 Collision happens when player is going through a surface.
517 // Make it easier to get on top of a node
520 bool negative_axis_collides =
521 (nodemax > playermin && nodemax <= playermin_old + neg_d
522 && m_speed.dotProduct(dirs[i]) < 0);
523 bool positive_axis_collides =
524 (nodemin < playermax && nodemin >= playermax_old - pos_d
525 && m_speed.dotProduct(dirs[i]) > 0);*/
526 bool negative_axis_collides =
527 (nodemax > playermin && nodemax <= playermin_old + d
528 && m_speed.dotProduct(dirs[i]) < 0);
529 bool positive_axis_collides =
530 (nodemin < playermax && nodemin >= playermax_old - d
531 && m_speed.dotProduct(dirs[i]) > 0);
532 bool main_axis_collides =
533 negative_axis_collides || positive_axis_collides;
536 Check overlap of player and node in other axes
538 bool other_axes_overlap = true;
539 for(u16 j=0; j<3; j++)
543 f32 nodemax = nodebox.MaxEdge.dotProduct(dirs[j]);
544 f32 nodemin = nodebox.MinEdge.dotProduct(dirs[j]);
545 f32 playermax = playerbox.MaxEdge.dotProduct(dirs[j]);
546 f32 playermin = playerbox.MinEdge.dotProduct(dirs[j]);
547 if(!(nodemax - d > playermin && nodemin + d < playermax))
549 other_axes_overlap = false;
555 If this is a collision, revert the position in the main
558 if(other_axes_overlap && main_axis_collides)
560 v3f old_speed = m_speed;
562 m_speed -= m_speed.dotProduct(dirs[i]) * dirs[i];
563 position -= position.dotProduct(dirs[i]) * dirs[i];
564 position += oldpos.dotProduct(dirs[i]) * dirs[i];
568 // Report fall collision
569 if(old_speed.Y < m_speed.Y - 0.1)
572 info.t = COLLISION_FALL;
573 info.speed = m_speed.Y - old_speed.Y;
574 collision_info->push_back(info);
583 Check the nodes under the player to see from which node the
584 player is sneaking from, if any.
587 v3s16 pos_i_bottom = floatToInt(position - v3f(0,BS/2,0), BS);
588 v2f player_p2df(position.X, position.Z);
589 f32 min_distance_f = 100000.0*BS;
590 // If already seeking from some node, compare to it.
591 /*if(m_sneak_node_exists)
593 v3f sneaknode_pf = intToFloat(m_sneak_node, BS);
594 v2f sneaknode_p2df(sneaknode_pf.X, sneaknode_pf.Z);
595 f32 d_horiz_f = player_p2df.getDistanceFrom(sneaknode_p2df);
596 f32 d_vert_f = fabs(sneaknode_pf.Y + BS*0.5 - position.Y);
597 // Ignore if player is not on the same level (likely dropped)
598 if(d_vert_f < 0.15*BS)
599 min_distance_f = d_horiz_f;
601 v3s16 new_sneak_node = m_sneak_node;
602 for(s16 x=-1; x<=1; x++)
603 for(s16 z=-1; z<=1; z++)
605 v3s16 p = pos_i_bottom + v3s16(x,0,z);
606 v3f pf = intToFloat(p, BS);
607 v2f node_p2df(pf.X, pf.Z);
608 f32 distance_f = player_p2df.getDistanceFrom(node_p2df);
609 f32 max_axis_distance_f = MYMAX(
610 fabs(player_p2df.X-node_p2df.X),
611 fabs(player_p2df.Y-node_p2df.Y));
613 if(distance_f > min_distance_f ||
614 max_axis_distance_f > 0.5*BS + sneak_max + 0.1*BS)
618 // The node to be sneaked on has to be walkable
619 if(content_walkable(map.getNode(p).d) == false)
621 // And the node above it has to be nonwalkable
622 if(content_walkable(map.getNode(p+v3s16(0,1,0)).d) == true)
625 catch(InvalidPositionException &e)
630 min_distance_f = distance_f;
634 bool sneak_node_found = (min_distance_f < 100000.0*BS*0.9);
636 if(control.sneak && m_sneak_node_exists)
639 m_sneak_node = new_sneak_node;
643 m_sneak_node = new_sneak_node;
644 m_sneak_node_exists = sneak_node_found;
648 If sneaking, the player's collision box can be in air, so
649 this has to be set explicitly
651 if(sneak_node_found && control.sneak)
652 touching_ground = true;
658 setPosition(position);
661 void LocalPlayer::move(f32 dtime, Map &map, f32 pos_max_d)
663 move(dtime, map, pos_max_d, NULL);
666 void LocalPlayer::applyControl(float dtime)
672 f32 walk_acceleration = 4.0 * BS;
673 f32 walkspeed_max = 4.0 * BS;
675 setPitch(control.pitch);
678 v3f move_direction = v3f(0,0,1);
679 move_direction.rotateXZBy(getYaw());
681 v3f speed = v3f(0,0,0);
683 bool free_move = g_settings.getBool("free_move");
684 bool fast_move = g_settings.getBool("fast_move");
685 bool continuous_forward = g_settings.getBool("continuous_forward");
689 v3f speed = getSpeed();
694 // Whether superspeed mode is used or not
695 bool superspeed = false;
697 // If free movement and fast movement, always move fast
698 if(free_move && fast_move)
701 // Auxiliary button 1 (E)
706 // In free movement mode, aux1 descends
707 v3f speed = getSpeed();
711 speed.Y = -walkspeed_max;
716 // If not free movement but fast is allowed, aux1 is
723 if(continuous_forward)
724 speed += move_direction;
728 if(continuous_forward)
731 speed += move_direction;
735 speed -= move_direction;
739 speed += move_direction.crossProduct(v3f(0,1,0));
743 speed += move_direction.crossProduct(v3f(0,-1,0));
749 v3f speed = getSpeed();
753 speed.Y = walkspeed_max;
756 else if(touching_ground)
758 v3f speed = getSpeed();
760 NOTE: The d value in move() affects jump height by
761 raising the height at which the jump speed is kept
762 at its starting value
767 // Use the oscillating value for getting out of water
768 // (so that the player doesn't fly on the surface)
771 v3f speed = getSpeed();
778 // The speed of the player (Y is ignored)
780 speed = speed.normalize() * walkspeed_max * 5.0;
781 else if(control.sneak)
782 speed = speed.normalize() * walkspeed_max / 3.0;
784 speed = speed.normalize() * walkspeed_max;
786 f32 inc = walk_acceleration * BS * dtime;
788 // Faster acceleration if fast and free movement
789 if(free_move && fast_move)
790 inc = walk_acceleration * BS * dtime * 10;
792 // Accelerate to target speed with maximum increment
793 accelerate(speed, inc);