Merge branch 'master' into 330
[getmangos.git] / src / game / Object.cpp
blobf367f482a260b37546cf3854b5db0dee8bd67b6a
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)
99 //DEBUG_LOG("Object desctr 1 check (%p)",(void*)this);
100 delete [] m_uint32Values;
101 delete [] m_uint32Values_mirror;
102 //DEBUG_LOG("Object desctr 2 check (%p)",(void*)this);
106 void Object::_InitValues()
108 m_uint32Values = new uint32[ m_valuesCount ];
109 memset(m_uint32Values, 0, m_valuesCount*sizeof(uint32));
111 m_uint32Values_mirror = new uint32[ m_valuesCount ];
112 memset(m_uint32Values_mirror, 0, m_valuesCount*sizeof(uint32));
114 m_objectUpdated = false;
117 void Object::_Create( uint32 guidlow, uint32 entry, HighGuid guidhigh )
119 if(!m_uint32Values) _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, uint32 flags ) const
130 ByteBuffer buf(500);
132 buf << uint8( UPDATETYPE_MOVEMENT );
133 buf.append(GetPackGUID());
135 BuildMovementUpdate(&buf, flags, 0x00000000);
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 flags = m_updateFlag;
147 uint32 flags2 = 0;
149 /** lower flag1 **/
150 if(target == this) // building packet for yourself
151 flags |= UPDATEFLAG_SELF;
153 if(flags & UPDATEFLAG_HAS_POSITION)
155 // UPDATETYPE_CREATE_OBJECT2 dynamic objects, corpses...
156 if(isType(TYPEMASK_DYNAMICOBJECT) || isType(TYPEMASK_CORPSE) || isType(TYPEMASK_PLAYER))
157 updatetype = UPDATETYPE_CREATE_OBJECT2;
159 // UPDATETYPE_CREATE_OBJECT2 for pets...
160 if(target->GetPetGUID() == GetGUID())
161 updatetype = UPDATETYPE_CREATE_OBJECT2;
163 // UPDATETYPE_CREATE_OBJECT2 for some gameobject types...
164 if(isType(TYPEMASK_GAMEOBJECT))
166 switch(((GameObject*)this)->GetGoType())
168 case GAMEOBJECT_TYPE_TRAP:
169 case GAMEOBJECT_TYPE_DUEL_ARBITER:
170 case GAMEOBJECT_TYPE_FLAGSTAND:
171 case GAMEOBJECT_TYPE_FLAGDROP:
172 updatetype = UPDATETYPE_CREATE_OBJECT2;
173 break;
174 case GAMEOBJECT_TYPE_TRANSPORT:
175 flags |= UPDATEFLAG_TRANSPORT;
176 break;
177 default:
178 break;
182 if(isType(TYPEMASK_UNIT))
184 if(((Unit*)this)->getVictim())
185 flags |= UPDATEFLAG_HAS_ATTACKING_TARGET;
189 //sLog.outDebug("BuildCreateUpdate: update-type: %u, object-type: %u got flags: %X, flags2: %X", updatetype, m_objectTypeId, flags, flags2);
191 ByteBuffer buf(500);
192 buf << (uint8)updatetype;
193 buf.append(GetPackGUID());
194 buf << (uint8)m_objectTypeId;
196 BuildMovementUpdate(&buf, flags, flags2);
198 UpdateMask updateMask;
199 updateMask.SetCount( m_valuesCount );
200 _SetCreateBits( &updateMask, target );
201 BuildValuesUpdate(updatetype, &buf, &updateMask, target);
202 data->AddUpdateBlock(buf);
205 void Object::SendCreateUpdateToPlayer(Player* player)
207 // send create update to player
208 UpdateData upd;
209 WorldPacket packet;
211 BuildCreateUpdateBlockForPlayer(&upd, player);
212 upd.BuildPacket(&packet);
213 player->GetSession()->SendPacket(&packet);
216 void Object::BuildValuesUpdateBlockForPlayer(UpdateData *data, Player *target) const
218 ByteBuffer buf(500);
220 buf << (uint8) UPDATETYPE_VALUES;
221 buf.append(GetPackGUID());
223 UpdateMask updateMask;
224 updateMask.SetCount( m_valuesCount );
226 _SetUpdateBits( &updateMask, target );
227 BuildValuesUpdate(UPDATETYPE_VALUES, &buf, &updateMask, target);
229 data->AddUpdateBlock(buf);
232 void Object::BuildOutOfRangeUpdateBlock(UpdateData * data) const
234 data->AddOutOfRangeGUID(GetGUID());
237 void Object::DestroyForPlayer( Player *target, bool anim ) const
239 ASSERT(target);
241 WorldPacket data(SMSG_DESTROY_OBJECT, 8);
242 data << uint64(GetGUID());
243 data << uint8(anim ? 1 : 0); // WotLK (bool), may be despawn animation
244 target->GetSession()->SendPacket( &data );
247 void Object::BuildMovementUpdate(ByteBuffer * data, uint16 flags, uint32 flags2) const
249 uint16 unk_flags = ((GetTypeId() == TYPEID_PLAYER) ? ((Player*)this)->m_movementInfo.unk1 : 0);
251 if(GetTypeId() == TYPEID_UNIT)
252 if(((Creature*)this)->isVehicle())
253 unk_flags |= 0x20; // always allow pitch
255 *data << (uint16)flags; // update flags
257 // 0x20
258 if (flags & UPDATEFLAG_LIVING)
260 switch(GetTypeId())
262 case TYPEID_UNIT:
264 flags2 = MOVEMENTFLAG_NONE;
266 if (!((Creature*)this)->IsStopped())
267 flags2 |= MOVEMENTFLAG_FORWARD; // not set if not really moving
269 if (((Creature*)this)->canFly())
271 flags2 |= MOVEMENTFLAG_LEVITATING; // (ok) most seem to have this
273 if (((Creature*)this)->IsStopped())
274 flags2 |= MOVEMENTFLAG_FLY_UNK1; // (ok) possibly some "hover" mode
275 else
277 if (((Creature*)this)->IsMounted())
278 flags2 |= MOVEMENTFLAG_FLYING; // seems to be often when mounted
279 /* for further research
280 else
281 flags2 |= MOVEMENTFLAG_FLYING2; // not seen, but work on some, even if not "correct"
286 break;
287 case TYPEID_PLAYER:
289 flags2 = ((Player*)this)->m_movementInfo.GetMovementFlags();
291 if(((Player*)this)->GetTransport())
292 flags2 |= MOVEMENTFLAG_ONTRANSPORT;
293 else
294 flags2 &= ~MOVEMENTFLAG_ONTRANSPORT;
296 // remove unknown, unused etc flags for now
297 flags2 &= ~MOVEMENTFLAG_SPLINE2; // will be set manually
299 if(((Player*)this)->isInFlight())
301 ASSERT(((Player*)this)->GetMotionMaster()->GetCurrentMovementGeneratorType() == FLIGHT_MOTION_TYPE);
302 flags2 = (MOVEMENTFLAG_FORWARD | MOVEMENTFLAG_SPLINE2);
305 break;
308 *data << uint32(flags2); // movement flags
309 *data << uint16(unk_flags); // unknown 2.3.0
310 *data << uint32(getMSTime()); // time (in milliseconds)
312 // position
313 *data << ((WorldObject*)this)->GetPositionX();
314 *data << ((WorldObject*)this)->GetPositionY();
315 *data << ((WorldObject*)this)->GetPositionZ();
316 *data << ((WorldObject*)this)->GetOrientation();
318 // 0x00000200
319 if(flags2 & MOVEMENTFLAG_ONTRANSPORT)
321 if(GetTypeId() == TYPEID_PLAYER)
323 data->append(((Player*)this)->GetTransport()->GetPackGUID());
324 *data << (float)((Player*)this)->GetTransOffsetX();
325 *data << (float)((Player*)this)->GetTransOffsetY();
326 *data << (float)((Player*)this)->GetTransOffsetZ();
327 *data << (float)((Player*)this)->GetTransOffsetO();
328 *data << (uint32)((Player*)this)->GetTransTime();
329 *data << (int8)((Player*)this)->GetTransSeat();
331 else
333 //MaNGOS currently not have support for other than player on transport
334 *data << uint8(0);
335 *data << float(0) << float(0) << float(0) << float(0);
336 *data << uint32(0);
337 *data << uint8(-1);
341 // 0x02200000
342 if((flags2 & (MOVEMENTFLAG_SWIMMING | MOVEMENTFLAG_FLYING)) || (unk_flags & 0x20))
344 if(GetTypeId() == TYPEID_PLAYER)
345 *data << (float)((Player*)this)->m_movementInfo.s_pitch;
346 else
347 *data << (float)0; // is't part of movement packet, we must store and send it...
350 if(GetTypeId() == TYPEID_PLAYER)
351 *data << (uint32)((Player*)this)->m_movementInfo.fallTime;
352 else
353 *data << (uint32)0; // last fall time
355 // 0x00001000
356 if(flags2 & MOVEMENTFLAG_JUMPING)
358 if(GetTypeId() == TYPEID_PLAYER)
360 *data << (float)((Player*)this)->m_movementInfo.j_unk;
361 *data << (float)((Player*)this)->m_movementInfo.j_sinAngle;
362 *data << (float)((Player*)this)->m_movementInfo.j_cosAngle;
363 *data << (float)((Player*)this)->m_movementInfo.j_xyspeed;
365 else
367 *data << (float)0;
368 *data << (float)0;
369 *data << (float)0;
370 *data << (float)0;
374 // 0x04000000
375 if(flags2 & MOVEMENTFLAG_SPLINE)
377 if(GetTypeId() == TYPEID_PLAYER)
378 *data << (float)((Player*)this)->m_movementInfo.u_unk1;
379 else
380 *data << (float)0;
383 *data << ((Unit*)this)->GetSpeed( MOVE_WALK );
384 *data << ((Unit*)this)->GetSpeed( MOVE_RUN );
385 *data << ((Unit*)this)->GetSpeed( MOVE_SWIM_BACK );
386 *data << ((Unit*)this)->GetSpeed( MOVE_SWIM );
387 *data << ((Unit*)this)->GetSpeed( MOVE_RUN_BACK );
388 *data << ((Unit*)this)->GetSpeed( MOVE_FLIGHT );
389 *data << ((Unit*)this)->GetSpeed( MOVE_FLIGHT_BACK );
390 *data << ((Unit*)this)->GetSpeed( MOVE_TURN_RATE );
391 *data << ((Unit*)this)->GetSpeed( MOVE_PITCH_RATE );
393 // 0x08000000
394 if(flags2 & MOVEMENTFLAG_SPLINE2)
396 if(GetTypeId() != TYPEID_PLAYER)
398 sLog.outDebug("_BuildMovementUpdate: MOVEMENTFLAG_SPLINE2 for non-player");
399 return;
402 if(!((Player*)this)->isInFlight())
404 sLog.outDebug("_BuildMovementUpdate: MOVEMENTFLAG_SPLINE2 but not in flight");
405 return;
408 ASSERT(((Player*)this)->GetMotionMaster()->GetCurrentMovementGeneratorType() == FLIGHT_MOTION_TYPE);
410 FlightPathMovementGenerator *fmg = (FlightPathMovementGenerator*)(((Player*)this)->GetMotionMaster()->top());
412 uint32 flags3 = MONSTER_MOVE_SPLINE_FLY;
414 *data << uint32(flags3); // splines flag?
416 if(flags3 & 0x20000) // may be orientation
418 *data << (float)0;
420 else
422 if(flags3 & 0x8000) // probably x,y,z coords there
424 *data << (float)0;
425 *data << (float)0;
426 *data << (float)0;
429 if(flags3 & 0x10000) // probably guid there
431 *data << uint64(0);
435 Path &path = fmg->GetPath();
437 float x, y, z;
438 ((Player*)this)->GetPosition(x, y, z);
440 uint32 inflighttime = uint32(path.GetPassedLength(fmg->GetCurrentNode(), x, y, z) * 32);
441 uint32 traveltime = uint32(path.GetTotalLength() * 32);
443 *data << uint32(inflighttime); // passed move time?
444 *data << uint32(traveltime); // full move time?
445 *data << uint32(0); // ticks count?
447 *data << float(0); // added in 3.1
448 *data << float(0); // added in 3.1
449 *data << float(0); // added in 3.1
451 *data << uint32(0); // added in 3.1
453 uint32 poscount = uint32(path.Size());
454 *data << uint32(poscount); // points count
456 for(uint32 i = 0; i < poscount; ++i)
458 *data << path.GetNodes()[i].x;
459 *data << path.GetNodes()[i].y;
460 *data << path.GetNodes()[i].z;
463 *data << uint8(0); // added in 3.0.8
465 *data << path.GetNodes()[poscount-1].x;
466 *data << path.GetNodes()[poscount-1].y;
467 *data << path.GetNodes()[poscount-1].z;
470 else
472 if(flags & UPDATEFLAG_POSITION)
474 *data << uint8(0); // unk PGUID!
475 *data << ((WorldObject*)this)->GetPositionX();
476 *data << ((WorldObject*)this)->GetPositionY();
477 *data << ((WorldObject*)this)->GetPositionZ();
478 *data << ((WorldObject*)this)->GetPositionX();
479 *data << ((WorldObject*)this)->GetPositionY();
480 *data << ((WorldObject*)this)->GetPositionZ();
481 *data << ((WorldObject*)this)->GetOrientation();
483 if(GetTypeId() == TYPEID_CORPSE)
484 *data << float(((WorldObject*)this)->GetOrientation());
485 else
486 *data << float(0);
488 else
490 // 0x40
491 if (flags & UPDATEFLAG_HAS_POSITION)
493 // 0x02
494 if(flags & UPDATEFLAG_TRANSPORT && ((GameObject*)this)->GetGoType() == GAMEOBJECT_TYPE_MO_TRANSPORT)
496 *data << (float)0;
497 *data << (float)0;
498 *data << (float)0;
499 *data << ((WorldObject *)this)->GetOrientation();
501 else
503 *data << ((WorldObject *)this)->GetPositionX();
504 *data << ((WorldObject *)this)->GetPositionY();
505 *data << ((WorldObject *)this)->GetPositionZ();
506 *data << ((WorldObject *)this)->GetOrientation();
512 // 0x8
513 if(flags & UPDATEFLAG_LOWGUID)
515 switch(GetTypeId())
517 case TYPEID_OBJECT:
518 case TYPEID_ITEM:
519 case TYPEID_CONTAINER:
520 case TYPEID_GAMEOBJECT:
521 case TYPEID_DYNAMICOBJECT:
522 case TYPEID_CORPSE:
523 *data << uint32(GetGUIDLow()); // GetGUIDLow()
524 break;
525 case TYPEID_UNIT:
526 *data << uint32(0x0000000B); // unk, can be 0xB or 0xC
527 break;
528 case TYPEID_PLAYER:
529 if(flags & UPDATEFLAG_SELF)
530 *data << uint32(0x0000002F); // unk, can be 0x15 or 0x22
531 else
532 *data << uint32(0x00000008); // unk, can be 0x7 or 0x8
533 break;
534 default:
535 *data << uint32(0x00000000); // unk
536 break;
540 // 0x10
541 if(flags & UPDATEFLAG_HIGHGUID)
543 switch(GetTypeId())
545 case TYPEID_OBJECT:
546 case TYPEID_ITEM:
547 case TYPEID_CONTAINER:
548 case TYPEID_GAMEOBJECT:
549 case TYPEID_DYNAMICOBJECT:
550 case TYPEID_CORPSE:
551 *data << uint32(GetGUIDHigh()); // GetGUIDHigh()
552 break;
553 case TYPEID_UNIT:
554 *data << uint32(0x0000000B); // unk, can be 0xB or 0xC
555 break;
556 case TYPEID_PLAYER:
557 if(flags & UPDATEFLAG_SELF)
558 *data << uint32(0x0000002F); // unk, can be 0x15 or 0x22
559 else
560 *data << uint32(0x00000008); // unk, can be 0x7 or 0x8
561 break;
562 default:
563 *data << uint32(0x00000000); // unk
564 break;
568 // 0x4
569 if(flags & UPDATEFLAG_HAS_ATTACKING_TARGET) // packed guid (current target guid)
571 if (((Unit*)this)->getVictim())
572 data->append(((Unit*)this)->getVictim()->GetPackGUID());
573 else
574 data->appendPackGUID(0);
577 // 0x2
578 if(flags & UPDATEFLAG_TRANSPORT)
580 *data << uint32(getMSTime()); // ms time
583 // 0x80
584 if(flags & UPDATEFLAG_VEHICLE) // unused for now
586 *data << uint32(((Vehicle*)this)->GetVehicleId()); // vehicle id
587 *data << float(0); // facing adjustment
590 // 0x200
591 if(flags & UPDATEFLAG_ROTATION)
593 *data << uint64(((GameObject*)this)->GetRotation());
597 void Object::BuildValuesUpdate(uint8 updatetype, ByteBuffer * data, UpdateMask *updateMask, Player *target) const
599 if(!target)
600 return;
602 bool IsActivateToQuest = false;
603 bool IsPerCasterAuraState = false;
604 if (updatetype == UPDATETYPE_CREATE_OBJECT || updatetype == UPDATETYPE_CREATE_OBJECT2)
606 if (isType(TYPEMASK_GAMEOBJECT) && !((GameObject*)this)->IsTransport())
608 if ( ((GameObject*)this)->ActivateToQuest(target) || target->isGameMaster())
609 IsActivateToQuest = true;
611 updateMask->SetBit(GAMEOBJECT_DYNAMIC);
613 else if (isType(TYPEMASK_UNIT))
615 if( ((Unit*)this)->HasAuraState(AURA_STATE_CONFLAGRATE))
617 IsPerCasterAuraState = true;
618 updateMask->SetBit(UNIT_FIELD_AURASTATE);
622 else // case UPDATETYPE_VALUES
624 if (isType(TYPEMASK_GAMEOBJECT) && !((GameObject*)this)->IsTransport())
626 if ( ((GameObject*)this)->ActivateToQuest(target) || target->isGameMaster())
628 IsActivateToQuest = true;
630 updateMask->SetBit(GAMEOBJECT_DYNAMIC);
631 updateMask->SetBit(GAMEOBJECT_BYTES_1);
633 else if (isType(TYPEMASK_UNIT))
635 if( ((Unit*)this)->HasAuraState(AURA_STATE_CONFLAGRATE))
637 IsPerCasterAuraState = true;
638 updateMask->SetBit(UNIT_FIELD_AURASTATE);
643 ASSERT(updateMask && updateMask->GetCount() == m_valuesCount);
645 *data << (uint8)updateMask->GetBlockCount();
646 data->append( updateMask->GetMask(), updateMask->GetLength() );
648 // 2 specialized loops for speed optimization in non-unit case
649 if(isType(TYPEMASK_UNIT)) // unit (creature/player) case
651 for( uint16 index = 0; index < m_valuesCount; ++index )
653 if( updateMask->GetBit( index ) )
655 if( index == UNIT_NPC_FLAGS )
657 // remove custom flag before sending
658 uint32 appendValue = m_uint32Values[ index ] & ~UNIT_NPC_FLAG_GUARD;
660 if (GetTypeId() == TYPEID_UNIT)
662 if (!target->canSeeSpellClickOn((Creature*)this))
663 appendValue &= ~UNIT_NPC_FLAG_SPELLCLICK;
665 if (appendValue & UNIT_NPC_FLAG_TRAINER)
667 if (!((Creature*)this)->isCanTrainingOf(target, false))
668 appendValue &= ~(UNIT_NPC_FLAG_TRAINER | UNIT_NPC_FLAG_TRAINER_CLASS | UNIT_NPC_FLAG_TRAINER_PROFESSION);
671 if (appendValue & UNIT_NPC_FLAG_STABLEMASTER)
673 if (target->getClass() != CLASS_HUNTER)
674 appendValue &= ~UNIT_NPC_FLAG_STABLEMASTER;
678 *data << uint32(appendValue);
680 else if (index == UNIT_FIELD_AURASTATE)
682 if(IsPerCasterAuraState)
684 // IsPerCasterAuraState set if related pet caster aura state set already
685 if (((Unit*)this)->HasAuraStateForCaster(AURA_STATE_CONFLAGRATE,target->GetGUID()))
686 *data << m_uint32Values[ index ];
687 else
688 *data << (m_uint32Values[ index ] & ~(1 << (AURA_STATE_CONFLAGRATE-1)));
690 else
691 *data << m_uint32Values[ index ];
693 // FIXME: Some values at server stored in float format but must be sent to client in uint32 format
694 else if(index >= UNIT_FIELD_BASEATTACKTIME && index <= UNIT_FIELD_RANGEDATTACKTIME)
696 // convert from float to uint32 and send
697 *data << uint32(m_floatValues[ index ] < 0 ? 0 : m_floatValues[ index ]);
699 // there are some float values which may be negative or can't get negative due to other checks
700 else if ((index >= UNIT_FIELD_NEGSTAT0 && index <= UNIT_FIELD_NEGSTAT4) ||
701 (index >= UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE && index <= (UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE + 6)) ||
702 (index >= UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE && index <= (UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE + 6)) ||
703 (index >= UNIT_FIELD_POSSTAT0 && index <= UNIT_FIELD_POSSTAT4))
705 *data << uint32(m_floatValues[ index ]);
707 // Gamemasters should be always able to select units - remove not selectable flag
708 else if(index == UNIT_FIELD_FLAGS && target->isGameMaster())
710 *data << (m_uint32Values[ index ] & ~UNIT_FLAG_NOT_SELECTABLE);
712 // hide lootable animation for unallowed players
713 else if(index == UNIT_DYNAMIC_FLAGS && GetTypeId() == TYPEID_UNIT)
715 if(!target->isAllowedToLoot((Creature*)this))
716 *data << (m_uint32Values[ index ] & ~UNIT_DYNFLAG_LOOTABLE);
717 else
718 *data << (m_uint32Values[ index ] & ~UNIT_DYNFLAG_OTHER_TAGGER);
720 else
722 // send in current format (float as float, uint32 as uint32)
723 *data << m_uint32Values[ index ];
728 else if(isType(TYPEMASK_GAMEOBJECT)) // gameobject case
730 for( uint16 index = 0; index < m_valuesCount; ++index )
732 if( updateMask->GetBit( index ) )
734 // send in current format (float as float, uint32 as uint32)
735 if ( index == GAMEOBJECT_DYNAMIC )
737 if(IsActivateToQuest )
739 switch(((GameObject*)this)->GetGoType())
741 case GAMEOBJECT_TYPE_CHEST:
742 // enable quest object. Represent 9, but 1 for client before 2.3.0
743 *data << uint16(9);
744 *data << uint16(-1);
745 break;
746 case GAMEOBJECT_TYPE_GOOBER:
747 *data << uint16(1);
748 *data << uint16(-1);
749 break;
750 default:
751 // unknown, not happen.
752 *data << uint16(0);
753 *data << uint16(-1);
754 break;
757 else
759 // disable quest object
760 *data << uint16(0);
761 *data << uint16(-1);
764 else
765 *data << m_uint32Values[ index ]; // other cases
769 else // other objects case (no special index checks)
771 for( uint16 index = 0; index < m_valuesCount; ++index )
773 if( updateMask->GetBit( index ) )
775 // send in current format (float as float, uint32 as uint32)
776 *data << m_uint32Values[ index ];
782 void Object::ClearUpdateMask(bool remove)
784 if(m_uint32Values)
786 for( uint16 index = 0; index < m_valuesCount; ++index )
788 if(m_uint32Values_mirror[index]!= m_uint32Values[index])
789 m_uint32Values_mirror[index] = m_uint32Values[index];
793 if(m_objectUpdated)
795 if(remove)
796 RemoveFromClientUpdateList();
797 m_objectUpdated = false;
801 bool Object::LoadValues(const char* data)
803 if(!m_uint32Values) _InitValues();
805 Tokens tokens = StrSplit(data, " ");
807 if(tokens.size() != m_valuesCount)
808 return false;
810 Tokens::iterator iter;
811 int index;
812 for (iter = tokens.begin(), index = 0; index < m_valuesCount; ++iter, ++index)
814 m_uint32Values[index] = atol((*iter).c_str());
817 return true;
820 void Object::_SetUpdateBits(UpdateMask *updateMask, Player* /*target*/) const
822 for( uint16 index = 0; index < m_valuesCount; ++index )
824 if(m_uint32Values_mirror[index]!= m_uint32Values[index])
825 updateMask->SetBit(index);
829 void Object::_SetCreateBits(UpdateMask *updateMask, Player* /*target*/) const
831 for( uint16 index = 0; index < m_valuesCount; ++index )
833 if(GetUInt32Value(index) != 0)
834 updateMask->SetBit(index);
838 void Object::SetInt32Value( uint16 index, int32 value )
840 ASSERT( index < m_valuesCount || PrintIndexError( index, true ) );
842 if(m_int32Values[ index ] != value)
844 m_int32Values[ index ] = value;
846 if(m_inWorld)
848 if(!m_objectUpdated)
850 AddToClientUpdateList();
851 m_objectUpdated = true;
857 void Object::SetUInt32Value( uint16 index, uint32 value )
859 ASSERT( index < m_valuesCount || PrintIndexError( index, true ) );
861 if(m_uint32Values[ index ] != value)
863 m_uint32Values[ index ] = value;
865 if(m_inWorld)
867 if(!m_objectUpdated)
869 AddToClientUpdateList();
870 m_objectUpdated = true;
876 void Object::SetUInt64Value( uint16 index, const uint64 &value )
878 ASSERT( index + 1 < m_valuesCount || PrintIndexError( index, true ) );
879 if(*((uint64*)&(m_uint32Values[ index ])) != value)
881 m_uint32Values[ index ] = *((uint32*)&value);
882 m_uint32Values[ index + 1 ] = *(((uint32*)&value) + 1);
884 if(m_inWorld)
886 if(!m_objectUpdated)
888 AddToClientUpdateList();
889 m_objectUpdated = true;
895 void Object::SetFloatValue( uint16 index, float value )
897 ASSERT( index < m_valuesCount || PrintIndexError( index, true ) );
899 if(m_floatValues[ index ] != value)
901 m_floatValues[ index ] = value;
903 if(m_inWorld)
905 if(!m_objectUpdated)
907 AddToClientUpdateList();
908 m_objectUpdated = true;
914 void Object::SetByteValue( uint16 index, uint8 offset, uint8 value )
916 ASSERT( index < m_valuesCount || PrintIndexError( index, true ) );
918 if(offset > 4)
920 sLog.outError("Object::SetByteValue: wrong offset %u", offset);
921 return;
924 if(uint8(m_uint32Values[ index ] >> (offset * 8)) != value)
926 m_uint32Values[ index ] &= ~uint32(uint32(0xFF) << (offset * 8));
927 m_uint32Values[ index ] |= uint32(uint32(value) << (offset * 8));
929 if(m_inWorld)
931 if(!m_objectUpdated)
933 AddToClientUpdateList();
934 m_objectUpdated = true;
940 void Object::SetUInt16Value( uint16 index, uint8 offset, uint16 value )
942 ASSERT( index < m_valuesCount || PrintIndexError( index, true ) );
944 if(offset > 2)
946 sLog.outError("Object::SetUInt16Value: wrong offset %u", offset);
947 return;
950 if(uint16(m_uint32Values[ index ] >> (offset * 16)) != value)
952 m_uint32Values[ index ] &= ~uint32(uint32(0xFFFF) << (offset * 16));
953 m_uint32Values[ index ] |= uint32(uint32(value) << (offset * 16));
955 if(m_inWorld)
957 if(!m_objectUpdated)
959 AddToClientUpdateList();
960 m_objectUpdated = true;
966 void Object::SetStatFloatValue( uint16 index, float value)
968 if(value < 0)
969 value = 0.0f;
971 SetFloatValue(index, value);
974 void Object::SetStatInt32Value( uint16 index, int32 value)
976 if(value < 0)
977 value = 0;
979 SetUInt32Value(index, uint32(value));
982 void Object::ApplyModUInt32Value(uint16 index, int32 val, bool apply)
984 int32 cur = GetUInt32Value(index);
985 cur += (apply ? val : -val);
986 if(cur < 0)
987 cur = 0;
988 SetUInt32Value(index, cur);
991 void Object::ApplyModInt32Value(uint16 index, int32 val, bool apply)
993 int32 cur = GetInt32Value(index);
994 cur += (apply ? val : -val);
995 SetInt32Value(index, cur);
998 void Object::ApplyModSignedFloatValue(uint16 index, float val, bool apply)
1000 float cur = GetFloatValue(index);
1001 cur += (apply ? val : -val);
1002 SetFloatValue(index, cur);
1005 void Object::ApplyModPositiveFloatValue(uint16 index, float val, bool apply)
1007 float cur = GetFloatValue(index);
1008 cur += (apply ? val : -val);
1009 if(cur < 0)
1010 cur = 0;
1011 SetFloatValue(index, cur);
1014 void Object::SetFlag( uint16 index, uint32 newFlag )
1016 ASSERT( index < m_valuesCount || PrintIndexError( index, true ) );
1017 uint32 oldval = m_uint32Values[ index ];
1018 uint32 newval = oldval | newFlag;
1020 if(oldval != newval)
1022 m_uint32Values[ index ] = newval;
1024 if(m_inWorld)
1026 if(!m_objectUpdated)
1028 AddToClientUpdateList();
1029 m_objectUpdated = true;
1035 void Object::RemoveFlag( uint16 index, uint32 oldFlag )
1037 ASSERT( index < m_valuesCount || PrintIndexError( index, true ) );
1038 uint32 oldval = m_uint32Values[ index ];
1039 uint32 newval = oldval & ~oldFlag;
1041 if(oldval != newval)
1043 m_uint32Values[ index ] = newval;
1045 if(m_inWorld)
1047 if(!m_objectUpdated)
1049 AddToClientUpdateList();
1050 m_objectUpdated = true;
1056 void Object::SetByteFlag( uint16 index, uint8 offset, uint8 newFlag )
1058 ASSERT( index < m_valuesCount || PrintIndexError( index, true ) );
1060 if(offset > 4)
1062 sLog.outError("Object::SetByteFlag: wrong offset %u", offset);
1063 return;
1066 if(!(uint8(m_uint32Values[ index ] >> (offset * 8)) & newFlag))
1068 m_uint32Values[ index ] |= uint32(uint32(newFlag) << (offset * 8));
1070 if(m_inWorld)
1072 if(!m_objectUpdated)
1074 AddToClientUpdateList();
1075 m_objectUpdated = true;
1081 void Object::RemoveByteFlag( uint16 index, uint8 offset, uint8 oldFlag )
1083 ASSERT( index < m_valuesCount || PrintIndexError( index, true ) );
1085 if(offset > 4)
1087 sLog.outError("Object::RemoveByteFlag: wrong offset %u", offset);
1088 return;
1091 if(uint8(m_uint32Values[ index ] >> (offset * 8)) & oldFlag)
1093 m_uint32Values[ index ] &= ~uint32(uint32(oldFlag) << (offset * 8));
1095 if(m_inWorld)
1097 if(!m_objectUpdated)
1099 AddToClientUpdateList();
1100 m_objectUpdated = true;
1106 bool Object::PrintIndexError(uint32 index, bool set) const
1108 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);
1110 // assert must fail after function call
1111 return false;
1114 void Object::BuildUpdateDataForPlayer(Player* pl, UpdateDataMapType& update_players)
1116 UpdateDataMapType::iterator iter = update_players.find(pl);
1118 if (iter == update_players.end())
1120 std::pair<UpdateDataMapType::iterator, bool> p = update_players.insert( UpdateDataMapType::value_type(pl, UpdateData()) );
1121 assert(p.second);
1122 iter = p.first;
1125 BuildValuesUpdateBlockForPlayer(&iter->second, iter->first);
1128 void Object::AddToClientUpdateList()
1130 sLog.outError("Unexpected call of Object::AddToClientUpdateList for object (TypeId: %u Update fields: %u)",GetTypeId(), m_valuesCount);
1131 ASSERT(false);
1134 void Object::RemoveFromClientUpdateList()
1136 sLog.outError("Unexpected call of Object::RemoveFromClientUpdateList for object (TypeId: %u Update fields: %u)",GetTypeId(), m_valuesCount);
1137 ASSERT(false);
1140 void Object::BuildUpdateData( UpdateDataMapType& update_players )
1142 sLog.outError("Unexpected call of Object::BuildUpdateData for object (TypeId: %u Update fields: %u)",GetTypeId(), m_valuesCount);
1143 ASSERT(false);
1146 WorldObject::WorldObject()
1147 : m_currMap(NULL), m_mapId(0), m_InstanceId(0), m_phaseMask(PHASEMASK_NORMAL),
1148 m_positionX(0.0f), m_positionY(0.0f), m_positionZ(0.0f), m_orientation(0.0f)
1152 void WorldObject::CleanupsBeforeDelete()
1154 RemoveFromWorld();
1157 void WorldObject::_Create( uint32 guidlow, HighGuid guidhigh, uint32 phaseMask )
1159 Object::_Create(guidlow, 0, guidhigh);
1160 m_phaseMask = phaseMask;
1163 uint32 WorldObject::GetZoneId() const
1165 return GetBaseMap()->GetZoneId(m_positionX, m_positionY, m_positionZ);
1168 uint32 WorldObject::GetAreaId() const
1170 return GetBaseMap()->GetAreaId(m_positionX, m_positionY, m_positionZ);
1173 void WorldObject::GetZoneAndAreaId(uint32& zoneid, uint32& areaid) const
1175 GetBaseMap()->GetZoneAndAreaId(zoneid, areaid, m_positionX, m_positionY, m_positionZ);
1178 InstanceData* WorldObject::GetInstanceData()
1180 Map *map = GetMap();
1181 return map->IsDungeon() ? ((InstanceMap*)map)->GetInstanceData() : NULL;
1184 //slow
1185 float WorldObject::GetDistance(const WorldObject* obj) const
1187 float dx = GetPositionX() - obj->GetPositionX();
1188 float dy = GetPositionY() - obj->GetPositionY();
1189 float dz = GetPositionZ() - obj->GetPositionZ();
1190 float sizefactor = GetObjectSize() + obj->GetObjectSize();
1191 float dist = sqrt((dx*dx) + (dy*dy) + (dz*dz)) - sizefactor;
1192 return ( dist > 0 ? dist : 0);
1195 float WorldObject::GetDistance2d(float x, float y) const
1197 float dx = GetPositionX() - x;
1198 float dy = GetPositionY() - y;
1199 float sizefactor = GetObjectSize();
1200 float dist = sqrt((dx*dx) + (dy*dy)) - sizefactor;
1201 return ( dist > 0 ? dist : 0);
1204 float WorldObject::GetDistance(float x, float y, float z) const
1206 float dx = GetPositionX() - x;
1207 float dy = GetPositionY() - y;
1208 float dz = GetPositionZ() - z;
1209 float sizefactor = GetObjectSize();
1210 float dist = sqrt((dx*dx) + (dy*dy) + (dz*dz)) - sizefactor;
1211 return ( dist > 0 ? dist : 0);
1214 float WorldObject::GetDistance2d(const WorldObject* obj) const
1216 float dx = GetPositionX() - obj->GetPositionX();
1217 float dy = GetPositionY() - obj->GetPositionY();
1218 float sizefactor = GetObjectSize() + obj->GetObjectSize();
1219 float dist = sqrt((dx*dx) + (dy*dy)) - sizefactor;
1220 return ( dist > 0 ? dist : 0);
1223 float WorldObject::GetDistanceZ(const WorldObject* obj) const
1225 float dz = fabs(GetPositionZ() - obj->GetPositionZ());
1226 float sizefactor = GetObjectSize() + obj->GetObjectSize();
1227 float dist = dz - sizefactor;
1228 return ( dist > 0 ? dist : 0);
1231 bool WorldObject::IsWithinDist3d(float x, float y, float z, float dist2compare) const
1233 float dx = GetPositionX() - x;
1234 float dy = GetPositionY() - y;
1235 float dz = GetPositionZ() - z;
1236 float distsq = dx*dx + dy*dy + dz*dz;
1238 float sizefactor = GetObjectSize();
1239 float maxdist = dist2compare + sizefactor;
1241 return distsq < maxdist * maxdist;
1244 bool WorldObject::IsWithinDist2d(float x, float y, float dist2compare) const
1246 float dx = GetPositionX() - x;
1247 float dy = GetPositionY() - y;
1248 float distsq = dx*dx + dy*dy;
1250 float sizefactor = GetObjectSize();
1251 float maxdist = dist2compare + sizefactor;
1253 return distsq < maxdist * maxdist;
1256 bool WorldObject::_IsWithinDist(WorldObject const* obj, float dist2compare, bool is3D) const
1258 float dx = GetPositionX() - obj->GetPositionX();
1259 float dy = GetPositionY() - obj->GetPositionY();
1260 float distsq = dx*dx + dy*dy;
1261 if(is3D)
1263 float dz = GetPositionZ() - obj->GetPositionZ();
1264 distsq += dz*dz;
1266 float sizefactor = GetObjectSize() + obj->GetObjectSize();
1267 float maxdist = dist2compare + sizefactor;
1269 return distsq < maxdist * maxdist;
1272 bool WorldObject::IsWithinLOSInMap(const WorldObject* obj) const
1274 if (!IsInMap(obj)) return false;
1275 float ox,oy,oz;
1276 obj->GetPosition(ox,oy,oz);
1277 return(IsWithinLOS(ox, oy, oz ));
1280 bool WorldObject::IsWithinLOS(float ox, float oy, float oz) const
1282 float x,y,z;
1283 GetPosition(x,y,z);
1284 VMAP::IVMapManager *vMapManager = VMAP::VMapFactory::createOrGetVMapManager();
1285 return vMapManager->isInLineOfSight(GetMapId(), x, y, z+2.0f, ox, oy, oz+2.0f);
1288 bool WorldObject::GetDistanceOrder(WorldObject const* obj1, WorldObject const* obj2, bool is3D /* = true */) const
1290 float dx1 = GetPositionX() - obj1->GetPositionX();
1291 float dy1 = GetPositionY() - obj1->GetPositionY();
1292 float distsq1 = dx1*dx1 + dy1*dy1;
1293 if(is3D)
1295 float dz1 = GetPositionZ() - obj1->GetPositionZ();
1296 distsq1 += dz1*dz1;
1299 float dx2 = GetPositionX() - obj2->GetPositionX();
1300 float dy2 = GetPositionY() - obj2->GetPositionY();
1301 float distsq2 = dx2*dx2 + dy2*dy2;
1302 if(is3D)
1304 float dz2 = GetPositionZ() - obj2->GetPositionZ();
1305 distsq2 += dz2*dz2;
1308 return distsq1 < distsq2;
1311 bool WorldObject::IsInRange(WorldObject const* obj, float minRange, float maxRange, bool is3D /* = true */) const
1313 float dx = GetPositionX() - obj->GetPositionX();
1314 float dy = GetPositionY() - obj->GetPositionY();
1315 float distsq = dx*dx + dy*dy;
1316 if(is3D)
1318 float dz = GetPositionZ() - obj->GetPositionZ();
1319 distsq += dz*dz;
1322 float sizefactor = GetObjectSize() + obj->GetObjectSize();
1324 // check only for real range
1325 if(minRange > 0.0f)
1327 float mindist = minRange + sizefactor;
1328 if(distsq < mindist * mindist)
1329 return false;
1332 float maxdist = maxRange + sizefactor;
1333 return distsq < maxdist * maxdist;
1336 bool WorldObject::IsInRange2d(float x, float y, float minRange, float maxRange) const
1338 float dx = GetPositionX() - x;
1339 float dy = GetPositionY() - y;
1340 float distsq = dx*dx + dy*dy;
1342 float sizefactor = GetObjectSize();
1344 // check only for real range
1345 if(minRange > 0.0f)
1347 float mindist = minRange + sizefactor;
1348 if(distsq < mindist * mindist)
1349 return false;
1352 float maxdist = maxRange + sizefactor;
1353 return distsq < maxdist * maxdist;
1356 bool WorldObject::IsInRange3d(float x, float y, float z, float minRange, float maxRange) const
1358 float dx = GetPositionX() - x;
1359 float dy = GetPositionY() - y;
1360 float dz = GetPositionZ() - z;
1361 float distsq = dx*dx + dy*dy + dz*dz;
1363 float sizefactor = GetObjectSize();
1365 // check only for real range
1366 if(minRange > 0.0f)
1368 float mindist = minRange + sizefactor;
1369 if(distsq < mindist * mindist)
1370 return false;
1373 float maxdist = maxRange + sizefactor;
1374 return distsq < maxdist * maxdist;
1377 float WorldObject::GetAngle(const WorldObject* obj) const
1379 if(!obj) return 0;
1380 return GetAngle( obj->GetPositionX(), obj->GetPositionY() );
1383 // Return angle in range 0..2*pi
1384 float WorldObject::GetAngle( const float x, const float y ) const
1386 float dx = x - GetPositionX();
1387 float dy = y - GetPositionY();
1389 float ang = atan2(dy, dx);
1390 ang = (ang >= 0) ? ang : 2 * M_PI + ang;
1391 return ang;
1394 bool WorldObject::HasInArc(const float arcangle, const WorldObject* obj) const
1396 // always have self in arc
1397 if(obj == this)
1398 return true;
1400 float arc = arcangle;
1402 // move arc to range 0.. 2*pi
1403 while( arc >= 2.0f * M_PI )
1404 arc -= 2.0f * M_PI;
1405 while( arc < 0 )
1406 arc += 2.0f * M_PI;
1408 float angle = GetAngle( obj );
1409 angle -= m_orientation;
1411 // move angle to range -pi ... +pi
1412 while( angle > M_PI)
1413 angle -= 2.0f * M_PI;
1414 while(angle < -M_PI)
1415 angle += 2.0f * M_PI;
1417 float lborder = -1 * (arc/2.0f); // in range -pi..0
1418 float rborder = (arc/2.0f); // in range 0..pi
1419 return (( angle >= lborder ) && ( angle <= rborder ));
1422 bool WorldObject::isInFrontInMap(WorldObject const* target, float distance, float arc) const
1424 return IsWithinDistInMap(target, distance) && HasInArc( arc, target );
1427 bool WorldObject::isInBackInMap(WorldObject const* target, float distance, float arc) const
1429 return IsWithinDistInMap(target, distance) && !HasInArc( 2 * M_PI - arc, target );
1432 bool WorldObject::isInFront(WorldObject const* target, float distance, float arc) const
1434 return IsWithinDist(target, distance) && HasInArc( arc, target );
1437 bool WorldObject::isInBack(WorldObject const* target, float distance, float arc) const
1439 return IsWithinDist(target, distance) && !HasInArc( 2 * M_PI - arc, target );
1442 void WorldObject::GetRandomPoint( float x, float y, float z, float distance, float &rand_x, float &rand_y, float &rand_z) const
1444 if(distance == 0)
1446 rand_x = x;
1447 rand_y = y;
1448 rand_z = z;
1449 return;
1452 // angle to face `obj` to `this`
1453 float angle = rand_norm()*2*M_PI;
1454 float new_dist = rand_norm()*distance;
1456 rand_x = x + new_dist * cos(angle);
1457 rand_y = y + new_dist * sin(angle);
1458 rand_z = z;
1460 MaNGOS::NormalizeMapCoord(rand_x);
1461 MaNGOS::NormalizeMapCoord(rand_y);
1462 UpdateGroundPositionZ(rand_x,rand_y,rand_z); // update to LOS height if available
1465 void WorldObject::UpdateGroundPositionZ(float x, float y, float &z) const
1467 float new_z = GetBaseMap()->GetHeight(x,y,z,true);
1468 if(new_z > INVALID_HEIGHT)
1469 z = new_z+ 0.05f; // just to be sure that we are not a few pixel under the surface
1472 bool WorldObject::IsPositionValid() const
1474 return MaNGOS::IsValidMapCoord(m_positionX,m_positionY,m_positionZ,m_orientation);
1477 void WorldObject::MonsterSay(const char* text, uint32 language, uint64 TargetGuid)
1479 WorldPacket data(SMSG_MESSAGECHAT, 200);
1480 BuildMonsterChat(&data,CHAT_MSG_MONSTER_SAY,text,language,GetName(),TargetGuid);
1481 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
1484 void WorldObject::MonsterYell(const char* text, uint32 language, uint64 TargetGuid)
1486 WorldPacket data(SMSG_MESSAGECHAT, 200);
1487 BuildMonsterChat(&data,CHAT_MSG_MONSTER_YELL,text,language,GetName(),TargetGuid);
1488 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
1491 void WorldObject::MonsterTextEmote(const char* text, uint64 TargetGuid, bool IsBossEmote)
1493 WorldPacket data(SMSG_MESSAGECHAT, 200);
1494 BuildMonsterChat(&data,IsBossEmote ? CHAT_MSG_RAID_BOSS_EMOTE : CHAT_MSG_MONSTER_EMOTE,text,LANG_UNIVERSAL,GetName(),TargetGuid);
1495 SendMessageToSetInRange(&data,sWorld.getConfig(IsBossEmote ? CONFIG_LISTEN_RANGE_YELL : CONFIG_LISTEN_RANGE_TEXTEMOTE),true);
1498 void WorldObject::MonsterWhisper(const char* text, uint64 receiver, bool IsBossWhisper)
1500 Player *player = sObjectMgr.GetPlayer(receiver);
1501 if(!player || !player->GetSession())
1502 return;
1504 WorldPacket data(SMSG_MESSAGECHAT, 200);
1505 BuildMonsterChat(&data,IsBossWhisper ? CHAT_MSG_RAID_BOSS_WHISPER : CHAT_MSG_MONSTER_WHISPER,text,LANG_UNIVERSAL,GetName(),receiver);
1507 player->GetSession()->SendPacket(&data);
1510 namespace MaNGOS
1512 class MonsterChatBuilder
1514 public:
1515 MonsterChatBuilder(WorldObject const& obj, ChatMsg msgtype, int32 textId, uint32 language, uint64 targetGUID)
1516 : i_object(obj), i_msgtype(msgtype), i_textId(textId), i_language(language), i_targetGUID(targetGUID) {}
1517 void operator()(WorldPacket& data, int32 loc_idx)
1519 char const* text = sObjectMgr.GetMangosString(i_textId,loc_idx);
1521 // TODO: i_object.GetName() also must be localized?
1522 i_object.BuildMonsterChat(&data,i_msgtype,text,i_language,i_object.GetNameForLocaleIdx(loc_idx),i_targetGUID);
1525 private:
1526 WorldObject const& i_object;
1527 ChatMsg i_msgtype;
1528 int32 i_textId;
1529 uint32 i_language;
1530 uint64 i_targetGUID;
1532 } // namespace MaNGOS
1534 void WorldObject::MonsterSay(int32 textId, uint32 language, uint64 TargetGuid)
1536 CellPair p = MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY());
1538 Cell cell(p);
1539 cell.data.Part.reserved = ALL_DISTRICT;
1540 cell.SetNoCreate();
1542 MaNGOS::MonsterChatBuilder say_build(*this, CHAT_MSG_MONSTER_SAY, textId,language,TargetGuid);
1543 MaNGOS::LocalizedPacketDo<MaNGOS::MonsterChatBuilder> say_do(say_build);
1544 MaNGOS::PlayerDistWorker<MaNGOS::LocalizedPacketDo<MaNGOS::MonsterChatBuilder> > say_worker(this,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),say_do);
1545 TypeContainerVisitor<MaNGOS::PlayerDistWorker<MaNGOS::LocalizedPacketDo<MaNGOS::MonsterChatBuilder> >, WorldTypeMapContainer > message(say_worker);
1546 CellLock<GridReadGuard> cell_lock(cell, p);
1547 cell_lock->Visit(cell_lock, message, *GetMap(), *this, sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY));
1550 void WorldObject::MonsterYell(int32 textId, uint32 language, uint64 TargetGuid)
1552 CellPair p = MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY());
1554 Cell cell(p);
1555 cell.data.Part.reserved = ALL_DISTRICT;
1556 cell.SetNoCreate();
1558 MaNGOS::MonsterChatBuilder say_build(*this, CHAT_MSG_MONSTER_YELL, textId,language,TargetGuid);
1559 MaNGOS::LocalizedPacketDo<MaNGOS::MonsterChatBuilder> say_do(say_build);
1560 MaNGOS::PlayerDistWorker<MaNGOS::LocalizedPacketDo<MaNGOS::MonsterChatBuilder> > say_worker(this,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),say_do);
1561 TypeContainerVisitor<MaNGOS::PlayerDistWorker<MaNGOS::LocalizedPacketDo<MaNGOS::MonsterChatBuilder> >, WorldTypeMapContainer > message(say_worker);
1562 CellLock<GridReadGuard> cell_lock(cell, p);
1563 cell_lock->Visit(cell_lock, message, *GetMap(), *this, sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL));
1566 void WorldObject::MonsterYellToZone(int32 textId, uint32 language, uint64 TargetGuid)
1568 MaNGOS::MonsterChatBuilder say_build(*this, CHAT_MSG_MONSTER_YELL, textId,language,TargetGuid);
1569 MaNGOS::LocalizedPacketDo<MaNGOS::MonsterChatBuilder> say_do(say_build);
1571 uint32 zoneid = GetZoneId();
1573 Map::PlayerList const& pList = GetMap()->GetPlayers();
1574 for(Map::PlayerList::const_iterator itr = pList.begin(); itr != pList.end(); ++itr)
1575 if(itr->getSource()->GetZoneId()==zoneid)
1576 say_do(itr->getSource());
1579 void WorldObject::MonsterTextEmote(int32 textId, uint64 TargetGuid, bool IsBossEmote)
1581 CellPair p = MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY());
1583 Cell cell(p);
1584 cell.data.Part.reserved = ALL_DISTRICT;
1585 cell.SetNoCreate();
1587 MaNGOS::MonsterChatBuilder say_build(*this, IsBossEmote ? CHAT_MSG_RAID_BOSS_EMOTE : CHAT_MSG_MONSTER_EMOTE, textId,LANG_UNIVERSAL,TargetGuid);
1588 MaNGOS::LocalizedPacketDo<MaNGOS::MonsterChatBuilder> say_do(say_build);
1589 MaNGOS::PlayerDistWorker<MaNGOS::LocalizedPacketDo<MaNGOS::MonsterChatBuilder> > say_worker(this,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),say_do);
1590 TypeContainerVisitor<MaNGOS::PlayerDistWorker<MaNGOS::LocalizedPacketDo<MaNGOS::MonsterChatBuilder> >, WorldTypeMapContainer > message(say_worker);
1591 CellLock<GridReadGuard> cell_lock(cell, p);
1592 cell_lock->Visit(cell_lock, message, *GetMap(), *this, sWorld.getConfig(IsBossEmote ? CONFIG_LISTEN_RANGE_YELL : CONFIG_LISTEN_RANGE_TEXTEMOTE));
1595 void WorldObject::MonsterWhisper(int32 textId, uint64 receiver, bool IsBossWhisper)
1597 Player *player = sObjectMgr.GetPlayer(receiver);
1598 if(!player || !player->GetSession())
1599 return;
1601 uint32 loc_idx = player->GetSession()->GetSessionDbLocaleIndex();
1602 char const* text = sObjectMgr.GetMangosString(textId,loc_idx);
1604 WorldPacket data(SMSG_MESSAGECHAT, 200);
1605 BuildMonsterChat(&data,IsBossWhisper ? CHAT_MSG_RAID_BOSS_WHISPER : CHAT_MSG_MONSTER_WHISPER,text,LANG_UNIVERSAL,GetNameForLocaleIdx(loc_idx),receiver);
1607 player->GetSession()->SendPacket(&data);
1610 void WorldObject::BuildMonsterChat(WorldPacket *data, uint8 msgtype, char const* text, uint32 language, char const* name, uint64 targetGuid) const
1612 *data << (uint8)msgtype;
1613 *data << (uint32)language;
1614 *data << (uint64)GetGUID();
1615 *data << (uint32)0; // 2.1.0
1616 *data << (uint32)(strlen(name)+1);
1617 *data << name;
1618 *data << (uint64)targetGuid; // Unit Target
1619 if( targetGuid && !IS_PLAYER_GUID(targetGuid) )
1621 *data << (uint32)1; // target name length
1622 *data << (uint8)0; // target name
1624 *data << (uint32)(strlen(text)+1);
1625 *data << text;
1626 *data << (uint8)0; // ChatTag
1629 void WorldObject::SendMessageToSet(WorldPacket *data, bool /*bToSelf*/)
1631 //if object is in world, map for it already created!
1632 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
1633 if(_map)
1634 _map->MessageBroadcast(this, data);
1637 void WorldObject::SendMessageToSetInRange(WorldPacket *data, float dist, bool /*bToSelf*/)
1639 //if object is in world, map for it already created!
1640 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
1641 if(_map)
1642 _map->MessageDistBroadcast(this, data, dist);
1645 void WorldObject::SendObjectDeSpawnAnim(uint64 guid)
1647 WorldPacket data(SMSG_GAMEOBJECT_DESPAWN_ANIM, 8);
1648 data << uint64(guid);
1649 SendMessageToSet(&data, true);
1652 void WorldObject::SetMap(Map * map)
1654 ASSERT(map);
1655 m_currMap = map;
1656 //lets save current map's Id/instanceId
1657 m_mapId = map->GetId();
1658 m_InstanceId = map->GetInstanceId();
1661 Map const* WorldObject::GetBaseMap() const
1663 ASSERT(m_currMap);
1664 return m_currMap->GetParent();
1667 void WorldObject::AddObjectToRemoveList()
1669 GetMap()->AddObjectToRemoveList(this);
1672 Creature* WorldObject::SummonCreature(uint32 id, float x, float y, float z, float ang,TempSummonType spwtype,uint32 despwtime)
1674 TemporarySummon* pCreature = new TemporarySummon(GetGUID());
1676 uint32 team = 0;
1677 if (GetTypeId()==TYPEID_PLAYER)
1678 team = ((Player*)this)->GetTeam();
1680 if (!pCreature->Create(sObjectMgr.GenerateLowGuid(HIGHGUID_UNIT), GetMap(), GetPhaseMask(), id, team))
1682 delete pCreature;
1683 return NULL;
1686 if (x == 0.0f && y == 0.0f && z == 0.0f)
1687 GetClosePoint(x, y, z, pCreature->GetObjectSize());
1689 pCreature->Relocate(x, y, z, ang);
1690 pCreature->SetSummonPoint(x, y, z, ang);
1692 if(!pCreature->IsPositionValid())
1694 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());
1695 delete pCreature;
1696 return NULL;
1699 pCreature->Summon(spwtype, despwtime);
1701 if(GetTypeId()==TYPEID_UNIT && ((Creature*)this)->AI())
1702 ((Creature*)this)->AI()->JustSummoned(pCreature);
1704 // return the creature therewith the summoner has access to it
1705 return pCreature;
1708 namespace MaNGOS
1710 class NearUsedPosDo
1712 public:
1713 NearUsedPosDo(WorldObject const& obj, WorldObject const* searcher, float angle, ObjectPosSelector& selector)
1714 : i_object(obj), i_searcher(searcher), i_angle(angle), i_selector(selector) {}
1716 void operator()(Corpse*) const {}
1717 void operator()(DynamicObject*) const {}
1719 void operator()(Creature* c) const
1721 // skip self or target
1722 if(c==i_searcher || c==&i_object)
1723 return;
1725 float x,y,z;
1727 if( !c->isAlive() || c->hasUnitState(UNIT_STAT_ROOT | UNIT_STAT_STUNNED | UNIT_STAT_DISTRACTED | UNIT_STAT_DIED) ||
1728 !c->GetMotionMaster()->GetDestination(x,y,z) )
1730 x = c->GetPositionX();
1731 y = c->GetPositionY();
1734 add(c,x,y);
1737 template<class T>
1738 void operator()(T* u) const
1740 // skip self or target
1741 if(u==i_searcher || u==&i_object)
1742 return;
1744 float x,y;
1746 x = u->GetPositionX();
1747 y = u->GetPositionY();
1749 add(u,x,y);
1752 // we must add used pos that can fill places around center
1753 void add(WorldObject* u, float x, float y) const
1755 // u is too nearest/far away to i_object
1756 if(!i_object.IsInRange2d(x,y,i_selector.m_dist - i_selector.m_size,i_selector.m_dist + i_selector.m_size))
1757 return;
1759 float angle = i_object.GetAngle(u)-i_angle;
1761 // move angle to range -pi ... +pi
1762 while( angle > M_PI)
1763 angle -= 2.0f * M_PI;
1764 while(angle < -M_PI)
1765 angle += 2.0f * M_PI;
1767 // dist include size of u
1768 float dist2d = i_object.GetDistance2d(x,y);
1769 i_selector.AddUsedPos(u->GetObjectSize(),angle,dist2d + i_object.GetObjectSize());
1771 private:
1772 WorldObject const& i_object;
1773 WorldObject const* i_searcher;
1774 float i_angle;
1775 ObjectPosSelector& i_selector;
1777 } // namespace MaNGOS
1779 //===================================================================================================
1781 void WorldObject::GetNearPoint2D(float &x, float &y, float distance2d, float absAngle ) const
1783 x = GetPositionX() + (GetObjectSize() + distance2d) * cos(absAngle);
1784 y = GetPositionY() + (GetObjectSize() + distance2d) * sin(absAngle);
1786 MaNGOS::NormalizeMapCoord(x);
1787 MaNGOS::NormalizeMapCoord(y);
1790 void WorldObject::GetNearPoint(WorldObject const* searcher, float &x, float &y, float &z, float searcher_size, float distance2d, float absAngle ) const
1792 GetNearPoint2D(x,y,distance2d+searcher_size,absAngle);
1793 z = GetPositionZ();
1795 // if detection disabled, return first point
1796 if(!sWorld.getConfig(CONFIG_DETECT_POS_COLLISION))
1798 UpdateGroundPositionZ(x,y,z); // update to LOS height if available
1799 return;
1802 // or remember first point
1803 float first_x = x;
1804 float first_y = y;
1805 bool first_los_conflict = false; // first point LOS problems
1807 // prepare selector for work
1808 ObjectPosSelector selector(GetPositionX(),GetPositionY(),GetObjectSize(),distance2d+searcher_size);
1810 // adding used positions around object
1812 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
1813 Cell cell(p);
1814 cell.data.Part.reserved = ALL_DISTRICT;
1815 cell.SetNoCreate();
1817 MaNGOS::NearUsedPosDo u_do(*this,searcher,absAngle,selector);
1818 MaNGOS::WorldObjectWorker<MaNGOS::NearUsedPosDo> worker(this,u_do);
1820 TypeContainerVisitor<MaNGOS::WorldObjectWorker<MaNGOS::NearUsedPosDo>, GridTypeMapContainer > grid_obj_worker(worker);
1821 TypeContainerVisitor<MaNGOS::WorldObjectWorker<MaNGOS::NearUsedPosDo>, WorldTypeMapContainer > world_obj_worker(worker);
1823 CellLock<GridReadGuard> cell_lock(cell, p);
1824 cell_lock->Visit(cell_lock, grid_obj_worker, *GetMap(), *this, distance2d);
1825 cell_lock->Visit(cell_lock, world_obj_worker, *GetMap(), *this, distance2d);
1828 // maybe can just place in primary position
1829 if( selector.CheckOriginal() )
1831 UpdateGroundPositionZ(x,y,z); // update to LOS height if available
1833 if(IsWithinLOS(x,y,z))
1834 return;
1836 first_los_conflict = true; // first point have LOS problems
1839 float angle; // candidate of angle for free pos
1841 // special case when one from list empty and then empty side preferred
1842 if(selector.FirstAngle(angle))
1844 GetNearPoint2D(x,y,distance2d,absAngle+angle);
1845 z = GetPositionZ();
1846 UpdateGroundPositionZ(x,y,z); // update to LOS height if available
1848 if(IsWithinLOS(x,y,z))
1849 return;
1852 // set first used pos in lists
1853 selector.InitializeAngle();
1855 // select in positions after current nodes (selection one by one)
1856 while(selector.NextAngle(angle)) // angle for free pos
1858 GetNearPoint2D(x,y,distance2d,absAngle+angle);
1859 z = GetPositionZ();
1860 UpdateGroundPositionZ(x,y,z); // update to LOS height if available
1862 if(IsWithinLOS(x,y,z))
1863 return;
1866 // BAD NEWS: not free pos (or used or have LOS problems)
1867 // Attempt find _used_ pos without LOS problem
1869 if(!first_los_conflict)
1871 x = first_x;
1872 y = first_y;
1874 UpdateGroundPositionZ(x,y,z); // update to LOS height if available
1875 return;
1878 // special case when one from list empty and then empty side preferred
1879 if( selector.IsNonBalanced() )
1881 if(!selector.FirstAngle(angle)) // _used_ pos
1883 GetNearPoint2D(x,y,distance2d,absAngle+angle);
1884 z = GetPositionZ();
1885 UpdateGroundPositionZ(x,y,z); // update to LOS height if available
1887 if(IsWithinLOS(x,y,z))
1888 return;
1892 // set first used pos in lists
1893 selector.InitializeAngle();
1895 // select in positions after current nodes (selection one by one)
1896 while(selector.NextUsedAngle(angle)) // angle for used pos but maybe without LOS problem
1898 GetNearPoint2D(x,y,distance2d,absAngle+angle);
1899 z = GetPositionZ();
1900 UpdateGroundPositionZ(x,y,z); // update to LOS height if available
1902 if(IsWithinLOS(x,y,z))
1903 return;
1906 // BAD BAD NEWS: all found pos (free and used) have LOS problem :(
1907 x = first_x;
1908 y = first_y;
1910 UpdateGroundPositionZ(x,y,z); // update to LOS height if available
1913 void WorldObject::SetPhaseMask(uint32 newPhaseMask, bool update)
1915 m_phaseMask = newPhaseMask;
1917 if(update && IsInWorld())
1918 UpdateObjectVisibility();
1921 void WorldObject::PlayDistanceSound( uint32 sound_id, Player* target /*= NULL*/ )
1923 WorldPacket data(SMSG_PLAY_OBJECT_SOUND,4+8);
1924 data << uint32(sound_id);
1925 data << uint64(GetGUID());
1926 if (target)
1927 target->SendDirectMessage( &data );
1928 else
1929 SendMessageToSet( &data, true );
1932 void WorldObject::PlayDirectSound( uint32 sound_id, Player* target /*= NULL*/ )
1934 WorldPacket data(SMSG_PLAY_SOUND, 4);
1935 data << uint32(sound_id);
1936 if (target)
1937 target->SendDirectMessage( &data );
1938 else
1939 SendMessageToSet( &data, true );
1942 void WorldObject::UpdateObjectVisibility()
1944 CellPair p = MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY());
1945 Cell cell(p);
1947 GetMap()->UpdateObjectVisibility(this, cell, p);
1950 void WorldObject::AddToClientUpdateList()
1952 GetMap()->AddUpdateObject(this);
1955 void WorldObject::RemoveFromClientUpdateList()
1957 GetMap()->RemoveUpdateObject(this);
1960 struct WorldObjectChangeAccumulator
1962 UpdateDataMapType &i_updateDatas;
1963 WorldObject &i_object;
1964 WorldObjectChangeAccumulator(WorldObject &obj, UpdateDataMapType &d) : i_updateDatas(d), i_object(obj) {}
1965 void Visit(PlayerMapType &m)
1967 for(PlayerMapType::iterator iter = m.begin(); iter != m.end(); ++iter)
1968 if(iter->getSource()->HaveAtClient(&i_object))
1969 i_object.BuildUpdateDataForPlayer(iter->getSource(), i_updateDatas);
1972 template<class SKIP> void Visit(GridRefManager<SKIP> &) {}
1975 void WorldObject::BuildUpdateData( UpdateDataMapType & update_players)
1977 CellPair p = MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY());
1978 Cell cell(p);
1979 cell.data.Part.reserved = ALL_DISTRICT;
1980 cell.SetNoCreate();
1981 WorldObjectChangeAccumulator notifier(*this, update_players);
1982 TypeContainerVisitor<WorldObjectChangeAccumulator, WorldTypeMapContainer > player_notifier(notifier);
1983 CellLock<GridReadGuard> cell_lock(cell, p);
1984 Map* aMap = GetMap();
1985 //we must build packets for all visible players
1986 cell_lock->Visit(cell_lock, player_notifier, *aMap, *this, aMap->GetVisibilityDistance());
1988 ClearUpdateMask(false);