root/trunk/src/game/Object.cpp @ 19

Revision 19, 45.8 kB (checked in by yumileroy, 17 years ago)

[svn] * Removed ObjectPosSelector? and DetectPosCollision?. See http://www.trinitycore.org/forum/project.php?issueid=3
* Need win32 build fix ;)

Original author: derex_tri
Date: 2008-10-06 07:39:04-05:00

Line 
1/*
2 * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
3 *
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.
8 *
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.
13 *
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
17 */
18
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 "ObjectMgr.h"
29#include "WorldSession.h"
30#include "UpdateData.h"
31#include "UpdateMask.h"
32#include "Util.h"
33#include "MapManager.h"
34#include "ObjectAccessor.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"
43
44#include "TemporarySummon.h"
45
46uint32 GuidHigh2TypeId(uint32 guid_hi)
47{
48    switch(guid_hi)
49    {
50        case HIGHGUID_ITEM:         return TYPEID_ITEM;
51        //case HIGHGUID_CONTAINER:    return TYPEID_CONTAINER; HIGHGUID_CONTAINER==HIGHGUID_ITEM currently
52        case HIGHGUID_UNIT:         return TYPEID_UNIT;
53        case HIGHGUID_PET:          return TYPEID_UNIT;
54        case HIGHGUID_PLAYER:       return TYPEID_PLAYER;
55        case HIGHGUID_GAMEOBJECT:   return TYPEID_GAMEOBJECT;
56        case HIGHGUID_DYNAMICOBJECT:return TYPEID_DYNAMICOBJECT;
57        case HIGHGUID_CORPSE:       return TYPEID_CORPSE;
58        case HIGHGUID_MO_TRANSPORT: return TYPEID_GAMEOBJECT;
59    }
60    return 10;                                              // unknown
61}
62
63Object::Object( )
64{
65    m_objectTypeId      = TYPEID_OBJECT;
66    m_objectType        = TYPEMASK_OBJECT;
67
68    m_uint32Values      = 0;
69    m_uint32Values_mirror = 0;
70    m_valuesCount       = 0;
71
72    m_inWorld           = false;
73    m_objectUpdated     = false;
74
75    m_PackGUID.clear();
76    m_PackGUID.appendPackGUID(0);
77}
78
79Object::~Object( )
80{
81    if(m_objectUpdated)
82        ObjectAccessor::Instance().RemoveUpdateObject(this);
83
84    if(m_uint32Values)
85    {
86        if(IsInWorld())
87        {
88            ///- Do NOT call RemoveFromWorld here, if the object is a player it will crash
89            sLog.outError("Object::~Object - guid="I64FMTD", typeid=%d deleted but still in world!!", GetGUID(), GetTypeId());
90            //assert(0);
91        }
92
93        //DEBUG_LOG("Object desctr 1 check (%p)",(void*)this);
94        delete [] m_uint32Values;
95        delete [] m_uint32Values_mirror;
96        //DEBUG_LOG("Object desctr 2 check (%p)",(void*)this);
97    }
98}
99
100void Object::_InitValues()
101{
102    m_uint32Values = new uint32[ m_valuesCount ];
103    memset(m_uint32Values, 0, m_valuesCount*sizeof(uint32));
104
105    m_uint32Values_mirror = new uint32[ m_valuesCount ];
106    memset(m_uint32Values_mirror, 0, m_valuesCount*sizeof(uint32));
107
108    m_objectUpdated = false;
109}
110
111void Object::_Create( uint32 guidlow, uint32 entry, HighGuid guidhigh )
112{
113    if(!m_uint32Values) _InitValues();
114
115    uint64 guid = MAKE_NEW_GUID(guidlow, entry, guidhigh);  // required more changes to make it working
116    SetUInt64Value( OBJECT_FIELD_GUID, guid );
117    SetUInt32Value( OBJECT_FIELD_TYPE, m_objectType );
118    m_PackGUID.clear();
119    m_PackGUID.appendPackGUID(GetGUID());
120}
121
122void Object::BuildMovementUpdateBlock(UpdateData * data, uint32 flags ) const
123{
124    ByteBuffer buf(500);
125
126    buf << uint8( UPDATETYPE_MOVEMENT );
127    buf << GetGUID();
128
129    _BuildMovementUpdate(&buf, flags, 0x00000000);
130
131    data->AddUpdateBlock(buf);
132}
133
134void Object::BuildCreateUpdateBlockForPlayer(UpdateData *data, Player *target) const
135{
136    if(!target)
137    {
138        return;
139    }
140
141    uint8  updatetype = UPDATETYPE_CREATE_OBJECT;
142    uint8  flags      = m_updateFlag;
143    uint32 flags2     = 0;
144
145    /** lower flag1 **/
146    if(target == this)                                      // building packet for oneself
147    {
148        flags |= UPDATEFLAG_SELF;
149
150        /*** temporary reverted - until real source of stack corruption will not found
151        updatetype = UPDATETYPE_CREATE_OBJECT2;
152        ****/
153    }
154
155    if(flags & UPDATEFLAG_HASPOSITION)
156    {
157        // UPDATETYPE_CREATE_OBJECT2 dynamic objects, corpses...
158        if(isType(TYPEMASK_DYNAMICOBJECT) || isType(TYPEMASK_CORPSE) || isType(TYPEMASK_PLAYER))
159            updatetype = UPDATETYPE_CREATE_OBJECT2;
160
161        // UPDATETYPE_CREATE_OBJECT2 for pets...
162        if(target->GetPetGUID() == GetGUID())
163            updatetype = UPDATETYPE_CREATE_OBJECT2;
164
165        // UPDATETYPE_CREATE_OBJECT2 for some gameobject types...
166        if(isType(TYPEMASK_GAMEOBJECT))
167        {
168            switch(((GameObject*)this)->GetGoType())
169            {
170                case GAMEOBJECT_TYPE_TRAP:
171                case GAMEOBJECT_TYPE_DUEL_ARBITER:
172                case GAMEOBJECT_TYPE_FLAGSTAND:
173                case GAMEOBJECT_TYPE_FLAGDROP:
174                    updatetype = UPDATETYPE_CREATE_OBJECT2;
175                    break;
176                case GAMEOBJECT_TYPE_TRANSPORT:
177                    flags |= UPDATEFLAG_TRANSPORT;
178                    break;
179            }
180        }
181    }
182
183    //sLog.outDebug("BuildCreateUpdate: update-type: %u, object-type: %u got flags: %X, flags2: %X", updatetype, m_objectTypeId, flags, flags2);
184
185    ByteBuffer buf(500);
186    buf << (uint8)updatetype;
187    //buf.append(GetPackGUID());    //client crashes when using this
188    buf << (uint8)0xFF << GetGUID();
189    buf << (uint8)m_objectTypeId;
190
191    _BuildMovementUpdate(&buf, flags, flags2);
192
193    UpdateMask updateMask;
194    updateMask.SetCount( m_valuesCount );
195    _SetCreateBits( &updateMask, target );
196    _BuildValuesUpdate(updatetype, &buf, &updateMask, target );
197    data->AddUpdateBlock(buf);
198}
199
200void Object::BuildUpdate(UpdateDataMapType &update_players)
201{
202    ObjectAccessor::_buildUpdateObject(this,update_players);
203    ClearUpdateMask(true);
204}
205
206void Object::SendUpdateToPlayer(Player* player)
207{
208    // send update to another players
209    SendUpdateObjectToAllExcept(player);
210
211    // send create update to player
212    UpdateData upd;
213    WorldPacket packet;
214
215    upd.Clear();
216    BuildCreateUpdateBlockForPlayer(&upd, player);
217    upd.BuildPacket(&packet);
218    player->GetSession()->SendPacket(&packet);
219
220    // now object updated/(create updated)
221}
222
223void Object::BuildValuesUpdateBlockForPlayer(UpdateData *data, Player *target) const
224{
225    ByteBuffer buf(500);
226
227    buf << (uint8) UPDATETYPE_VALUES;
228    //buf.append(GetPackGUID());    //client crashes when using this. but not have crash in debug mode
229    buf << (uint8)0xFF;
230    buf << GetGUID();
231
232    UpdateMask updateMask;
233    updateMask.SetCount( m_valuesCount );
234
235    _SetUpdateBits( &updateMask, target );
236    _BuildValuesUpdate(UPDATETYPE_VALUES, &buf, &updateMask, target );
237
238    data->AddUpdateBlock(buf);
239}
240
241void Object::BuildOutOfRangeUpdateBlock(UpdateData * data) const
242{
243    data->AddOutOfRangeGUID(GetGUID());
244}
245
246void Object::DestroyForPlayer(Player *target) const
247{
248    ASSERT(target);
249
250    WorldPacket data(SMSG_DESTROY_OBJECT, 8);
251    data << GetGUID();
252    target->GetSession()->SendPacket( &data );
253}
254
255void Object::_BuildMovementUpdate(ByteBuffer * data, uint8 flags, uint32 flags2 ) const
256{
257    *data << (uint8)flags;                                  // update flags
258
259    // 0x20
260    if (flags & UPDATEFLAG_LIVING)
261    {
262        switch(GetTypeId())
263        {
264            case TYPEID_UNIT:
265            {
266                flags2 = ((Unit*)this)->GetUnitMovementFlags();
267            }
268            break;
269            case TYPEID_PLAYER:
270            {
271                flags2 = ((Player*)this)->GetUnitMovementFlags();
272
273                if(((Player*)this)->GetTransport())
274                    flags2 |= MOVEMENTFLAG_ONTRANSPORT;
275                else
276                    flags2 &= ~MOVEMENTFLAG_ONTRANSPORT;
277
278                // remove unknown, unused etc flags for now
279                flags2 &= ~MOVEMENTFLAG_SPLINE2;            // will be set manually
280
281                if(((Player*)this)->isInFlight())
282                {
283                    WPAssert(((Player*)this)->GetMotionMaster()->GetCurrentMovementGeneratorType() == FLIGHT_MOTION_TYPE);
284                    flags2 = (MOVEMENTFLAG_FORWARD | MOVEMENTFLAG_SPLINE2);
285                }
286            }
287            break;
288        }
289
290        *data << uint32(flags2);                            // movement flags
291        *data << uint8(0);                                  // unk 2.3.0
292        *data << uint32(getMSTime());                       // time (in milliseconds)
293    }
294
295    // 0x40
296    if (flags & UPDATEFLAG_HASPOSITION)
297    {
298        // 0x02
299        if(flags & UPDATEFLAG_TRANSPORT && ((GameObject*)this)->GetGoType() == GAMEOBJECT_TYPE_MO_TRANSPORT)
300        {
301            *data << (float)0;
302            *data << (float)0;
303            *data << (float)0;
304            *data << ((WorldObject *)this)->GetOrientation();
305        }
306        else
307        {
308            *data << ((WorldObject *)this)->GetPositionX();
309            *data << ((WorldObject *)this)->GetPositionY();
310            *data << ((WorldObject *)this)->GetPositionZ();
311            *data << ((WorldObject *)this)->GetOrientation();
312        }
313    }
314
315    // 0x20
316    if(flags & UPDATEFLAG_LIVING)
317    {
318        // 0x00000200
319        if(flags2 & MOVEMENTFLAG_ONTRANSPORT)
320        {
321            if(GetTypeId() == TYPEID_PLAYER)
322            {
323                *data << (uint64)((Player*)this)->GetTransport()->GetGUID();
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            }
330            //MaNGOS currently not have support for other than player on transport
331        }
332
333        // 0x02200000
334        if(flags2 & (MOVEMENTFLAG_SWIMMING | MOVEMENTFLAG_FLYING2))
335        {
336            if(GetTypeId() == TYPEID_PLAYER)
337                *data << (float)((Player*)this)->m_movementInfo.s_pitch;
338            else
339                *data << (float)0;                          // is't part of movement packet, we must store and send it...
340        }
341
342        if(GetTypeId() == TYPEID_PLAYER)
343            *data << (uint32)((Player*)this)->m_movementInfo.fallTime;
344        else
345            *data << (uint32)0;                             // last fall time
346
347        // 0x00001000
348        if(flags2 & MOVEMENTFLAG_JUMPING)
349        {
350            if(GetTypeId() == TYPEID_PLAYER)
351            {
352                *data << (float)((Player*)this)->m_movementInfo.j_unk;
353                *data << (float)((Player*)this)->m_movementInfo.j_sinAngle;
354                *data << (float)((Player*)this)->m_movementInfo.j_cosAngle;
355                *data << (float)((Player*)this)->m_movementInfo.j_xyspeed;
356            }
357            else
358            {
359                *data << (float)0;
360                *data << (float)0;
361                *data << (float)0;
362                *data << (float)0;
363            }
364        }
365
366        // 0x04000000
367        if(flags2 & MOVEMENTFLAG_SPLINE)
368        {
369            if(GetTypeId() == TYPEID_PLAYER)
370                *data << (float)((Player*)this)->m_movementInfo.u_unk1;
371            else
372                *data << (float)0;
373        }
374
375        *data << ((Unit*)this)->GetSpeed( MOVE_WALK );
376        *data << ((Unit*)this)->GetSpeed( MOVE_RUN );
377        *data << ((Unit*)this)->GetSpeed( MOVE_SWIMBACK );
378        *data << ((Unit*)this)->GetSpeed( MOVE_SWIM );
379        *data << ((Unit*)this)->GetSpeed( MOVE_WALKBACK );
380        *data << ((Unit*)this)->GetSpeed( MOVE_FLY );
381        *data << ((Unit*)this)->GetSpeed( MOVE_FLYBACK );
382        *data << ((Unit*)this)->GetSpeed( MOVE_TURN );
383
384        // 0x08000000
385        if(flags2 & MOVEMENTFLAG_SPLINE2)
386        {
387            if(GetTypeId() != TYPEID_PLAYER)
388            {
389                sLog.outDebug("_BuildMovementUpdate: MOVEMENTFLAG_SPLINE2 for non-player");
390                return;
391            }
392
393            if(!((Player*)this)->isInFlight())
394            {
395                sLog.outDebug("_BuildMovementUpdate: MOVEMENTFLAG_SPLINE2 but not in flight");
396                return;
397            }
398
399            WPAssert(((Player*)this)->GetMotionMaster()->GetCurrentMovementGeneratorType() == FLIGHT_MOTION_TYPE);
400
401            FlightPathMovementGenerator *fmg = (FlightPathMovementGenerator*)(((Player*)this)->GetMotionMaster()->top());
402
403            uint32 flags3 = 0x00000300;
404
405            *data << uint32(flags3);                        // splines flag?
406
407            if(flags3 & 0x10000)                            // probably x,y,z coords there
408            {
409                *data << (float)0;
410                *data << (float)0;
411                *data << (float)0;
412            }
413
414            if(flags3 & 0x20000)                            // probably guid there
415            {
416                *data << uint64(0);
417            }
418
419            if(flags3 & 0x40000)                            // may be orientation
420            {
421                *data << (float)0;
422            }
423
424            Path &path = fmg->GetPath();
425
426            float x, y, z;
427            ((Player*)this)->GetPosition(x, y, z);
428
429            uint32 inflighttime = uint32(path.GetPassedLength(fmg->GetCurrentNode(), x, y, z) * 32);
430            uint32 traveltime = uint32(path.GetTotalLength() * 32);
431
432            *data << uint32(inflighttime);                  // passed move time?
433            *data << uint32(traveltime);                    // full move time?
434            *data << uint32(0);                             // ticks count?
435
436            uint32 poscount = uint32(path.Size());
437
438            *data << uint32(poscount);                      // points count
439
440            for(uint32 i = 0; i < poscount; ++i)
441            {
442                *data << path.GetNodes()[i].x;
443                *data << path.GetNodes()[i].y;
444                *data << path.GetNodes()[i].z;
445            }
446
447            /*for(uint32 i = 0; i < poscount; i++)
448            {
449                // path points
450                *data << (float)0;
451                *data << (float)0;
452                *data << (float)0;
453            }*/
454
455            *data << path.GetNodes()[poscount-1].x;
456            *data << path.GetNodes()[poscount-1].y;
457            *data << path.GetNodes()[poscount-1].z;
458
459            // target position (path end)
460            /**data << ((Unit*)this)->GetPositionX();
461             *data << ((Unit*)this)->GetPositionY();
462             *data << ((Unit*)this)->GetPositionZ();*/
463        }
464    }
465
466    // 0x8
467    if(flags & UPDATEFLAG_LOWGUID)
468    {
469        switch(GetTypeId())
470        {
471            case TYPEID_OBJECT:
472            case TYPEID_ITEM:
473            case TYPEID_CONTAINER:
474            case TYPEID_GAMEOBJECT:
475            case TYPEID_DYNAMICOBJECT:
476            case TYPEID_CORPSE:
477                *data << uint32(GetGUIDLow());              // GetGUIDLow()
478                break;
479            case TYPEID_UNIT:
480                *data << uint32(0x0000000B);                // unk, can be 0xB or 0xC
481                break;
482            case TYPEID_PLAYER:
483                if(flags & UPDATEFLAG_SELF)
484                    *data << uint32(0x00000015);            // unk, can be 0x15 or 0x22
485                else
486                    *data << uint32(0x00000008);            // unk, can be 0x7 or 0x8
487                break;
488            default:
489                *data << uint32(0x00000000);                // unk
490                break;
491        }
492    }
493
494    // 0x10
495    if(flags & UPDATEFLAG_HIGHGUID)
496    {
497        switch(GetTypeId())
498        {
499            case TYPEID_OBJECT:
500            case TYPEID_ITEM:
501            case TYPEID_CONTAINER:
502            case TYPEID_GAMEOBJECT:
503            case TYPEID_DYNAMICOBJECT:
504            case TYPEID_CORPSE:
505                *data << uint32(GetGUIDHigh());             // GetGUIDHigh()
506                break;
507            default:
508                *data << uint32(0x00000000);                // unk
509                break;
510        }
511    }
512
513    // 0x4
514    if(flags & UPDATEFLAG_FULLGUID)
515    {
516        *data << uint8(0);                                  // packed guid (probably target guid)
517    }
518
519    // 0x2
520    if(flags & UPDATEFLAG_TRANSPORT)
521    {
522        *data << uint32(getMSTime());                       // ms time
523    }
524}
525
526void Object::_BuildValuesUpdate(uint8 updatetype, ByteBuffer * data, UpdateMask *updateMask, Player *target) const
527{
528    if(!target)
529        return;
530
531    bool IsActivateToQuest = false;
532    if (updatetype == UPDATETYPE_CREATE_OBJECT || updatetype == UPDATETYPE_CREATE_OBJECT2)
533    {
534        if (isType(TYPEMASK_GAMEOBJECT) && !((GameObject*)this)->IsTransport())
535        {
536            if ( ((GameObject*)this)->ActivateToQuest(target) || target->isGameMaster())
537            {
538                IsActivateToQuest = true;
539                updateMask->SetBit(GAMEOBJECT_DYN_FLAGS);
540            }
541        }
542    }
543    else                                                    //case UPDATETYPE_VALUES
544    {
545        if (isType(TYPEMASK_GAMEOBJECT) && !((GameObject*)this)->IsTransport())
546        {
547            if ( ((GameObject*)this)->ActivateToQuest(target) || target->isGameMaster())
548            {
549                IsActivateToQuest = true;
550            }
551            updateMask->SetBit(GAMEOBJECT_DYN_FLAGS);
552            updateMask->SetBit(GAMEOBJECT_ANIMPROGRESS);
553        }
554    }
555
556    WPAssert(updateMask && updateMask->GetCount() == m_valuesCount);
557
558    *data << (uint8)updateMask->GetBlockCount();
559    data->append( updateMask->GetMask(), updateMask->GetLength() );
560
561    // 2 specialized loops for speed optimization in non-unit case
562    if(isType(TYPEMASK_UNIT))                               // unit (creature/player) case
563    {
564        for( uint16 index = 0; index < m_valuesCount; index ++ )
565        {
566            if( updateMask->GetBit( index ) )
567            {
568                // remove custom flag before send
569                if( index == UNIT_NPC_FLAGS )
570                    *data << uint32(m_uint32Values[ index ] & ~UNIT_NPC_FLAG_GUARD);
571                // FIXME: Some values at server stored in float format but must be sent to client in uint32 format
572                else if(index >= UNIT_FIELD_BASEATTACKTIME && index <= UNIT_FIELD_RANGEDATTACKTIME)
573                {
574                    // convert from float to uint32 and send
575                    *data << uint32(m_floatValues[ index ] < 0 ? 0 : m_floatValues[ index ]);
576                }
577                // there are some float values which may be negative or can't get negative due to other checks
578                else if(index >= UNIT_FIELD_NEGSTAT0   && index <= UNIT_FIELD_NEGSTAT4 ||
579                    index >= UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE  && index <= (UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE + 6) ||
580                    index >= UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE  && index <= (UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE + 6) ||
581                    index >= UNIT_FIELD_POSSTAT0   && index <= UNIT_FIELD_POSSTAT4)
582                {
583                    *data << uint32(m_floatValues[ index ]);
584                }
585                // Gamemasters should be always able to select units - remove not selectable flag
586                else if(index == UNIT_FIELD_FLAGS && target->isGameMaster())
587                {
588                    *data << (m_uint32Values[ index ] & ~UNIT_FLAG_NOT_SELECTABLE);
589                }
590                // hide lootable animation for unallowed players
591                else if(index == UNIT_DYNAMIC_FLAGS && GetTypeId() == TYPEID_UNIT)
592                {
593                    if(!target->isAllowedToLoot((Creature*)this))
594                        *data << (m_uint32Values[ index ] & ~UNIT_DYNFLAG_LOOTABLE);
595                    else
596                        *data << (m_uint32Values[ index ] & ~UNIT_DYNFLAG_OTHER_TAGGER);
597                }
598                else
599                {
600                    // send in current format (float as float, uint32 as uint32)
601                    *data << m_uint32Values[ index ];
602                }
603            }
604        }
605    }
606    else if(isType(TYPEMASK_GAMEOBJECT))                    // gameobject case
607    {
608        for( uint16 index = 0; index < m_valuesCount; index ++ )
609        {
610            if( updateMask->GetBit( index ) )
611            {
612                // send in current format (float as float, uint32 as uint32)
613                if ( index == GAMEOBJECT_DYN_FLAGS )
614                {
615                    if(IsActivateToQuest )
616                    {
617                        switch(((GameObject*)this)->GetGoType())
618                        {
619                            case GAMEOBJECT_TYPE_CHEST:
620                                *data << uint32(9);         // enable quest object. Represent 9, but 1 for client before 2.3.0
621                                break;
622                            case GAMEOBJECT_TYPE_GOOBER:
623                                *data << uint32(1);
624                                break;
625                            default:
626                                *data << uint32(0);         //unknown. not happen.
627                                break;
628                        }
629                    }
630                    else
631                        *data << uint32(0);                 // disable quest object
632                }
633                else
634                    *data << m_uint32Values[ index ];       // other cases
635            }
636        }
637    }
638    else                                                    // other objects case (no special index checks)
639    {
640        for( uint16 index = 0; index < m_valuesCount; index ++ )
641        {
642            if( updateMask->GetBit( index ) )
643            {
644                // send in current format (float as float, uint32 as uint32)
645                *data << m_uint32Values[ index ];
646            }
647        }
648    }
649}
650
651void Object::ClearUpdateMask(bool remove)
652{
653    for( uint16 index = 0; index < m_valuesCount; index ++ )
654    {
655        if(m_uint32Values_mirror[index]!= m_uint32Values[index])
656            m_uint32Values_mirror[index] = m_uint32Values[index];
657    }
658    if(m_objectUpdated)
659    {
660        if(remove)
661            ObjectAccessor::Instance().RemoveUpdateObject(this);
662        m_objectUpdated = false;
663    }
664}
665
666// Send current value fields changes to all viewers
667void Object::SendUpdateObjectToAllExcept(Player* exceptPlayer)
668{
669    // changes will be send in create packet
670    if(!IsInWorld())
671        return;
672
673    // nothing do
674    if(!m_objectUpdated)
675        return;
676
677    ObjectAccessor::UpdateObject(this,exceptPlayer);
678}
679
680bool Object::LoadValues(const char* data)
681{
682    if(!m_uint32Values) _InitValues();
683
684    Tokens tokens = StrSplit(data, " ");
685
686    if(tokens.size() != m_valuesCount)
687        return false;
688
689    Tokens::iterator iter;
690    int index;
691    for (iter = tokens.begin(), index = 0; index < m_valuesCount; ++iter, ++index)
692    {
693        m_uint32Values[index] = atol((*iter).c_str());
694    }
695
696    return true;
697}
698
699void Object::_SetUpdateBits(UpdateMask *updateMask, Player* /*target*/) const
700{
701    for( uint16 index = 0; index < m_valuesCount; index ++ )
702    {
703        if(m_uint32Values_mirror[index]!= m_uint32Values[index])
704            updateMask->SetBit(index);
705    }
706}
707
708void Object::_SetCreateBits(UpdateMask *updateMask, Player* /*target*/) const
709{
710    for( uint16 index = 0; index < m_valuesCount; index++ )
711    {
712        if(GetUInt32Value(index) != 0)
713            updateMask->SetBit(index);
714    }
715}
716
717void Object::SetInt32Value( uint16 index, int32 value )
718{
719    ASSERT( index < m_valuesCount || PrintIndexError( index , true ) );
720
721    if(m_int32Values[ index ] != value)
722    {
723        m_int32Values[ index ] = value;
724
725        if(m_inWorld)
726        {
727            if(!m_objectUpdated)
728            {
729                ObjectAccessor::Instance().AddUpdateObject(this);
730                m_objectUpdated = true;
731            }
732        }
733    }
734}
735
736void Object::SetUInt32Value( uint16 index, uint32 value )
737{
738    ASSERT( index < m_valuesCount || PrintIndexError( index , true ) );
739
740    if(m_uint32Values[ index ] != value)
741    {
742        m_uint32Values[ index ] = value;
743
744        if(m_inWorld)
745        {
746            if(!m_objectUpdated)
747            {
748                ObjectAccessor::Instance().AddUpdateObject(this);
749                m_objectUpdated = true;
750            }
751        }
752    }
753}
754
755void Object::SetUInt64Value( uint16 index, const uint64 &value )
756{
757    ASSERT( index + 1 < m_valuesCount || PrintIndexError( index , true ) );
758    if(*((uint64*)&(m_uint32Values[ index ])) != value)
759    {
760        m_uint32Values[ index ] = *((uint32*)&value);
761        m_uint32Values[ index + 1 ] = *(((uint32*)&value) + 1);
762
763        if(m_inWorld)
764        {
765            if(!m_objectUpdated)
766            {
767                ObjectAccessor::Instance().AddUpdateObject(this);
768                m_objectUpdated = true;
769            }
770        }
771    }
772}
773
774void Object::SetFloatValue( uint16 index, float value )
775{
776    ASSERT( index < m_valuesCount || PrintIndexError( index , true ) );
777
778    if(m_floatValues[ index ] != value)
779    {
780        m_floatValues[ index ] = value;
781
782        if(m_inWorld)
783        {
784            if(!m_objectUpdated)
785            {
786                ObjectAccessor::Instance().AddUpdateObject(this);
787                m_objectUpdated = true;
788            }
789        }
790    }
791}
792
793void Object::SetByteValue( uint16 index, uint8 offset, uint8 value )
794{
795    ASSERT( index < m_valuesCount || PrintIndexError( index , true ) );
796
797    if(offset > 4)
798    {
799        sLog.outError("Object::SetByteValue: wrong offset %u", offset);
800        return;
801    }
802
803    if(uint8(m_uint32Values[ index ] >> (offset * 8)) != value)
804    {
805        m_uint32Values[ index ] &= ~uint32(uint32(0xFF) << (offset * 8));
806        m_uint32Values[ index ] |= uint32(uint32(value) << (offset * 8));
807
808        if(m_inWorld)
809        {
810            if(!m_objectUpdated)
811            {
812                ObjectAccessor::Instance().AddUpdateObject(this);
813                m_objectUpdated = true;
814            }
815        }
816    }
817}
818
819void Object::SetUInt16Value( uint16 index, uint8 offset, uint16 value )
820{
821    ASSERT( index < m_valuesCount || PrintIndexError( index , true ) );
822
823    if(offset > 2)
824    {
825        sLog.outError("Object::SetUInt16Value: wrong offset %u", offset);
826        return;
827    }
828
829    if(uint8(m_uint32Values[ index ] >> (offset * 16)) != value)
830    {
831        m_uint32Values[ index ] &= ~uint32(uint32(0xFFFF) << (offset * 16));
832        m_uint32Values[ index ] |= uint32(uint32(value) << (offset * 16));
833
834        if(m_inWorld)
835        {
836            if(!m_objectUpdated)
837            {
838                ObjectAccessor::Instance().AddUpdateObject(this);
839                m_objectUpdated = true;
840            }
841        }
842    }
843}
844
845void Object::SetStatFloatValue( uint16 index, float value)
846{
847    if(value < 0)
848        value = 0.0f;
849
850    SetFloatValue(index, value);
851}
852
853void Object::SetStatInt32Value( uint16 index, int32 value)
854{
855    if(value < 0)
856        value = 0;
857
858    SetUInt32Value(index, uint32(value));
859}
860
861void Object::ApplyModUInt32Value(uint16 index, int32 val, bool apply)
862{
863    int32 cur = GetUInt32Value(index);
864    cur += (apply ? val : -val);
865    if(cur < 0)
866        cur = 0;
867    SetUInt32Value(index,cur);
868}
869
870void Object::ApplyModInt32Value(uint16 index, int32 val, bool apply)
871{
872    int32 cur = GetInt32Value(index);
873    cur += (apply ? val : -val);
874    SetInt32Value(index,cur);
875}
876
877void Object::ApplyModSignedFloatValue(uint16 index, float  val, bool apply)
878{
879    float cur = GetFloatValue(index);
880    cur += (apply ? val : -val);
881    SetFloatValue(index,cur);
882}
883
884void Object::ApplyModPositiveFloatValue(uint16 index, float  val, bool apply)
885{
886    float cur = GetFloatValue(index);
887    cur += (apply ? val : -val);
888    if(cur < 0)
889        cur = 0;
890    SetFloatValue(index,cur);
891}
892
893void Object::SetFlag( uint16 index, uint32 newFlag )
894{
895    ASSERT( index < m_valuesCount || PrintIndexError( index , true ) );
896    uint32 oldval = m_uint32Values[ index ];
897    uint32 newval = oldval | newFlag;
898
899    if(oldval != newval)
900    {
901        m_uint32Values[ index ] = newval;
902
903        if(m_inWorld)
904        {
905            if(!m_objectUpdated)
906            {
907                ObjectAccessor::Instance().AddUpdateObject(this);
908                m_objectUpdated = true;
909            }
910        }
911    }
912}
913
914void Object::RemoveFlag( uint16 index, uint32 oldFlag )
915{
916    ASSERT( index < m_valuesCount || PrintIndexError( index , true ) );
917    uint32 oldval = m_uint32Values[ index ];
918    uint32 newval = oldval & ~oldFlag;
919
920    if(oldval != newval)
921    {
922        m_uint32Values[ index ] = newval;
923
924        if(m_inWorld)
925        {
926            if(!m_objectUpdated)
927            {
928                ObjectAccessor::Instance().AddUpdateObject(this);
929                m_objectUpdated = true;
930            }
931        }
932    }
933}
934
935bool Object::PrintIndexError(uint32 index, bool set) const
936{
937    sLog.outError("ERROR: 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);
938
939    // assert must fail after function call
940    return false;
941}
942
943WorldObject::WorldObject()
944{
945    m_positionX         = 0.0f;
946    m_positionY         = 0.0f;
947    m_positionZ         = 0.0f;
948    m_orientation       = 0.0f;
949
950    m_mapId             = 0;
951    m_InstanceId        = 0;
952
953    m_name = "";
954
955    mSemaphoreTeleport  = false;
956}
957
958void WorldObject::_Create( uint32 guidlow, HighGuid guidhigh, uint32 mapid )
959{
960    Object::_Create(guidlow, 0, guidhigh);
961
962    m_mapId = mapid;
963}
964
965uint32 WorldObject::GetZoneId() const
966{
967    return MapManager::Instance().GetBaseMap(m_mapId)->GetZoneId(m_positionX,m_positionY);
968}
969
970uint32 WorldObject::GetAreaId() const
971{
972    return MapManager::Instance().GetBaseMap(m_mapId)->GetAreaId(m_positionX,m_positionY);
973}
974
975InstanceData* WorldObject::GetInstanceData()
976{
977    Map *map = MapManager::Instance().GetMap(m_mapId, this);
978    return map->IsDungeon() ? ((InstanceMap*)map)->GetInstanceData() : NULL;
979}
980
981                                                            //slow
982float WorldObject::GetDistance(const WorldObject* obj) const
983{
984    float dx = GetPositionX() - obj->GetPositionX();
985    float dy = GetPositionY() - obj->GetPositionY();
986    float dz = GetPositionZ() - obj->GetPositionZ();
987    float sizefactor = GetObjectSize() + obj->GetObjectSize();
988    float dist = sqrt((dx*dx) + (dy*dy) + (dz*dz)) - sizefactor;
989    return ( dist > 0 ? dist : 0);
990}
991
992float WorldObject::GetDistance2d(float x, float y) const
993{
994    float dx = GetPositionX() - x;
995    float dy = GetPositionY() - y;
996    float sizefactor = GetObjectSize();
997    float dist = sqrt((dx*dx) + (dy*dy)) - sizefactor;
998    return ( dist > 0 ? dist : 0);
999}
1000
1001float WorldObject::GetDistance(const float x, const float y, const float z) const
1002{
1003    float dx = GetPositionX() - x;
1004    float dy = GetPositionY() - y;
1005    float dz = GetPositionZ() - z;
1006    float sizefactor = GetObjectSize();
1007    float dist = sqrt((dx*dx) + (dy*dy) + (dz*dz)) - sizefactor;
1008    return ( dist > 0 ? dist : 0);
1009}
1010
1011float WorldObject::GetDistance2d(const WorldObject* obj) const
1012{
1013    float dx = GetPositionX() - obj->GetPositionX();
1014    float dy = GetPositionY() - obj->GetPositionY();
1015    float sizefactor = GetObjectSize() + obj->GetObjectSize();
1016    float dist = sqrt((dx*dx) + (dy*dy)) - sizefactor;
1017    return ( dist > 0 ? dist : 0);
1018}
1019
1020float WorldObject::GetDistanceZ(const WorldObject* obj) const
1021{
1022    float dz = fabs(GetPositionZ() - obj->GetPositionZ());
1023    float sizefactor = GetObjectSize() + obj->GetObjectSize();
1024    float dist = dz - sizefactor;
1025    return ( dist > 0 ? dist : 0);
1026}
1027
1028bool WorldObject::IsWithinDistInMap(const WorldObject* obj, const float dist2compare) const
1029{
1030    if (!obj || !IsInMap(obj)) return false;
1031
1032    float dx = GetPositionX() - obj->GetPositionX();
1033    float dy = GetPositionY() - obj->GetPositionY();
1034    float dz = GetPositionZ() - obj->GetPositionZ();
1035    float distsq = dx*dx + dy*dy + dz*dz;
1036    float sizefactor = GetObjectSize() + obj->GetObjectSize();
1037    float maxdist = dist2compare + sizefactor;
1038
1039    return distsq < maxdist * maxdist;
1040}
1041
1042bool WorldObject::IsWithinLOSInMap(const WorldObject* obj) const
1043{
1044    if (!IsInMap(obj)) return false;
1045    float ox,oy,oz;
1046    obj->GetPosition(ox,oy,oz);
1047    return(IsWithinLOS(ox, oy, oz ));
1048}
1049
1050bool WorldObject::IsWithinLOS(const float ox, const float oy, const float oz ) const
1051{
1052    float x,y,z;
1053    GetPosition(x,y,z);
1054    VMAP::IVMapManager *vMapManager = VMAP::VMapFactory::createOrGetVMapManager();
1055    return vMapManager->isInLineOfSight(GetMapId(), x, y, z+2.0f, ox, oy, oz+2.0f);
1056}
1057
1058float WorldObject::GetAngle(const WorldObject* obj) const
1059{
1060    if(!obj) return 0;
1061    return GetAngle( obj->GetPositionX(), obj->GetPositionY() );
1062}
1063
1064// Return angle in range 0..2*pi
1065float WorldObject::GetAngle( const float x, const float y ) const
1066{
1067    float dx = x - GetPositionX();
1068    float dy = y - GetPositionY();
1069
1070    float ang = atan2(dy, dx);
1071    ang = (ang >= 0) ? ang : 2 * M_PI + ang;
1072    return ang;
1073}
1074
1075bool WorldObject::HasInArc(const float arcangle, const WorldObject* obj) const
1076{
1077    float arc = arcangle;
1078
1079    // move arc to range 0.. 2*pi
1080    while( arc >= 2.0f * M_PI )
1081        arc -=  2.0f * M_PI;
1082    while( arc < 0 )
1083        arc +=  2.0f * M_PI;
1084
1085    float angle = GetAngle( obj );
1086    angle -= m_orientation;
1087
1088    // move angle to range -pi ... +pi
1089    while( angle > M_PI)
1090        angle -= 2.0f * M_PI;
1091    while(angle < -M_PI)
1092        angle += 2.0f * M_PI;
1093
1094    float lborder =  -1 * (arc/2.0f);                       // in range -pi..0
1095    float rborder = (arc/2.0f);                             // in range 0..pi
1096    return (( angle >= lborder ) && ( angle <= rborder ));
1097}
1098
1099void WorldObject::GetRandomPoint( float x, float y, float z, float distance, float &rand_x, float &rand_y, float &rand_z) const
1100{
1101    if(distance==0)
1102    {
1103        rand_x = x;
1104        rand_y = y;
1105        rand_z = z;
1106        return;
1107    }
1108
1109    // angle to face `obj` to `this`
1110    float angle = rand_norm()*2*M_PI;
1111    float new_dist = rand_norm()*distance;
1112
1113    rand_x = x + new_dist * cos(angle);
1114    rand_y = y + new_dist * sin(angle);
1115    rand_z = z;
1116
1117    MaNGOS::NormalizeMapCoord(rand_x);
1118    MaNGOS::NormalizeMapCoord(rand_y);
1119    UpdateGroundPositionZ(rand_x,rand_y,rand_z);            // update to LOS height if available
1120}
1121
1122void WorldObject::UpdateGroundPositionZ(float x, float y, float &z) const
1123{
1124    float new_z = MapManager::Instance().GetBaseMap(GetMapId())->GetHeight(x,y,z,true);
1125    if(new_z > INVALID_HEIGHT)
1126        z = new_z+ 0.05f;                                   // just to be sure that we are not a few pixel under the surface
1127}
1128
1129bool WorldObject::IsPositionValid() const
1130{
1131    return MaNGOS::IsValidMapCoord(m_positionX,m_positionY,m_positionZ,m_orientation);
1132}
1133
1134void WorldObject::MonsterSay(const char* text, uint32 language, uint64 TargetGuid)
1135{
1136    WorldPacket data(SMSG_MESSAGECHAT, 200);
1137    BuildMonsterChat(&data,CHAT_MSG_MONSTER_SAY,text,language,GetName(),TargetGuid);
1138    SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
1139}
1140
1141void WorldObject::MonsterYell(const char* text, uint32 language, uint64 TargetGuid)
1142{
1143    WorldPacket data(SMSG_MESSAGECHAT, 200);
1144    BuildMonsterChat(&data,CHAT_MSG_MONSTER_YELL,text,language,GetName(),TargetGuid);
1145    SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
1146}
1147
1148void WorldObject::MonsterTextEmote(const char* text, uint64 TargetGuid, bool IsBossEmote)
1149{
1150    WorldPacket data(SMSG_MESSAGECHAT, 200);
1151    BuildMonsterChat(&data,IsBossEmote ? CHAT_MSG_RAID_BOSS_EMOTE : CHAT_MSG_MONSTER_EMOTE,text,LANG_UNIVERSAL,GetName(),TargetGuid);
1152    SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),true);
1153}
1154
1155void WorldObject::MonsterWhisper(const char* text, uint64 receiver, bool IsBossWhisper)
1156{
1157    Player *player = objmgr.GetPlayer(receiver);
1158    if(!player || !player->GetSession())
1159        return;
1160
1161    WorldPacket data(SMSG_MESSAGECHAT, 200);
1162    BuildMonsterChat(&data,IsBossWhisper ? CHAT_MSG_RAID_BOSS_WHISPER : CHAT_MSG_MONSTER_WHISPER,text,LANG_UNIVERSAL,GetName(),receiver);
1163
1164    player->GetSession()->SendPacket(&data);
1165}
1166
1167void WorldObject::SendPlaySound(uint32 Sound, bool OnlySelf)
1168{
1169    WorldPacket data(SMSG_PLAY_SOUND, 4);
1170    data << Sound;
1171    if (OnlySelf && GetTypeId() == TYPEID_PLAYER )
1172        ((Player*)this)->GetSession()->SendPacket( &data );
1173    else
1174        SendMessageToSet( &data, true ); // ToSelf ignored in this case
1175}
1176
1177namespace MaNGOS
1178{
1179    class MessageChatLocaleCacheDo
1180    {
1181        public:
1182            MessageChatLocaleCacheDo(WorldObject const& obj, ChatMsg msgtype, int32 textId, uint32 language, uint64 targetGUID, float dist)
1183                : i_object(obj), i_msgtype(msgtype), i_textId(textId), i_language(language), 
1184                i_targetGUID(targetGUID), i_dist(dist)
1185            {
1186            }
1187
1188            ~MessageChatLocaleCacheDo()
1189            {
1190                for(int i = 0; i < i_data_cache.size(); ++i)
1191                    delete i_data_cache[i];
1192            }
1193
1194            void operator()(Player* p)
1195            {
1196                // skip far away players
1197                if(p->GetDistance(&i_object) > i_dist)
1198                    return;
1199
1200                uint32 loc_idx = p->GetSession()->GetSessionDbLocaleIndex();
1201                uint32 cache_idx = loc_idx+1;
1202                WorldPacket* data;
1203
1204                // create if not cached yet
1205                if(i_data_cache.size() < cache_idx+1 || !i_data_cache[cache_idx])
1206                {
1207                    if(i_data_cache.size() < cache_idx+1)
1208                        i_data_cache.resize(cache_idx+1);
1209
1210                    char const* text = objmgr.GetMangosString(i_textId,loc_idx);
1211
1212                    data = new WorldPacket(SMSG_MESSAGECHAT, 200);
1213
1214                    // TODO: i_object.GetName() also must be localized?
1215                    i_object.BuildMonsterChat(data,i_msgtype,text,i_language,i_object.GetName(),i_targetGUID);
1216
1217                    i_data_cache[cache_idx] = data;
1218                }
1219                else
1220                    data = i_data_cache[cache_idx];
1221
1222                p->SendDirectMessage(data);
1223            }
1224
1225        private:
1226            WorldObject const& i_object;
1227            ChatMsg i_msgtype;
1228            int32 i_textId;
1229            uint32 i_language;
1230            uint64 i_targetGUID;
1231            float i_dist;
1232            std::vector<WorldPacket*> i_data_cache;             // 0 = default, i => i-1 locale index
1233    };
1234}                                                           // namespace MaNGOS
1235
1236void WorldObject::MonsterSay(int32 textId, uint32 language, uint64 TargetGuid)
1237{
1238    CellPair p = MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY());
1239
1240    Cell cell(p);
1241    cell.data.Part.reserved = ALL_DISTRICT;
1242    cell.SetNoCreate();
1243
1244    MaNGOS::MessageChatLocaleCacheDo say_do(*this, CHAT_MSG_MONSTER_SAY, textId,language,TargetGuid,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY));
1245    MaNGOS::PlayerWorker<MaNGOS::MessageChatLocaleCacheDo> say_worker(say_do);
1246    TypeContainerVisitor<MaNGOS::PlayerWorker<MaNGOS::MessageChatLocaleCacheDo>, WorldTypeMapContainer > message(say_worker);
1247    CellLock<GridReadGuard> cell_lock(cell, p);
1248    cell_lock->Visit(cell_lock, message, *GetMap());
1249}
1250
1251void WorldObject::MonsterYell(int32 textId, uint32 language, uint64 TargetGuid)
1252{
1253    CellPair p = MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY());
1254
1255    Cell cell(p);
1256    cell.data.Part.reserved = ALL_DISTRICT;
1257    cell.SetNoCreate();
1258
1259    MaNGOS::MessageChatLocaleCacheDo say_do(*this, CHAT_MSG_MONSTER_YELL, textId,language,TargetGuid,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL));
1260    MaNGOS::PlayerWorker<MaNGOS::MessageChatLocaleCacheDo> say_worker(say_do);
1261    TypeContainerVisitor<MaNGOS::PlayerWorker<MaNGOS::MessageChatLocaleCacheDo>, WorldTypeMapContainer > message(say_worker);
1262    CellLock<GridReadGuard> cell_lock(cell, p);
1263    cell_lock->Visit(cell_lock, message, *GetMap());
1264}
1265
1266void WorldObject::MonsterTextEmote(int32 textId, uint64 TargetGuid, bool IsBossEmote)
1267{
1268    CellPair p = MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY());
1269
1270    Cell cell(p);
1271    cell.data.Part.reserved = ALL_DISTRICT;
1272    cell.SetNoCreate();
1273
1274    MaNGOS::MessageChatLocaleCacheDo say_do(*this, IsBossEmote ? CHAT_MSG_RAID_BOSS_EMOTE : CHAT_MSG_MONSTER_EMOTE, textId,LANG_UNIVERSAL,TargetGuid,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE));
1275    MaNGOS::PlayerWorker<MaNGOS::MessageChatLocaleCacheDo> say_worker(say_do);
1276    TypeContainerVisitor<MaNGOS::PlayerWorker<MaNGOS::MessageChatLocaleCacheDo>, WorldTypeMapContainer > message(say_worker);
1277    CellLock<GridReadGuard> cell_lock(cell, p);
1278    cell_lock->Visit(cell_lock, message, *GetMap());
1279}
1280
1281void WorldObject::MonsterWhisper(int32 textId, uint64 receiver, bool IsBossWhisper)
1282{
1283    Player *player = objmgr.GetPlayer(receiver);
1284    if(!player || !player->GetSession())
1285        return;
1286
1287    uint32 loc_idx = player->GetSession()->GetSessionDbLocaleIndex();
1288    char const* text = objmgr.GetMangosString(textId,loc_idx);
1289
1290    WorldPacket data(SMSG_MESSAGECHAT, 200);
1291    BuildMonsterChat(&data,IsBossWhisper ? CHAT_MSG_RAID_BOSS_WHISPER : CHAT_MSG_MONSTER_WHISPER,text,LANG_UNIVERSAL,GetName(),receiver);
1292
1293    player->GetSession()->SendPacket(&data);
1294}
1295
1296void WorldObject::BuildMonsterChat(WorldPacket *data, uint8 msgtype, char const* text, uint32 language, char const* name, uint64 targetGuid) const
1297{
1298    bool pre = (msgtype==CHAT_MSG_MONSTER_EMOTE || msgtype==CHAT_MSG_RAID_BOSS_EMOTE);
1299
1300    *data << (uint8)msgtype;
1301    *data << (uint32)language;
1302    *data << (uint64)GetGUID();
1303    *data << (uint32)0;                                     //2.1.0
1304    *data << (uint32)(strlen(name)+1);
1305    *data << name;
1306    *data << (uint64)targetGuid;                            //Unit Target
1307    if( targetGuid && !IS_PLAYER_GUID(targetGuid) )
1308    {
1309        *data << (uint32)1;                                 // target name length
1310        *data << (uint8)0;                                  // target name
1311    }
1312    *data << (uint32)(strlen(text)+1+(pre?3:0));
1313    if(pre)
1314        data->append("%s ",3);
1315    *data << text;
1316    *data << (uint8)0;                                      // ChatTag
1317}
1318
1319void WorldObject::BuildHeartBeatMsg(WorldPacket *data) const
1320{
1321    //Heartbeat message cannot be used for non-units
1322    if (!isType(TYPEMASK_UNIT))
1323        return;
1324
1325    data->Initialize(MSG_MOVE_HEARTBEAT, 32);
1326    data->append(GetPackGUID());
1327    *data << uint32(((Unit*)this)->GetUnitMovementFlags()); // movement flags
1328    *data << uint8(0);                                      // 2.3.0
1329    *data << getMSTime();                                   // time
1330    *data << m_positionX;
1331    *data << m_positionY;
1332    *data << m_positionZ;
1333    *data << m_orientation;
1334    *data << uint32(0);
1335}
1336
1337void WorldObject::BuildTeleportAckMsg(WorldPacket *data, float x, float y, float z, float ang) const
1338{
1339    //TeleportAck message cannot be used for non-units
1340    if (!isType(TYPEMASK_UNIT))
1341        return;
1342
1343    data->Initialize(MSG_MOVE_TELEPORT_ACK, 41);
1344    data->append(GetPackGUID());
1345    *data << uint32(0);                                     // this value increments every time
1346    *data << uint32(((Unit*)this)->GetUnitMovementFlags()); // movement flags
1347    *data << uint8(0);                                      // 2.3.0
1348    *data << getMSTime();                                   // time
1349    *data << x;
1350    *data << y;
1351    *data << z;
1352    *data << ang;
1353    *data << uint32(0);
1354}
1355
1356void WorldObject::SendMessageToSet(WorldPacket *data, bool /*bToSelf*/)
1357{
1358    MapManager::Instance().GetMap(m_mapId, this)->MessageBroadcast(this, data);
1359}
1360
1361void WorldObject::SendMessageToSetInRange(WorldPacket *data, float dist, bool /*bToSelf*/)
1362{
1363    MapManager::Instance().GetMap(m_mapId, this)->MessageDistBroadcast(this, data, dist);
1364}
1365
1366void WorldObject::SendObjectDeSpawnAnim(uint64 guid)
1367{
1368    WorldPacket data(SMSG_GAMEOBJECT_DESPAWN_ANIM, 8);
1369    data << guid;
1370    SendMessageToSet(&data, true);
1371}
1372
1373Map* WorldObject::GetMap() const
1374{
1375    return MapManager::Instance().GetMap(GetMapId(), this);
1376}
1377
1378Map const* WorldObject::GetBaseMap() const
1379{
1380    return MapManager::Instance().GetBaseMap(GetMapId());
1381}
1382
1383void WorldObject::AddObjectToRemoveList()
1384{
1385    Map* map = GetMap();
1386    if(!map)
1387    {
1388        sLog.outError("Object (TypeId: %u Entry: %u GUID: %u) at attempt add to move list not have valid map (Id: %u).",GetTypeId(),GetEntry(),GetGUIDLow(),GetMapId());
1389        return;
1390    }
1391
1392    map->AddObjectToRemoveList(this);
1393}
1394
1395Creature* WorldObject::SummonCreature(uint32 id, float x, float y, float z, float ang,TempSummonType spwtype,uint32 despwtime)
1396{
1397    TemporarySummon* pCreature = new TemporarySummon(GetGUID());
1398
1399    pCreature->SetInstanceId(GetInstanceId());
1400    uint32 team = 0;
1401    if (GetTypeId()==TYPEID_PLAYER)
1402        team = ((Player*)this)->GetTeam();
1403
1404    if (!pCreature->Create(objmgr.GenerateLowGuid(HIGHGUID_UNIT), GetMap(), id, team))
1405    {
1406        delete pCreature;
1407        return NULL;
1408    }
1409
1410    if (x == 0.0f && y == 0.0f && z == 0.0f)
1411        GetClosePoint(x, y, z, pCreature->GetObjectSize());
1412
1413    pCreature->Relocate(x, y, z, ang);
1414
1415    if(!pCreature->IsPositionValid())
1416    {
1417        sLog.outError("ERROR: Creature (guidlow %d, entry %d) not summoned. Suggested coordinates isn't valid (X: %f Y: %f)",pCreature->GetGUIDLow(),pCreature->GetEntry(),pCreature->GetPositionX(),pCreature->GetPositionY());
1418        delete pCreature;
1419        return NULL;
1420    }
1421
1422    pCreature->Summon(spwtype, despwtime);
1423
1424    if(GetTypeId()==TYPEID_UNIT && ((Creature*)this)->AI())
1425        ((Creature*)this)->AI()->JustSummoned(pCreature);
1426
1427    //return the creature therewith the summoner has access to it
1428    return pCreature;
1429}
1430
1431void WorldObject::GetNearPoint2D(float &x, float &y, float distance2d, float absAngle ) const
1432{
1433    x = GetPositionX() + (GetObjectSize() + distance2d) * cos(absAngle);
1434    y = GetPositionY() + (GetObjectSize() + distance2d) * sin(absAngle);
1435
1436    MaNGOS::NormalizeMapCoord(x);
1437    MaNGOS::NormalizeMapCoord(y);
1438}
1439
1440void WorldObject::GetNearPoint(WorldObject const* searcher, float &x, float &y, float &z, float searcher_size, float distance2d, float absAngle ) const
1441{
1442    GetNearPoint2D(x,y,distance2d+searcher_size,absAngle);
1443   
1444    z = GetPositionZ();
1445   
1446    UpdateGroundPositionZ(x,y,z);
1447}
Note: See TracBrowser for help on using the browser.