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),
39 updateName("<not set>");
47 void Player::resetInventory()
50 inventory.addList("main", PLAYER_INVENTORY_SIZE);
51 inventory.addList("craft", 9);
52 inventory.addList("craftresult", 1);
55 // Y direction is ignored
56 void Player::accelerate(v3f target_speed, f32 max_increase)
58 v3f d_wanted = target_speed - m_speed;
60 f32 dl_wanted = d_wanted.getLength();
65 v3f d = d_wanted.normalize() * dl;
72 if(m_speed.X < target_speed.X - max_increase)
73 m_speed.X += max_increase;
74 else if(m_speed.X > target_speed.X + max_increase)
75 m_speed.X -= max_increase;
76 else if(m_speed.X < target_speed.X)
77 m_speed.X = target_speed.X;
78 else if(m_speed.X > target_speed.X)
79 m_speed.X = target_speed.X;
81 if(m_speed.Z < target_speed.Z - max_increase)
82 m_speed.Z += max_increase;
83 else if(m_speed.Z > target_speed.Z + max_increase)
84 m_speed.Z -= max_increase;
85 else if(m_speed.Z < target_speed.Z)
86 m_speed.Z = target_speed.Z;
87 else if(m_speed.Z > target_speed.Z)
88 m_speed.Z = target_speed.Z;
92 void Player::serialize(std::ostream &os)
94 // Utilize a Settings object for storing values
96 args.setS32("version", 1);
97 args.set("name", m_name);
98 args.setFloat("pitch", m_pitch);
99 args.setFloat("yaw", m_yaw);
100 args.setV3F("position", m_position);
101 args.setBool("craftresult_is_preview", craftresult_is_preview);
102 args.setS32("hp", hp);
106 os<<"PlayerArgsEnd\n";
108 inventory.serialize(os);
111 void Player::deSerialize(std::istream &is)
118 throw SerializationError
119 ("Player::deSerialize(): PlayerArgsEnd not found");
121 std::getline(is, line);
122 std::string trimmedline = trim(line);
123 if(trimmedline == "PlayerArgsEnd")
125 args.parseConfigLine(line);
128 //args.getS32("version");
129 std::string name = args.get("name");
130 updateName(name.c_str());
131 m_pitch = args.getFloat("pitch");
132 m_yaw = args.getFloat("yaw");
133 m_position = args.getV3F("position");
135 craftresult_is_preview = args.getBool("craftresult_is_preview");
136 }catch(SettingNotFoundException &e){
137 craftresult_is_preview = true;
140 hp = args.getS32("hp");
141 }catch(SettingNotFoundException &e){
145 inventory.deSerialize(is);
154 RemotePlayer::RemotePlayer(
155 scene::ISceneNode* parent,
156 IrrlichtDevice *device,
158 scene::ISceneNode(parent, (device==NULL)?NULL:device->getSceneManager(), id),
161 m_box = core::aabbox3d<f32>(-BS/2,0,-BS/2,BS/2,BS*2,BS/2);
163 if(parent != NULL && device != NULL)
165 // ISceneNode stores a member called SceneManager
166 scene::ISceneManager* mgr = SceneManager;
167 video::IVideoDriver* driver = mgr->getVideoDriver();
168 gui::IGUIEnvironment* gui = device->getGUIEnvironment();
170 // Add a text node for showing the name
171 wchar_t wname[1] = {0};
172 m_text = mgr->addTextSceneNode(gui->getBuiltInFont(),
173 wname, video::SColor(255,255,255,255), this);
174 m_text->setPosition(v3f(0, (f32)BS*2.1, 0));
176 // Attach a simple mesh to the player for showing an image
177 scene::SMesh *mesh = new scene::SMesh();
179 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
180 video::SColor c(255,255,255,255);
181 video::S3DVertex vertices[4] =
183 video::S3DVertex(-BS/2,0,0, 0,0,0, c, 0,1),
184 video::S3DVertex(BS/2,0,0, 0,0,0, c, 1,1),
185 video::S3DVertex(BS/2,BS*2,0, 0,0,0, c, 1,0),
186 video::S3DVertex(-BS/2,BS*2,0, 0,0,0, c, 0,0),
188 u16 indices[] = {0,1,2,2,3,0};
189 buf->append(vertices, 4, indices, 6);
191 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
192 //buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
193 buf->getMaterial().setTexture(0, driver->getTexture(porting::getDataPath("player.png").c_str()));
194 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
195 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
196 //buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
197 buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
199 mesh->addMeshBuffer(buf);
203 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
204 video::SColor c(255,255,255,255);
205 video::S3DVertex vertices[4] =
207 video::S3DVertex(BS/2,0,0, 0,0,0, c, 1,1),
208 video::S3DVertex(-BS/2,0,0, 0,0,0, c, 0,1),
209 video::S3DVertex(-BS/2,BS*2,0, 0,0,0, c, 0,0),
210 video::S3DVertex(BS/2,BS*2,0, 0,0,0, c, 1,0),
212 u16 indices[] = {0,1,2,2,3,0};
213 buf->append(vertices, 4, indices, 6);
215 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
216 //buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
217 buf->getMaterial().setTexture(0, driver->getTexture(porting::getDataPath("player_back.png").c_str()));
218 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
219 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
220 buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
222 mesh->addMeshBuffer(buf);
225 m_node = mgr->addMeshSceneNode(mesh, this);
227 m_node->setPosition(v3f(0,0,0));
231 RemotePlayer::~RemotePlayer()
233 if(SceneManager != NULL)
234 ISceneNode::remove();
237 void RemotePlayer::updateName(const char *name)
239 Player::updateName(name);
242 wchar_t wname[PLAYERNAME_SIZE];
243 mbstowcs(wname, m_name, strlen(m_name)+1);
244 m_text->setText(wname);
248 void RemotePlayer::move(f32 dtime, Map &map, f32 pos_max_d)
250 m_pos_animation_time_counter += dtime;
251 m_pos_animation_counter += dtime;
252 v3f movevector = m_position - m_oldpos;
254 if(m_pos_animation_time < 0.001)
257 moveratio = m_pos_animation_counter / m_pos_animation_time;
260 m_showpos = m_oldpos + movevector * moveratio;
262 ISceneNode::setPosition(m_showpos);
272 LocalPlayer::LocalPlayer():
273 m_sneak_node(32767,32767,32767),
274 m_sneak_node_exists(false)
276 // Initialize hp to 0, so that no hearts will be shown if server
277 // doesn't support health points
281 LocalPlayer::~LocalPlayer()
285 void LocalPlayer::move(f32 dtime, Map &map, f32 pos_max_d,
286 core::list<CollisionInfo> *collision_info)
288 v3f position = getPosition();
289 v3f oldpos = position;
290 v3s16 oldpos_i = floatToInt(oldpos, BS);
292 /*std::cout<<"oldpos_i=("<<oldpos_i.X<<","<<oldpos_i.Y<<","
293 <<oldpos_i.Z<<")"<<std::endl;*/
296 Calculate new position
298 position += m_speed * dtime;
300 // Skip collision detection if a special movement mode is used
301 bool free_move = g_settings.getBool("free_move");
304 setPosition(position);
312 // Player position in nodes
313 v3s16 pos_i = floatToInt(position, BS);
316 Check if player is in water (the oscillating value)
319 // If in water, the threshold of coming out is at higher y
322 v3s16 pp = floatToInt(position + v3f(0,BS*0.1,0), BS);
323 in_water = content_liquid(map.getNode(pp).d);
325 // If not in water, the threshold of going in is at lower y
328 v3s16 pp = floatToInt(position + v3f(0,BS*0.5,0), BS);
329 in_water = content_liquid(map.getNode(pp).d);
332 catch(InvalidPositionException &e)
338 Check if player is in water (the stable value)
341 v3s16 pp = floatToInt(position + v3f(0,0,0), BS);
342 in_water_stable = content_liquid(map.getNode(pp).d);
344 catch(InvalidPositionException &e)
346 in_water_stable = false;
350 Collision uncertainty radius
351 Make it a bit larger than the maximum distance of movement
353 //f32 d = pos_max_d * 1.1;
354 // A fairly large value in here makes moving smoother
357 // This should always apply, otherwise there are glitches
358 assert(d > pos_max_d);
360 float player_radius = BS*0.35;
361 float player_height = BS*1.7;
363 // Maximum distance over border for sneaking
364 f32 sneak_max = BS*0.4;
367 If sneaking, player has larger collision radius to keep from
371 player_radius = sneak_max + d*1.1;*/
374 If sneaking, keep in range from the last walked node and don't
377 if(control.sneak && m_sneak_node_exists)
379 f32 maxd = 0.5*BS + sneak_max;
380 v3f lwn_f = intToFloat(m_sneak_node, BS);
381 position.X = rangelim(position.X, lwn_f.X-maxd, lwn_f.X+maxd);
382 position.Z = rangelim(position.Z, lwn_f.Z-maxd, lwn_f.Z+maxd);
384 f32 min_y = lwn_f.Y + 0.5*BS;
385 if(position.Y < min_y)
394 Calculate player collision box (new and old)
396 core::aabbox3d<f32> playerbox(
397 position.X - player_radius,
399 position.Z - player_radius,
400 position.X + player_radius,
401 position.Y + player_height,
402 position.Z + player_radius
404 core::aabbox3d<f32> playerbox_old(
405 oldpos.X - player_radius,
407 oldpos.Z - player_radius,
408 oldpos.X + player_radius,
409 oldpos.Y + player_height,
410 oldpos.Z + player_radius
414 If the player's feet touch the topside of any node, this is
417 Player is allowed to jump when this is true.
419 touching_ground = false;
421 /*std::cout<<"Checking collisions for ("
422 <<oldpos_i.X<<","<<oldpos_i.Y<<","<<oldpos_i.Z
424 <<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z
428 Go through every node around the player
430 for(s16 y = oldpos_i.Y - 1; y <= oldpos_i.Y + 2; y++)
431 for(s16 z = oldpos_i.Z - 1; z <= oldpos_i.Z + 1; z++)
432 for(s16 x = oldpos_i.X - 1; x <= oldpos_i.X + 1; x++)
435 // Player collides into walkable nodes
436 if(content_walkable(map.getNode(v3s16(x,y,z)).d) == false)
439 catch(InvalidPositionException &e)
441 // Doing nothing here will block the player from
442 // walking over map borders
445 core::aabbox3d<f32> nodebox = getNodeBox(v3s16(x,y,z), BS);
448 See if the player is touching ground.
450 Player touches ground if player's minimum Y is near node's
451 maximum Y and player's X-Z-area overlaps with the node's
454 Use 0.15*BS so that it is easier to get on a node.
457 //fabs(nodebox.MaxEdge.Y-playerbox.MinEdge.Y) < d
458 fabs(nodebox.MaxEdge.Y-playerbox.MinEdge.Y) < 0.15*BS
459 && nodebox.MaxEdge.X-d > playerbox.MinEdge.X
460 && nodebox.MinEdge.X+d < playerbox.MaxEdge.X
461 && nodebox.MaxEdge.Z-d > playerbox.MinEdge.Z
462 && nodebox.MinEdge.Z+d < playerbox.MaxEdge.Z
464 touching_ground = true;
467 // If player doesn't intersect with node, ignore node.
468 if(playerbox.intersectsWithBox(nodebox) == false)
472 Go through every axis
475 v3f(0,0,1), // back-front
476 v3f(0,1,0), // top-bottom
477 v3f(1,0,0), // right-left
479 for(u16 i=0; i<3; i++)
482 Calculate values along the axis
484 f32 nodemax = nodebox.MaxEdge.dotProduct(dirs[i]);
485 f32 nodemin = nodebox.MinEdge.dotProduct(dirs[i]);
486 f32 playermax = playerbox.MaxEdge.dotProduct(dirs[i]);
487 f32 playermin = playerbox.MinEdge.dotProduct(dirs[i]);
488 f32 playermax_old = playerbox_old.MaxEdge.dotProduct(dirs[i]);
489 f32 playermin_old = playerbox_old.MinEdge.dotProduct(dirs[i]);
492 Check collision for the axis.
493 Collision happens when player is going through a surface.
497 // Make it easier to get on top of a node
500 bool negative_axis_collides =
501 (nodemax > playermin && nodemax <= playermin_old + neg_d
502 && m_speed.dotProduct(dirs[i]) < 0);
503 bool positive_axis_collides =
504 (nodemin < playermax && nodemin >= playermax_old - pos_d
505 && m_speed.dotProduct(dirs[i]) > 0);*/
506 bool negative_axis_collides =
507 (nodemax > playermin && nodemax <= playermin_old + d
508 && m_speed.dotProduct(dirs[i]) < 0);
509 bool positive_axis_collides =
510 (nodemin < playermax && nodemin >= playermax_old - d
511 && m_speed.dotProduct(dirs[i]) > 0);
512 bool main_axis_collides =
513 negative_axis_collides || positive_axis_collides;
516 Check overlap of player and node in other axes
518 bool other_axes_overlap = true;
519 for(u16 j=0; j<3; j++)
523 f32 nodemax = nodebox.MaxEdge.dotProduct(dirs[j]);
524 f32 nodemin = nodebox.MinEdge.dotProduct(dirs[j]);
525 f32 playermax = playerbox.MaxEdge.dotProduct(dirs[j]);
526 f32 playermin = playerbox.MinEdge.dotProduct(dirs[j]);
527 if(!(nodemax - d > playermin && nodemin + d < playermax))
529 other_axes_overlap = false;
535 If this is a collision, revert the position in the main
538 if(other_axes_overlap && main_axis_collides)
540 v3f old_speed = m_speed;
542 m_speed -= m_speed.dotProduct(dirs[i]) * dirs[i];
543 position -= position.dotProduct(dirs[i]) * dirs[i];
544 position += oldpos.dotProduct(dirs[i]) * dirs[i];
548 // Report fall collision
549 if(old_speed.Y < m_speed.Y - 0.1)
552 info.t = COLLISION_FALL;
553 info.speed = m_speed.Y - old_speed.Y;
554 collision_info->push_back(info);
563 Check the nodes under the player to see from which node the
564 player is sneaking from, if any.
567 v3s16 pos_i_bottom = floatToInt(position - v3f(0,BS/2,0), BS);
568 v2f player_p2df(position.X, position.Z);
569 f32 min_distance_f = 100000.0*BS;
570 // If already seeking from some node, compare to it.
571 /*if(m_sneak_node_exists)
573 v3f sneaknode_pf = intToFloat(m_sneak_node, BS);
574 v2f sneaknode_p2df(sneaknode_pf.X, sneaknode_pf.Z);
575 f32 d_horiz_f = player_p2df.getDistanceFrom(sneaknode_p2df);
576 f32 d_vert_f = fabs(sneaknode_pf.Y + BS*0.5 - position.Y);
577 // Ignore if player is not on the same level (likely dropped)
578 if(d_vert_f < 0.15*BS)
579 min_distance_f = d_horiz_f;
581 v3s16 new_sneak_node = m_sneak_node;
582 for(s16 x=-1; x<=1; x++)
583 for(s16 z=-1; z<=1; z++)
585 v3s16 p = pos_i_bottom + v3s16(x,0,z);
586 v3f pf = intToFloat(p, BS);
587 v2f node_p2df(pf.X, pf.Z);
588 f32 distance_f = player_p2df.getDistanceFrom(node_p2df);
589 f32 max_axis_distance_f = MYMAX(
590 fabs(player_p2df.X-node_p2df.X),
591 fabs(player_p2df.Y-node_p2df.Y));
593 if(distance_f > min_distance_f ||
594 max_axis_distance_f > 0.5*BS + sneak_max + 0.1*BS)
598 // The node to be sneaked on has to be walkable
599 if(content_walkable(map.getNode(p).d) == false)
601 // And the node above it has to be nonwalkable
602 if(content_walkable(map.getNode(p+v3s16(0,1,0)).d) == true)
605 catch(InvalidPositionException &e)
610 min_distance_f = distance_f;
614 bool sneak_node_found = (min_distance_f < 100000.0*BS*0.9);
616 if(control.sneak && m_sneak_node_exists)
619 m_sneak_node = new_sneak_node;
623 m_sneak_node = new_sneak_node;
624 m_sneak_node_exists = sneak_node_found;
628 If sneaking, the player's collision box can be in air, so
629 this has to be set explicitly
631 if(sneak_node_found && control.sneak)
632 touching_ground = true;
638 setPosition(position);
641 void LocalPlayer::move(f32 dtime, Map &map, f32 pos_max_d)
643 move(dtime, map, pos_max_d, NULL);
646 void LocalPlayer::applyControl(float dtime)
652 f32 walk_acceleration = 4.0 * BS;
653 f32 walkspeed_max = 4.0 * BS;
655 setPitch(control.pitch);
658 v3f move_direction = v3f(0,0,1);
659 move_direction.rotateXZBy(getYaw());
661 v3f speed = v3f(0,0,0);
663 bool free_move = g_settings.getBool("free_move");
664 bool fast_move = g_settings.getBool("fast_move");
665 bool continuous_forward = g_settings.getBool("continuous_forward");
669 v3f speed = getSpeed();
674 // Whether superspeed mode is used or not
675 bool superspeed = false;
677 // If free movement and fast movement, always move fast
678 if(free_move && fast_move)
681 // Auxiliary button 1 (E)
686 // In free movement mode, aux1 descends
687 v3f speed = getSpeed();
691 speed.Y = -walkspeed_max;
696 // If not free movement but fast is allowed, aux1 is
703 if(continuous_forward)
704 speed += move_direction;
708 if(continuous_forward)
711 speed += move_direction;
715 speed -= move_direction;
719 speed += move_direction.crossProduct(v3f(0,1,0));
723 speed += move_direction.crossProduct(v3f(0,-1,0));
729 v3f speed = getSpeed();
733 speed.Y = walkspeed_max;
736 else if(touching_ground)
738 v3f speed = getSpeed();
740 NOTE: The d value in move() affects jump height by
741 raising the height at which the jump speed is kept
742 at its starting value
747 // Use the oscillating value for getting out of water
748 // (so that the player doesn't fly on the surface)
751 v3f speed = getSpeed();
758 // The speed of the player (Y is ignored)
760 speed = speed.normalize() * walkspeed_max * 5.0;
761 else if(control.sneak)
762 speed = speed.normalize() * walkspeed_max / 3.0;
764 speed = speed.normalize() * walkspeed_max;
766 f32 inc = walk_acceleration * BS * dtime;
768 // Faster acceleration if fast and free movement
769 if(free_move && fast_move)
770 inc = walk_acceleration * BS * dtime * 10;
772 // Accelerate to target speed with maximum increment
773 accelerate(speed, inc);