[9290] Some cleanups in realmd, no functional changes
[getmangos.git] / src / game / Object.cpp
blob8e05784918923410962f621f1ede0a67cb6316e6
1 /*
2 * Copyright (C) 2005-2010 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 "SharedDefines.h"
21 #include "WorldPacket.h"
22 #include "Opcodes.h"
23 #include "Log.h"
24 #include "World.h"
25 #include "Object.h"
26 #include "Creature.h"
27 #include "Player.h"
28 #include "Vehicle.h"
29 #include "ObjectMgr.h"
30 #include "ObjectDefines.h"
31 #include "UpdateData.h"
32 #include "UpdateMask.h"
33 #include "Util.h"
34 #include "MapManager.h"
35 #include "Log.h"
36 #include "Transports.h"
37 #include "TargetedMovementGenerator.h"
38 #include "WaypointMovementGenerator.h"
39 #include "VMapFactory.h"
40 #include "CellImpl.h"
41 #include "GridNotifiers.h"
42 #include "GridNotifiersImpl.h"
44 #include "ObjectPosSelector.h"
46 #include "TemporarySummon.h"
48 uint32 GuidHigh2TypeId(uint32 guid_hi)
50 switch(guid_hi)
52 case HIGHGUID_ITEM: return TYPEID_ITEM;
53 //case HIGHGUID_CONTAINER: return TYPEID_CONTAINER; HIGHGUID_CONTAINER==HIGHGUID_ITEM currently
54 case HIGHGUID_UNIT: return TYPEID_UNIT;
55 case HIGHGUID_PET: return TYPEID_UNIT;
56 case HIGHGUID_PLAYER: return TYPEID_PLAYER;
57 case HIGHGUID_GAMEOBJECT: return TYPEID_GAMEOBJECT;
58 case HIGHGUID_DYNAMICOBJECT:return TYPEID_DYNAMICOBJECT;
59 case HIGHGUID_CORPSE: return TYPEID_CORPSE;
60 case HIGHGUID_MO_TRANSPORT: return TYPEID_GAMEOBJECT;
61 case HIGHGUID_VEHICLE: return TYPEID_UNIT;
63 return NUM_CLIENT_OBJECT_TYPES; // unknown
66 Object::Object( ) : m_PackGUID(sizeof(uint64)+1)
68 m_objectTypeId = TYPEID_OBJECT;
69 m_objectType = TYPEMASK_OBJECT;
71 m_uint32Values = 0;
72 m_uint32Values_mirror = 0;
73 m_valuesCount = 0;
75 m_inWorld = false;
76 m_objectUpdated = false;
78 m_PackGUID.appendPackGUID(0);
81 Object::~Object( )
83 if(IsInWorld())
85 ///- Do NOT call RemoveFromWorld here, if the object is a player it will crash
86 sLog.outError("Object::~Object (GUID: %u TypeId: %u) deleted but still in world!!", GetGUIDLow(), GetTypeId());
87 ASSERT(false);
90 if(m_objectUpdated)
92 sLog.outError("Object::~Object (GUID: %u TypeId: %u) deleted but still have updated status!!", GetGUIDLow(), GetTypeId());
93 ASSERT(false);
96 if(m_uint32Values)
98 //DEBUG_LOG("Object desctr 1 check (%p)",(void*)this);
99 delete [] m_uint32Values;
100 delete [] m_uint32Values_mirror;
101 //DEBUG_LOG("Object desctr 2 check (%p)",(void*)this);
105 void Object::_InitValues()
107 m_uint32Values = new uint32[ m_valuesCount ];
108 memset(m_uint32Values, 0, m_valuesCount*sizeof(uint32));
110 m_uint32Values_mirror = new uint32[ m_valuesCount ];
111 memset(m_uint32Values_mirror, 0, m_valuesCount*sizeof(uint32));
113 m_objectUpdated = false;
116 void Object::_Create( uint32 guidlow, uint32 entry, HighGuid guidhigh )
118 if(!m_uint32Values)
119 _InitValues();
121 uint64 guid = MAKE_NEW_GUID(guidlow, entry, guidhigh);
122 SetUInt64Value(OBJECT_FIELD_GUID, guid);
123 SetUInt32Value(OBJECT_FIELD_TYPE, m_objectType);
124 m_PackGUID.wpos(0);
125 m_PackGUID.appendPackGUID(GetGUID());
128 void Object::BuildMovementUpdateBlock(UpdateData * data, uint16 flags ) const
130 ByteBuffer buf(500);
132 buf << uint8(UPDATETYPE_MOVEMENT);
133 buf.append(GetPackGUID());
135 BuildMovementUpdate(&buf, flags);
137 data->AddUpdateBlock(buf);
140 void Object::BuildCreateUpdateBlockForPlayer(UpdateData *data, Player *target) const
142 if(!target)
143 return;
145 uint8 updatetype = UPDATETYPE_CREATE_OBJECT;
146 uint16 updateFlags = m_updateFlag;
148 /** lower flag1 **/
149 if(target == this) // building packet for yourself
150 updateFlags |= UPDATEFLAG_SELF;
152 if(updateFlags & UPDATEFLAG_HAS_POSITION)
154 // UPDATETYPE_CREATE_OBJECT2 dynamic objects, corpses...
155 if(isType(TYPEMASK_DYNAMICOBJECT) || isType(TYPEMASK_CORPSE) || isType(TYPEMASK_PLAYER))
156 updatetype = UPDATETYPE_CREATE_OBJECT2;
158 // UPDATETYPE_CREATE_OBJECT2 for pets...
159 if(target->GetPetGUID() == GetGUID())
160 updatetype = UPDATETYPE_CREATE_OBJECT2;
162 // UPDATETYPE_CREATE_OBJECT2 for some gameobject types...
163 if(isType(TYPEMASK_GAMEOBJECT))
165 switch(((GameObject*)this)->GetGoType())
167 case GAMEOBJECT_TYPE_TRAP:
168 case GAMEOBJECT_TYPE_DUEL_ARBITER:
169 case GAMEOBJECT_TYPE_FLAGSTAND:
170 case GAMEOBJECT_TYPE_FLAGDROP:
171 updatetype = UPDATETYPE_CREATE_OBJECT2;
172 break;
173 case GAMEOBJECT_TYPE_TRANSPORT:
174 updateFlags |= UPDATEFLAG_TRANSPORT;
175 break;
176 default:
177 break;
181 if(isType(TYPEMASK_UNIT))
183 if(((Unit*)this)->getVictim())
184 updateFlags |= UPDATEFLAG_HAS_ATTACKING_TARGET;
188 //sLog.outDebug("BuildCreateUpdate: update-type: %u, object-type: %u got updateFlags: %X", updatetype, m_objectTypeId, updateFlags);
190 ByteBuffer buf(500);
191 buf << uint8(updatetype);
192 buf.append(GetPackGUID());
193 buf << uint8(m_objectTypeId);
195 BuildMovementUpdate(&buf, updateFlags);
197 UpdateMask updateMask;
198 updateMask.SetCount(m_valuesCount);
199 _SetCreateBits(&updateMask, target);
200 BuildValuesUpdate(updatetype, &buf, &updateMask, target);
201 data->AddUpdateBlock(buf);
204 void Object::SendCreateUpdateToPlayer(Player* player)
206 // send create update to player
207 UpdateData upd;
208 WorldPacket packet;
210 BuildCreateUpdateBlockForPlayer(&upd, player);
211 upd.BuildPacket(&packet);
212 player->GetSession()->SendPacket(&packet);
215 void Object::BuildValuesUpdateBlockForPlayer(UpdateData *data, Player *target) const
217 ByteBuffer buf(500);
219 buf << uint8(UPDATETYPE_VALUES);
220 buf.append(GetPackGUID());
222 UpdateMask updateMask;
223 updateMask.SetCount(m_valuesCount);
225 _SetUpdateBits(&updateMask, target);
226 BuildValuesUpdate(UPDATETYPE_VALUES, &buf, &updateMask, target);
228 data->AddUpdateBlock(buf);
231 void Object::BuildOutOfRangeUpdateBlock(UpdateData * data) const
233 data->AddOutOfRangeGUID(GetGUID());
236 void Object::DestroyForPlayer( Player *target, bool anim ) const
238 ASSERT(target);
240 WorldPacket data(SMSG_DESTROY_OBJECT, 8);
241 data << uint64(GetGUID());
242 data << uint8(anim ? 1 : 0); // WotLK (bool), may be despawn animation
243 target->GetSession()->SendPacket(&data);
246 void Object::BuildMovementUpdate(ByteBuffer * data, uint16 updateFlags) const
248 uint16 moveFlags2 = (isType(TYPEMASK_UNIT) ? ((Unit*)this)->m_movementInfo.GetMovementFlags2() : MOVEFLAG2_NONE);
250 if(GetTypeId() == TYPEID_UNIT)
251 if(((Creature*)this)->isVehicle())
252 moveFlags2 |= MOVEFLAG2_ALLOW_PITCHING; // always allow pitch
254 *data << uint16(updateFlags); // update flags
256 // 0x20
257 if (updateFlags & UPDATEFLAG_LIVING)
259 Unit *unit = ((Unit*)this);
261 switch(GetTypeId())
263 case TYPEID_UNIT:
265 unit->m_movementInfo.SetMovementFlags(MOVEFLAG_NONE);
267 // disabled, makes them run-in-same-place before movement generator updated once.
268 /*if (((Creature*)unit)->hasUnitState(UNIT_STAT_MOVING))
269 unit->m_movementInfo.SetMovementFlags(MOVEFLAG_FORWARD);*/
271 if (((Creature*)unit)->canFly())
273 // (ok) most seem to have this
274 unit->m_movementInfo.AddMovementFlag(MOVEFLAG_LEVITATING);
276 if (!((Creature*)unit)->hasUnitState(UNIT_STAT_MOVING))
278 // (ok) possibly some "hover" mode
279 unit->m_movementInfo.AddMovementFlag(MOVEFLAG_FLY_UNK1);
281 else
283 if (((Creature*)unit)->IsMounted())
285 // seems to be often when mounted
286 unit->m_movementInfo.AddMovementFlag(MOVEFLAG_FLYING);
291 break;
292 case TYPEID_PLAYER:
294 Player *player = ((Player*)unit);
296 if(player->GetTransport())
297 player->m_movementInfo.AddMovementFlag(MOVEFLAG_ONTRANSPORT);
298 else
299 player->m_movementInfo.RemoveMovementFlag(MOVEFLAG_ONTRANSPORT);
301 // remove unknown, unused etc flags for now
302 player->m_movementInfo.RemoveMovementFlag(MOVEFLAG_SPLINE2);
304 if(player->isInFlight())
306 ASSERT(player->GetMotionMaster()->GetCurrentMovementGeneratorType() == FLIGHT_MOTION_TYPE);
307 player->m_movementInfo.AddMovementFlag(MOVEFLAG_FORWARD);
308 player->m_movementInfo.AddMovementFlag(MOVEFLAG_SPLINE2);
311 break;
314 // Update movement info time
315 unit->m_movementInfo.UpdateTime(getMSTime());
316 // Write movement info
317 unit->m_movementInfo.Write(*data);
319 // Unit speeds
320 *data << float(unit->GetSpeed(MOVE_WALK));
321 *data << float(unit->GetSpeed(MOVE_RUN));
322 *data << float(unit->GetSpeed(MOVE_SWIM_BACK));
323 *data << float(unit->GetSpeed(MOVE_SWIM));
324 *data << float(unit->GetSpeed(MOVE_RUN_BACK));
325 *data << float(unit->GetSpeed(MOVE_FLIGHT));
326 *data << float(unit->GetSpeed(MOVE_FLIGHT_BACK));
327 *data << float(unit->GetSpeed(MOVE_TURN_RATE));
328 *data << float(unit->GetSpeed(MOVE_PITCH_RATE));
330 // 0x08000000
331 if(unit->m_movementInfo.GetMovementFlags() & MOVEFLAG_SPLINE2)
333 if(GetTypeId() != TYPEID_PLAYER)
335 sLog.outDebug("_BuildMovementUpdate: MOVEFLAG_SPLINE2 for non-player");
336 return;
339 Player *player = ((Player*)unit);
341 if(!player->isInFlight())
343 sLog.outDebug("_BuildMovementUpdate: MOVEFLAG_SPLINE2 but not in flight");
344 return;
347 ASSERT(player->GetMotionMaster()->GetCurrentMovementGeneratorType() == FLIGHT_MOTION_TYPE);
349 FlightPathMovementGenerator *fmg = (FlightPathMovementGenerator*)(player->GetMotionMaster()->top());
351 uint32 flags3 = MONSTER_MOVE_SPLINE_FLY;
353 *data << uint32(flags3); // splines flag?
355 if(flags3 & SPLINE_MOVE_FLAG_FACING) // may be orientation
357 *data << float(0);
359 else
361 if(flags3 & SPLINE_MOVE_FLAG_GUID) // probably guid there
363 *data << uint64(0);
365 else
367 if(flags3 & SPLINE_MOVE_FLAG_POINT) // probably x,y,z coords there
369 *data << float(0);
370 *data << float(0);
371 *data << float(0);
376 Path &path = fmg->GetPath();
378 float x, y, z;
379 player->GetPosition(x, y, z);
381 uint32 inflighttime = uint32(path.GetPassedLength(fmg->GetCurrentNode(), x, y, z) * 32);
382 uint32 traveltime = uint32(path.GetTotalLength() * 32);
384 *data << uint32(inflighttime); // passed move time?
385 *data << uint32(traveltime); // full move time?
386 *data << uint32(0); // sequenceId
388 *data << float(0); // added in 3.1
389 *data << float(0); // added in 3.1
390 *data << float(0); // added in 3.1
392 *data << uint32(0); // added in 3.1
394 uint32 poscount = uint32(path.Size());
395 *data << uint32(poscount); // points count
397 for(uint32 i = 0; i < poscount; ++i)
399 *data << float(path.GetNodes()[i].x);
400 *data << float(path.GetNodes()[i].y);
401 *data << float(path.GetNodes()[i].z);
404 *data << uint8(0); // splineMode
406 *data << float(path.GetNodes()[poscount-1].x);
407 *data << float(path.GetNodes()[poscount-1].y);
408 *data << float(path.GetNodes()[poscount-1].z);
411 else
413 if(updateFlags & UPDATEFLAG_POSITION)
415 *data << uint8(0); // unk PGUID!
416 *data << float(((WorldObject*)this)->GetPositionX());
417 *data << float(((WorldObject*)this)->GetPositionY());
418 *data << float(((WorldObject*)this)->GetPositionZ());
419 *data << float(((WorldObject*)this)->GetPositionX());
420 *data << float(((WorldObject*)this)->GetPositionY());
421 *data << float(((WorldObject*)this)->GetPositionZ());
422 *data << float(((WorldObject*)this)->GetOrientation());
424 if(GetTypeId() == TYPEID_CORPSE)
425 *data << float(((WorldObject*)this)->GetOrientation());
426 else
427 *data << float(0);
429 else
431 // 0x40
432 if (updateFlags & UPDATEFLAG_HAS_POSITION)
434 // 0x02
435 if(updateFlags & UPDATEFLAG_TRANSPORT && ((GameObject*)this)->GetGoType() == GAMEOBJECT_TYPE_MO_TRANSPORT)
437 *data << float(0);
438 *data << float(0);
439 *data << float(0);
440 *data << float(((WorldObject *)this)->GetOrientation());
442 else
444 *data << float(((WorldObject *)this)->GetPositionX());
445 *data << float(((WorldObject *)this)->GetPositionY());
446 *data << float(((WorldObject *)this)->GetPositionZ());
447 *data << float(((WorldObject *)this)->GetOrientation());
453 // 0x8
454 if(updateFlags & UPDATEFLAG_LOWGUID)
456 switch(GetTypeId())
458 case TYPEID_OBJECT:
459 case TYPEID_ITEM:
460 case TYPEID_CONTAINER:
461 case TYPEID_GAMEOBJECT:
462 case TYPEID_DYNAMICOBJECT:
463 case TYPEID_CORPSE:
464 *data << uint32(GetGUIDLow()); // GetGUIDLow()
465 break;
466 case TYPEID_UNIT:
467 *data << uint32(0x0000000B); // unk, can be 0xB or 0xC
468 break;
469 case TYPEID_PLAYER:
470 if(updateFlags & UPDATEFLAG_SELF)
471 *data << uint32(0x0000002F); // unk, can be 0x15 or 0x22
472 else
473 *data << uint32(0x00000008); // unk, can be 0x7 or 0x8
474 break;
475 default:
476 *data << uint32(0x00000000); // unk
477 break;
481 // 0x10
482 if(updateFlags & UPDATEFLAG_HIGHGUID)
484 switch(GetTypeId())
486 case TYPEID_OBJECT:
487 case TYPEID_ITEM:
488 case TYPEID_CONTAINER:
489 case TYPEID_GAMEOBJECT:
490 case TYPEID_DYNAMICOBJECT:
491 case TYPEID_CORPSE:
492 *data << uint32(GetGUIDHigh()); // GetGUIDHigh()
493 break;
494 case TYPEID_UNIT:
495 *data << uint32(0x0000000B); // unk, can be 0xB or 0xC
496 break;
497 case TYPEID_PLAYER:
498 if(updateFlags & UPDATEFLAG_SELF)
499 *data << uint32(0x0000002F); // unk, can be 0x15 or 0x22
500 else
501 *data << uint32(0x00000008); // unk, can be 0x7 or 0x8
502 break;
503 default:
504 *data << uint32(0x00000000); // unk
505 break;
509 // 0x4
510 if(updateFlags & UPDATEFLAG_HAS_ATTACKING_TARGET) // packed guid (current target guid)
512 if (((Unit*)this)->getVictim())
513 data->append(((Unit*)this)->getVictim()->GetPackGUID());
514 else
515 data->appendPackGUID(0);
518 // 0x2
519 if(updateFlags & UPDATEFLAG_TRANSPORT)
521 *data << uint32(getMSTime()); // ms time
524 // 0x80
525 if(updateFlags & UPDATEFLAG_VEHICLE) // unused for now
527 *data << uint32(((Vehicle*)this)->GetVehicleId()); // vehicle id
528 *data << float(0); // facing adjustment
531 // 0x200
532 if(updateFlags & UPDATEFLAG_ROTATION)
534 *data << uint64(((GameObject*)this)->GetRotation());
538 void Object::BuildValuesUpdate(uint8 updatetype, ByteBuffer * data, UpdateMask *updateMask, Player *target) const
540 if(!target)
541 return;
543 bool IsActivateToQuest = false;
544 bool IsPerCasterAuraState = false;
545 if (updatetype == UPDATETYPE_CREATE_OBJECT || updatetype == UPDATETYPE_CREATE_OBJECT2)
547 if (isType(TYPEMASK_GAMEOBJECT) && !((GameObject*)this)->IsTransport())
549 if ( ((GameObject*)this)->ActivateToQuest(target) || target->isGameMaster())
550 IsActivateToQuest = true;
552 updateMask->SetBit(GAMEOBJECT_DYNAMIC);
554 else if (isType(TYPEMASK_UNIT))
556 if( ((Unit*)this)->HasAuraState(AURA_STATE_CONFLAGRATE))
558 IsPerCasterAuraState = true;
559 updateMask->SetBit(UNIT_FIELD_AURASTATE);
563 else // case UPDATETYPE_VALUES
565 if (isType(TYPEMASK_GAMEOBJECT) && !((GameObject*)this)->IsTransport())
567 if ( ((GameObject*)this)->ActivateToQuest(target) || target->isGameMaster())
569 IsActivateToQuest = true;
571 updateMask->SetBit(GAMEOBJECT_DYNAMIC);
572 updateMask->SetBit(GAMEOBJECT_BYTES_1);
574 else if (isType(TYPEMASK_UNIT))
576 if( ((Unit*)this)->HasAuraState(AURA_STATE_CONFLAGRATE))
578 IsPerCasterAuraState = true;
579 updateMask->SetBit(UNIT_FIELD_AURASTATE);
584 ASSERT(updateMask && updateMask->GetCount() == m_valuesCount);
586 *data << (uint8)updateMask->GetBlockCount();
587 data->append( updateMask->GetMask(), updateMask->GetLength() );
589 // 2 specialized loops for speed optimization in non-unit case
590 if(isType(TYPEMASK_UNIT)) // unit (creature/player) case
592 for( uint16 index = 0; index < m_valuesCount; ++index )
594 if( updateMask->GetBit( index ) )
596 if( index == UNIT_NPC_FLAGS )
598 // remove custom flag before sending
599 uint32 appendValue = m_uint32Values[ index ] & ~UNIT_NPC_FLAG_GUARD;
601 if (GetTypeId() == TYPEID_UNIT)
603 if (!target->canSeeSpellClickOn((Creature*)this))
604 appendValue &= ~UNIT_NPC_FLAG_SPELLCLICK;
606 if (appendValue & UNIT_NPC_FLAG_TRAINER)
608 if (!((Creature*)this)->isCanTrainingOf(target, false))
609 appendValue &= ~(UNIT_NPC_FLAG_TRAINER | UNIT_NPC_FLAG_TRAINER_CLASS | UNIT_NPC_FLAG_TRAINER_PROFESSION);
612 if (appendValue & UNIT_NPC_FLAG_STABLEMASTER)
614 if (target->getClass() != CLASS_HUNTER)
615 appendValue &= ~UNIT_NPC_FLAG_STABLEMASTER;
619 *data << uint32(appendValue);
621 else if (index == UNIT_FIELD_AURASTATE)
623 if(IsPerCasterAuraState)
625 // IsPerCasterAuraState set if related pet caster aura state set already
626 if (((Unit*)this)->HasAuraStateForCaster(AURA_STATE_CONFLAGRATE,target->GetGUID()))
627 *data << m_uint32Values[ index ];
628 else
629 *data << (m_uint32Values[ index ] & ~(1 << (AURA_STATE_CONFLAGRATE-1)));
631 else
632 *data << m_uint32Values[ index ];
634 // FIXME: Some values at server stored in float format but must be sent to client in uint32 format
635 else if(index >= UNIT_FIELD_BASEATTACKTIME && index <= UNIT_FIELD_RANGEDATTACKTIME)
637 // convert from float to uint32 and send
638 *data << uint32(m_floatValues[ index ] < 0 ? 0 : m_floatValues[ index ]);
640 // there are some float values which may be negative or can't get negative due to other checks
641 else if ((index >= UNIT_FIELD_NEGSTAT0 && index <= UNIT_FIELD_NEGSTAT4) ||
642 (index >= UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE && index <= (UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE + 6)) ||
643 (index >= UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE && index <= (UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE + 6)) ||
644 (index >= UNIT_FIELD_POSSTAT0 && index <= UNIT_FIELD_POSSTAT4))
646 *data << uint32(m_floatValues[ index ]);
648 // Gamemasters should be always able to select units - remove not selectable flag
649 else if(index == UNIT_FIELD_FLAGS && target->isGameMaster())
651 *data << (m_uint32Values[ index ] & ~UNIT_FLAG_NOT_SELECTABLE);
653 // hide lootable animation for unallowed players
654 else if(index == UNIT_DYNAMIC_FLAGS && GetTypeId() == TYPEID_UNIT)
656 if(!target->isAllowedToLoot((Creature*)this))
657 *data << (m_uint32Values[ index ] & ~UNIT_DYNFLAG_LOOTABLE);
658 else
659 *data << (m_uint32Values[ index ] & ~UNIT_DYNFLAG_TAPPED);
661 else
663 // send in current format (float as float, uint32 as uint32)
664 *data << m_uint32Values[ index ];
669 else if(isType(TYPEMASK_GAMEOBJECT)) // gameobject case
671 for( uint16 index = 0; index < m_valuesCount; ++index )
673 if( updateMask->GetBit( index ) )
675 // send in current format (float as float, uint32 as uint32)
676 if ( index == GAMEOBJECT_DYNAMIC )
678 if(IsActivateToQuest )
680 switch(((GameObject*)this)->GetGoType())
682 case GAMEOBJECT_TYPE_CHEST:
683 // enable quest object. Represent 9, but 1 for client before 2.3.0
684 *data << uint16(9);
685 *data << uint16(-1);
686 break;
687 case GAMEOBJECT_TYPE_GOOBER:
688 *data << uint16(1);
689 *data << uint16(-1);
690 break;
691 default:
692 // unknown, not happen.
693 *data << uint16(0);
694 *data << uint16(-1);
695 break;
698 else
700 // disable quest object
701 *data << uint16(0);
702 *data << uint16(-1);
705 else
706 *data << m_uint32Values[ index ]; // other cases
710 else // other objects case (no special index checks)
712 for( uint16 index = 0; index < m_valuesCount; ++index )
714 if( updateMask->GetBit( index ) )
716 // send in current format (float as float, uint32 as uint32)
717 *data << m_uint32Values[ index ];
723 void Object::ClearUpdateMask(bool remove)
725 if(m_uint32Values)
727 for( uint16 index = 0; index < m_valuesCount; ++index )
729 if(m_uint32Values_mirror[index]!= m_uint32Values[index])
730 m_uint32Values_mirror[index] = m_uint32Values[index];
734 if(m_objectUpdated)
736 if(remove)
737 RemoveFromClientUpdateList();
738 m_objectUpdated = false;
742 bool Object::LoadValues(const char* data)
744 if(!m_uint32Values) _InitValues();
746 Tokens tokens = StrSplit(data, " ");
748 if(tokens.size() != m_valuesCount)
749 return false;
751 Tokens::iterator iter;
752 int index;
753 for (iter = tokens.begin(), index = 0; index < m_valuesCount; ++iter, ++index)
755 m_uint32Values[index] = atol((*iter).c_str());
758 return true;
761 void Object::_SetUpdateBits(UpdateMask *updateMask, Player* /*target*/) const
763 for( uint16 index = 0; index < m_valuesCount; ++index )
765 if(m_uint32Values_mirror[index]!= m_uint32Values[index])
766 updateMask->SetBit(index);
770 void Object::_SetCreateBits(UpdateMask *updateMask, Player* /*target*/) const
772 for( uint16 index = 0; index < m_valuesCount; ++index )
774 if(GetUInt32Value(index) != 0)
775 updateMask->SetBit(index);
779 void Object::SetInt32Value( uint16 index, int32 value )
781 ASSERT( index < m_valuesCount || PrintIndexError( index, true ) );
783 if(m_int32Values[ index ] != value)
785 m_int32Values[ index ] = value;
787 if(m_inWorld)
789 if(!m_objectUpdated)
791 AddToClientUpdateList();
792 m_objectUpdated = true;
798 void Object::SetUInt32Value( uint16 index, uint32 value )
800 ASSERT( index < m_valuesCount || PrintIndexError( index, true ) );
802 if(m_uint32Values[ index ] != value)
804 m_uint32Values[ index ] = value;
806 if(m_inWorld)
808 if(!m_objectUpdated)
810 AddToClientUpdateList();
811 m_objectUpdated = true;
817 void Object::SetUInt64Value( uint16 index, const uint64 &value )
819 ASSERT( index + 1 < m_valuesCount || PrintIndexError( index, true ) );
820 if(*((uint64*)&(m_uint32Values[ index ])) != value)
822 m_uint32Values[ index ] = *((uint32*)&value);
823 m_uint32Values[ index + 1 ] = *(((uint32*)&value) + 1);
825 if(m_inWorld)
827 if(!m_objectUpdated)
829 AddToClientUpdateList();
830 m_objectUpdated = true;
836 void Object::SetFloatValue( uint16 index, float value )
838 ASSERT( index < m_valuesCount || PrintIndexError( index, true ) );
840 if(m_floatValues[ index ] != value)
842 m_floatValues[ index ] = value;
844 if(m_inWorld)
846 if(!m_objectUpdated)
848 AddToClientUpdateList();
849 m_objectUpdated = true;
855 void Object::SetByteValue( uint16 index, uint8 offset, uint8 value )
857 ASSERT( index < m_valuesCount || PrintIndexError( index, true ) );
859 if(offset > 4)
861 sLog.outError("Object::SetByteValue: wrong offset %u", offset);
862 return;
865 if(uint8(m_uint32Values[ index ] >> (offset * 8)) != value)
867 m_uint32Values[ index ] &= ~uint32(uint32(0xFF) << (offset * 8));
868 m_uint32Values[ index ] |= uint32(uint32(value) << (offset * 8));
870 if(m_inWorld)
872 if(!m_objectUpdated)
874 AddToClientUpdateList();
875 m_objectUpdated = true;
881 void Object::SetUInt16Value( uint16 index, uint8 offset, uint16 value )
883 ASSERT( index < m_valuesCount || PrintIndexError( index, true ) );
885 if(offset > 2)
887 sLog.outError("Object::SetUInt16Value: wrong offset %u", offset);
888 return;
891 if(uint16(m_uint32Values[ index ] >> (offset * 16)) != value)
893 m_uint32Values[ index ] &= ~uint32(uint32(0xFFFF) << (offset * 16));
894 m_uint32Values[ index ] |= uint32(uint32(value) << (offset * 16));
896 if(m_inWorld)
898 if(!m_objectUpdated)
900 AddToClientUpdateList();
901 m_objectUpdated = true;
907 void Object::SetStatFloatValue( uint16 index, float value)
909 if(value < 0)
910 value = 0.0f;
912 SetFloatValue(index, value);
915 void Object::SetStatInt32Value( uint16 index, int32 value)
917 if(value < 0)
918 value = 0;
920 SetUInt32Value(index, uint32(value));
923 void Object::ApplyModUInt32Value(uint16 index, int32 val, bool apply)
925 int32 cur = GetUInt32Value(index);
926 cur += (apply ? val : -val);
927 if(cur < 0)
928 cur = 0;
929 SetUInt32Value(index, cur);
932 void Object::ApplyModInt32Value(uint16 index, int32 val, bool apply)
934 int32 cur = GetInt32Value(index);
935 cur += (apply ? val : -val);
936 SetInt32Value(index, cur);
939 void Object::ApplyModSignedFloatValue(uint16 index, float val, bool apply)
941 float cur = GetFloatValue(index);
942 cur += (apply ? val : -val);
943 SetFloatValue(index, cur);
946 void Object::ApplyModPositiveFloatValue(uint16 index, float val, bool apply)
948 float cur = GetFloatValue(index);
949 cur += (apply ? val : -val);
950 if(cur < 0)
951 cur = 0;
952 SetFloatValue(index, cur);
955 void Object::SetFlag( uint16 index, uint32 newFlag )
957 ASSERT( index < m_valuesCount || PrintIndexError( index, true ) );
958 uint32 oldval = m_uint32Values[ index ];
959 uint32 newval = oldval | newFlag;
961 if(oldval != newval)
963 m_uint32Values[ index ] = newval;
965 if(m_inWorld)
967 if(!m_objectUpdated)
969 AddToClientUpdateList();
970 m_objectUpdated = true;
976 void Object::RemoveFlag( uint16 index, uint32 oldFlag )
978 ASSERT( index < m_valuesCount || PrintIndexError( index, true ) );
979 uint32 oldval = m_uint32Values[ index ];
980 uint32 newval = oldval & ~oldFlag;
982 if(oldval != newval)
984 m_uint32Values[ index ] = newval;
986 if(m_inWorld)
988 if(!m_objectUpdated)
990 AddToClientUpdateList();
991 m_objectUpdated = true;
997 void Object::SetByteFlag( uint16 index, uint8 offset, uint8 newFlag )
999 ASSERT( index < m_valuesCount || PrintIndexError( index, true ) );
1001 if(offset > 4)
1003 sLog.outError("Object::SetByteFlag: wrong offset %u", offset);
1004 return;
1007 if(!(uint8(m_uint32Values[ index ] >> (offset * 8)) & newFlag))
1009 m_uint32Values[ index ] |= uint32(uint32(newFlag) << (offset * 8));
1011 if(m_inWorld)
1013 if(!m_objectUpdated)
1015 AddToClientUpdateList();
1016 m_objectUpdated = true;
1022 void Object::RemoveByteFlag( uint16 index, uint8 offset, uint8 oldFlag )
1024 ASSERT( index < m_valuesCount || PrintIndexError( index, true ) );
1026 if(offset > 4)
1028 sLog.outError("Object::RemoveByteFlag: wrong offset %u", offset);
1029 return;
1032 if(uint8(m_uint32Values[ index ] >> (offset * 8)) & oldFlag)
1034 m_uint32Values[ index ] &= ~uint32(uint32(oldFlag) << (offset * 8));
1036 if(m_inWorld)
1038 if(!m_objectUpdated)
1040 AddToClientUpdateList();
1041 m_objectUpdated = true;
1047 bool Object::PrintIndexError(uint32 index, bool set) const
1049 sLog.outError("Attempt %s non-existed value field: %u (count: %u) for object typeid: %u type mask: %u",(set ? "set value to" : "get value from"),index,m_valuesCount,GetTypeId(),m_objectType);
1051 // assert must fail after function call
1052 return false;
1055 void Object::BuildUpdateDataForPlayer(Player* pl, UpdateDataMapType& update_players)
1057 UpdateDataMapType::iterator iter = update_players.find(pl);
1059 if (iter == update_players.end())
1061 std::pair<UpdateDataMapType::iterator, bool> p = update_players.insert( UpdateDataMapType::value_type(pl, UpdateData()) );
1062 assert(p.second);
1063 iter = p.first;
1066 BuildValuesUpdateBlockForPlayer(&iter->second, iter->first);
1069 void Object::AddToClientUpdateList()
1071 sLog.outError("Unexpected call of Object::AddToClientUpdateList for object (TypeId: %u Update fields: %u)",GetTypeId(), m_valuesCount);
1072 ASSERT(false);
1075 void Object::RemoveFromClientUpdateList()
1077 sLog.outError("Unexpected call of Object::RemoveFromClientUpdateList for object (TypeId: %u Update fields: %u)",GetTypeId(), m_valuesCount);
1078 ASSERT(false);
1081 void Object::BuildUpdateData( UpdateDataMapType& update_players )
1083 sLog.outError("Unexpected call of Object::BuildUpdateData for object (TypeId: %u Update fields: %u)",GetTypeId(), m_valuesCount);
1084 ASSERT(false);
1087 WorldObject::WorldObject()
1088 : m_currMap(NULL), m_mapId(0), m_InstanceId(0), m_phaseMask(PHASEMASK_NORMAL),
1089 m_positionX(0.0f), m_positionY(0.0f), m_positionZ(0.0f), m_orientation(0.0f)
1093 void WorldObject::CleanupsBeforeDelete()
1095 RemoveFromWorld();
1098 void WorldObject::_Create( uint32 guidlow, HighGuid guidhigh, uint32 phaseMask )
1100 Object::_Create(guidlow, 0, guidhigh);
1101 m_phaseMask = phaseMask;
1104 void WorldObject::Relocate(float x, float y, float z, float orientation)
1106 m_positionX = x;
1107 m_positionY = y;
1108 m_positionZ = z;
1109 m_orientation = orientation;
1111 if(isType(TYPEMASK_UNIT))
1112 ((Unit*)this)->m_movementInfo.ChangePosition(x, y, z, orientation);
1115 void WorldObject::Relocate(float x, float y, float z)
1117 m_positionX = x;
1118 m_positionY = y;
1119 m_positionZ = z;
1121 if(isType(TYPEMASK_UNIT))
1122 ((Unit*)this)->m_movementInfo.ChangePosition(x, y, z, GetOrientation());
1125 uint32 WorldObject::GetZoneId() const
1127 return GetBaseMap()->GetZoneId(m_positionX, m_positionY, m_positionZ);
1130 uint32 WorldObject::GetAreaId() const
1132 return GetBaseMap()->GetAreaId(m_positionX, m_positionY, m_positionZ);
1135 void WorldObject::GetZoneAndAreaId(uint32& zoneid, uint32& areaid) const
1137 GetBaseMap()->GetZoneAndAreaId(zoneid, areaid, m_positionX, m_positionY, m_positionZ);
1140 InstanceData* WorldObject::GetInstanceData()
1142 Map *map = GetMap();
1143 return map->IsDungeon() ? ((InstanceMap*)map)->GetInstanceData() : NULL;
1146 //slow
1147 float WorldObject::GetDistance(const WorldObject* obj) const
1149 float dx = GetPositionX() - obj->GetPositionX();
1150 float dy = GetPositionY() - obj->GetPositionY();
1151 float dz = GetPositionZ() - obj->GetPositionZ();
1152 float sizefactor = GetObjectSize() + obj->GetObjectSize();
1153 float dist = sqrt((dx*dx) + (dy*dy) + (dz*dz)) - sizefactor;
1154 return ( dist > 0 ? dist : 0);
1157 float WorldObject::GetDistance2d(float x, float y) const
1159 float dx = GetPositionX() - x;
1160 float dy = GetPositionY() - y;
1161 float sizefactor = GetObjectSize();
1162 float dist = sqrt((dx*dx) + (dy*dy)) - sizefactor;
1163 return ( dist > 0 ? dist : 0);
1166 float WorldObject::GetDistance(float x, float y, float z) const
1168 float dx = GetPositionX() - x;
1169 float dy = GetPositionY() - y;
1170 float dz = GetPositionZ() - z;
1171 float sizefactor = GetObjectSize();
1172 float dist = sqrt((dx*dx) + (dy*dy) + (dz*dz)) - sizefactor;
1173 return ( dist > 0 ? dist : 0);
1176 float WorldObject::GetDistance2d(const WorldObject* obj) const
1178 float dx = GetPositionX() - obj->GetPositionX();
1179 float dy = GetPositionY() - obj->GetPositionY();
1180 float sizefactor = GetObjectSize() + obj->GetObjectSize();
1181 float dist = sqrt((dx*dx) + (dy*dy)) - sizefactor;
1182 return ( dist > 0 ? dist : 0);
1185 float WorldObject::GetDistanceZ(const WorldObject* obj) const
1187 float dz = fabs(GetPositionZ() - obj->GetPositionZ());
1188 float sizefactor = GetObjectSize() + obj->GetObjectSize();
1189 float dist = dz - sizefactor;
1190 return ( dist > 0 ? dist : 0);
1193 bool WorldObject::IsWithinDist3d(float x, float y, float z, float dist2compare) const
1195 float dx = GetPositionX() - x;
1196 float dy = GetPositionY() - y;
1197 float dz = GetPositionZ() - z;
1198 float distsq = dx*dx + dy*dy + dz*dz;
1200 float sizefactor = GetObjectSize();
1201 float maxdist = dist2compare + sizefactor;
1203 return distsq < maxdist * maxdist;
1206 bool WorldObject::IsWithinDist2d(float x, float y, float dist2compare) const
1208 float dx = GetPositionX() - x;
1209 float dy = GetPositionY() - y;
1210 float distsq = dx*dx + dy*dy;
1212 float sizefactor = GetObjectSize();
1213 float maxdist = dist2compare + sizefactor;
1215 return distsq < maxdist * maxdist;
1218 bool WorldObject::_IsWithinDist(WorldObject const* obj, float dist2compare, bool is3D) const
1220 float dx = GetPositionX() - obj->GetPositionX();
1221 float dy = GetPositionY() - obj->GetPositionY();
1222 float distsq = dx*dx + dy*dy;
1223 if(is3D)
1225 float dz = GetPositionZ() - obj->GetPositionZ();
1226 distsq += dz*dz;
1228 float sizefactor = GetObjectSize() + obj->GetObjectSize();
1229 float maxdist = dist2compare + sizefactor;
1231 return distsq < maxdist * maxdist;
1234 bool WorldObject::IsWithinLOSInMap(const WorldObject* obj) const
1236 if (!IsInMap(obj)) return false;
1237 float ox,oy,oz;
1238 obj->GetPosition(ox,oy,oz);
1239 return(IsWithinLOS(ox, oy, oz ));
1242 bool WorldObject::IsWithinLOS(float ox, float oy, float oz) const
1244 float x,y,z;
1245 GetPosition(x,y,z);
1246 VMAP::IVMapManager *vMapManager = VMAP::VMapFactory::createOrGetVMapManager();
1247 return vMapManager->isInLineOfSight(GetMapId(), x, y, z+2.0f, ox, oy, oz+2.0f);
1250 bool WorldObject::GetDistanceOrder(WorldObject const* obj1, WorldObject const* obj2, bool is3D /* = true */) const
1252 float dx1 = GetPositionX() - obj1->GetPositionX();
1253 float dy1 = GetPositionY() - obj1->GetPositionY();
1254 float distsq1 = dx1*dx1 + dy1*dy1;
1255 if(is3D)
1257 float dz1 = GetPositionZ() - obj1->GetPositionZ();
1258 distsq1 += dz1*dz1;
1261 float dx2 = GetPositionX() - obj2->GetPositionX();
1262 float dy2 = GetPositionY() - obj2->GetPositionY();
1263 float distsq2 = dx2*dx2 + dy2*dy2;
1264 if(is3D)
1266 float dz2 = GetPositionZ() - obj2->GetPositionZ();
1267 distsq2 += dz2*dz2;
1270 return distsq1 < distsq2;
1273 bool WorldObject::IsInRange(WorldObject const* obj, float minRange, float maxRange, bool is3D /* = true */) const
1275 float dx = GetPositionX() - obj->GetPositionX();
1276 float dy = GetPositionY() - obj->GetPositionY();
1277 float distsq = dx*dx + dy*dy;
1278 if(is3D)
1280 float dz = GetPositionZ() - obj->GetPositionZ();
1281 distsq += dz*dz;
1284 float sizefactor = GetObjectSize() + obj->GetObjectSize();
1286 // check only for real range
1287 if(minRange > 0.0f)
1289 float mindist = minRange + sizefactor;
1290 if(distsq < mindist * mindist)
1291 return false;
1294 float maxdist = maxRange + sizefactor;
1295 return distsq < maxdist * maxdist;
1298 bool WorldObject::IsInRange2d(float x, float y, float minRange, float maxRange) const
1300 float dx = GetPositionX() - x;
1301 float dy = GetPositionY() - y;
1302 float distsq = dx*dx + dy*dy;
1304 float sizefactor = GetObjectSize();
1306 // check only for real range
1307 if(minRange > 0.0f)
1309 float mindist = minRange + sizefactor;
1310 if(distsq < mindist * mindist)
1311 return false;
1314 float maxdist = maxRange + sizefactor;
1315 return distsq < maxdist * maxdist;
1318 bool WorldObject::IsInRange3d(float x, float y, float z, float minRange, float maxRange) const
1320 float dx = GetPositionX() - x;
1321 float dy = GetPositionY() - y;
1322 float dz = GetPositionZ() - z;
1323 float distsq = dx*dx + dy*dy + dz*dz;
1325 float sizefactor = GetObjectSize();
1327 // check only for real range
1328 if(minRange > 0.0f)
1330 float mindist = minRange + sizefactor;
1331 if(distsq < mindist * mindist)
1332 return false;
1335 float maxdist = maxRange + sizefactor;
1336 return distsq < maxdist * maxdist;
1339 float WorldObject::GetAngle(const WorldObject* obj) const
1341 if(!obj) return 0;
1342 return GetAngle( obj->GetPositionX(), obj->GetPositionY() );
1345 // Return angle in range 0..2*pi
1346 float WorldObject::GetAngle( const float x, const float y ) const
1348 float dx = x - GetPositionX();
1349 float dy = y - GetPositionY();
1351 float ang = atan2(dy, dx);
1352 ang = (ang >= 0) ? ang : 2 * M_PI + ang;
1353 return ang;
1356 bool WorldObject::HasInArc(const float arcangle, const WorldObject* obj) const
1358 // always have self in arc
1359 if(obj == this)
1360 return true;
1362 float arc = arcangle;
1364 // move arc to range 0.. 2*pi
1365 while( arc >= 2.0f * M_PI )
1366 arc -= 2.0f * M_PI;
1367 while( arc < 0 )
1368 arc += 2.0f * M_PI;
1370 float angle = GetAngle( obj );
1371 angle -= m_orientation;
1373 // move angle to range -pi ... +pi
1374 while( angle > M_PI)
1375 angle -= 2.0f * M_PI;
1376 while(angle < -M_PI)
1377 angle += 2.0f * M_PI;
1379 float lborder = -1 * (arc/2.0f); // in range -pi..0
1380 float rborder = (arc/2.0f); // in range 0..pi
1381 return (( angle >= lborder ) && ( angle <= rborder ));
1384 bool WorldObject::isInFrontInMap(WorldObject const* target, float distance, float arc) const
1386 return IsWithinDistInMap(target, distance) && HasInArc( arc, target );
1389 bool WorldObject::isInBackInMap(WorldObject const* target, float distance, float arc) const
1391 return IsWithinDistInMap(target, distance) && !HasInArc( 2 * M_PI - arc, target );
1394 bool WorldObject::isInFront(WorldObject const* target, float distance, float arc) const
1396 return IsWithinDist(target, distance) && HasInArc( arc, target );
1399 bool WorldObject::isInBack(WorldObject const* target, float distance, float arc) const
1401 return IsWithinDist(target, distance) && !HasInArc( 2 * M_PI - arc, target );
1404 void WorldObject::GetRandomPoint( float x, float y, float z, float distance, float &rand_x, float &rand_y, float &rand_z) const
1406 if(distance == 0)
1408 rand_x = x;
1409 rand_y = y;
1410 rand_z = z;
1411 return;
1414 // angle to face `obj` to `this`
1415 float angle = rand_norm()*2*M_PI;
1416 float new_dist = rand_norm()*distance;
1418 rand_x = x + new_dist * cos(angle);
1419 rand_y = y + new_dist * sin(angle);
1420 rand_z = z;
1422 MaNGOS::NormalizeMapCoord(rand_x);
1423 MaNGOS::NormalizeMapCoord(rand_y);
1424 UpdateGroundPositionZ(rand_x,rand_y,rand_z); // update to LOS height if available
1427 void WorldObject::UpdateGroundPositionZ(float x, float y, float &z) const
1429 float new_z = GetBaseMap()->GetHeight(x,y,z,true);
1430 if(new_z > INVALID_HEIGHT)
1431 z = new_z+ 0.05f; // just to be sure that we are not a few pixel under the surface
1434 bool WorldObject::IsPositionValid() const
1436 return MaNGOS::IsValidMapCoord(m_positionX,m_positionY,m_positionZ,m_orientation);
1439 void WorldObject::MonsterSay(const char* text, uint32 language, uint64 TargetGuid)
1441 WorldPacket data(SMSG_MESSAGECHAT, 200);
1442 BuildMonsterChat(&data,CHAT_MSG_MONSTER_SAY,text,language,GetName(),TargetGuid);
1443 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
1446 void WorldObject::MonsterYell(const char* text, uint32 language, uint64 TargetGuid)
1448 WorldPacket data(SMSG_MESSAGECHAT, 200);
1449 BuildMonsterChat(&data,CHAT_MSG_MONSTER_YELL,text,language,GetName(),TargetGuid);
1450 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
1453 void WorldObject::MonsterTextEmote(const char* text, uint64 TargetGuid, bool IsBossEmote)
1455 WorldPacket data(SMSG_MESSAGECHAT, 200);
1456 BuildMonsterChat(&data,IsBossEmote ? CHAT_MSG_RAID_BOSS_EMOTE : CHAT_MSG_MONSTER_EMOTE,text,LANG_UNIVERSAL,GetName(),TargetGuid);
1457 SendMessageToSetInRange(&data,sWorld.getConfig(IsBossEmote ? CONFIG_LISTEN_RANGE_YELL : CONFIG_LISTEN_RANGE_TEXTEMOTE),true);
1460 void WorldObject::MonsterWhisper(const char* text, uint64 receiver, bool IsBossWhisper)
1462 Player *player = sObjectMgr.GetPlayer(receiver);
1463 if(!player || !player->GetSession())
1464 return;
1466 WorldPacket data(SMSG_MESSAGECHAT, 200);
1467 BuildMonsterChat(&data,IsBossWhisper ? CHAT_MSG_RAID_BOSS_WHISPER : CHAT_MSG_MONSTER_WHISPER,text,LANG_UNIVERSAL,GetName(),receiver);
1469 player->GetSession()->SendPacket(&data);
1472 namespace MaNGOS
1474 class MonsterChatBuilder
1476 public:
1477 MonsterChatBuilder(WorldObject const& obj, ChatMsg msgtype, int32 textId, uint32 language, uint64 targetGUID)
1478 : i_object(obj), i_msgtype(msgtype), i_textId(textId), i_language(language), i_targetGUID(targetGUID) {}
1479 void operator()(WorldPacket& data, int32 loc_idx)
1481 char const* text = sObjectMgr.GetMangosString(i_textId,loc_idx);
1483 // TODO: i_object.GetName() also must be localized?
1484 i_object.BuildMonsterChat(&data,i_msgtype,text,i_language,i_object.GetNameForLocaleIdx(loc_idx),i_targetGUID);
1487 private:
1488 WorldObject const& i_object;
1489 ChatMsg i_msgtype;
1490 int32 i_textId;
1491 uint32 i_language;
1492 uint64 i_targetGUID;
1494 } // namespace MaNGOS
1496 void WorldObject::MonsterSay(int32 textId, uint32 language, uint64 TargetGuid)
1498 CellPair p = MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY());
1500 Cell cell(p);
1501 cell.data.Part.reserved = ALL_DISTRICT;
1502 cell.SetNoCreate();
1504 MaNGOS::MonsterChatBuilder say_build(*this, CHAT_MSG_MONSTER_SAY, textId,language,TargetGuid);
1505 MaNGOS::LocalizedPacketDo<MaNGOS::MonsterChatBuilder> say_do(say_build);
1506 MaNGOS::PlayerDistWorker<MaNGOS::LocalizedPacketDo<MaNGOS::MonsterChatBuilder> > say_worker(this,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),say_do);
1507 TypeContainerVisitor<MaNGOS::PlayerDistWorker<MaNGOS::LocalizedPacketDo<MaNGOS::MonsterChatBuilder> >, WorldTypeMapContainer > message(say_worker);
1508 cell.Visit(p, message, *GetMap(), *this, sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY));
1511 void WorldObject::MonsterYell(int32 textId, uint32 language, uint64 TargetGuid)
1513 CellPair p = MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY());
1515 Cell cell(p);
1516 cell.data.Part.reserved = ALL_DISTRICT;
1517 cell.SetNoCreate();
1519 float range = sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL);
1521 MaNGOS::MonsterChatBuilder say_build(*this, CHAT_MSG_MONSTER_YELL, textId,language,TargetGuid);
1522 MaNGOS::LocalizedPacketDo<MaNGOS::MonsterChatBuilder> say_do(say_build);
1523 MaNGOS::PlayerDistWorker<MaNGOS::LocalizedPacketDo<MaNGOS::MonsterChatBuilder> > say_worker(this,range,say_do);
1524 TypeContainerVisitor<MaNGOS::PlayerDistWorker<MaNGOS::LocalizedPacketDo<MaNGOS::MonsterChatBuilder> >, WorldTypeMapContainer > message(say_worker);
1525 cell.Visit(p, message, *GetMap(), *this, range);
1528 void WorldObject::MonsterYellToZone(int32 textId, uint32 language, uint64 TargetGuid)
1530 MaNGOS::MonsterChatBuilder say_build(*this, CHAT_MSG_MONSTER_YELL, textId,language,TargetGuid);
1531 MaNGOS::LocalizedPacketDo<MaNGOS::MonsterChatBuilder> say_do(say_build);
1533 uint32 zoneid = GetZoneId();
1535 Map::PlayerList const& pList = GetMap()->GetPlayers();
1536 for(Map::PlayerList::const_iterator itr = pList.begin(); itr != pList.end(); ++itr)
1537 if(itr->getSource()->GetZoneId()==zoneid)
1538 say_do(itr->getSource());
1541 void WorldObject::MonsterTextEmote(int32 textId, uint64 TargetGuid, bool IsBossEmote)
1543 CellPair p = MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY());
1545 Cell cell(p);
1546 cell.data.Part.reserved = ALL_DISTRICT;
1547 cell.SetNoCreate();
1549 float range = sWorld.getConfig(IsBossEmote ? CONFIG_LISTEN_RANGE_YELL : CONFIG_LISTEN_RANGE_TEXTEMOTE);
1551 MaNGOS::MonsterChatBuilder say_build(*this, IsBossEmote ? CHAT_MSG_RAID_BOSS_EMOTE : CHAT_MSG_MONSTER_EMOTE, textId,LANG_UNIVERSAL,TargetGuid);
1552 MaNGOS::LocalizedPacketDo<MaNGOS::MonsterChatBuilder> say_do(say_build);
1553 MaNGOS::PlayerDistWorker<MaNGOS::LocalizedPacketDo<MaNGOS::MonsterChatBuilder> > say_worker(this,range,say_do);
1554 TypeContainerVisitor<MaNGOS::PlayerDistWorker<MaNGOS::LocalizedPacketDo<MaNGOS::MonsterChatBuilder> >, WorldTypeMapContainer > message(say_worker);
1555 cell.Visit(p, message, *GetMap(), *this, range);
1558 void WorldObject::MonsterWhisper(int32 textId, uint64 receiver, bool IsBossWhisper)
1560 Player *player = sObjectMgr.GetPlayer(receiver);
1561 if(!player || !player->GetSession())
1562 return;
1564 uint32 loc_idx = player->GetSession()->GetSessionDbLocaleIndex();
1565 char const* text = sObjectMgr.GetMangosString(textId,loc_idx);
1567 WorldPacket data(SMSG_MESSAGECHAT, 200);
1568 BuildMonsterChat(&data,IsBossWhisper ? CHAT_MSG_RAID_BOSS_WHISPER : CHAT_MSG_MONSTER_WHISPER,text,LANG_UNIVERSAL,GetNameForLocaleIdx(loc_idx),receiver);
1570 player->GetSession()->SendPacket(&data);
1573 void WorldObject::BuildMonsterChat(WorldPacket *data, uint8 msgtype, char const* text, uint32 language, char const* name, uint64 targetGuid) const
1575 *data << (uint8)msgtype;
1576 *data << (uint32)language;
1577 *data << (uint64)GetGUID();
1578 *data << (uint32)0; // 2.1.0
1579 *data << (uint32)(strlen(name)+1);
1580 *data << name;
1581 *data << (uint64)targetGuid; // Unit Target
1582 if( targetGuid && !IS_PLAYER_GUID(targetGuid) )
1584 *data << (uint32)1; // target name length
1585 *data << (uint8)0; // target name
1587 *data << (uint32)(strlen(text)+1);
1588 *data << text;
1589 *data << (uint8)0; // ChatTag
1592 void WorldObject::SendMessageToSet(WorldPacket *data, bool /*bToSelf*/)
1594 //if object is in world, map for it already created!
1595 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
1596 if(_map)
1597 _map->MessageBroadcast(this, data);
1600 void WorldObject::SendMessageToSetInRange(WorldPacket *data, float dist, bool /*bToSelf*/)
1602 //if object is in world, map for it already created!
1603 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
1604 if(_map)
1605 _map->MessageDistBroadcast(this, data, dist);
1608 void WorldObject::SendObjectDeSpawnAnim(uint64 guid)
1610 WorldPacket data(SMSG_GAMEOBJECT_DESPAWN_ANIM, 8);
1611 data << uint64(guid);
1612 SendMessageToSet(&data, true);
1615 void WorldObject::SendGameObjectCustomAnim(uint64 guid)
1617 WorldPacket data(SMSG_GAMEOBJECT_CUSTOM_ANIM, 8+4);
1618 data << uint64(guid);
1619 data << uint32(0); // not known what this is
1620 SendMessageToSet(&data, true);
1623 void WorldObject::SetMap(Map * map)
1625 ASSERT(map);
1626 m_currMap = map;
1627 //lets save current map's Id/instanceId
1628 m_mapId = map->GetId();
1629 m_InstanceId = map->GetInstanceId();
1632 Map const* WorldObject::GetBaseMap() const
1634 ASSERT(m_currMap);
1635 return m_currMap->GetParent();
1638 void WorldObject::AddObjectToRemoveList()
1640 GetMap()->AddObjectToRemoveList(this);
1643 Creature* WorldObject::SummonCreature(uint32 id, float x, float y, float z, float ang,TempSummonType spwtype,uint32 despwtime)
1645 TemporarySummon* pCreature = new TemporarySummon(GetGUID());
1647 uint32 team = 0;
1648 if (GetTypeId()==TYPEID_PLAYER)
1649 team = ((Player*)this)->GetTeam();
1651 if (!pCreature->Create(sObjectMgr.GenerateLowGuid(HIGHGUID_UNIT), GetMap(), GetPhaseMask(), id, team))
1653 delete pCreature;
1654 return NULL;
1657 if (x == 0.0f && y == 0.0f && z == 0.0f)
1658 GetClosePoint(x, y, z, pCreature->GetObjectSize());
1660 pCreature->Relocate(x, y, z, ang);
1661 pCreature->SetSummonPoint(x, y, z, ang);
1663 if(!pCreature->IsPositionValid())
1665 sLog.outError("Creature (guidlow %d, entry %d) not summoned. Suggested coordinates isn't valid (X: %f Y: %f)",pCreature->GetGUIDLow(),pCreature->GetEntry(),pCreature->GetPositionX(),pCreature->GetPositionY());
1666 delete pCreature;
1667 return NULL;
1670 pCreature->Summon(spwtype, despwtime);
1672 if(GetTypeId()==TYPEID_UNIT && ((Creature*)this)->AI())
1673 ((Creature*)this)->AI()->JustSummoned(pCreature);
1675 // return the creature therewith the summoner has access to it
1676 return pCreature;
1679 namespace MaNGOS
1681 class NearUsedPosDo
1683 public:
1684 NearUsedPosDo(WorldObject const& obj, WorldObject const* searcher, float angle, ObjectPosSelector& selector)
1685 : i_object(obj), i_searcher(searcher), i_angle(angle), i_selector(selector) {}
1687 void operator()(Corpse*) const {}
1688 void operator()(DynamicObject*) const {}
1690 void operator()(Creature* c) const
1692 // skip self or target
1693 if(c==i_searcher || c==&i_object)
1694 return;
1696 float x,y,z;
1698 if( !c->isAlive() || c->hasUnitState(UNIT_STAT_NOT_MOVE) ||
1699 !c->GetMotionMaster()->GetDestination(x,y,z) )
1701 x = c->GetPositionX();
1702 y = c->GetPositionY();
1705 add(c,x,y);
1708 template<class T>
1709 void operator()(T* u) const
1711 // skip self or target
1712 if(u==i_searcher || u==&i_object)
1713 return;
1715 float x,y;
1717 x = u->GetPositionX();
1718 y = u->GetPositionY();
1720 add(u,x,y);
1723 // we must add used pos that can fill places around center
1724 void add(WorldObject* u, float x, float y) const
1726 // u is too nearest/far away to i_object
1727 if(!i_object.IsInRange2d(x,y,i_selector.m_dist - i_selector.m_size,i_selector.m_dist + i_selector.m_size))
1728 return;
1730 float angle = i_object.GetAngle(u)-i_angle;
1732 // move angle to range -pi ... +pi
1733 while( angle > M_PI)
1734 angle -= 2.0f * M_PI;
1735 while(angle < -M_PI)
1736 angle += 2.0f * M_PI;
1738 // dist include size of u
1739 float dist2d = i_object.GetDistance2d(x,y);
1740 i_selector.AddUsedPos(u->GetObjectSize(),angle,dist2d + i_object.GetObjectSize());
1742 private:
1743 WorldObject const& i_object;
1744 WorldObject const* i_searcher;
1745 float i_angle;
1746 ObjectPosSelector& i_selector;
1748 } // namespace MaNGOS
1750 //===================================================================================================
1752 void WorldObject::GetNearPoint2D(float &x, float &y, float distance2d, float absAngle ) const
1754 x = GetPositionX() + (GetObjectSize() + distance2d) * cos(absAngle);
1755 y = GetPositionY() + (GetObjectSize() + distance2d) * sin(absAngle);
1757 MaNGOS::NormalizeMapCoord(x);
1758 MaNGOS::NormalizeMapCoord(y);
1761 void WorldObject::GetNearPoint(WorldObject const* searcher, float &x, float &y, float &z, float searcher_size, float distance2d, float absAngle ) const
1763 GetNearPoint2D(x,y,distance2d+searcher_size,absAngle);
1764 z = GetPositionZ();
1766 // if detection disabled, return first point
1767 if(!sWorld.getConfig(CONFIG_DETECT_POS_COLLISION))
1769 UpdateGroundPositionZ(x,y,z); // update to LOS height if available
1770 return;
1773 // or remember first point
1774 float first_x = x;
1775 float first_y = y;
1776 bool first_los_conflict = false; // first point LOS problems
1778 // prepare selector for work
1779 ObjectPosSelector selector(GetPositionX(),GetPositionY(),GetObjectSize(),distance2d+searcher_size);
1781 // adding used positions around object
1783 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
1784 Cell cell(p);
1785 cell.data.Part.reserved = ALL_DISTRICT;
1786 cell.SetNoCreate();
1788 MaNGOS::NearUsedPosDo u_do(*this,searcher,absAngle,selector);
1789 MaNGOS::WorldObjectWorker<MaNGOS::NearUsedPosDo> worker(this,u_do);
1791 TypeContainerVisitor<MaNGOS::WorldObjectWorker<MaNGOS::NearUsedPosDo>, GridTypeMapContainer > grid_obj_worker(worker);
1792 TypeContainerVisitor<MaNGOS::WorldObjectWorker<MaNGOS::NearUsedPosDo>, WorldTypeMapContainer > world_obj_worker(worker);
1794 cell.Visit(p, grid_obj_worker, *GetMap(), *this, distance2d);
1795 cell.Visit(p, world_obj_worker, *GetMap(), *this, distance2d);
1798 // maybe can just place in primary position
1799 if( selector.CheckOriginal() )
1801 UpdateGroundPositionZ(x,y,z); // update to LOS height if available
1803 if(IsWithinLOS(x,y,z))
1804 return;
1806 first_los_conflict = true; // first point have LOS problems
1809 float angle; // candidate of angle for free pos
1811 // special case when one from list empty and then empty side preferred
1812 if(selector.FirstAngle(angle))
1814 GetNearPoint2D(x,y,distance2d,absAngle+angle);
1815 z = GetPositionZ();
1816 UpdateGroundPositionZ(x,y,z); // update to LOS height if available
1818 if(IsWithinLOS(x,y,z))
1819 return;
1822 // set first used pos in lists
1823 selector.InitializeAngle();
1825 // select in positions after current nodes (selection one by one)
1826 while(selector.NextAngle(angle)) // angle for free pos
1828 GetNearPoint2D(x,y,distance2d,absAngle+angle);
1829 z = GetPositionZ();
1830 UpdateGroundPositionZ(x,y,z); // update to LOS height if available
1832 if(IsWithinLOS(x,y,z))
1833 return;
1836 // BAD NEWS: not free pos (or used or have LOS problems)
1837 // Attempt find _used_ pos without LOS problem
1839 if(!first_los_conflict)
1841 x = first_x;
1842 y = first_y;
1844 UpdateGroundPositionZ(x,y,z); // update to LOS height if available
1845 return;
1848 // special case when one from list empty and then empty side preferred
1849 if( selector.IsNonBalanced() )
1851 if(!selector.FirstAngle(angle)) // _used_ pos
1853 GetNearPoint2D(x,y,distance2d,absAngle+angle);
1854 z = GetPositionZ();
1855 UpdateGroundPositionZ(x,y,z); // update to LOS height if available
1857 if(IsWithinLOS(x,y,z))
1858 return;
1862 // set first used pos in lists
1863 selector.InitializeAngle();
1865 // select in positions after current nodes (selection one by one)
1866 while(selector.NextUsedAngle(angle)) // angle for used pos but maybe without LOS problem
1868 GetNearPoint2D(x,y,distance2d,absAngle+angle);
1869 z = GetPositionZ();
1870 UpdateGroundPositionZ(x,y,z); // update to LOS height if available
1872 if(IsWithinLOS(x,y,z))
1873 return;
1876 // BAD BAD NEWS: all found pos (free and used) have LOS problem :(
1877 x = first_x;
1878 y = first_y;
1880 UpdateGroundPositionZ(x,y,z); // update to LOS height if available
1883 void WorldObject::SetPhaseMask(uint32 newPhaseMask, bool update)
1885 m_phaseMask = newPhaseMask;
1887 if(update && IsInWorld())
1888 UpdateObjectVisibility();
1891 void WorldObject::PlayDistanceSound( uint32 sound_id, Player* target /*= NULL*/ )
1893 WorldPacket data(SMSG_PLAY_OBJECT_SOUND,4+8);
1894 data << uint32(sound_id);
1895 data << uint64(GetGUID());
1896 if (target)
1897 target->SendDirectMessage( &data );
1898 else
1899 SendMessageToSet( &data, true );
1902 void WorldObject::PlayDirectSound( uint32 sound_id, Player* target /*= NULL*/ )
1904 WorldPacket data(SMSG_PLAY_SOUND, 4);
1905 data << uint32(sound_id);
1906 if (target)
1907 target->SendDirectMessage( &data );
1908 else
1909 SendMessageToSet( &data, true );
1912 void WorldObject::UpdateObjectVisibility()
1914 CellPair p = MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY());
1915 Cell cell(p);
1917 GetMap()->UpdateObjectVisibility(this, cell, p);
1920 void WorldObject::AddToClientUpdateList()
1922 GetMap()->AddUpdateObject(this);
1925 void WorldObject::RemoveFromClientUpdateList()
1927 GetMap()->RemoveUpdateObject(this);
1930 struct WorldObjectChangeAccumulator
1932 UpdateDataMapType &i_updateDatas;
1933 WorldObject &i_object;
1934 WorldObjectChangeAccumulator(WorldObject &obj, UpdateDataMapType &d) : i_updateDatas(d), i_object(obj) {}
1935 void Visit(PlayerMapType &m)
1937 for(PlayerMapType::iterator iter = m.begin(); iter != m.end(); ++iter)
1938 if(iter->getSource()->HaveAtClient(&i_object))
1939 i_object.BuildUpdateDataForPlayer(iter->getSource(), i_updateDatas);
1942 template<class SKIP> void Visit(GridRefManager<SKIP> &) {}
1945 void WorldObject::BuildUpdateData( UpdateDataMapType & update_players)
1947 CellPair p = MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY());
1948 Cell cell(p);
1949 cell.data.Part.reserved = ALL_DISTRICT;
1950 cell.SetNoCreate();
1951 WorldObjectChangeAccumulator notifier(*this, update_players);
1952 TypeContainerVisitor<WorldObjectChangeAccumulator, WorldTypeMapContainer > player_notifier(notifier);
1953 Map* aMap = GetMap();
1954 //we must build packets for all visible players
1955 cell.Visit(p, player_notifier, *aMap, *this, aMap->GetVisibilityDistance());
1957 ClearUpdateMask(false);