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"
26 // Convert a privileges value into a human-readable string,
27 // with each component separated by a comma.
28 std::wstring privsToString(u64 privs)
30 std::wostringstream os(std::ios_base::binary);
31 if(privs & PRIV_BUILD)
33 if(privs & PRIV_TELEPORT)
35 if(privs & PRIV_SETTIME)
37 if(privs & PRIV_PRIVS)
41 // Drop the trailing comma. (Why on earth can't
42 // you truncate a C++ stream anyway???)
43 std::wstring tmp = os.str();
44 return tmp.substr(0, tmp.length() -1);
49 // Converts a comma-seperated list of privilege values into a
50 // privileges value. The reverse of privsToString(). Returns
51 // PRIV_INVALID if there is anything wrong with the input.
52 u64 stringToPrivs(std::wstring str)
55 std::vector<std::wstring> pr;
56 pr=str_split(str, ',');
57 for(std::vector<std::wstring>::iterator i = pr.begin();
62 else if(*i == L"teleport")
63 privs |= PRIV_TELEPORT;
64 else if(*i == L"settime")
65 privs |= PRIV_SETTIME;
66 else if(*i == L"privs")
76 touching_ground(false),
78 in_water_stable(false),
80 craftresult_is_preview(true),
83 peer_id(PEER_ID_INEXISTENT),
89 updateName("<not set>");
98 void Player::resetInventory()
101 inventory.addList("main", PLAYER_INVENTORY_SIZE);
102 inventory.addList("craft", 9);
103 inventory.addList("craftresult", 1);
106 // Y direction is ignored
107 void Player::accelerate(v3f target_speed, f32 max_increase)
109 v3f d_wanted = target_speed - m_speed;
111 f32 dl_wanted = d_wanted.getLength();
113 if(dl > max_increase)
116 v3f d = d_wanted.normalize() * dl;
123 if(m_speed.X < target_speed.X - max_increase)
124 m_speed.X += max_increase;
125 else if(m_speed.X > target_speed.X + max_increase)
126 m_speed.X -= max_increase;
127 else if(m_speed.X < target_speed.X)
128 m_speed.X = target_speed.X;
129 else if(m_speed.X > target_speed.X)
130 m_speed.X = target_speed.X;
132 if(m_speed.Z < target_speed.Z - max_increase)
133 m_speed.Z += max_increase;
134 else if(m_speed.Z > target_speed.Z + max_increase)
135 m_speed.Z -= max_increase;
136 else if(m_speed.Z < target_speed.Z)
137 m_speed.Z = target_speed.Z;
138 else if(m_speed.Z > target_speed.Z)
139 m_speed.Z = target_speed.Z;
143 void Player::serialize(std::ostream &os)
145 // Utilize a Settings object for storing values
147 args.setS32("version", 1);
148 args.set("name", m_name);
149 args.set("password", m_password);
150 args.setFloat("pitch", m_pitch);
151 args.setFloat("yaw", m_yaw);
152 args.setV3F("position", m_position);
153 args.setBool("craftresult_is_preview", craftresult_is_preview);
154 args.setS32("hp", hp);
155 args.setU64("privs", privs);
159 os<<"PlayerArgsEnd\n";
161 inventory.serialize(os);
164 void Player::deSerialize(std::istream &is)
171 throw SerializationError
172 ("Player::deSerialize(): PlayerArgsEnd not found");
174 std::getline(is, line);
175 std::string trimmedline = trim(line);
176 if(trimmedline == "PlayerArgsEnd")
178 args.parseConfigLine(line);
181 //args.getS32("version");
182 std::string name = args.get("name");
183 updateName(name.c_str());
184 std::string password = "";
185 if(args.exists("password"))
186 password = args.get("password");
187 updatePassword(password.c_str());
188 m_pitch = args.getFloat("pitch");
189 m_yaw = args.getFloat("yaw");
190 m_position = args.getV3F("position");
192 craftresult_is_preview = args.getBool("craftresult_is_preview");
193 }catch(SettingNotFoundException &e){
194 craftresult_is_preview = true;
197 hp = args.getS32("hp");
198 }catch(SettingNotFoundException &e){
202 std::string sprivs = args.get("privs");
209 std::istringstream ss(sprivs);
212 }catch(SettingNotFoundException &e){
213 privs = PRIV_DEFAULT;
216 inventory.deSerialize(is);
225 RemotePlayer::RemotePlayer(
226 scene::ISceneNode* parent,
227 IrrlichtDevice *device,
229 scene::ISceneNode(parent, (device==NULL)?NULL:device->getSceneManager(), id),
232 m_box = core::aabbox3d<f32>(-BS/2,0,-BS/2,BS/2,BS*2,BS/2);
234 if(parent != NULL && device != NULL)
236 // ISceneNode stores a member called SceneManager
237 scene::ISceneManager* mgr = SceneManager;
238 video::IVideoDriver* driver = mgr->getVideoDriver();
239 gui::IGUIEnvironment* gui = device->getGUIEnvironment();
241 // Add a text node for showing the name
242 wchar_t wname[1] = {0};
243 m_text = mgr->addTextSceneNode(gui->getBuiltInFont(),
244 wname, video::SColor(255,255,255,255), this);
245 m_text->setPosition(v3f(0, (f32)BS*2.1, 0));
247 // Attach a simple mesh to the player for showing an image
248 scene::SMesh *mesh = new scene::SMesh();
250 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
251 video::SColor c(255,255,255,255);
252 video::S3DVertex vertices[4] =
254 video::S3DVertex(-BS/2,0,0, 0,0,0, c, 0,1),
255 video::S3DVertex(BS/2,0,0, 0,0,0, c, 1,1),
256 video::S3DVertex(BS/2,BS*2,0, 0,0,0, c, 1,0),
257 video::S3DVertex(-BS/2,BS*2,0, 0,0,0, c, 0,0),
259 u16 indices[] = {0,1,2,2,3,0};
260 buf->append(vertices, 4, indices, 6);
262 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
263 //buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
264 buf->getMaterial().setTexture(0, driver->getTexture(porting::getDataPath("player.png").c_str()));
265 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
266 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
267 //buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
268 buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
270 mesh->addMeshBuffer(buf);
274 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
275 video::SColor c(255,255,255,255);
276 video::S3DVertex vertices[4] =
278 video::S3DVertex(BS/2,0,0, 0,0,0, c, 1,1),
279 video::S3DVertex(-BS/2,0,0, 0,0,0, c, 0,1),
280 video::S3DVertex(-BS/2,BS*2,0, 0,0,0, c, 0,0),
281 video::S3DVertex(BS/2,BS*2,0, 0,0,0, c, 1,0),
283 u16 indices[] = {0,1,2,2,3,0};
284 buf->append(vertices, 4, indices, 6);
286 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
287 //buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
288 buf->getMaterial().setTexture(0, driver->getTexture(porting::getDataPath("player_back.png").c_str()));
289 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
290 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
291 buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
293 mesh->addMeshBuffer(buf);
296 m_node = mgr->addMeshSceneNode(mesh, this);
298 m_node->setPosition(v3f(0,0,0));
302 RemotePlayer::~RemotePlayer()
304 if(SceneManager != NULL)
305 ISceneNode::remove();
308 void RemotePlayer::updateName(const char *name)
310 Player::updateName(name);
313 wchar_t wname[PLAYERNAME_SIZE];
314 mbstowcs(wname, m_name, strlen(m_name)+1);
315 m_text->setText(wname);
319 void RemotePlayer::move(f32 dtime, Map &map, f32 pos_max_d)
321 m_pos_animation_time_counter += dtime;
322 m_pos_animation_counter += dtime;
323 v3f movevector = m_position - m_oldpos;
325 if(m_pos_animation_time < 0.001)
328 moveratio = m_pos_animation_counter / m_pos_animation_time;
331 m_showpos = m_oldpos + movevector * moveratio;
333 ISceneNode::setPosition(m_showpos);
343 LocalPlayer::LocalPlayer():
344 m_sneak_node(32767,32767,32767),
345 m_sneak_node_exists(false)
347 // Initialize hp to 0, so that no hearts will be shown if server
348 // doesn't support health points
352 LocalPlayer::~LocalPlayer()
356 void LocalPlayer::move(f32 dtime, Map &map, f32 pos_max_d,
357 core::list<CollisionInfo> *collision_info)
359 v3f position = getPosition();
360 v3f oldpos = position;
361 v3s16 oldpos_i = floatToInt(oldpos, BS);
363 /*std::cout<<"oldpos_i=("<<oldpos_i.X<<","<<oldpos_i.Y<<","
364 <<oldpos_i.Z<<")"<<std::endl;*/
367 Calculate new position
369 position += m_speed * dtime;
371 // Skip collision detection if a special movement mode is used
372 bool free_move = g_settings.getBool("free_move");
375 setPosition(position);
383 // Player position in nodes
384 v3s16 pos_i = floatToInt(position, BS);
387 Check if player is in water (the oscillating value)
390 // If in water, the threshold of coming out is at higher y
393 v3s16 pp = floatToInt(position + v3f(0,BS*0.1,0), BS);
394 in_water = content_liquid(map.getNode(pp).d);
396 // If not in water, the threshold of going in is at lower y
399 v3s16 pp = floatToInt(position + v3f(0,BS*0.5,0), BS);
400 in_water = content_liquid(map.getNode(pp).d);
403 catch(InvalidPositionException &e)
409 Check if player is in water (the stable value)
412 v3s16 pp = floatToInt(position + v3f(0,0,0), BS);
413 in_water_stable = content_liquid(map.getNode(pp).d);
415 catch(InvalidPositionException &e)
417 in_water_stable = false;
421 Collision uncertainty radius
422 Make it a bit larger than the maximum distance of movement
424 //f32 d = pos_max_d * 1.1;
425 // A fairly large value in here makes moving smoother
428 // This should always apply, otherwise there are glitches
429 assert(d > pos_max_d);
431 float player_radius = BS*0.35;
432 float player_height = BS*1.7;
434 // Maximum distance over border for sneaking
435 f32 sneak_max = BS*0.4;
438 If sneaking, player has larger collision radius to keep from
442 player_radius = sneak_max + d*1.1;*/
445 If sneaking, keep in range from the last walked node and don't
448 if(control.sneak && m_sneak_node_exists)
450 f32 maxd = 0.5*BS + sneak_max;
451 v3f lwn_f = intToFloat(m_sneak_node, BS);
452 position.X = rangelim(position.X, lwn_f.X-maxd, lwn_f.X+maxd);
453 position.Z = rangelim(position.Z, lwn_f.Z-maxd, lwn_f.Z+maxd);
455 f32 min_y = lwn_f.Y + 0.5*BS;
456 if(position.Y < min_y)
465 Calculate player collision box (new and old)
467 core::aabbox3d<f32> playerbox(
468 position.X - player_radius,
470 position.Z - player_radius,
471 position.X + player_radius,
472 position.Y + player_height,
473 position.Z + player_radius
475 core::aabbox3d<f32> playerbox_old(
476 oldpos.X - player_radius,
478 oldpos.Z - player_radius,
479 oldpos.X + player_radius,
480 oldpos.Y + player_height,
481 oldpos.Z + player_radius
485 If the player's feet touch the topside of any node, this is
488 Player is allowed to jump when this is true.
490 touching_ground = false;
492 /*std::cout<<"Checking collisions for ("
493 <<oldpos_i.X<<","<<oldpos_i.Y<<","<<oldpos_i.Z
495 <<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z
499 Go through every node around the player
501 for(s16 y = oldpos_i.Y - 1; y <= oldpos_i.Y + 2; y++)
502 for(s16 z = oldpos_i.Z - 1; z <= oldpos_i.Z + 1; z++)
503 for(s16 x = oldpos_i.X - 1; x <= oldpos_i.X + 1; x++)
506 // Player collides into walkable nodes
507 if(content_walkable(map.getNode(v3s16(x,y,z)).d) == false)
510 catch(InvalidPositionException &e)
512 // Doing nothing here will block the player from
513 // walking over map borders
516 core::aabbox3d<f32> nodebox = getNodeBox(v3s16(x,y,z), BS);
519 See if the player is touching ground.
521 Player touches ground if player's minimum Y is near node's
522 maximum Y and player's X-Z-area overlaps with the node's
525 Use 0.15*BS so that it is easier to get on a node.
528 //fabs(nodebox.MaxEdge.Y-playerbox.MinEdge.Y) < d
529 fabs(nodebox.MaxEdge.Y-playerbox.MinEdge.Y) < 0.15*BS
530 && nodebox.MaxEdge.X-d > playerbox.MinEdge.X
531 && nodebox.MinEdge.X+d < playerbox.MaxEdge.X
532 && nodebox.MaxEdge.Z-d > playerbox.MinEdge.Z
533 && nodebox.MinEdge.Z+d < playerbox.MaxEdge.Z
535 touching_ground = true;
538 // If player doesn't intersect with node, ignore node.
539 if(playerbox.intersectsWithBox(nodebox) == false)
543 Go through every axis
546 v3f(0,0,1), // back-front
547 v3f(0,1,0), // top-bottom
548 v3f(1,0,0), // right-left
550 for(u16 i=0; i<3; i++)
553 Calculate values along the axis
555 f32 nodemax = nodebox.MaxEdge.dotProduct(dirs[i]);
556 f32 nodemin = nodebox.MinEdge.dotProduct(dirs[i]);
557 f32 playermax = playerbox.MaxEdge.dotProduct(dirs[i]);
558 f32 playermin = playerbox.MinEdge.dotProduct(dirs[i]);
559 f32 playermax_old = playerbox_old.MaxEdge.dotProduct(dirs[i]);
560 f32 playermin_old = playerbox_old.MinEdge.dotProduct(dirs[i]);
563 Check collision for the axis.
564 Collision happens when player is going through a surface.
568 // Make it easier to get on top of a node
571 bool negative_axis_collides =
572 (nodemax > playermin && nodemax <= playermin_old + neg_d
573 && m_speed.dotProduct(dirs[i]) < 0);
574 bool positive_axis_collides =
575 (nodemin < playermax && nodemin >= playermax_old - pos_d
576 && m_speed.dotProduct(dirs[i]) > 0);*/
577 bool negative_axis_collides =
578 (nodemax > playermin && nodemax <= playermin_old + d
579 && m_speed.dotProduct(dirs[i]) < 0);
580 bool positive_axis_collides =
581 (nodemin < playermax && nodemin >= playermax_old - d
582 && m_speed.dotProduct(dirs[i]) > 0);
583 bool main_axis_collides =
584 negative_axis_collides || positive_axis_collides;
587 Check overlap of player and node in other axes
589 bool other_axes_overlap = true;
590 for(u16 j=0; j<3; j++)
594 f32 nodemax = nodebox.MaxEdge.dotProduct(dirs[j]);
595 f32 nodemin = nodebox.MinEdge.dotProduct(dirs[j]);
596 f32 playermax = playerbox.MaxEdge.dotProduct(dirs[j]);
597 f32 playermin = playerbox.MinEdge.dotProduct(dirs[j]);
598 if(!(nodemax - d > playermin && nodemin + d < playermax))
600 other_axes_overlap = false;
606 If this is a collision, revert the position in the main
609 if(other_axes_overlap && main_axis_collides)
611 v3f old_speed = m_speed;
613 m_speed -= m_speed.dotProduct(dirs[i]) * dirs[i];
614 position -= position.dotProduct(dirs[i]) * dirs[i];
615 position += oldpos.dotProduct(dirs[i]) * dirs[i];
619 // Report fall collision
620 if(old_speed.Y < m_speed.Y - 0.1)
623 info.t = COLLISION_FALL;
624 info.speed = m_speed.Y - old_speed.Y;
625 collision_info->push_back(info);
634 Check the nodes under the player to see from which node the
635 player is sneaking from, if any.
638 v3s16 pos_i_bottom = floatToInt(position - v3f(0,BS/2,0), BS);
639 v2f player_p2df(position.X, position.Z);
640 f32 min_distance_f = 100000.0*BS;
641 // If already seeking from some node, compare to it.
642 /*if(m_sneak_node_exists)
644 v3f sneaknode_pf = intToFloat(m_sneak_node, BS);
645 v2f sneaknode_p2df(sneaknode_pf.X, sneaknode_pf.Z);
646 f32 d_horiz_f = player_p2df.getDistanceFrom(sneaknode_p2df);
647 f32 d_vert_f = fabs(sneaknode_pf.Y + BS*0.5 - position.Y);
648 // Ignore if player is not on the same level (likely dropped)
649 if(d_vert_f < 0.15*BS)
650 min_distance_f = d_horiz_f;
652 v3s16 new_sneak_node = m_sneak_node;
653 for(s16 x=-1; x<=1; x++)
654 for(s16 z=-1; z<=1; z++)
656 v3s16 p = pos_i_bottom + v3s16(x,0,z);
657 v3f pf = intToFloat(p, BS);
658 v2f node_p2df(pf.X, pf.Z);
659 f32 distance_f = player_p2df.getDistanceFrom(node_p2df);
660 f32 max_axis_distance_f = MYMAX(
661 fabs(player_p2df.X-node_p2df.X),
662 fabs(player_p2df.Y-node_p2df.Y));
664 if(distance_f > min_distance_f ||
665 max_axis_distance_f > 0.5*BS + sneak_max + 0.1*BS)
669 // The node to be sneaked on has to be walkable
670 if(content_walkable(map.getNode(p).d) == false)
672 // And the node above it has to be nonwalkable
673 if(content_walkable(map.getNode(p+v3s16(0,1,0)).d) == true)
676 catch(InvalidPositionException &e)
681 min_distance_f = distance_f;
685 bool sneak_node_found = (min_distance_f < 100000.0*BS*0.9);
687 if(control.sneak && m_sneak_node_exists)
690 m_sneak_node = new_sneak_node;
694 m_sneak_node = new_sneak_node;
695 m_sneak_node_exists = sneak_node_found;
699 If sneaking, the player's collision box can be in air, so
700 this has to be set explicitly
702 if(sneak_node_found && control.sneak)
703 touching_ground = true;
709 setPosition(position);
712 void LocalPlayer::move(f32 dtime, Map &map, f32 pos_max_d)
714 move(dtime, map, pos_max_d, NULL);
717 void LocalPlayer::applyControl(float dtime)
723 f32 walk_acceleration = 4.0 * BS;
724 f32 walkspeed_max = 4.0 * BS;
726 setPitch(control.pitch);
729 v3f move_direction = v3f(0,0,1);
730 move_direction.rotateXZBy(getYaw());
732 v3f speed = v3f(0,0,0);
734 bool free_move = g_settings.getBool("free_move");
735 bool fast_move = g_settings.getBool("fast_move");
736 bool continuous_forward = g_settings.getBool("continuous_forward");
740 v3f speed = getSpeed();
745 // Whether superspeed mode is used or not
746 bool superspeed = false;
748 // If free movement and fast movement, always move fast
749 if(free_move && fast_move)
752 // Auxiliary button 1 (E)
757 // In free movement mode, aux1 descends
758 v3f speed = getSpeed();
762 speed.Y = -walkspeed_max;
767 // If not free movement but fast is allowed, aux1 is
774 if(continuous_forward)
775 speed += move_direction;
779 if(continuous_forward)
782 speed += move_direction;
786 speed -= move_direction;
790 speed += move_direction.crossProduct(v3f(0,1,0));
794 speed += move_direction.crossProduct(v3f(0,-1,0));
800 v3f speed = getSpeed();
804 speed.Y = walkspeed_max;
807 else if(touching_ground)
809 v3f speed = getSpeed();
811 NOTE: The d value in move() affects jump height by
812 raising the height at which the jump speed is kept
813 at its starting value
818 // Use the oscillating value for getting out of water
819 // (so that the player doesn't fly on the surface)
822 v3f speed = getSpeed();
829 // The speed of the player (Y is ignored)
831 speed = speed.normalize() * walkspeed_max * 5.0;
832 else if(control.sneak)
833 speed = speed.normalize() * walkspeed_max / 3.0;
835 speed = speed.normalize() * walkspeed_max;
837 f32 inc = walk_acceleration * BS * dtime;
839 // Faster acceleration if fast and free movement
840 if(free_move && fast_move)
841 inc = walk_acceleration * BS * dtime * 10;
843 // Accelerate to target speed with maximum increment
844 accelerate(speed, inc);