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"
27 touching_ground(false),
29 in_water_stable(false),
31 craftresult_is_preview(true),
33 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.setFloat("pitch", m_pitch);
100 args.setFloat("yaw", m_yaw);
101 args.setV3F("position", m_position);
102 args.setBool("craftresult_is_preview", craftresult_is_preview);
103 args.setS32("hp", hp);
104 args.setU64("privs", privs);
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 m_pitch = args.getFloat("pitch");
134 m_yaw = args.getFloat("yaw");
135 m_position = args.getV3F("position");
137 craftresult_is_preview = args.getBool("craftresult_is_preview");
138 }catch(SettingNotFoundException &e){
139 craftresult_is_preview = true;
142 hp = args.getS32("hp");
143 }catch(SettingNotFoundException &e){
147 std::string sprivs = args.get("privs");
154 std::istringstream ss(sprivs);
157 }catch(SettingNotFoundException &e){
158 privs = PRIV_DEFAULT;
161 inventory.deSerialize(is);
170 RemotePlayer::RemotePlayer(
171 scene::ISceneNode* parent,
172 IrrlichtDevice *device,
174 scene::ISceneNode(parent, (device==NULL)?NULL:device->getSceneManager(), id),
177 m_box = core::aabbox3d<f32>(-BS/2,0,-BS/2,BS/2,BS*2,BS/2);
179 if(parent != NULL && device != NULL)
181 // ISceneNode stores a member called SceneManager
182 scene::ISceneManager* mgr = SceneManager;
183 video::IVideoDriver* driver = mgr->getVideoDriver();
184 gui::IGUIEnvironment* gui = device->getGUIEnvironment();
186 // Add a text node for showing the name
187 wchar_t wname[1] = {0};
188 m_text = mgr->addTextSceneNode(gui->getBuiltInFont(),
189 wname, video::SColor(255,255,255,255), this);
190 m_text->setPosition(v3f(0, (f32)BS*2.1, 0));
192 // Attach a simple mesh to the player for showing an image
193 scene::SMesh *mesh = new scene::SMesh();
195 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
196 video::SColor c(255,255,255,255);
197 video::S3DVertex vertices[4] =
199 video::S3DVertex(-BS/2,0,0, 0,0,0, c, 0,1),
200 video::S3DVertex(BS/2,0,0, 0,0,0, c, 1,1),
201 video::S3DVertex(BS/2,BS*2,0, 0,0,0, c, 1,0),
202 video::S3DVertex(-BS/2,BS*2,0, 0,0,0, c, 0,0),
204 u16 indices[] = {0,1,2,2,3,0};
205 buf->append(vertices, 4, indices, 6);
207 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
208 //buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
209 buf->getMaterial().setTexture(0, driver->getTexture(porting::getDataPath("player.png").c_str()));
210 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
211 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
212 //buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
213 buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
215 mesh->addMeshBuffer(buf);
219 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
220 video::SColor c(255,255,255,255);
221 video::S3DVertex vertices[4] =
223 video::S3DVertex(BS/2,0,0, 0,0,0, c, 1,1),
224 video::S3DVertex(-BS/2,0,0, 0,0,0, c, 0,1),
225 video::S3DVertex(-BS/2,BS*2,0, 0,0,0, c, 0,0),
226 video::S3DVertex(BS/2,BS*2,0, 0,0,0, c, 1,0),
228 u16 indices[] = {0,1,2,2,3,0};
229 buf->append(vertices, 4, indices, 6);
231 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
232 //buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
233 buf->getMaterial().setTexture(0, driver->getTexture(porting::getDataPath("player_back.png").c_str()));
234 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
235 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
236 buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
238 mesh->addMeshBuffer(buf);
241 m_node = mgr->addMeshSceneNode(mesh, this);
243 m_node->setPosition(v3f(0,0,0));
247 RemotePlayer::~RemotePlayer()
249 if(SceneManager != NULL)
250 ISceneNode::remove();
253 void RemotePlayer::updateName(const char *name)
255 Player::updateName(name);
258 wchar_t wname[PLAYERNAME_SIZE];
259 mbstowcs(wname, m_name, strlen(m_name)+1);
260 m_text->setText(wname);
264 void RemotePlayer::move(f32 dtime, Map &map, f32 pos_max_d)
266 m_pos_animation_time_counter += dtime;
267 m_pos_animation_counter += dtime;
268 v3f movevector = m_position - m_oldpos;
270 if(m_pos_animation_time < 0.001)
273 moveratio = m_pos_animation_counter / m_pos_animation_time;
276 m_showpos = m_oldpos + movevector * moveratio;
278 ISceneNode::setPosition(m_showpos);
288 LocalPlayer::LocalPlayer():
289 m_sneak_node(32767,32767,32767),
290 m_sneak_node_exists(false)
292 // Initialize hp to 0, so that no hearts will be shown if server
293 // doesn't support health points
297 LocalPlayer::~LocalPlayer()
301 void LocalPlayer::move(f32 dtime, Map &map, f32 pos_max_d,
302 core::list<CollisionInfo> *collision_info)
304 v3f position = getPosition();
305 v3f oldpos = position;
306 v3s16 oldpos_i = floatToInt(oldpos, BS);
308 /*std::cout<<"oldpos_i=("<<oldpos_i.X<<","<<oldpos_i.Y<<","
309 <<oldpos_i.Z<<")"<<std::endl;*/
312 Calculate new position
314 position += m_speed * dtime;
316 // Skip collision detection if a special movement mode is used
317 bool free_move = g_settings.getBool("free_move");
320 setPosition(position);
328 // Player position in nodes
329 v3s16 pos_i = floatToInt(position, BS);
332 Check if player is in water (the oscillating value)
335 // If in water, the threshold of coming out is at higher y
338 v3s16 pp = floatToInt(position + v3f(0,BS*0.1,0), BS);
339 in_water = content_liquid(map.getNode(pp).d);
341 // If not in water, the threshold of going in is at lower y
344 v3s16 pp = floatToInt(position + v3f(0,BS*0.5,0), BS);
345 in_water = content_liquid(map.getNode(pp).d);
348 catch(InvalidPositionException &e)
354 Check if player is in water (the stable value)
357 v3s16 pp = floatToInt(position + v3f(0,0,0), BS);
358 in_water_stable = content_liquid(map.getNode(pp).d);
360 catch(InvalidPositionException &e)
362 in_water_stable = false;
366 Collision uncertainty radius
367 Make it a bit larger than the maximum distance of movement
369 //f32 d = pos_max_d * 1.1;
370 // A fairly large value in here makes moving smoother
373 // This should always apply, otherwise there are glitches
374 assert(d > pos_max_d);
376 float player_radius = BS*0.35;
377 float player_height = BS*1.7;
379 // Maximum distance over border for sneaking
380 f32 sneak_max = BS*0.4;
383 If sneaking, player has larger collision radius to keep from
387 player_radius = sneak_max + d*1.1;*/
390 If sneaking, keep in range from the last walked node and don't
393 if(control.sneak && m_sneak_node_exists)
395 f32 maxd = 0.5*BS + sneak_max;
396 v3f lwn_f = intToFloat(m_sneak_node, BS);
397 position.X = rangelim(position.X, lwn_f.X-maxd, lwn_f.X+maxd);
398 position.Z = rangelim(position.Z, lwn_f.Z-maxd, lwn_f.Z+maxd);
400 f32 min_y = lwn_f.Y + 0.5*BS;
401 if(position.Y < min_y)
410 Calculate player collision box (new and old)
412 core::aabbox3d<f32> playerbox(
413 position.X - player_radius,
415 position.Z - player_radius,
416 position.X + player_radius,
417 position.Y + player_height,
418 position.Z + player_radius
420 core::aabbox3d<f32> playerbox_old(
421 oldpos.X - player_radius,
423 oldpos.Z - player_radius,
424 oldpos.X + player_radius,
425 oldpos.Y + player_height,
426 oldpos.Z + player_radius
430 If the player's feet touch the topside of any node, this is
433 Player is allowed to jump when this is true.
435 touching_ground = false;
437 /*std::cout<<"Checking collisions for ("
438 <<oldpos_i.X<<","<<oldpos_i.Y<<","<<oldpos_i.Z
440 <<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z
444 Go through every node around the player
446 for(s16 y = oldpos_i.Y - 1; y <= oldpos_i.Y + 2; y++)
447 for(s16 z = oldpos_i.Z - 1; z <= oldpos_i.Z + 1; z++)
448 for(s16 x = oldpos_i.X - 1; x <= oldpos_i.X + 1; x++)
451 // Player collides into walkable nodes
452 if(content_walkable(map.getNode(v3s16(x,y,z)).d) == false)
455 catch(InvalidPositionException &e)
457 // Doing nothing here will block the player from
458 // walking over map borders
461 core::aabbox3d<f32> nodebox = getNodeBox(v3s16(x,y,z), BS);
464 See if the player is touching ground.
466 Player touches ground if player's minimum Y is near node's
467 maximum Y and player's X-Z-area overlaps with the node's
470 Use 0.15*BS so that it is easier to get on a node.
473 //fabs(nodebox.MaxEdge.Y-playerbox.MinEdge.Y) < d
474 fabs(nodebox.MaxEdge.Y-playerbox.MinEdge.Y) < 0.15*BS
475 && nodebox.MaxEdge.X-d > playerbox.MinEdge.X
476 && nodebox.MinEdge.X+d < playerbox.MaxEdge.X
477 && nodebox.MaxEdge.Z-d > playerbox.MinEdge.Z
478 && nodebox.MinEdge.Z+d < playerbox.MaxEdge.Z
480 touching_ground = true;
483 // If player doesn't intersect with node, ignore node.
484 if(playerbox.intersectsWithBox(nodebox) == false)
488 Go through every axis
491 v3f(0,0,1), // back-front
492 v3f(0,1,0), // top-bottom
493 v3f(1,0,0), // right-left
495 for(u16 i=0; i<3; i++)
498 Calculate values along the axis
500 f32 nodemax = nodebox.MaxEdge.dotProduct(dirs[i]);
501 f32 nodemin = nodebox.MinEdge.dotProduct(dirs[i]);
502 f32 playermax = playerbox.MaxEdge.dotProduct(dirs[i]);
503 f32 playermin = playerbox.MinEdge.dotProduct(dirs[i]);
504 f32 playermax_old = playerbox_old.MaxEdge.dotProduct(dirs[i]);
505 f32 playermin_old = playerbox_old.MinEdge.dotProduct(dirs[i]);
508 Check collision for the axis.
509 Collision happens when player is going through a surface.
513 // Make it easier to get on top of a node
516 bool negative_axis_collides =
517 (nodemax > playermin && nodemax <= playermin_old + neg_d
518 && m_speed.dotProduct(dirs[i]) < 0);
519 bool positive_axis_collides =
520 (nodemin < playermax && nodemin >= playermax_old - pos_d
521 && m_speed.dotProduct(dirs[i]) > 0);*/
522 bool negative_axis_collides =
523 (nodemax > playermin && nodemax <= playermin_old + d
524 && m_speed.dotProduct(dirs[i]) < 0);
525 bool positive_axis_collides =
526 (nodemin < playermax && nodemin >= playermax_old - d
527 && m_speed.dotProduct(dirs[i]) > 0);
528 bool main_axis_collides =
529 negative_axis_collides || positive_axis_collides;
532 Check overlap of player and node in other axes
534 bool other_axes_overlap = true;
535 for(u16 j=0; j<3; j++)
539 f32 nodemax = nodebox.MaxEdge.dotProduct(dirs[j]);
540 f32 nodemin = nodebox.MinEdge.dotProduct(dirs[j]);
541 f32 playermax = playerbox.MaxEdge.dotProduct(dirs[j]);
542 f32 playermin = playerbox.MinEdge.dotProduct(dirs[j]);
543 if(!(nodemax - d > playermin && nodemin + d < playermax))
545 other_axes_overlap = false;
551 If this is a collision, revert the position in the main
554 if(other_axes_overlap && main_axis_collides)
556 v3f old_speed = m_speed;
558 m_speed -= m_speed.dotProduct(dirs[i]) * dirs[i];
559 position -= position.dotProduct(dirs[i]) * dirs[i];
560 position += oldpos.dotProduct(dirs[i]) * dirs[i];
564 // Report fall collision
565 if(old_speed.Y < m_speed.Y - 0.1)
568 info.t = COLLISION_FALL;
569 info.speed = m_speed.Y - old_speed.Y;
570 collision_info->push_back(info);
579 Check the nodes under the player to see from which node the
580 player is sneaking from, if any.
583 v3s16 pos_i_bottom = floatToInt(position - v3f(0,BS/2,0), BS);
584 v2f player_p2df(position.X, position.Z);
585 f32 min_distance_f = 100000.0*BS;
586 // If already seeking from some node, compare to it.
587 /*if(m_sneak_node_exists)
589 v3f sneaknode_pf = intToFloat(m_sneak_node, BS);
590 v2f sneaknode_p2df(sneaknode_pf.X, sneaknode_pf.Z);
591 f32 d_horiz_f = player_p2df.getDistanceFrom(sneaknode_p2df);
592 f32 d_vert_f = fabs(sneaknode_pf.Y + BS*0.5 - position.Y);
593 // Ignore if player is not on the same level (likely dropped)
594 if(d_vert_f < 0.15*BS)
595 min_distance_f = d_horiz_f;
597 v3s16 new_sneak_node = m_sneak_node;
598 for(s16 x=-1; x<=1; x++)
599 for(s16 z=-1; z<=1; z++)
601 v3s16 p = pos_i_bottom + v3s16(x,0,z);
602 v3f pf = intToFloat(p, BS);
603 v2f node_p2df(pf.X, pf.Z);
604 f32 distance_f = player_p2df.getDistanceFrom(node_p2df);
605 f32 max_axis_distance_f = MYMAX(
606 fabs(player_p2df.X-node_p2df.X),
607 fabs(player_p2df.Y-node_p2df.Y));
609 if(distance_f > min_distance_f ||
610 max_axis_distance_f > 0.5*BS + sneak_max + 0.1*BS)
614 // The node to be sneaked on has to be walkable
615 if(content_walkable(map.getNode(p).d) == false)
617 // And the node above it has to be nonwalkable
618 if(content_walkable(map.getNode(p+v3s16(0,1,0)).d) == true)
621 catch(InvalidPositionException &e)
626 min_distance_f = distance_f;
630 bool sneak_node_found = (min_distance_f < 100000.0*BS*0.9);
632 if(control.sneak && m_sneak_node_exists)
635 m_sneak_node = new_sneak_node;
639 m_sneak_node = new_sneak_node;
640 m_sneak_node_exists = sneak_node_found;
644 If sneaking, the player's collision box can be in air, so
645 this has to be set explicitly
647 if(sneak_node_found && control.sneak)
648 touching_ground = true;
654 setPosition(position);
657 void LocalPlayer::move(f32 dtime, Map &map, f32 pos_max_d)
659 move(dtime, map, pos_max_d, NULL);
662 void LocalPlayer::applyControl(float dtime)
668 f32 walk_acceleration = 4.0 * BS;
669 f32 walkspeed_max = 4.0 * BS;
671 setPitch(control.pitch);
674 v3f move_direction = v3f(0,0,1);
675 move_direction.rotateXZBy(getYaw());
677 v3f speed = v3f(0,0,0);
679 bool free_move = g_settings.getBool("free_move");
680 bool fast_move = g_settings.getBool("fast_move");
681 bool continuous_forward = g_settings.getBool("continuous_forward");
685 v3f speed = getSpeed();
690 // Whether superspeed mode is used or not
691 bool superspeed = false;
693 // If free movement and fast movement, always move fast
694 if(free_move && fast_move)
697 // Auxiliary button 1 (E)
702 // In free movement mode, aux1 descends
703 v3f speed = getSpeed();
707 speed.Y = -walkspeed_max;
712 // If not free movement but fast is allowed, aux1 is
719 if(continuous_forward)
720 speed += move_direction;
724 if(continuous_forward)
727 speed += move_direction;
731 speed -= move_direction;
735 speed += move_direction.crossProduct(v3f(0,1,0));
739 speed += move_direction.crossProduct(v3f(0,-1,0));
745 v3f speed = getSpeed();
749 speed.Y = walkspeed_max;
752 else if(touching_ground)
754 v3f speed = getSpeed();
756 NOTE: The d value in move() affects jump height by
757 raising the height at which the jump speed is kept
758 at its starting value
763 // Use the oscillating value for getting out of water
764 // (so that the player doesn't fly on the surface)
767 v3f speed = getSpeed();
774 // The speed of the player (Y is ignored)
776 speed = speed.normalize() * walkspeed_max * 5.0;
777 else if(control.sneak)
778 speed = speed.normalize() * walkspeed_max / 3.0;
780 speed = speed.normalize() * walkspeed_max;
782 f32 inc = walk_acceleration * BS * dtime;
784 // Faster acceleration if fast and free movement
785 if(free_move && fast_move)
786 inc = walk_acceleration * BS * dtime * 10;
788 // Accelerate to target speed with maximum increment
789 accelerate(speed, inc);