[7279] Allow equipped items loading at relogin to arena map.
[AHbot.git] / src / game / MovementHandler.cpp
blob9dc84d62ff683e76b1d9318900d24be1abdc6615
1 /*
2 * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "WorldPacket.h"
21 #include "WorldSession.h"
22 #include "Opcodes.h"
23 #include "Log.h"
24 #include "World.h"
25 #include "Corpse.h"
26 #include "Player.h"
27 #include "MapManager.h"
28 #include "Transports.h"
29 #include "BattleGround.h"
30 #include "WaypointMovementGenerator.h"
31 #include "InstanceSaveMgr.h"
32 #include "ObjectMgr.h"
34 void WorldSession::HandleMoveWorldportAckOpcode( WorldPacket & /*recv_data*/ )
36 sLog.outDebug( "WORLD: got MSG_MOVE_WORLDPORT_ACK." );
37 HandleMoveWorldportAckOpcode();
40 void WorldSession::HandleMoveWorldportAckOpcode()
42 // get the teleport destination
43 WorldLocation &loc = GetPlayer()->GetTeleportDest();
45 // possible errors in the coordinate validity check
46 if(!MapManager::IsValidMapCoord(loc.mapid,loc.x,loc.y,loc.z,loc.o))
48 LogoutPlayer(false);
49 return;
52 // get the destination map entry, not the current one, this will fix homebind and reset greeting
53 MapEntry const* mEntry = sMapStore.LookupEntry(loc.mapid);
54 InstanceTemplate const* mInstance = objmgr.GetInstanceTemplate(loc.mapid);
56 // reset instance validity, except if going to an instance inside an instance
57 if(GetPlayer()->m_InstanceValid == false && !mInstance)
58 GetPlayer()->m_InstanceValid = true;
60 GetPlayer()->SetSemaphoreTeleport(false);
62 // relocate the player to the teleport destination
63 GetPlayer()->SetMapId(loc.mapid);
64 GetPlayer()->Relocate(loc.x, loc.y, loc.z, loc.o);
66 // since the MapId is set before the GetInstance call, the InstanceId must be set to 0
67 // to let GetInstance() determine the proper InstanceId based on the player's binds
68 GetPlayer()->SetInstanceId(0);
70 // check this before Map::Add(player), because that will create the instance save!
71 bool reset_notify = (GetPlayer()->GetBoundInstance(GetPlayer()->GetMapId(), GetPlayer()->GetDifficulty()) == NULL);
73 GetPlayer()->SendInitialPacketsBeforeAddToMap();
74 // the CanEnter checks are done in TeleporTo but conditions may change
75 // while the player is in transit, for example the map may get full
76 if(!GetPlayer()->GetMap()->Add(GetPlayer()))
78 sLog.outDebug("WORLD: teleport of player %s (%d) to location %d,%f,%f,%f,%f failed", GetPlayer()->GetName(), GetPlayer()->GetGUIDLow(), loc.mapid, loc.x, loc.y, loc.z, loc.o);
79 // teleport the player home
80 GetPlayer()->SetDontMove(false);
81 if(!GetPlayer()->TeleportTo(GetPlayer()->m_homebindMapId, GetPlayer()->m_homebindX, GetPlayer()->m_homebindY, GetPlayer()->m_homebindZ, GetPlayer()->GetOrientation()))
83 // the player must always be able to teleport home
84 sLog.outError("WORLD: failed to teleport player %s (%d) to homebind location %d,%f,%f,%f,%f!", GetPlayer()->GetName(), GetPlayer()->GetGUIDLow(), GetPlayer()->m_homebindMapId, GetPlayer()->m_homebindX, GetPlayer()->m_homebindY, GetPlayer()->m_homebindZ, GetPlayer()->GetOrientation());
85 assert(false);
87 return;
90 //this will set player's team ... so IT MUST BE CALLED BEFORE SendInitialPacketsAfterAddToMap()
91 // battleground state prepare (in case join to BG), at relogin/tele player not invited
92 // only add to bg group and object, if the player was invited (else he entered through command)
93 if(_player->InBattleGround())
95 // cleanup seting if outdated
96 if(!mEntry->IsBattleGroundOrArena())
98 _player->SetBattleGroundId(0); // We're not in BG.
99 // reset destination bg team
100 _player->SetBGTeam(0);
102 // join to bg case
103 else if(BattleGround *bg = _player->GetBattleGround())
105 if(_player->IsInvitedForBattleGroundInstance(_player->GetBattleGroundId()))
106 bg->AddPlayer(_player);
110 GetPlayer()->SendInitialPacketsAfterAddToMap();
112 // flight fast teleport case
113 if(GetPlayer()->GetMotionMaster()->GetCurrentMovementGeneratorType()==FLIGHT_MOTION_TYPE)
115 if(!_player->InBattleGround())
117 // short preparations to continue flight
118 GetPlayer()->SetDontMove(false);
119 FlightPathMovementGenerator* flight = (FlightPathMovementGenerator*)(GetPlayer()->GetMotionMaster()->top());
120 flight->Initialize(*GetPlayer());
121 return;
124 // battleground state prepare, stop flight
125 GetPlayer()->GetMotionMaster()->MovementExpired();
126 GetPlayer()->m_taxi.ClearTaxiDestinations();
129 // resurrect character at enter into instance where his corpse exist after add to map
130 Corpse *corpse = GetPlayer()->GetCorpse();
131 if (corpse && corpse->GetType() != CORPSE_BONES && corpse->GetMapId() == GetPlayer()->GetMapId())
133 if( mEntry->IsDungeon() )
135 GetPlayer()->ResurrectPlayer(0.5f);
136 GetPlayer()->SpawnCorpseBones();
137 GetPlayer()->SaveToDB();
141 if(mEntry->IsRaid() && mInstance)
143 if(reset_notify)
145 uint32 timeleft = sInstanceSaveManager.GetResetTimeFor(GetPlayer()->GetMapId()) - time(NULL);
146 GetPlayer()->SendInstanceResetWarning(GetPlayer()->GetMapId(), timeleft); // greeting at the entrance of the resort raid instance
150 // mount allow check
151 if(!mEntry->IsMountAllowed())
152 _player->RemoveSpellsCausingAura(SPELL_AURA_MOUNTED);
154 // honorless target
155 if(GetPlayer()->pvpInfo.inHostileArea)
156 GetPlayer()->CastSpell(GetPlayer(), 2479, true);
158 // resummon pet
159 if(GetPlayer()->m_temporaryUnsummonedPetNumber)
161 Pet* NewPet = new Pet;
162 if(!NewPet->LoadPetFromDB(GetPlayer(), 0, GetPlayer()->m_temporaryUnsummonedPetNumber, true))
163 delete NewPet;
165 GetPlayer()->m_temporaryUnsummonedPetNumber = 0;
168 GetPlayer()->SetDontMove(false);
171 void WorldSession::HandleMovementOpcodes( WorldPacket & recv_data )
173 uint32 opcode = recv_data.GetOpcode();
174 sLog.outDebug("WORLD: Recvd %s (%u, 0x%X) opcode", LookupOpcodeName(opcode), opcode, opcode);
176 if(GetPlayer()->GetDontMove())
177 return;
179 /* extract packet */
180 MovementInfo movementInfo;
181 ReadMovementInfo(recv_data, &movementInfo);
182 /*----------------*/
184 if(recv_data.size() != recv_data.rpos())
186 sLog.outError("MovementHandler: player %s (guid %d, account %u) sent a packet (opcode %u) that is %u bytes larger than it should be. Kicked as cheater.", _player->GetName(), _player->GetGUIDLow(), _player->GetSession()->GetAccountId(), recv_data.GetOpcode(), recv_data.size() - recv_data.rpos());
187 KickPlayer();
188 return;
191 if (!MaNGOS::IsValidMapCoord(movementInfo.x, movementInfo.y, movementInfo.z, movementInfo.o))
192 return;
194 /* handle special cases */
195 if (movementInfo.flags & MOVEMENTFLAG_ONTRANSPORT)
197 // transports size limited
198 // (also received at zeppelin leave by some reason with t_* as absolute in continent coordinates, can be safely skipped)
199 if( movementInfo.t_x > 50 || movementInfo.t_y > 50 || movementInfo.t_z > 50 )
200 return;
202 if( !MaNGOS::IsValidMapCoord(movementInfo.x+movementInfo.t_x, movementInfo.y+movementInfo.t_y,
203 movementInfo.z+movementInfo.t_z, movementInfo.o+movementInfo.t_o) )
204 return;
206 // if we boarded a transport, add us to it
207 if (!GetPlayer()->m_transport)
209 // elevators also cause the client to send MOVEMENTFLAG_ONTRANSPORT - just unmount if the guid can be found in the transport list
210 for (MapManager::TransportSet::iterator iter = MapManager::Instance().m_Transports.begin(); iter != MapManager::Instance().m_Transports.end(); ++iter)
212 if ((*iter)->GetGUID() == movementInfo.t_guid)
214 GetPlayer()->m_transport = (*iter);
215 (*iter)->AddPassenger(GetPlayer());
216 break;
221 else if (GetPlayer()->m_transport) // if we were on a transport, leave
223 GetPlayer()->m_transport->RemovePassenger(GetPlayer());
224 GetPlayer()->m_transport = NULL;
225 movementInfo.t_x = 0.0f;
226 movementInfo.t_y = 0.0f;
227 movementInfo.t_z = 0.0f;
228 movementInfo.t_o = 0.0f;
229 movementInfo.t_time = 0;
230 movementInfo.t_seat = -1;
233 // fall damage generation (ignore in flight case that can be triggered also at lags in moment teleportation to another map).
234 if (opcode == MSG_MOVE_FALL_LAND && !GetPlayer()->isInFlight())
236 // calculate total z distance of the fall
237 float z_diff = GetPlayer()->m_lastFallZ - movementInfo.z;
238 sLog.outDebug("zDiff = %f", z_diff);
239 Player *target = GetPlayer();
241 //Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored
242 // 14.57 can be calculated by resolving damageperc formular below to 0
243 if (z_diff >= 14.57f && !target->isDead() && !target->isGameMaster() &&
244 !target->HasAuraType(SPELL_AURA_HOVER) && !target->HasAuraType(SPELL_AURA_FEATHER_FALL) &&
245 !target->HasAuraType(SPELL_AURA_FLY) && !target->IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL) )
247 //Safe fall, fall height reduction
248 int32 safe_fall = target->GetTotalAuraModifier(SPELL_AURA_SAFE_FALL);
250 float damageperc = 0.018f*(z_diff-safe_fall)-0.2426f;
252 if(damageperc >0 )
254 uint32 damage = (uint32)(damageperc * target->GetMaxHealth()*sWorld.getRate(RATE_DAMAGE_FALL));
256 float height = movementInfo.z;
257 target->UpdateGroundPositionZ(movementInfo.x,movementInfo.y,height);
259 if (damage > 0)
261 //Prevent fall damage from being more than the player maximum health
262 if (damage > target->GetMaxHealth())
263 damage = target->GetMaxHealth();
265 // Gust of Wind
266 if (target->GetDummyAura(43621))
267 damage = target->GetMaxHealth()/2;
269 target->EnvironmentalDamage(target->GetGUID(), DAMAGE_FALL, damage);
271 // recheck alive, might have died of EnvironmentalDamage
272 if (target->isAlive())
273 target->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING, uint32(z_diff*100));
276 //Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction
277 DEBUG_LOG("FALLDAMAGE z=%f sz=%f pZ=%f FallTime=%d mZ=%f damage=%d SF=%d" , movementInfo.z, height, target->GetPositionZ(), movementInfo.fallTime, height, damage, safe_fall);
282 if(((movementInfo.flags & MOVEMENTFLAG_SWIMMING) != 0) != GetPlayer()->IsInWater())
284 // now client not include swimming flag in case jumping under water
285 GetPlayer()->SetInWater( !GetPlayer()->IsInWater() || GetPlayer()->GetBaseMap()->IsUnderWater(movementInfo.x, movementInfo.y, movementInfo.z) );
288 /*----------------------*/
290 /* process position-change */
291 Unit *mover = _player->m_mover;
292 recv_data.put<uint32>(6, getMSTime()); // fix time, offset flags(4) + unk(2)
293 WorldPacket data(recv_data.GetOpcode(), (mover->GetPackGUID().size()+recv_data.size()));
294 data.append(_player->m_mover->GetPackGUID()); // use mover guid
295 data.append(recv_data.contents(), recv_data.size());
296 GetPlayer()->SendMessageToSet(&data, false);
298 if(!_player->GetCharmGUID()) // nothing is charmed
300 _player->SetPosition(movementInfo.x, movementInfo.y, movementInfo.z, movementInfo.o);
301 _player->m_movementInfo = movementInfo;
302 _player->SetUnitMovementFlags(movementInfo.flags);
304 else
306 if(mover->GetTypeId() != TYPEID_PLAYER) // unit, creature, pet, vehicle...
308 if(Map *map = mover->GetMap())
309 map->CreatureRelocation((Creature*)mover, movementInfo.x, movementInfo.y, movementInfo.z, movementInfo.o);
310 mover->SetUnitMovementFlags(movementInfo.flags);
312 else // player
314 ((Player*)mover)->SetPosition(movementInfo.x, movementInfo.y, movementInfo.z, movementInfo.o);
315 ((Player*)mover)->m_movementInfo = movementInfo;
316 ((Player*)mover)->SetUnitMovementFlags(movementInfo.flags);
320 if (GetPlayer()->m_lastFallTime >= movementInfo.fallTime || GetPlayer()->m_lastFallZ <=movementInfo.z || recv_data.GetOpcode() == MSG_MOVE_FALL_LAND)
321 GetPlayer()->SetFallInformation(movementInfo.fallTime, movementInfo.z);
323 if(GetPlayer()->isMovingOrTurning())
324 GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
326 if(movementInfo.z < -500.0f)
328 if(GetPlayer()->InBattleGround()
329 && GetPlayer()->GetBattleGround()
330 && GetPlayer()->GetBattleGround()->HandlePlayerUnderMap(_player))
332 // do nothing, the handle already did if returned true
334 else
336 // NOTE: this is actually called many times while falling
337 // even after the player has been teleported away
338 // TODO: discard movement packets after the player is rooted
339 if(GetPlayer()->isAlive())
341 GetPlayer()->EnvironmentalDamage(GetPlayer()->GetGUID(),DAMAGE_FALL_TO_VOID, GetPlayer()->GetMaxHealth());
342 // change the death state to CORPSE to prevent the death timer from
343 // starting in the next player update
344 GetPlayer()->KillPlayer();
345 GetPlayer()->BuildPlayerRepop();
348 // cancel the death timer here if started
349 GetPlayer()->RepopAtGraveyard();
354 void WorldSession::HandleForceSpeedChangeAck(WorldPacket &recv_data)
356 sLog.outDebug("WORLD: Recvd %s (%u, 0x%X) opcode", LookupOpcodeName(recv_data.GetOpcode()), recv_data.GetOpcode(), recv_data.GetOpcode());
358 CHECK_PACKET_SIZE(recv_data, recv_data.rpos()+8+4);
360 /* extract packet */
361 uint64 guid;
362 uint32 unk1;
363 float newspeed;
365 recv_data >> guid;
367 // now can skip not our packet
368 if(_player->GetGUID() != guid)
369 return;
371 // continue parse packet
373 recv_data >> unk1; // counter or moveEvent
375 MovementInfo movementInfo;
376 ReadMovementInfo(recv_data, &movementInfo);
378 // recheck
379 CHECK_PACKET_SIZE(recv_data, recv_data.rpos()+4);
381 recv_data >> newspeed;
382 /*----------------*/
384 // client ACK send one packet for mounted/run case and need skip all except last from its
385 // in other cases anti-cheat check can be fail in false case
386 UnitMoveType move_type;
387 UnitMoveType force_move_type;
389 static char const* move_type_name[MAX_MOVE_TYPE] = { "Walk", "Run", "RunBack", "Swim", "SwimBack", "TurnRate", "Flight", "FlightBack", "PitchRate" };
391 uint16 opcode = recv_data.GetOpcode();
392 switch(opcode)
394 case CMSG_FORCE_WALK_SPEED_CHANGE_ACK: move_type = MOVE_WALK; force_move_type = MOVE_WALK; break;
395 case CMSG_FORCE_RUN_SPEED_CHANGE_ACK: move_type = MOVE_RUN; force_move_type = MOVE_RUN; break;
396 case CMSG_FORCE_RUN_BACK_SPEED_CHANGE_ACK: move_type = MOVE_RUN_BACK; force_move_type = MOVE_RUN_BACK; break;
397 case CMSG_FORCE_SWIM_SPEED_CHANGE_ACK: move_type = MOVE_SWIM; force_move_type = MOVE_SWIM; break;
398 case CMSG_FORCE_SWIM_BACK_SPEED_CHANGE_ACK: move_type = MOVE_SWIM_BACK; force_move_type = MOVE_SWIM_BACK; break;
399 case CMSG_FORCE_TURN_RATE_CHANGE_ACK: move_type = MOVE_TURN_RATE; force_move_type = MOVE_TURN_RATE; break;
400 case CMSG_FORCE_FLIGHT_SPEED_CHANGE_ACK: move_type = MOVE_FLIGHT; force_move_type = MOVE_FLIGHT; break;
401 case CMSG_FORCE_FLIGHT_BACK_SPEED_CHANGE_ACK: move_type = MOVE_FLIGHT_BACK; force_move_type = MOVE_FLIGHT_BACK; break;
402 case CMSG_FORCE_PITCH_RATE_CHANGE_ACK: move_type = MOVE_PITCH_RATE; force_move_type = MOVE_PITCH_RATE; break;
403 default:
404 sLog.outError("WorldSession::HandleForceSpeedChangeAck: Unknown move type opcode: %u", opcode);
405 return;
408 // skip all forced speed changes except last and unexpected
409 // in run/mounted case used one ACK and it must be skipped.m_forced_speed_changes[MOVE_RUN} store both.
410 if(_player->m_forced_speed_changes[force_move_type] > 0)
412 --_player->m_forced_speed_changes[force_move_type];
413 if(_player->m_forced_speed_changes[force_move_type] > 0)
414 return;
417 if (!_player->GetTransport() && fabs(_player->GetSpeed(move_type) - newspeed) > 0.01f)
419 if(_player->GetSpeed(move_type) > newspeed) // must be greater - just correct
421 sLog.outError("%sSpeedChange player %s is NOT correct (must be %f instead %f), force set to correct value",
422 move_type_name[move_type], _player->GetName(), _player->GetSpeed(move_type), newspeed);
423 _player->SetSpeed(move_type,_player->GetSpeedRate(move_type),true);
425 else // must be lesser - cheating
427 sLog.outBasic("Player %s from account id %u kicked for incorrect speed (must be %f instead %f)",
428 _player->GetName(),_player->GetSession()->GetAccountId(),_player->GetSpeed(move_type), newspeed);
429 _player->GetSession()->KickPlayer();
434 void WorldSession::HandleSetActiveMoverOpcode(WorldPacket &recv_data)
436 sLog.outDebug("WORLD: Recvd CMSG_SET_ACTIVE_MOVER");
437 recv_data.hexlike();
439 CHECK_PACKET_SIZE(recv_data, 8);
441 uint64 guid;
442 recv_data >> guid;
444 if(_player->m_mover->GetGUID() != guid)
446 sLog.outError("HandleSetActiveMoverOpcode: incorrect mover guid: mover is " I64FMT " and should be " I64FMT, _player->m_mover->GetGUID(), guid);
447 return;
451 void WorldSession::HandleMoveNotActiveMover(WorldPacket &recv_data)
453 sLog.outDebug("WORLD: Recvd CMSG_MOVE_NOT_ACTIVE_MOVER");
454 recv_data.hexlike();
456 CHECK_PACKET_SIZE(recv_data, recv_data.rpos()+8);
458 uint64 old_mover_guid;
459 recv_data >> old_mover_guid;
461 if(_player->m_mover->GetGUID() == old_mover_guid)
463 sLog.outError("HandleMoveNotActiveMover: incorrect mover guid: mover is " I64FMT " and should be " I64FMT " instead of " I64FMT, _player->m_mover->GetGUID(), _player->GetGUID(), old_mover_guid);
464 return;
467 MovementInfo mi;
468 ReadMovementInfo(recv_data, &mi);
469 _player->m_movementInfo = mi;
472 void WorldSession::HandleDismissControlledVehicle(WorldPacket &recv_data)
474 sLog.outDebug("WORLD: Recvd CMSG_DISMISS_CONTROLLED_VEHICLE");
475 recv_data.hexlike();
477 uint64 vehicleGUID = _player->GetCharmGUID();
479 if(!vehicleGUID) // something wrong here...
480 return;
482 MovementInfo mi;
483 ReadMovementInfo(recv_data, &mi);
484 _player->m_movementInfo = mi;
486 // using charm guid, because we don't have vehicle guid...
487 if(Vehicle *vehicle = ObjectAccessor::GetVehicle(vehicleGUID))
489 _player->ExitVehicle(vehicle);
490 vehicle->Dismiss();
494 void WorldSession::HandleMountSpecialAnimOpcode(WorldPacket& /*recvdata*/)
496 //sLog.outDebug("WORLD: Recvd CMSG_MOUNTSPECIAL_ANIM");
498 WorldPacket data(SMSG_MOUNTSPECIAL_ANIM, 8);
499 data << uint64(GetPlayer()->GetGUID());
501 GetPlayer()->SendMessageToSet(&data, false);
504 void WorldSession::HandleMoveKnockBackAck( WorldPacket & /*recv_data*/ )
506 // CHECK_PACKET_SIZE(recv_data,?);
507 sLog.outDebug("CMSG_MOVE_KNOCK_BACK_ACK");
508 // Currently not used but maybe use later for recheck final player position
509 // (must be at call same as into "recv_data >> x >> y >> z >> orientation;"
512 uint32 flags, time;
513 float x, y, z, orientation;
514 uint64 guid;
515 uint32 sequence;
516 uint32 ukn1;
517 float xdirection,ydirection,hspeed,vspeed;
519 recv_data >> guid;
520 recv_data >> sequence;
521 recv_data >> flags >> time;
522 recv_data >> x >> y >> z >> orientation;
523 recv_data >> ukn1; //unknown
524 recv_data >> vspeed >> xdirection >> ydirection >> hspeed;
526 // skip not personal message;
527 if(GetPlayer()->GetGUID()!=guid)
528 return;
530 // check code
534 void WorldSession::HandleMoveHoverAck( WorldPacket& /*recv_data*/ )
536 sLog.outDebug("CMSG_MOVE_HOVER_ACK");
539 void WorldSession::HandleMoveWaterWalkAck(WorldPacket& /*recv_data*/)
541 sLog.outDebug("CMSG_MOVE_WATER_WALK_ACK");
544 void WorldSession::HandleSummonResponseOpcode(WorldPacket& recv_data)
546 CHECK_PACKET_SIZE(recv_data,8+1);
548 if(!_player->isAlive() || _player->isInCombat() )
549 return;
551 uint64 summoner_guid;
552 bool agree;
553 recv_data >> summoner_guid;
554 recv_data >> agree;
556 _player->SummonIfPossible(agree);