[9545] Rename ObjectDefines.h -> ObjectGuid.h
[getmangos.git] / src / game / Object.cpp
blob5dea8a5f1ededcabc17a574b8bed10801aaed8b4
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 "ObjectGuid.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_ROOT);
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_SPLINE_ENABLED);
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_SPLINE_ENABLED);
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_SPLINE_ENABLED)
333 if(GetTypeId() != TYPEID_PLAYER)
335 sLog.outDebug("_BuildMovementUpdate: MOVEFLAG_SPLINE_ENABLED for non-player");
336 return;
339 Player *player = ((Player*)unit);
341 if(!player->isInFlight())
343 sLog.outDebug("_BuildMovementUpdate: MOVEFLAG_SPLINE_ENABLED but not in flight");
344 return;
347 ASSERT(player->GetMotionMaster()->GetCurrentMovementGeneratorType() == FLIGHT_MOTION_TYPE);
349 FlightPathMovementGenerator *fmg = (FlightPathMovementGenerator*)(player->GetMotionMaster()->top());
351 uint32 flags3 = SPLINEFLAG_WALKMODE | SPLINEFLAG_FLYING;
353 *data << uint32(flags3); // splines flag?
355 if(flags3 & SPLINEFLAG_FINALFACING) // may be orientation
357 *data << float(0);
359 else
361 if(flags3 & SPLINEFLAG_FINALTARGET) // probably guid there
363 *data << uint64(0);
365 else
367 if(flags3 & SPLINEFLAG_FINALPOINT) // 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(((WorldObject*)this)->GetOrientation());
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 ]);
641 // there are some float values which may be negative or can't get negative due to other checks
642 else if ((index >= UNIT_FIELD_NEGSTAT0 && index <= UNIT_FIELD_NEGSTAT4) ||
643 (index >= UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE && index <= (UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE + 6)) ||
644 (index >= UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE && index <= (UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE + 6)) ||
645 (index >= UNIT_FIELD_POSSTAT0 && index <= UNIT_FIELD_POSSTAT4))
647 *data << uint32(m_floatValues[ index ]);
650 // Gamemasters should be always able to select units - remove not selectable flag
651 else if(index == UNIT_FIELD_FLAGS && target->isGameMaster())
653 *data << (m_uint32Values[ index ] & ~UNIT_FLAG_NOT_SELECTABLE);
655 // hide lootable animation for unallowed players
656 else if(index == UNIT_DYNAMIC_FLAGS && GetTypeId() == TYPEID_UNIT)
658 if(!target->isAllowedToLoot((Creature*)this))
659 *data << (m_uint32Values[ index ] & ~UNIT_DYNFLAG_LOOTABLE);
660 else
661 *data << (m_uint32Values[ index ] & ~UNIT_DYNFLAG_TAPPED);
663 else
665 // send in current format (float as float, uint32 as uint32)
666 *data << m_uint32Values[ index ];
671 else if(isType(TYPEMASK_GAMEOBJECT)) // gameobject case
673 for( uint16 index = 0; index < m_valuesCount; ++index )
675 if( updateMask->GetBit( index ) )
677 // send in current format (float as float, uint32 as uint32)
678 if ( index == GAMEOBJECT_DYNAMIC )
680 if(IsActivateToQuest )
682 switch(((GameObject*)this)->GetGoType())
684 case GAMEOBJECT_TYPE_CHEST:
685 // enable quest object. Represent 9, but 1 for client before 2.3.0
686 *data << uint16(9);
687 *data << uint16(-1);
688 break;
689 case GAMEOBJECT_TYPE_GOOBER:
690 *data << uint16(1);
691 *data << uint16(-1);
692 break;
693 default:
694 // unknown, not happen.
695 *data << uint16(0);
696 *data << uint16(-1);
697 break;
700 else
702 // disable quest object
703 *data << uint16(0);
704 *data << uint16(-1);
707 else
708 *data << m_uint32Values[ index ]; // other cases
712 else // other objects case (no special index checks)
714 for( uint16 index = 0; index < m_valuesCount; ++index )
716 if( updateMask->GetBit( index ) )
718 // send in current format (float as float, uint32 as uint32)
719 *data << m_uint32Values[ index ];
725 void Object::ClearUpdateMask(bool remove)
727 if(m_uint32Values)
729 for( uint16 index = 0; index < m_valuesCount; ++index )
731 if(m_uint32Values_mirror[index]!= m_uint32Values[index])
732 m_uint32Values_mirror[index] = m_uint32Values[index];
736 if(m_objectUpdated)
738 if(remove)
739 RemoveFromClientUpdateList();
740 m_objectUpdated = false;
744 bool Object::LoadValues(const char* data)
746 if(!m_uint32Values) _InitValues();
748 Tokens tokens = StrSplit(data, " ");
750 if(tokens.size() != m_valuesCount)
751 return false;
753 Tokens::iterator iter;
754 int index;
755 for (iter = tokens.begin(), index = 0; index < m_valuesCount; ++iter, ++index)
757 m_uint32Values[index] = atol((*iter).c_str());
760 return true;
763 void Object::_SetUpdateBits(UpdateMask *updateMask, Player* /*target*/) const
765 for( uint16 index = 0; index < m_valuesCount; ++index )
767 if(m_uint32Values_mirror[index]!= m_uint32Values[index])
768 updateMask->SetBit(index);
772 void Object::_SetCreateBits(UpdateMask *updateMask, Player* /*target*/) const
774 for( uint16 index = 0; index < m_valuesCount; ++index )
776 if(GetUInt32Value(index) != 0)
777 updateMask->SetBit(index);
781 void Object::SetInt32Value( uint16 index, int32 value )
783 ASSERT( index < m_valuesCount || PrintIndexError( index, true ) );
785 if(m_int32Values[ index ] != value)
787 m_int32Values[ index ] = value;
789 if(m_inWorld)
791 if(!m_objectUpdated)
793 AddToClientUpdateList();
794 m_objectUpdated = true;
800 void Object::SetUInt32Value( uint16 index, uint32 value )
802 ASSERT( index < m_valuesCount || PrintIndexError( index, true ) );
804 if(m_uint32Values[ index ] != value)
806 m_uint32Values[ index ] = value;
808 if(m_inWorld)
810 if(!m_objectUpdated)
812 AddToClientUpdateList();
813 m_objectUpdated = true;
819 void Object::SetUInt64Value( uint16 index, const uint64 &value )
821 ASSERT( index + 1 < m_valuesCount || PrintIndexError( index, true ) );
822 if(*((uint64*)&(m_uint32Values[ index ])) != value)
824 m_uint32Values[ index ] = *((uint32*)&value);
825 m_uint32Values[ index + 1 ] = *(((uint32*)&value) + 1);
827 if(m_inWorld)
829 if(!m_objectUpdated)
831 AddToClientUpdateList();
832 m_objectUpdated = true;
838 void Object::SetFloatValue( uint16 index, float value )
840 ASSERT( index < m_valuesCount || PrintIndexError( index, true ) );
842 if(m_floatValues[ index ] != value)
844 m_floatValues[ index ] = value;
846 if(m_inWorld)
848 if(!m_objectUpdated)
850 AddToClientUpdateList();
851 m_objectUpdated = true;
857 void Object::SetByteValue( uint16 index, uint8 offset, uint8 value )
859 ASSERT( index < m_valuesCount || PrintIndexError( index, true ) );
861 if(offset > 4)
863 sLog.outError("Object::SetByteValue: wrong offset %u", offset);
864 return;
867 if(uint8(m_uint32Values[ index ] >> (offset * 8)) != value)
869 m_uint32Values[ index ] &= ~uint32(uint32(0xFF) << (offset * 8));
870 m_uint32Values[ index ] |= uint32(uint32(value) << (offset * 8));
872 if(m_inWorld)
874 if(!m_objectUpdated)
876 AddToClientUpdateList();
877 m_objectUpdated = true;
883 void Object::SetUInt16Value( uint16 index, uint8 offset, uint16 value )
885 ASSERT( index < m_valuesCount || PrintIndexError( index, true ) );
887 if(offset > 2)
889 sLog.outError("Object::SetUInt16Value: wrong offset %u", offset);
890 return;
893 if(uint16(m_uint32Values[ index ] >> (offset * 16)) != value)
895 m_uint32Values[ index ] &= ~uint32(uint32(0xFFFF) << (offset * 16));
896 m_uint32Values[ index ] |= uint32(uint32(value) << (offset * 16));
898 if(m_inWorld)
900 if(!m_objectUpdated)
902 AddToClientUpdateList();
903 m_objectUpdated = true;
909 void Object::SetStatFloatValue( uint16 index, float value)
911 if(value < 0)
912 value = 0.0f;
914 SetFloatValue(index, value);
917 void Object::SetStatInt32Value( uint16 index, int32 value)
919 if(value < 0)
920 value = 0;
922 SetUInt32Value(index, uint32(value));
925 void Object::ApplyModUInt32Value(uint16 index, int32 val, bool apply)
927 int32 cur = GetUInt32Value(index);
928 cur += (apply ? val : -val);
929 if(cur < 0)
930 cur = 0;
931 SetUInt32Value(index, cur);
934 void Object::ApplyModInt32Value(uint16 index, int32 val, bool apply)
936 int32 cur = GetInt32Value(index);
937 cur += (apply ? val : -val);
938 SetInt32Value(index, cur);
941 void Object::ApplyModSignedFloatValue(uint16 index, float val, bool apply)
943 float cur = GetFloatValue(index);
944 cur += (apply ? val : -val);
945 SetFloatValue(index, cur);
948 void Object::ApplyModPositiveFloatValue(uint16 index, float val, bool apply)
950 float cur = GetFloatValue(index);
951 cur += (apply ? val : -val);
952 if(cur < 0)
953 cur = 0;
954 SetFloatValue(index, cur);
957 void Object::SetFlag( uint16 index, uint32 newFlag )
959 ASSERT( index < m_valuesCount || PrintIndexError( index, true ) );
960 uint32 oldval = m_uint32Values[ index ];
961 uint32 newval = oldval | newFlag;
963 if(oldval != newval)
965 m_uint32Values[ index ] = newval;
967 if(m_inWorld)
969 if(!m_objectUpdated)
971 AddToClientUpdateList();
972 m_objectUpdated = true;
978 void Object::RemoveFlag( uint16 index, uint32 oldFlag )
980 ASSERT( index < m_valuesCount || PrintIndexError( index, true ) );
981 uint32 oldval = m_uint32Values[ index ];
982 uint32 newval = oldval & ~oldFlag;
984 if(oldval != newval)
986 m_uint32Values[ index ] = newval;
988 if(m_inWorld)
990 if(!m_objectUpdated)
992 AddToClientUpdateList();
993 m_objectUpdated = true;
999 void Object::SetByteFlag( uint16 index, uint8 offset, uint8 newFlag )
1001 ASSERT( index < m_valuesCount || PrintIndexError( index, true ) );
1003 if(offset > 4)
1005 sLog.outError("Object::SetByteFlag: wrong offset %u", offset);
1006 return;
1009 if(!(uint8(m_uint32Values[ index ] >> (offset * 8)) & newFlag))
1011 m_uint32Values[ index ] |= uint32(uint32(newFlag) << (offset * 8));
1013 if(m_inWorld)
1015 if(!m_objectUpdated)
1017 AddToClientUpdateList();
1018 m_objectUpdated = true;
1024 void Object::RemoveByteFlag( uint16 index, uint8 offset, uint8 oldFlag )
1026 ASSERT( index < m_valuesCount || PrintIndexError( index, true ) );
1028 if(offset > 4)
1030 sLog.outError("Object::RemoveByteFlag: wrong offset %u", offset);
1031 return;
1034 if(uint8(m_uint32Values[ index ] >> (offset * 8)) & oldFlag)
1036 m_uint32Values[ index ] &= ~uint32(uint32(oldFlag) << (offset * 8));
1038 if(m_inWorld)
1040 if(!m_objectUpdated)
1042 AddToClientUpdateList();
1043 m_objectUpdated = true;
1049 bool Object::PrintIndexError(uint32 index, bool set) const
1051 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);
1053 // assert must fail after function call
1054 return false;
1057 void Object::BuildUpdateDataForPlayer(Player* pl, UpdateDataMapType& update_players)
1059 UpdateDataMapType::iterator iter = update_players.find(pl);
1061 if (iter == update_players.end())
1063 std::pair<UpdateDataMapType::iterator, bool> p = update_players.insert( UpdateDataMapType::value_type(pl, UpdateData()) );
1064 assert(p.second);
1065 iter = p.first;
1068 BuildValuesUpdateBlockForPlayer(&iter->second, iter->first);
1071 void Object::AddToClientUpdateList()
1073 sLog.outError("Unexpected call of Object::AddToClientUpdateList for object (TypeId: %u Update fields: %u)",GetTypeId(), m_valuesCount);
1074 ASSERT(false);
1077 void Object::RemoveFromClientUpdateList()
1079 sLog.outError("Unexpected call of Object::RemoveFromClientUpdateList for object (TypeId: %u Update fields: %u)",GetTypeId(), m_valuesCount);
1080 ASSERT(false);
1083 void Object::BuildUpdateData( UpdateDataMapType& /*update_players */)
1085 sLog.outError("Unexpected call of Object::BuildUpdateData for object (TypeId: %u Update fields: %u)",GetTypeId(), m_valuesCount);
1086 ASSERT(false);
1089 WorldObject::WorldObject()
1090 : m_currMap(NULL), m_mapId(0), m_InstanceId(0), m_phaseMask(PHASEMASK_NORMAL),
1091 m_positionX(0.0f), m_positionY(0.0f), m_positionZ(0.0f), m_orientation(0.0f)
1095 void WorldObject::CleanupsBeforeDelete()
1097 RemoveFromWorld();
1100 void WorldObject::_Create( uint32 guidlow, HighGuid guidhigh, uint32 phaseMask )
1102 Object::_Create(guidlow, 0, guidhigh);
1103 m_phaseMask = phaseMask;
1106 void WorldObject::Relocate(float x, float y, float z, float orientation)
1108 m_positionX = x;
1109 m_positionY = y;
1110 m_positionZ = z;
1111 m_orientation = orientation;
1113 if(isType(TYPEMASK_UNIT))
1114 ((Unit*)this)->m_movementInfo.ChangePosition(x, y, z, orientation);
1117 void WorldObject::Relocate(float x, float y, float z)
1119 m_positionX = x;
1120 m_positionY = y;
1121 m_positionZ = z;
1123 if(isType(TYPEMASK_UNIT))
1124 ((Unit*)this)->m_movementInfo.ChangePosition(x, y, z, GetOrientation());
1127 uint32 WorldObject::GetZoneId() const
1129 return GetBaseMap()->GetZoneId(m_positionX, m_positionY, m_positionZ);
1132 uint32 WorldObject::GetAreaId() const
1134 return GetBaseMap()->GetAreaId(m_positionX, m_positionY, m_positionZ);
1137 void WorldObject::GetZoneAndAreaId(uint32& zoneid, uint32& areaid) const
1139 GetBaseMap()->GetZoneAndAreaId(zoneid, areaid, m_positionX, m_positionY, m_positionZ);
1142 InstanceData* WorldObject::GetInstanceData()
1144 Map *map = GetMap();
1145 return map->IsDungeon() ? ((InstanceMap*)map)->GetInstanceData() : NULL;
1148 //slow
1149 float WorldObject::GetDistance(const WorldObject* obj) const
1151 float dx = GetPositionX() - obj->GetPositionX();
1152 float dy = GetPositionY() - obj->GetPositionY();
1153 float dz = GetPositionZ() - obj->GetPositionZ();
1154 float sizefactor = GetObjectSize() + obj->GetObjectSize();
1155 float dist = sqrt((dx*dx) + (dy*dy) + (dz*dz)) - sizefactor;
1156 return ( dist > 0 ? dist : 0);
1159 float WorldObject::GetDistance2d(float x, float y) const
1161 float dx = GetPositionX() - x;
1162 float dy = GetPositionY() - y;
1163 float sizefactor = GetObjectSize();
1164 float dist = sqrt((dx*dx) + (dy*dy)) - sizefactor;
1165 return ( dist > 0 ? dist : 0);
1168 float WorldObject::GetDistance(float x, float y, float z) const
1170 float dx = GetPositionX() - x;
1171 float dy = GetPositionY() - y;
1172 float dz = GetPositionZ() - z;
1173 float sizefactor = GetObjectSize();
1174 float dist = sqrt((dx*dx) + (dy*dy) + (dz*dz)) - sizefactor;
1175 return ( dist > 0 ? dist : 0);
1178 float WorldObject::GetDistance2d(const WorldObject* obj) const
1180 float dx = GetPositionX() - obj->GetPositionX();
1181 float dy = GetPositionY() - obj->GetPositionY();
1182 float sizefactor = GetObjectSize() + obj->GetObjectSize();
1183 float dist = sqrt((dx*dx) + (dy*dy)) - sizefactor;
1184 return ( dist > 0 ? dist : 0);
1187 float WorldObject::GetDistanceZ(const WorldObject* obj) const
1189 float dz = fabs(GetPositionZ() - obj->GetPositionZ());
1190 float sizefactor = GetObjectSize() + obj->GetObjectSize();
1191 float dist = dz - sizefactor;
1192 return ( dist > 0 ? dist : 0);
1195 bool WorldObject::IsWithinDist3d(float x, float y, float z, float dist2compare) const
1197 float dx = GetPositionX() - x;
1198 float dy = GetPositionY() - y;
1199 float dz = GetPositionZ() - z;
1200 float distsq = dx*dx + dy*dy + dz*dz;
1202 float sizefactor = GetObjectSize();
1203 float maxdist = dist2compare + sizefactor;
1205 return distsq < maxdist * maxdist;
1208 bool WorldObject::IsWithinDist2d(float x, float y, float dist2compare) const
1210 float dx = GetPositionX() - x;
1211 float dy = GetPositionY() - y;
1212 float distsq = dx*dx + dy*dy;
1214 float sizefactor = GetObjectSize();
1215 float maxdist = dist2compare + sizefactor;
1217 return distsq < maxdist * maxdist;
1220 bool WorldObject::_IsWithinDist(WorldObject const* obj, float dist2compare, bool is3D) const
1222 float dx = GetPositionX() - obj->GetPositionX();
1223 float dy = GetPositionY() - obj->GetPositionY();
1224 float distsq = dx*dx + dy*dy;
1225 if(is3D)
1227 float dz = GetPositionZ() - obj->GetPositionZ();
1228 distsq += dz*dz;
1230 float sizefactor = GetObjectSize() + obj->GetObjectSize();
1231 float maxdist = dist2compare + sizefactor;
1233 return distsq < maxdist * maxdist;
1236 bool WorldObject::IsWithinLOSInMap(const WorldObject* obj) const
1238 if (!IsInMap(obj)) return false;
1239 float ox,oy,oz;
1240 obj->GetPosition(ox,oy,oz);
1241 return(IsWithinLOS(ox, oy, oz ));
1244 bool WorldObject::IsWithinLOS(float ox, float oy, float oz) const
1246 float x,y,z;
1247 GetPosition(x,y,z);
1248 VMAP::IVMapManager *vMapManager = VMAP::VMapFactory::createOrGetVMapManager();
1249 return vMapManager->isInLineOfSight(GetMapId(), x, y, z+2.0f, ox, oy, oz+2.0f);
1252 bool WorldObject::GetDistanceOrder(WorldObject const* obj1, WorldObject const* obj2, bool is3D /* = true */) const
1254 float dx1 = GetPositionX() - obj1->GetPositionX();
1255 float dy1 = GetPositionY() - obj1->GetPositionY();
1256 float distsq1 = dx1*dx1 + dy1*dy1;
1257 if(is3D)
1259 float dz1 = GetPositionZ() - obj1->GetPositionZ();
1260 distsq1 += dz1*dz1;
1263 float dx2 = GetPositionX() - obj2->GetPositionX();
1264 float dy2 = GetPositionY() - obj2->GetPositionY();
1265 float distsq2 = dx2*dx2 + dy2*dy2;
1266 if(is3D)
1268 float dz2 = GetPositionZ() - obj2->GetPositionZ();
1269 distsq2 += dz2*dz2;
1272 return distsq1 < distsq2;
1275 bool WorldObject::IsInRange(WorldObject const* obj, float minRange, float maxRange, bool is3D /* = true */) const
1277 float dx = GetPositionX() - obj->GetPositionX();
1278 float dy = GetPositionY() - obj->GetPositionY();
1279 float distsq = dx*dx + dy*dy;
1280 if(is3D)
1282 float dz = GetPositionZ() - obj->GetPositionZ();
1283 distsq += dz*dz;
1286 float sizefactor = GetObjectSize() + obj->GetObjectSize();
1288 // check only for real range
1289 if(minRange > 0.0f)
1291 float mindist = minRange + sizefactor;
1292 if(distsq < mindist * mindist)
1293 return false;
1296 float maxdist = maxRange + sizefactor;
1297 return distsq < maxdist * maxdist;
1300 bool WorldObject::IsInRange2d(float x, float y, float minRange, float maxRange) const
1302 float dx = GetPositionX() - x;
1303 float dy = GetPositionY() - y;
1304 float distsq = dx*dx + dy*dy;
1306 float sizefactor = GetObjectSize();
1308 // check only for real range
1309 if(minRange > 0.0f)
1311 float mindist = minRange + sizefactor;
1312 if(distsq < mindist * mindist)
1313 return false;
1316 float maxdist = maxRange + sizefactor;
1317 return distsq < maxdist * maxdist;
1320 bool WorldObject::IsInRange3d(float x, float y, float z, float minRange, float maxRange) const
1322 float dx = GetPositionX() - x;
1323 float dy = GetPositionY() - y;
1324 float dz = GetPositionZ() - z;
1325 float distsq = dx*dx + dy*dy + dz*dz;
1327 float sizefactor = GetObjectSize();
1329 // check only for real range
1330 if(minRange > 0.0f)
1332 float mindist = minRange + sizefactor;
1333 if(distsq < mindist * mindist)
1334 return false;
1337 float maxdist = maxRange + sizefactor;
1338 return distsq < maxdist * maxdist;
1341 float WorldObject::GetAngle(const WorldObject* obj) const
1343 if(!obj) return 0;
1344 return GetAngle( obj->GetPositionX(), obj->GetPositionY() );
1347 // Return angle in range 0..2*pi
1348 float WorldObject::GetAngle( const float x, const float y ) const
1350 float dx = x - GetPositionX();
1351 float dy = y - GetPositionY();
1353 float ang = atan2(dy, dx);
1354 ang = (ang >= 0) ? ang : 2 * M_PI_F + ang;
1355 return ang;
1358 bool WorldObject::HasInArc(const float arcangle, const WorldObject* obj) const
1360 // always have self in arc
1361 if(obj == this)
1362 return true;
1364 float arc = arcangle;
1366 // move arc to range 0.. 2*pi
1367 while( arc >= 2.0f * M_PI_F )
1368 arc -= 2.0f * M_PI_F;
1369 while( arc < 0 )
1370 arc += 2.0f * M_PI_F;
1372 float angle = GetAngle( obj );
1373 angle -= m_orientation;
1375 // move angle to range -pi ... +pi
1376 while( angle > M_PI_F)
1377 angle -= 2.0f * M_PI_F;
1378 while(angle < -M_PI_F)
1379 angle += 2.0f * M_PI_F;
1381 float lborder = -1 * (arc/2.0f); // in range -pi..0
1382 float rborder = (arc/2.0f); // in range 0..pi
1383 return (( angle >= lborder ) && ( angle <= rborder ));
1386 bool WorldObject::isInFrontInMap(WorldObject const* target, float distance, float arc) const
1388 return IsWithinDistInMap(target, distance) && HasInArc( arc, target );
1391 bool WorldObject::isInBackInMap(WorldObject const* target, float distance, float arc) const
1393 return IsWithinDistInMap(target, distance) && !HasInArc( 2 * M_PI_F - arc, target );
1396 bool WorldObject::isInFront(WorldObject const* target, float distance, float arc) const
1398 return IsWithinDist(target, distance) && HasInArc( arc, target );
1401 bool WorldObject::isInBack(WorldObject const* target, float distance, float arc) const
1403 return IsWithinDist(target, distance) && !HasInArc( 2 * M_PI_F - arc, target );
1406 void WorldObject::GetRandomPoint( float x, float y, float z, float distance, float &rand_x, float &rand_y, float &rand_z) const
1408 if(distance == 0)
1410 rand_x = x;
1411 rand_y = y;
1412 rand_z = z;
1413 return;
1416 // angle to face `obj` to `this`
1417 float angle = rand_norm_f()*2*M_PI_F;
1418 float new_dist = rand_norm_f()*distance;
1420 rand_x = x + new_dist * cos(angle);
1421 rand_y = y + new_dist * sin(angle);
1422 rand_z = z;
1424 MaNGOS::NormalizeMapCoord(rand_x);
1425 MaNGOS::NormalizeMapCoord(rand_y);
1426 UpdateGroundPositionZ(rand_x,rand_y,rand_z); // update to LOS height if available
1429 void WorldObject::UpdateGroundPositionZ(float x, float y, float &z) const
1431 float new_z = GetBaseMap()->GetHeight(x,y,z,true);
1432 if(new_z > INVALID_HEIGHT)
1433 z = new_z+ 0.05f; // just to be sure that we are not a few pixel under the surface
1436 bool WorldObject::IsPositionValid() const
1438 return MaNGOS::IsValidMapCoord(m_positionX,m_positionY,m_positionZ,m_orientation);
1441 void WorldObject::MonsterSay(const char* text, uint32 language, uint64 TargetGuid)
1443 WorldPacket data(SMSG_MESSAGECHAT, 200);
1444 BuildMonsterChat(&data,CHAT_MSG_MONSTER_SAY,text,language,GetName(),TargetGuid);
1445 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_FLOAT_LISTEN_RANGE_SAY),true);
1448 void WorldObject::MonsterYell(const char* text, uint32 language, uint64 TargetGuid)
1450 WorldPacket data(SMSG_MESSAGECHAT, 200);
1451 BuildMonsterChat(&data,CHAT_MSG_MONSTER_YELL,text,language,GetName(),TargetGuid);
1452 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_FLOAT_LISTEN_RANGE_YELL),true);
1455 void WorldObject::MonsterTextEmote(const char* text, uint64 TargetGuid, bool IsBossEmote)
1457 WorldPacket data(SMSG_MESSAGECHAT, 200);
1458 BuildMonsterChat(&data,IsBossEmote ? CHAT_MSG_RAID_BOSS_EMOTE : CHAT_MSG_MONSTER_EMOTE,text,LANG_UNIVERSAL,GetName(),TargetGuid);
1459 SendMessageToSetInRange(&data,sWorld.getConfig(IsBossEmote ? CONFIG_FLOAT_LISTEN_RANGE_YELL : CONFIG_FLOAT_LISTEN_RANGE_TEXTEMOTE),true);
1462 void WorldObject::MonsterWhisper(const char* text, uint64 receiver, bool IsBossWhisper)
1464 Player *player = sObjectMgr.GetPlayer(receiver);
1465 if(!player || !player->GetSession())
1466 return;
1468 WorldPacket data(SMSG_MESSAGECHAT, 200);
1469 BuildMonsterChat(&data,IsBossWhisper ? CHAT_MSG_RAID_BOSS_WHISPER : CHAT_MSG_MONSTER_WHISPER,text,LANG_UNIVERSAL,GetName(),receiver);
1471 player->GetSession()->SendPacket(&data);
1474 namespace MaNGOS
1476 class MonsterChatBuilder
1478 public:
1479 MonsterChatBuilder(WorldObject const& obj, ChatMsg msgtype, int32 textId, uint32 language, uint64 targetGUID)
1480 : i_object(obj), i_msgtype(msgtype), i_textId(textId), i_language(language), i_targetGUID(targetGUID) {}
1481 void operator()(WorldPacket& data, int32 loc_idx)
1483 char const* text = sObjectMgr.GetMangosString(i_textId,loc_idx);
1485 // TODO: i_object.GetName() also must be localized?
1486 i_object.BuildMonsterChat(&data,i_msgtype,text,i_language,i_object.GetNameForLocaleIdx(loc_idx),i_targetGUID);
1489 private:
1490 WorldObject const& i_object;
1491 ChatMsg i_msgtype;
1492 int32 i_textId;
1493 uint32 i_language;
1494 uint64 i_targetGUID;
1496 } // namespace MaNGOS
1498 void WorldObject::MonsterSay(int32 textId, uint32 language, uint64 TargetGuid)
1500 CellPair p = MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY());
1502 Cell cell(p);
1503 cell.data.Part.reserved = ALL_DISTRICT;
1504 cell.SetNoCreate();
1506 MaNGOS::MonsterChatBuilder say_build(*this, CHAT_MSG_MONSTER_SAY, textId,language,TargetGuid);
1507 MaNGOS::LocalizedPacketDo<MaNGOS::MonsterChatBuilder> say_do(say_build);
1508 MaNGOS::PlayerDistWorker<MaNGOS::LocalizedPacketDo<MaNGOS::MonsterChatBuilder> > say_worker(this,sWorld.getConfig(CONFIG_FLOAT_LISTEN_RANGE_SAY),say_do);
1509 TypeContainerVisitor<MaNGOS::PlayerDistWorker<MaNGOS::LocalizedPacketDo<MaNGOS::MonsterChatBuilder> >, WorldTypeMapContainer > message(say_worker);
1510 cell.Visit(p, message, *GetMap(), *this, sWorld.getConfig(CONFIG_FLOAT_LISTEN_RANGE_SAY));
1513 void WorldObject::MonsterYell(int32 textId, uint32 language, uint64 TargetGuid)
1515 CellPair p = MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY());
1517 Cell cell(p);
1518 cell.data.Part.reserved = ALL_DISTRICT;
1519 cell.SetNoCreate();
1521 float range = sWorld.getConfig(CONFIG_FLOAT_LISTEN_RANGE_YELL);
1523 MaNGOS::MonsterChatBuilder say_build(*this, CHAT_MSG_MONSTER_YELL, textId,language,TargetGuid);
1524 MaNGOS::LocalizedPacketDo<MaNGOS::MonsterChatBuilder> say_do(say_build);
1525 MaNGOS::PlayerDistWorker<MaNGOS::LocalizedPacketDo<MaNGOS::MonsterChatBuilder> > say_worker(this,range,say_do);
1526 TypeContainerVisitor<MaNGOS::PlayerDistWorker<MaNGOS::LocalizedPacketDo<MaNGOS::MonsterChatBuilder> >, WorldTypeMapContainer > message(say_worker);
1527 cell.Visit(p, message, *GetMap(), *this, range);
1530 void WorldObject::MonsterYellToZone(int32 textId, uint32 language, uint64 TargetGuid)
1532 MaNGOS::MonsterChatBuilder say_build(*this, CHAT_MSG_MONSTER_YELL, textId,language,TargetGuid);
1533 MaNGOS::LocalizedPacketDo<MaNGOS::MonsterChatBuilder> say_do(say_build);
1535 uint32 zoneid = GetZoneId();
1537 Map::PlayerList const& pList = GetMap()->GetPlayers();
1538 for(Map::PlayerList::const_iterator itr = pList.begin(); itr != pList.end(); ++itr)
1539 if(itr->getSource()->GetZoneId()==zoneid)
1540 say_do(itr->getSource());
1543 void WorldObject::MonsterTextEmote(int32 textId, uint64 TargetGuid, bool IsBossEmote)
1545 CellPair p = MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY());
1547 Cell cell(p);
1548 cell.data.Part.reserved = ALL_DISTRICT;
1549 cell.SetNoCreate();
1551 float range = sWorld.getConfig(IsBossEmote ? CONFIG_FLOAT_LISTEN_RANGE_YELL : CONFIG_FLOAT_LISTEN_RANGE_TEXTEMOTE);
1553 MaNGOS::MonsterChatBuilder say_build(*this, IsBossEmote ? CHAT_MSG_RAID_BOSS_EMOTE : CHAT_MSG_MONSTER_EMOTE, textId,LANG_UNIVERSAL,TargetGuid);
1554 MaNGOS::LocalizedPacketDo<MaNGOS::MonsterChatBuilder> say_do(say_build);
1555 MaNGOS::PlayerDistWorker<MaNGOS::LocalizedPacketDo<MaNGOS::MonsterChatBuilder> > say_worker(this,range,say_do);
1556 TypeContainerVisitor<MaNGOS::PlayerDistWorker<MaNGOS::LocalizedPacketDo<MaNGOS::MonsterChatBuilder> >, WorldTypeMapContainer > message(say_worker);
1557 cell.Visit(p, message, *GetMap(), *this, range);
1560 void WorldObject::MonsterWhisper(int32 textId, uint64 receiver, bool IsBossWhisper)
1562 Player *player = sObjectMgr.GetPlayer(receiver);
1563 if(!player || !player->GetSession())
1564 return;
1566 uint32 loc_idx = player->GetSession()->GetSessionDbLocaleIndex();
1567 char const* text = sObjectMgr.GetMangosString(textId,loc_idx);
1569 WorldPacket data(SMSG_MESSAGECHAT, 200);
1570 BuildMonsterChat(&data,IsBossWhisper ? CHAT_MSG_RAID_BOSS_WHISPER : CHAT_MSG_MONSTER_WHISPER,text,LANG_UNIVERSAL,GetNameForLocaleIdx(loc_idx),receiver);
1572 player->GetSession()->SendPacket(&data);
1575 void WorldObject::BuildMonsterChat(WorldPacket *data, uint8 msgtype, char const* text, uint32 language, char const* name, uint64 targetGuid) const
1577 *data << (uint8)msgtype;
1578 *data << (uint32)language;
1579 *data << (uint64)GetGUID();
1580 *data << (uint32)0; // 2.1.0
1581 *data << (uint32)(strlen(name)+1);
1582 *data << name;
1583 *data << (uint64)targetGuid; // Unit Target
1584 if( targetGuid && !IS_PLAYER_GUID(targetGuid) )
1586 *data << (uint32)1; // target name length
1587 *data << (uint8)0; // target name
1589 *data << (uint32)(strlen(text)+1);
1590 *data << text;
1591 *data << (uint8)0; // ChatTag
1594 void WorldObject::SendMessageToSet(WorldPacket *data, bool /*bToSelf*/)
1596 //if object is in world, map for it already created!
1597 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
1598 if(_map)
1599 _map->MessageBroadcast(this, data);
1602 void WorldObject::SendMessageToSetInRange(WorldPacket *data, float dist, bool /*bToSelf*/)
1604 //if object is in world, map for it already created!
1605 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
1606 if(_map)
1607 _map->MessageDistBroadcast(this, data, dist);
1610 void WorldObject::SendObjectDeSpawnAnim(uint64 guid)
1612 WorldPacket data(SMSG_GAMEOBJECT_DESPAWN_ANIM, 8);
1613 data << uint64(guid);
1614 SendMessageToSet(&data, true);
1617 void WorldObject::SendGameObjectCustomAnim(uint64 guid)
1619 WorldPacket data(SMSG_GAMEOBJECT_CUSTOM_ANIM, 8+4);
1620 data << uint64(guid);
1621 data << uint32(0); // not known what this is
1622 SendMessageToSet(&data, true);
1625 void WorldObject::SetMap(Map * map)
1627 ASSERT(map);
1628 m_currMap = map;
1629 //lets save current map's Id/instanceId
1630 m_mapId = map->GetId();
1631 m_InstanceId = map->GetInstanceId();
1634 Map const* WorldObject::GetBaseMap() const
1636 ASSERT(m_currMap);
1637 return m_currMap->GetParent();
1640 void WorldObject::AddObjectToRemoveList()
1642 GetMap()->AddObjectToRemoveList(this);
1645 Creature* WorldObject::SummonCreature(uint32 id, float x, float y, float z, float ang,TempSummonType spwtype,uint32 despwtime)
1647 TemporarySummon* pCreature = new TemporarySummon(GetGUID());
1649 uint32 team = 0;
1650 if (GetTypeId()==TYPEID_PLAYER)
1651 team = ((Player*)this)->GetTeam();
1653 if (!pCreature->Create(sObjectMgr.GenerateLowGuid(HIGHGUID_UNIT), GetMap(), GetPhaseMask(), id, team))
1655 delete pCreature;
1656 return NULL;
1659 if (x == 0.0f && y == 0.0f && z == 0.0f)
1660 GetClosePoint(x, y, z, pCreature->GetObjectSize());
1662 pCreature->Relocate(x, y, z, ang);
1663 pCreature->SetSummonPoint(x, y, z, ang);
1665 if(!pCreature->IsPositionValid())
1667 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());
1668 delete pCreature;
1669 return NULL;
1672 pCreature->Summon(spwtype, despwtime);
1674 if(GetTypeId()==TYPEID_UNIT && ((Creature*)this)->AI())
1675 ((Creature*)this)->AI()->JustSummoned(pCreature);
1677 // return the creature therewith the summoner has access to it
1678 return pCreature;
1681 namespace MaNGOS
1683 class NearUsedPosDo
1685 public:
1686 NearUsedPosDo(WorldObject const& obj, WorldObject const* searcher, float angle, ObjectPosSelector& selector)
1687 : i_object(obj), i_searcher(searcher), i_angle(angle), i_selector(selector) {}
1689 void operator()(Corpse*) const {}
1690 void operator()(DynamicObject*) const {}
1692 void operator()(Creature* c) const
1694 // skip self or target
1695 if(c==i_searcher || c==&i_object)
1696 return;
1698 float x,y,z;
1700 if( !c->isAlive() || c->hasUnitState(UNIT_STAT_NOT_MOVE) ||
1701 !c->GetMotionMaster()->GetDestination(x,y,z) )
1703 x = c->GetPositionX();
1704 y = c->GetPositionY();
1707 add(c,x,y);
1710 template<class T>
1711 void operator()(T* u) const
1713 // skip self or target
1714 if(u==i_searcher || u==&i_object)
1715 return;
1717 float x,y;
1719 x = u->GetPositionX();
1720 y = u->GetPositionY();
1722 add(u,x,y);
1725 // we must add used pos that can fill places around center
1726 void add(WorldObject* u, float x, float y) const
1728 // u is too nearest/far away to i_object
1729 if(!i_object.IsInRange2d(x,y,i_selector.m_dist - i_selector.m_size,i_selector.m_dist + i_selector.m_size))
1730 return;
1732 float angle = i_object.GetAngle(u)-i_angle;
1734 // move angle to range -pi ... +pi
1735 while( angle > M_PI_F)
1736 angle -= 2.0f * M_PI_F;
1737 while(angle < -M_PI_F)
1738 angle += 2.0f * M_PI_F;
1740 // dist include size of u
1741 float dist2d = i_object.GetDistance2d(x,y);
1742 i_selector.AddUsedPos(u->GetObjectSize(),angle,dist2d + i_object.GetObjectSize());
1744 private:
1745 WorldObject const& i_object;
1746 WorldObject const* i_searcher;
1747 float i_angle;
1748 ObjectPosSelector& i_selector;
1750 } // namespace MaNGOS
1752 //===================================================================================================
1754 void WorldObject::GetNearPoint2D(float &x, float &y, float distance2d, float absAngle ) const
1756 x = GetPositionX() + (GetObjectSize() + distance2d) * cos(absAngle);
1757 y = GetPositionY() + (GetObjectSize() + distance2d) * sin(absAngle);
1759 MaNGOS::NormalizeMapCoord(x);
1760 MaNGOS::NormalizeMapCoord(y);
1763 void WorldObject::GetNearPoint(WorldObject const* searcher, float &x, float &y, float &z, float searcher_size, float distance2d, float absAngle ) const
1765 GetNearPoint2D(x,y,distance2d+searcher_size,absAngle);
1766 z = GetPositionZ();
1768 // if detection disabled, return first point
1769 if(!sWorld.getConfig(CONFIG_BOOL_DETECT_POS_COLLISION))
1771 UpdateGroundPositionZ(x,y,z); // update to LOS height if available
1772 return;
1775 // or remember first point
1776 float first_x = x;
1777 float first_y = y;
1778 bool first_los_conflict = false; // first point LOS problems
1780 // prepare selector for work
1781 ObjectPosSelector selector(GetPositionX(),GetPositionY(),GetObjectSize(),distance2d+searcher_size);
1783 // adding used positions around object
1785 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
1786 Cell cell(p);
1787 cell.data.Part.reserved = ALL_DISTRICT;
1788 cell.SetNoCreate();
1790 MaNGOS::NearUsedPosDo u_do(*this,searcher,absAngle,selector);
1791 MaNGOS::WorldObjectWorker<MaNGOS::NearUsedPosDo> worker(this,u_do);
1793 TypeContainerVisitor<MaNGOS::WorldObjectWorker<MaNGOS::NearUsedPosDo>, GridTypeMapContainer > grid_obj_worker(worker);
1794 TypeContainerVisitor<MaNGOS::WorldObjectWorker<MaNGOS::NearUsedPosDo>, WorldTypeMapContainer > world_obj_worker(worker);
1796 cell.Visit(p, grid_obj_worker, *GetMap(), *this, distance2d);
1797 cell.Visit(p, world_obj_worker, *GetMap(), *this, distance2d);
1800 // maybe can just place in primary position
1801 if( selector.CheckOriginal() )
1803 UpdateGroundPositionZ(x,y,z); // update to LOS height if available
1805 if(IsWithinLOS(x,y,z))
1806 return;
1808 first_los_conflict = true; // first point have LOS problems
1811 float angle; // candidate of angle for free pos
1813 // special case when one from list empty and then empty side preferred
1814 if(selector.FirstAngle(angle))
1816 GetNearPoint2D(x,y,distance2d,absAngle+angle);
1817 z = GetPositionZ();
1818 UpdateGroundPositionZ(x,y,z); // update to LOS height if available
1820 if(IsWithinLOS(x,y,z))
1821 return;
1824 // set first used pos in lists
1825 selector.InitializeAngle();
1827 // select in positions after current nodes (selection one by one)
1828 while(selector.NextAngle(angle)) // angle for free pos
1830 GetNearPoint2D(x,y,distance2d,absAngle+angle);
1831 z = GetPositionZ();
1832 UpdateGroundPositionZ(x,y,z); // update to LOS height if available
1834 if(IsWithinLOS(x,y,z))
1835 return;
1838 // BAD NEWS: not free pos (or used or have LOS problems)
1839 // Attempt find _used_ pos without LOS problem
1841 if(!first_los_conflict)
1843 x = first_x;
1844 y = first_y;
1846 UpdateGroundPositionZ(x,y,z); // update to LOS height if available
1847 return;
1850 // special case when one from list empty and then empty side preferred
1851 if( selector.IsNonBalanced() )
1853 if(!selector.FirstAngle(angle)) // _used_ pos
1855 GetNearPoint2D(x,y,distance2d,absAngle+angle);
1856 z = GetPositionZ();
1857 UpdateGroundPositionZ(x,y,z); // update to LOS height if available
1859 if(IsWithinLOS(x,y,z))
1860 return;
1864 // set first used pos in lists
1865 selector.InitializeAngle();
1867 // select in positions after current nodes (selection one by one)
1868 while(selector.NextUsedAngle(angle)) // angle for used pos but maybe without LOS problem
1870 GetNearPoint2D(x,y,distance2d,absAngle+angle);
1871 z = GetPositionZ();
1872 UpdateGroundPositionZ(x,y,z); // update to LOS height if available
1874 if(IsWithinLOS(x,y,z))
1875 return;
1878 // BAD BAD NEWS: all found pos (free and used) have LOS problem :(
1879 x = first_x;
1880 y = first_y;
1882 UpdateGroundPositionZ(x,y,z); // update to LOS height if available
1885 void WorldObject::SetPhaseMask(uint32 newPhaseMask, bool update)
1887 m_phaseMask = newPhaseMask;
1889 if(update && IsInWorld())
1890 UpdateObjectVisibility();
1893 void WorldObject::PlayDistanceSound( uint32 sound_id, Player* target /*= NULL*/ )
1895 WorldPacket data(SMSG_PLAY_OBJECT_SOUND,4+8);
1896 data << uint32(sound_id);
1897 data << uint64(GetGUID());
1898 if (target)
1899 target->SendDirectMessage( &data );
1900 else
1901 SendMessageToSet( &data, true );
1904 void WorldObject::PlayDirectSound( uint32 sound_id, Player* target /*= NULL*/ )
1906 WorldPacket data(SMSG_PLAY_SOUND, 4);
1907 data << uint32(sound_id);
1908 if (target)
1909 target->SendDirectMessage( &data );
1910 else
1911 SendMessageToSet( &data, true );
1914 void WorldObject::UpdateObjectVisibility()
1916 CellPair p = MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY());
1917 Cell cell(p);
1919 GetMap()->UpdateObjectVisibility(this, cell, p);
1922 void WorldObject::AddToClientUpdateList()
1924 GetMap()->AddUpdateObject(this);
1927 void WorldObject::RemoveFromClientUpdateList()
1929 GetMap()->RemoveUpdateObject(this);
1932 struct WorldObjectChangeAccumulator
1934 UpdateDataMapType &i_updateDatas;
1935 WorldObject &i_object;
1936 WorldObjectChangeAccumulator(WorldObject &obj, UpdateDataMapType &d) : i_updateDatas(d), i_object(obj) {}
1937 void Visit(PlayerMapType &m)
1939 for(PlayerMapType::iterator iter = m.begin(); iter != m.end(); ++iter)
1940 if(iter->getSource()->HaveAtClient(&i_object))
1941 i_object.BuildUpdateDataForPlayer(iter->getSource(), i_updateDatas);
1944 template<class SKIP> void Visit(GridRefManager<SKIP> &) {}
1947 void WorldObject::BuildUpdateData( UpdateDataMapType & update_players)
1949 CellPair p = MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY());
1950 Cell cell(p);
1951 cell.data.Part.reserved = ALL_DISTRICT;
1952 cell.SetNoCreate();
1953 WorldObjectChangeAccumulator notifier(*this, update_players);
1954 TypeContainerVisitor<WorldObjectChangeAccumulator, WorldTypeMapContainer > player_notifier(notifier);
1955 Map* aMap = GetMap();
1956 //we must build packets for all visible players
1957 cell.Visit(p, player_notifier, *aMap, *this, aMap->GetVisibilityDistance());
1959 ClearUpdateMask(false);
1962 bool WorldObject::IsControlledByPlayer() const
1964 switch (GetTypeId())
1966 case TYPEID_GAMEOBJECT:
1967 return IS_PLAYER_GUID(((GameObject*)this)->GetOwnerGUID());
1968 case TYPEID_UNIT:
1969 case TYPEID_PLAYER:
1970 return ((Unit*)this)->IsCharmerOrOwnerPlayerOrPlayerItself();
1971 case TYPEID_DYNAMICOBJECT:
1972 return IS_PLAYER_GUID(((DynamicObject*)this)->GetCasterGUID());
1973 case TYPEID_CORPSE:
1974 return true;
1975 default:
1976 return false;