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

Revision 268, 49.4 kB (checked in by yumileroy, 17 years ago)

*Move object update from objectaccessor to map
*Move activeobject list from objectaccessor to map
*Open grid for all active creatures (previously only for possessed ones)

Original author: megamage
Date: 2008-11-21 15:41:18-06:00

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