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),
82 peer_id(PEER_ID_INEXISTENT),
89 updateName("<not set>");
97 void Player::resetInventory()
100 inventory.addList("main", PLAYER_INVENTORY_SIZE);
101 inventory.addList("craft", 9);
102 inventory.addList("craftresult", 1);
105 // Y direction is ignored
106 void Player::accelerate(v3f target_speed, f32 max_increase)
108 v3f d_wanted = target_speed - m_speed;
110 f32 dl_wanted = d_wanted.getLength();
112 if(dl > max_increase)
115 v3f d = d_wanted.normalize() * dl;
122 if(m_speed.X < target_speed.X - max_increase)
123 m_speed.X += max_increase;
124 else if(m_speed.X > target_speed.X + max_increase)
125 m_speed.X -= max_increase;
126 else if(m_speed.X < target_speed.X)
127 m_speed.X = target_speed.X;
128 else if(m_speed.X > target_speed.X)
129 m_speed.X = target_speed.X;
131 if(m_speed.Z < target_speed.Z - max_increase)
132 m_speed.Z += max_increase;
133 else if(m_speed.Z > target_speed.Z + max_increase)
134 m_speed.Z -= max_increase;
135 else if(m_speed.Z < target_speed.Z)
136 m_speed.Z = target_speed.Z;
137 else if(m_speed.Z > target_speed.Z)
138 m_speed.Z = target_speed.Z;
142 void Player::serialize(std::ostream &os)
144 // Utilize a Settings object for storing values
146 args.setS32("version", 1);
147 args.set("name", m_name);
148 args.setFloat("pitch", m_pitch);
149 args.setFloat("yaw", m_yaw);
150 args.setV3F("position", m_position);
151 args.setBool("craftresult_is_preview", craftresult_is_preview);
152 args.setS32("hp", hp);
153 args.setU64("privs", privs);
157 os<<"PlayerArgsEnd\n";
159 inventory.serialize(os);
162 void Player::deSerialize(std::istream &is)
169 throw SerializationError
170 ("Player::deSerialize(): PlayerArgsEnd not found");
172 std::getline(is, line);
173 std::string trimmedline = trim(line);
174 if(trimmedline == "PlayerArgsEnd")
176 args.parseConfigLine(line);
179 //args.getS32("version");
180 std::string name = args.get("name");
181 updateName(name.c_str());
182 m_pitch = args.getFloat("pitch");
183 m_yaw = args.getFloat("yaw");
184 m_position = args.getV3F("position");
186 craftresult_is_preview = args.getBool("craftresult_is_preview");
187 }catch(SettingNotFoundException &e){
188 craftresult_is_preview = true;
191 hp = args.getS32("hp");
192 }catch(SettingNotFoundException &e){
196 std::string sprivs = args.get("privs");
203 std::istringstream ss(sprivs);
206 }catch(SettingNotFoundException &e){
207 privs = PRIV_DEFAULT;
210 inventory.deSerialize(is);
219 RemotePlayer::RemotePlayer(
220 scene::ISceneNode* parent,
221 IrrlichtDevice *device,
223 scene::ISceneNode(parent, (device==NULL)?NULL:device->getSceneManager(), id),
226 m_box = core::aabbox3d<f32>(-BS/2,0,-BS/2,BS/2,BS*2,BS/2);
228 if(parent != NULL && device != NULL)
230 // ISceneNode stores a member called SceneManager
231 scene::ISceneManager* mgr = SceneManager;
232 video::IVideoDriver* driver = mgr->getVideoDriver();
233 gui::IGUIEnvironment* gui = device->getGUIEnvironment();
235 // Add a text node for showing the name
236 wchar_t wname[1] = {0};
237 m_text = mgr->addTextSceneNode(gui->getBuiltInFont(),
238 wname, video::SColor(255,255,255,255), this);
239 m_text->setPosition(v3f(0, (f32)BS*2.1, 0));
241 // Attach a simple mesh to the player for showing an image
242 scene::SMesh *mesh = new scene::SMesh();
244 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
245 video::SColor c(255,255,255,255);
246 video::S3DVertex vertices[4] =
248 video::S3DVertex(-BS/2,0,0, 0,0,0, c, 0,1),
249 video::S3DVertex(BS/2,0,0, 0,0,0, c, 1,1),
250 video::S3DVertex(BS/2,BS*2,0, 0,0,0, c, 1,0),
251 video::S3DVertex(-BS/2,BS*2,0, 0,0,0, c, 0,0),
253 u16 indices[] = {0,1,2,2,3,0};
254 buf->append(vertices, 4, indices, 6);
256 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
257 //buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
258 buf->getMaterial().setTexture(0, driver->getTexture(porting::getDataPath("player.png").c_str()));
259 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
260 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
261 //buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
262 buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
264 mesh->addMeshBuffer(buf);
268 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
269 video::SColor c(255,255,255,255);
270 video::S3DVertex vertices[4] =
272 video::S3DVertex(BS/2,0,0, 0,0,0, c, 1,1),
273 video::S3DVertex(-BS/2,0,0, 0,0,0, c, 0,1),
274 video::S3DVertex(-BS/2,BS*2,0, 0,0,0, c, 0,0),
275 video::S3DVertex(BS/2,BS*2,0, 0,0,0, c, 1,0),
277 u16 indices[] = {0,1,2,2,3,0};
278 buf->append(vertices, 4, indices, 6);
280 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
281 //buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
282 buf->getMaterial().setTexture(0, driver->getTexture(porting::getDataPath("player_back.png").c_str()));
283 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
284 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
285 buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
287 mesh->addMeshBuffer(buf);
290 m_node = mgr->addMeshSceneNode(mesh, this);
292 m_node->setPosition(v3f(0,0,0));
296 RemotePlayer::~RemotePlayer()
298 if(SceneManager != NULL)
299 ISceneNode::remove();
302 void RemotePlayer::updateName(const char *name)
304 Player::updateName(name);
307 wchar_t wname[PLAYERNAME_SIZE];
308 mbstowcs(wname, m_name, strlen(m_name)+1);
309 m_text->setText(wname);
313 void RemotePlayer::move(f32 dtime, Map &map, f32 pos_max_d)
315 m_pos_animation_time_counter += dtime;
316 m_pos_animation_counter += dtime;
317 v3f movevector = m_position - m_oldpos;
319 if(m_pos_animation_time < 0.001)
322 moveratio = m_pos_animation_counter / m_pos_animation_time;
325 m_showpos = m_oldpos + movevector * moveratio;
327 ISceneNode::setPosition(m_showpos);
337 LocalPlayer::LocalPlayer():
338 m_sneak_node(32767,32767,32767),
339 m_sneak_node_exists(false)
341 // Initialize hp to 0, so that no hearts will be shown if server
342 // doesn't support health points
346 LocalPlayer::~LocalPlayer()
350 void LocalPlayer::move(f32 dtime, Map &map, f32 pos_max_d,
351 core::list<CollisionInfo> *collision_info)
353 v3f position = getPosition();
354 v3f oldpos = position;
355 v3s16 oldpos_i = floatToInt(oldpos, BS);
357 /*std::cout<<"oldpos_i=("<<oldpos_i.X<<","<<oldpos_i.Y<<","
358 <<oldpos_i.Z<<")"<<std::endl;*/
361 Calculate new position
363 position += m_speed * dtime;
365 // Skip collision detection if a special movement mode is used
366 bool free_move = g_settings.getBool("free_move");
369 setPosition(position);
377 // Player position in nodes
378 v3s16 pos_i = floatToInt(position, BS);
381 Check if player is in water (the oscillating value)
384 // If in water, the threshold of coming out is at higher y
387 v3s16 pp = floatToInt(position + v3f(0,BS*0.1,0), BS);
388 in_water = content_liquid(map.getNode(pp).d);
390 // If not in water, the threshold of going in is at lower y
393 v3s16 pp = floatToInt(position + v3f(0,BS*0.5,0), BS);
394 in_water = content_liquid(map.getNode(pp).d);
397 catch(InvalidPositionException &e)
403 Check if player is in water (the stable value)
406 v3s16 pp = floatToInt(position + v3f(0,0,0), BS);
407 in_water_stable = content_liquid(map.getNode(pp).d);
409 catch(InvalidPositionException &e)
411 in_water_stable = false;
415 Collision uncertainty radius
416 Make it a bit larger than the maximum distance of movement
418 //f32 d = pos_max_d * 1.1;
419 // A fairly large value in here makes moving smoother
422 // This should always apply, otherwise there are glitches
423 assert(d > pos_max_d);
425 float player_radius = BS*0.35;
426 float player_height = BS*1.7;
428 // Maximum distance over border for sneaking
429 f32 sneak_max = BS*0.4;
432 If sneaking, player has larger collision radius to keep from
436 player_radius = sneak_max + d*1.1;*/
439 If sneaking, keep in range from the last walked node and don't
442 if(control.sneak && m_sneak_node_exists)
444 f32 maxd = 0.5*BS + sneak_max;
445 v3f lwn_f = intToFloat(m_sneak_node, BS);
446 position.X = rangelim(position.X, lwn_f.X-maxd, lwn_f.X+maxd);
447 position.Z = rangelim(position.Z, lwn_f.Z-maxd, lwn_f.Z+maxd);
449 f32 min_y = lwn_f.Y + 0.5*BS;
450 if(position.Y < min_y)
459 Calculate player collision box (new and old)
461 core::aabbox3d<f32> playerbox(
462 position.X - player_radius,
464 position.Z - player_radius,
465 position.X + player_radius,
466 position.Y + player_height,
467 position.Z + player_radius
469 core::aabbox3d<f32> playerbox_old(
470 oldpos.X - player_radius,
472 oldpos.Z - player_radius,
473 oldpos.X + player_radius,
474 oldpos.Y + player_height,
475 oldpos.Z + player_radius
479 If the player's feet touch the topside of any node, this is
482 Player is allowed to jump when this is true.
484 touching_ground = false;
486 /*std::cout<<"Checking collisions for ("
487 <<oldpos_i.X<<","<<oldpos_i.Y<<","<<oldpos_i.Z
489 <<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z
493 Go through every node around the player
495 for(s16 y = oldpos_i.Y - 1; y <= oldpos_i.Y + 2; y++)
496 for(s16 z = oldpos_i.Z - 1; z <= oldpos_i.Z + 1; z++)
497 for(s16 x = oldpos_i.X - 1; x <= oldpos_i.X + 1; x++)
500 // Player collides into walkable nodes
501 if(content_walkable(map.getNode(v3s16(x,y,z)).d) == false)
504 catch(InvalidPositionException &e)
506 // Doing nothing here will block the player from
507 // walking over map borders
510 core::aabbox3d<f32> nodebox = getNodeBox(v3s16(x,y,z), BS);
513 See if the player is touching ground.
515 Player touches ground if player's minimum Y is near node's
516 maximum Y and player's X-Z-area overlaps with the node's
519 Use 0.15*BS so that it is easier to get on a node.
522 //fabs(nodebox.MaxEdge.Y-playerbox.MinEdge.Y) < d
523 fabs(nodebox.MaxEdge.Y-playerbox.MinEdge.Y) < 0.15*BS
524 && nodebox.MaxEdge.X-d > playerbox.MinEdge.X
525 && nodebox.MinEdge.X+d < playerbox.MaxEdge.X
526 && nodebox.MaxEdge.Z-d > playerbox.MinEdge.Z
527 && nodebox.MinEdge.Z+d < playerbox.MaxEdge.Z
529 touching_ground = true;
532 // If player doesn't intersect with node, ignore node.
533 if(playerbox.intersectsWithBox(nodebox) == false)
537 Go through every axis
540 v3f(0,0,1), // back-front
541 v3f(0,1,0), // top-bottom
542 v3f(1,0,0), // right-left
544 for(u16 i=0; i<3; i++)
547 Calculate values along the axis
549 f32 nodemax = nodebox.MaxEdge.dotProduct(dirs[i]);
550 f32 nodemin = nodebox.MinEdge.dotProduct(dirs[i]);
551 f32 playermax = playerbox.MaxEdge.dotProduct(dirs[i]);
552 f32 playermin = playerbox.MinEdge.dotProduct(dirs[i]);
553 f32 playermax_old = playerbox_old.MaxEdge.dotProduct(dirs[i]);
554 f32 playermin_old = playerbox_old.MinEdge.dotProduct(dirs[i]);
557 Check collision for the axis.
558 Collision happens when player is going through a surface.
562 // Make it easier to get on top of a node
565 bool negative_axis_collides =
566 (nodemax > playermin && nodemax <= playermin_old + neg_d
567 && m_speed.dotProduct(dirs[i]) < 0);
568 bool positive_axis_collides =
569 (nodemin < playermax && nodemin >= playermax_old - pos_d
570 && m_speed.dotProduct(dirs[i]) > 0);*/
571 bool negative_axis_collides =
572 (nodemax > playermin && nodemax <= playermin_old + d
573 && m_speed.dotProduct(dirs[i]) < 0);
574 bool positive_axis_collides =
575 (nodemin < playermax && nodemin >= playermax_old - d
576 && m_speed.dotProduct(dirs[i]) > 0);
577 bool main_axis_collides =
578 negative_axis_collides || positive_axis_collides;
581 Check overlap of player and node in other axes
583 bool other_axes_overlap = true;
584 for(u16 j=0; j<3; j++)
588 f32 nodemax = nodebox.MaxEdge.dotProduct(dirs[j]);
589 f32 nodemin = nodebox.MinEdge.dotProduct(dirs[j]);
590 f32 playermax = playerbox.MaxEdge.dotProduct(dirs[j]);
591 f32 playermin = playerbox.MinEdge.dotProduct(dirs[j]);
592 if(!(nodemax - d > playermin && nodemin + d < playermax))
594 other_axes_overlap = false;
600 If this is a collision, revert the position in the main
603 if(other_axes_overlap && main_axis_collides)
605 v3f old_speed = m_speed;
607 m_speed -= m_speed.dotProduct(dirs[i]) * dirs[i];
608 position -= position.dotProduct(dirs[i]) * dirs[i];
609 position += oldpos.dotProduct(dirs[i]) * dirs[i];
613 // Report fall collision
614 if(old_speed.Y < m_speed.Y - 0.1)
617 info.t = COLLISION_FALL;
618 info.speed = m_speed.Y - old_speed.Y;
619 collision_info->push_back(info);
628 Check the nodes under the player to see from which node the
629 player is sneaking from, if any.
632 v3s16 pos_i_bottom = floatToInt(position - v3f(0,BS/2,0), BS);
633 v2f player_p2df(position.X, position.Z);
634 f32 min_distance_f = 100000.0*BS;
635 // If already seeking from some node, compare to it.
636 /*if(m_sneak_node_exists)
638 v3f sneaknode_pf = intToFloat(m_sneak_node, BS);
639 v2f sneaknode_p2df(sneaknode_pf.X, sneaknode_pf.Z);
640 f32 d_horiz_f = player_p2df.getDistanceFrom(sneaknode_p2df);
641 f32 d_vert_f = fabs(sneaknode_pf.Y + BS*0.5 - position.Y);
642 // Ignore if player is not on the same level (likely dropped)
643 if(d_vert_f < 0.15*BS)
644 min_distance_f = d_horiz_f;
646 v3s16 new_sneak_node = m_sneak_node;
647 for(s16 x=-1; x<=1; x++)
648 for(s16 z=-1; z<=1; z++)
650 v3s16 p = pos_i_bottom + v3s16(x,0,z);
651 v3f pf = intToFloat(p, BS);
652 v2f node_p2df(pf.X, pf.Z);
653 f32 distance_f = player_p2df.getDistanceFrom(node_p2df);
654 f32 max_axis_distance_f = MYMAX(
655 fabs(player_p2df.X-node_p2df.X),
656 fabs(player_p2df.Y-node_p2df.Y));
658 if(distance_f > min_distance_f ||
659 max_axis_distance_f > 0.5*BS + sneak_max + 0.1*BS)
663 // The node to be sneaked on has to be walkable
664 if(content_walkable(map.getNode(p).d) == false)
666 // And the node above it has to be nonwalkable
667 if(content_walkable(map.getNode(p+v3s16(0,1,0)).d) == true)
670 catch(InvalidPositionException &e)
675 min_distance_f = distance_f;
679 bool sneak_node_found = (min_distance_f < 100000.0*BS*0.9);
681 if(control.sneak && m_sneak_node_exists)
684 m_sneak_node = new_sneak_node;
688 m_sneak_node = new_sneak_node;
689 m_sneak_node_exists = sneak_node_found;
693 If sneaking, the player's collision box can be in air, so
694 this has to be set explicitly
696 if(sneak_node_found && control.sneak)
697 touching_ground = true;
703 setPosition(position);
706 void LocalPlayer::move(f32 dtime, Map &map, f32 pos_max_d)
708 move(dtime, map, pos_max_d, NULL);
711 void LocalPlayer::applyControl(float dtime)
717 f32 walk_acceleration = 4.0 * BS;
718 f32 walkspeed_max = 4.0 * BS;
720 setPitch(control.pitch);
723 v3f move_direction = v3f(0,0,1);
724 move_direction.rotateXZBy(getYaw());
726 v3f speed = v3f(0,0,0);
728 bool free_move = g_settings.getBool("free_move");
729 bool fast_move = g_settings.getBool("fast_move");
730 bool continuous_forward = g_settings.getBool("continuous_forward");
734 v3f speed = getSpeed();
739 // Whether superspeed mode is used or not
740 bool superspeed = false;
742 // If free movement and fast movement, always move fast
743 if(free_move && fast_move)
746 // Auxiliary button 1 (E)
751 // In free movement mode, aux1 descends
752 v3f speed = getSpeed();
756 speed.Y = -walkspeed_max;
761 // If not free movement but fast is allowed, aux1 is
768 if(continuous_forward)
769 speed += move_direction;
773 if(continuous_forward)
776 speed += move_direction;
780 speed -= move_direction;
784 speed += move_direction.crossProduct(v3f(0,1,0));
788 speed += move_direction.crossProduct(v3f(0,-1,0));
794 v3f speed = getSpeed();
798 speed.Y = walkspeed_max;
801 else if(touching_ground)
803 v3f speed = getSpeed();
805 NOTE: The d value in move() affects jump height by
806 raising the height at which the jump speed is kept
807 at its starting value
812 // Use the oscillating value for getting out of water
813 // (so that the player doesn't fly on the surface)
816 v3f speed = getSpeed();
823 // The speed of the player (Y is ignored)
825 speed = speed.normalize() * walkspeed_max * 5.0;
826 else if(control.sneak)
827 speed = speed.normalize() * walkspeed_max / 3.0;
829 speed = speed.normalize() * walkspeed_max;
831 f32 inc = walk_acceleration * BS * dtime;
833 // Faster acceleration if fast and free movement
834 if(free_move && fast_move)
835 inc = walk_acceleration * BS * dtime * 10;
837 // Accelerate to target speed with maximum increment
838 accelerate(speed, inc);