root/trunk/src/game/Map.cpp @ 233

Revision 233, 64.9 kB (checked in by yumileroy, 17 years ago)

[svn] * Reimplemented packet/update forwarding in more generic way
* Implemented far sight spells (Far Sight, Eagle Eye, etc) at unlimited range and properly forward packets
* Implemented bind vision spells (Mind Vision, etc) to forward packets at unlimited distance
* Implemented Sentry Totem (both vision switching/forwarding and alerting)
* Other misc possession fixes
* Added .bindsight and .unbindsight commands

Please test out the above spells (including Mind Control) and report any issues on the forums.

Original author: gvcoman
Date: 2008-11-14 20:40:35-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 "MapManager.h"
22#include "Player.h"
23#include "GridNotifiers.h"
24#include "WorldSession.h"
25#include "Log.h"
26#include "GridStates.h"
27#include "CellImpl.h"
28#include "InstanceData.h"
29#include "Map.h"
30#include "GridNotifiersImpl.h"
31#include "Config/ConfigEnv.h"
32#include "Transports.h"
33#include "ObjectAccessor.h"
34#include "ObjectMgr.h"
35#include "World.h"
36#include "ScriptCalls.h"
37#include "Group.h"
38
39#include "MapInstanced.h"
40#include "InstanceSaveMgr.h"
41#include "VMapFactory.h"
42
43#define DEFAULT_GRID_EXPIRY     300
44#define MAX_GRID_LOAD_TIME      50
45
46// magic *.map header
47const char MAP_MAGIC[] = "MAP_2.00";
48
49GridState* si_GridStates[MAX_GRID_STATE];
50
51Map::~Map()
52{
53    UnloadAll(true);
54}
55
56bool Map::ExistMap(uint32 mapid,int x,int y)
57{
58    int len = sWorld.GetDataPath().length()+strlen("maps/%03u%02u%02u.map")+1;
59    char* tmp = new char[len];
60    snprintf(tmp, len, (char *)(sWorld.GetDataPath()+"maps/%03u%02u%02u.map").c_str(),mapid,x,y);
61
62    FILE *pf=fopen(tmp,"rb");
63
64    if(!pf)
65    {
66        sLog.outError("Check existing of map file '%s': not exist!",tmp);
67        delete[] tmp;
68        return false;
69    }
70
71    char magic[8];
72    fread(magic,1,8,pf);
73    if(strncmp(MAP_MAGIC,magic,8))
74    {
75        sLog.outError("Map file '%s' is non-compatible version (outdated?). Please, create new using ad.exe program.",tmp);
76        delete [] tmp;
77        fclose(pf);                                         //close file before return
78        return false;
79    }
80
81    delete [] tmp;
82    fclose(pf);
83
84    return true;
85}
86
87bool Map::ExistVMap(uint32 mapid,int x,int y)
88{
89    if(VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager())
90    {
91        if(vmgr->isMapLoadingEnabled())
92        {
93                                                            // x and y are swapped !! => fixed now
94            bool exists = vmgr->existsMap((sWorld.GetDataPath()+ "vmaps").c_str(),  mapid, x,y);
95            if(!exists)
96            {
97                std::string name = vmgr->getDirFileName(mapid,x,y);
98                sLog.outError("VMap file '%s' is missing or point to wrong version vmap file, redo vmaps with latest vmap_assembler.exe program", (sWorld.GetDataPath()+"vmaps/"+name).c_str());
99                return false;
100            }
101        }
102    }
103
104    return true;
105}
106
107void Map::LoadVMap(int x,int y)
108{
109                                                            // x and y are swapped !!
110    int vmapLoadResult = VMAP::VMapFactory::createOrGetVMapManager()->loadMap((sWorld.GetDataPath()+ "vmaps").c_str(),  GetId(), x,y);
111    switch(vmapLoadResult)
112    {
113        case VMAP::VMAP_LOAD_RESULT_OK:
114            sLog.outDetail("VMAP loaded name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", GetMapName(), GetId(), x,y, x,y);
115            break;
116        case VMAP::VMAP_LOAD_RESULT_ERROR:
117            sLog.outDetail("Could not load VMAP name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", GetMapName(), GetId(), x,y, x,y);
118            break;
119        case VMAP::VMAP_LOAD_RESULT_IGNORED:
120            DEBUG_LOG("Ignored VMAP name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", GetMapName(), GetId(), x,y, x,y);
121            break;
122    }
123}
124
125void Map::LoadMap(uint32 mapid, uint32 instanceid, int x,int y)
126{
127    if( instanceid != 0 )
128    {
129        if(GridMaps[x][y])
130            return;
131
132        Map* baseMap = const_cast<Map*>(MapManager::Instance().GetBaseMap(mapid));
133
134        // load gridmap for base map
135        if (!baseMap->GridMaps[x][y])
136            baseMap->EnsureGridCreated(GridPair(63-x,63-y));
137
138//+++        if (!baseMap->GridMaps[x][y])  don't check for GridMaps[gx][gy], we need the management for vmaps
139//            return;
140
141        ((MapInstanced*)(baseMap))->AddGridMapReference(GridPair(x,y));
142        baseMap->SetUnloadFlag(GridPair(63-x,63-y), false);
143        GridMaps[x][y] = baseMap->GridMaps[x][y];
144        return;
145    }
146
147    //map already load, delete it before reloading (Is it necessary? Do we really need the ability the reload maps during runtime?)
148    if(GridMaps[x][y])
149    {
150        sLog.outDetail("Unloading already loaded map %u before reloading.",mapid);
151        delete (GridMaps[x][y]);
152        GridMaps[x][y]=NULL;
153    }
154
155    // map file name
156    char *tmp=NULL;
157    // Pihhan: dataPath length + "maps/" + 3+2+2+ ".map" length may be > 32 !
158    int len = sWorld.GetDataPath().length()+strlen("maps/%03u%02u%02u.map")+1;
159    tmp = new char[len];
160    snprintf(tmp, len, (char *)(sWorld.GetDataPath()+"maps/%03u%02u%02u.map").c_str(),mapid,x,y);
161    sLog.outDetail("Loading map %s",tmp);
162    // loading data
163    FILE *pf=fopen(tmp,"rb");
164    if(!pf)
165    {
166        delete [] tmp;
167        return;
168    }
169
170    char magic[8];
171    fread(magic,1,8,pf);
172    if(strncmp(MAP_MAGIC,magic,8))
173    {
174        sLog.outError("Map file '%s' is non-compatible version (outdated?). Please, create new using ad.exe program.",tmp);
175        delete [] tmp;
176        fclose(pf);                                         //close file before return
177        return;
178    }
179    delete []  tmp;
180
181    GridMap * buf= new GridMap;
182    fread(buf,1,sizeof(GridMap),pf);
183    fclose(pf);
184
185    GridMaps[x][y] = buf;
186}
187
188void Map::LoadMapAndVMap(uint32 mapid, uint32 instanceid, int x,int y)
189{
190    LoadMap(mapid,instanceid,x,y);
191    if(instanceid == 0)
192        LoadVMap(x, y);                                     // Only load the data for the base map
193}
194
195void Map::InitStateMachine()
196{
197    si_GridStates[GRID_STATE_INVALID] = new InvalidState;
198    si_GridStates[GRID_STATE_ACTIVE] = new ActiveState;
199    si_GridStates[GRID_STATE_IDLE] = new IdleState;
200    si_GridStates[GRID_STATE_REMOVAL] = new RemovalState;
201}
202
203void Map::DeleteStateMachine()
204{
205    delete si_GridStates[GRID_STATE_INVALID];
206    delete si_GridStates[GRID_STATE_ACTIVE];
207    delete si_GridStates[GRID_STATE_IDLE];
208    delete si_GridStates[GRID_STATE_REMOVAL];
209}
210
211Map::Map(uint32 id, time_t expiry, uint32 InstanceId, uint8 SpawnMode)
212  : i_id(id), i_gridExpiry(expiry), i_mapEntry (sMapStore.LookupEntry(id)),
213 i_InstanceId(InstanceId), i_spawnMode(SpawnMode), m_unloadTimer(0)
214{
215    for(unsigned int idx=0; idx < MAX_NUMBER_OF_GRIDS; ++idx)
216    {
217        for(unsigned int j=0; j < MAX_NUMBER_OF_GRIDS; ++j)
218        {
219            //z code
220            GridMaps[idx][j] =NULL;
221            setNGrid(NULL, idx, j);
222        }
223    }
224}
225
226// Template specialization of utility methods
227template<class T>
228void Map::AddToGrid(T* obj, NGridType *grid, Cell const& cell)
229{
230    (*grid)(cell.CellX(), cell.CellY()).template AddGridObject<T>(obj, obj->GetGUID());
231}
232
233template<>
234void Map::AddToGrid(Player* obj, NGridType *grid, Cell const& cell)
235{
236    (*grid)(cell.CellX(), cell.CellY()).AddWorldObject(obj, obj->GetGUID());
237}
238
239template<>
240void Map::AddToGrid(Corpse *obj, NGridType *grid, Cell const& cell)
241{
242    // add to world object registry in grid
243    if(obj->GetType()!=CORPSE_BONES)
244    {
245        (*grid)(cell.CellX(), cell.CellY()).AddWorldObject(obj, obj->GetGUID());
246    }
247    // add to grid object store
248    else
249    {
250        (*grid)(cell.CellX(), cell.CellY()).AddGridObject(obj, obj->GetGUID());
251    }
252}
253
254template<>
255void Map::AddToGrid(Creature* obj, NGridType *grid, Cell const& cell)
256{
257    // add to world object registry in grid
258    if(obj->isPet() || obj->isPossessedByPlayer())
259    {
260        (*grid)(cell.CellX(), cell.CellY()).AddWorldObject<Creature>(obj, obj->GetGUID());
261        obj->SetCurrentCell(cell);
262    }
263    // add to grid object store
264    else
265    {
266        (*grid)(cell.CellX(), cell.CellY()).AddGridObject<Creature>(obj, obj->GetGUID());
267        obj->SetCurrentCell(cell);
268    }
269}
270
271template<class T>
272void Map::RemoveFromGrid(T* obj, NGridType *grid, Cell const& cell)
273{
274    (*grid)(cell.CellX(), cell.CellY()).template RemoveGridObject<T>(obj, obj->GetGUID());
275}
276
277template<>
278void Map::RemoveFromGrid(Player* obj, NGridType *grid, Cell const& cell)
279{
280    (*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject(obj, obj->GetGUID());
281}
282
283template<>
284void Map::RemoveFromGrid(Corpse *obj, NGridType *grid, Cell const& cell)
285{
286    // remove from world object registry in grid
287    if(obj->GetType()!=CORPSE_BONES)
288    {
289        (*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject(obj, obj->GetGUID());
290    }
291    // remove from grid object store
292    else
293    {
294        (*grid)(cell.CellX(), cell.CellY()).RemoveGridObject(obj, obj->GetGUID());
295    }
296}
297
298template<>
299void Map::RemoveFromGrid(Creature* obj, NGridType *grid, Cell const& cell)
300{
301    // remove from world object registry in grid
302    if(obj->isPet() || obj->isPossessedByPlayer())
303    {
304        (*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject<Creature>(obj, obj->GetGUID());
305    }
306    // remove from grid object store
307    else
308    {
309        (*grid)(cell.CellX(), cell.CellY()).RemoveGridObject<Creature>(obj, obj->GetGUID());
310    }
311}
312
313template<class T>
314void Map::SwitchGridContainers(T* obj, bool active)
315{
316    CellPair pair = Trinity::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
317    Cell cell(pair);
318    NGridType *ngrid = getNGrid(cell.GridX(), cell.GridY());
319    GridType &grid = (*ngrid)(cell.CellX(), cell.CellY());
320
321    if (active)
322    {
323        if (!grid.GetWorldObject(obj->GetGUID(), obj))
324        {
325            grid.RemoveGridObject<T>(obj, obj->GetGUID());
326            grid.AddWorldObject<T>(obj, obj->GetGUID());
327        }
328    } else
329    {
330        if (!grid.GetGridObject(obj->GetGUID(), obj))
331        {
332            grid.RemoveWorldObject<T>(obj, obj->GetGUID());
333            grid.AddGridObject<T>(obj, obj->GetGUID());
334        }
335    }
336}
337
338template void Map::SwitchGridContainers(Creature *, bool);
339template void Map::SwitchGridContainers(Corpse *, bool);
340template void Map::SwitchGridContainers(DynamicObject *, bool);
341
342template<class T>
343void Map::DeleteFromWorld(T* obj)
344{
345    // Note: In case resurrectable corpse and pet its removed from global lists in own destructor
346    delete obj;
347}
348
349template<class T>
350void Map::AddNotifier(T* , Cell const& , CellPair const& )
351{
352}
353
354template<>
355void Map::AddNotifier(Player* obj, Cell const& cell, CellPair const& cellpair)
356{
357    PlayerRelocationNotify(obj,cell,cellpair);
358}
359
360template<>
361void Map::AddNotifier(Creature* obj, Cell const& cell, CellPair const& cellpair)
362{
363    CreatureRelocationNotify(obj,cell,cellpair);
364}
365
366void
367Map::EnsureGridCreated(const GridPair &p)
368{
369    if(!getNGrid(p.x_coord, p.y_coord))
370    {
371        Guard guard(*this);
372        if(!getNGrid(p.x_coord, p.y_coord))
373        {
374            setNGrid(new NGridType(p.x_coord*MAX_NUMBER_OF_GRIDS + p.y_coord, p.x_coord, p.y_coord, i_gridExpiry, sWorld.getConfig(CONFIG_GRID_UNLOAD)),
375                p.x_coord, p.y_coord);
376
377            // build a linkage between this map and NGridType
378            buildNGridLinkage(getNGrid(p.x_coord, p.y_coord));
379
380            getNGrid(p.x_coord, p.y_coord)->SetGridState(GRID_STATE_IDLE);
381
382            //z coord
383            int gx=63-p.x_coord;
384            int gy=63-p.y_coord;
385
386            if(!GridMaps[gx][gy])
387                Map::LoadMapAndVMap(i_id,i_InstanceId,gx,gy);
388        }
389    }
390}
391
392void
393Map::EnsureGridLoadedForPlayer(const Cell &cell, Player *player, bool add_player)
394{
395    EnsureGridCreated(GridPair(cell.GridX(), cell.GridY()));
396    NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
397
398    assert(grid != NULL);
399    if( !isGridObjectDataLoaded(cell.GridX(), cell.GridY()) )
400    {
401        if( player != NULL )
402        {
403            player->SendDelayResponse(MAX_GRID_LOAD_TIME);
404            DEBUG_LOG("Player %s enter cell[%u,%u] triggers of loading grid[%u,%u] on map %u", player->GetName(), cell.CellX(), cell.CellY(), cell.GridX(), cell.GridY(), i_id);
405        }
406        else
407        {
408            DEBUG_LOG("Player nearby triggers of loading grid [%u,%u] on map %u", cell.GridX(), cell.GridY(), i_id);
409        }
410
411        ObjectGridLoader loader(*grid, this, cell);
412        loader.LoadN();
413        setGridObjectDataLoaded(true, cell.GridX(), cell.GridY());
414
415        // Add resurrectable corpses to world object list in grid
416        ObjectAccessor::Instance().AddCorpsesToGrid(GridPair(cell.GridX(),cell.GridY()),(*grid)(cell.CellX(), cell.CellY()), this);
417
418        ResetGridExpiry(*getNGrid(cell.GridX(), cell.GridY()), 0.1f);
419        grid->SetGridState(GRID_STATE_ACTIVE);
420
421        if( add_player && player != NULL )
422            (*grid)(cell.CellX(), cell.CellY()).AddWorldObject(player, player->GetGUID());
423    }
424    else if( player && add_player )
425        AddToGrid(player,grid,cell);
426}
427
428void
429Map::LoadGrid(const Cell& cell, bool no_unload)
430{
431    EnsureGridCreated(GridPair(cell.GridX(), cell.GridY()));
432    NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
433
434    assert(grid != NULL);
435    if( !isGridObjectDataLoaded(cell.GridX(), cell.GridY()) )
436    {
437        ObjectGridLoader loader(*grid, this, cell);
438        loader.LoadN();
439
440        // Add resurrectable corpses to world object list in grid
441        ObjectAccessor::Instance().AddCorpsesToGrid(GridPair(cell.GridX(),cell.GridY()),(*grid)(cell.CellX(), cell.CellY()), this);
442
443        setGridObjectDataLoaded(true,cell.GridX(), cell.GridY());
444        if(no_unload)
445            getNGrid(cell.GridX(), cell.GridY())->setUnloadFlag(false);
446    }
447    LoadVMap(63-cell.GridX(),63-cell.GridY());
448}
449
450bool Map::Add(Player *player)
451{
452    player->SetInstanceId(GetInstanceId());
453
454    // update player state for other player and visa-versa
455    CellPair p = Trinity::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
456    Cell cell(p);
457    EnsureGridLoadedForPlayer(cell, player, true);
458    player->AddToWorld();
459
460    SendInitSelf(player);
461    SendInitTransports(player);
462
463    UpdatePlayerVisibility(player,cell,p);
464    UpdateObjectsVisibilityFor(player,cell,p);
465
466    AddNotifier(player,cell,p);
467    return true;
468}
469
470template<class T>
471void
472Map::Add(T *obj)
473{
474    CellPair p = Trinity::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
475
476    assert(obj);
477
478    if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
479    {
480        sLog.outError("Map::Add: Object " I64FMTD " have invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUID(), obj->GetPositionX(), obj->GetPositionY(), p.x_coord, p.y_coord);
481        return;
482    }
483
484    Cell cell(p);
485    EnsureGridCreated(GridPair(cell.GridX(), cell.GridY()));
486    NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
487    assert( grid != NULL );
488
489    AddToGrid(obj,grid,cell);
490    obj->AddToWorld();
491
492    DEBUG_LOG("Object %u enters grid[%u,%u]", GUID_LOPART(obj->GetGUID()), cell.GridX(), cell.GridY());
493
494    UpdateObjectVisibility(obj,cell,p);
495
496    AddNotifier(obj,cell,p);
497}
498
499void Map::MessageBroadcast(Player *player, WorldPacket *msg, bool to_self, bool to_possessor)
500{
501    CellPair p = Trinity::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
502
503    if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
504    {
505        sLog.outError("Map::MessageBroadcast: Player (GUID: %u) have invalid coordinates X:%f Y:%f grid cell [%u:%u]", player->GetGUIDLow(), player->GetPositionX(), player->GetPositionY(), p.x_coord, p.y_coord);
506        return;
507    }
508
509    Cell cell(p);
510    cell.data.Part.reserved = ALL_DISTRICT;
511
512    if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
513        return;
514
515    Trinity::MessageDeliverer post_man(*player, msg, to_possessor, to_self);
516    TypeContainerVisitor<Trinity::MessageDeliverer, WorldTypeMapContainer > message(post_man);
517    CellLock<ReadGuard> cell_lock(cell, p);
518    cell_lock->Visit(cell_lock, message, *this);
519}
520
521void Map::MessageBroadcast(WorldObject *obj, WorldPacket *msg, bool to_possessor)
522{
523    CellPair p = Trinity::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
524
525    if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
526    {
527        sLog.outError("Map::MessageBroadcast: Object " I64FMTD " have invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUID(), obj->GetPositionX(), obj->GetPositionY(), p.x_coord, p.y_coord);
528        return;
529    }
530
531    Cell cell(p);
532    cell.data.Part.reserved = ALL_DISTRICT;
533    cell.SetNoCreate();
534
535    if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
536        return;
537
538    Trinity::ObjectMessageDeliverer post_man(*obj, msg, to_possessor);
539    TypeContainerVisitor<Trinity::ObjectMessageDeliverer, WorldTypeMapContainer > message(post_man);
540    CellLock<ReadGuard> cell_lock(cell, p);
541    cell_lock->Visit(cell_lock, message, *this);
542}
543
544void Map::MessageDistBroadcast(Player *player, WorldPacket *msg, float dist, bool to_self, bool to_possessor, bool own_team_only)
545{
546    CellPair p = Trinity::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
547
548    if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
549    {
550        sLog.outError("Map::MessageBroadcast: Player (GUID: %u) have invalid coordinates X:%f Y:%f grid cell [%u:%u]", player->GetGUIDLow(), player->GetPositionX(), player->GetPositionY(), p.x_coord, p.y_coord);
551        return;
552    }
553
554    Cell cell(p);
555    cell.data.Part.reserved = ALL_DISTRICT;
556
557    if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
558        return;
559
560    Trinity::MessageDistDeliverer post_man(*player, msg, to_possessor, dist, to_self, own_team_only);
561    TypeContainerVisitor<Trinity::MessageDistDeliverer , WorldTypeMapContainer > message(post_man);
562    CellLock<ReadGuard> cell_lock(cell, p);
563    cell_lock->Visit(cell_lock, message, *this);
564}
565
566void Map::MessageDistBroadcast(WorldObject *obj, WorldPacket *msg, float dist, bool to_possessor)
567{
568    CellPair p = Trinity::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
569
570    if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
571    {
572        sLog.outError("Map::MessageBroadcast: Object " I64FMTD " have invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUID(), obj->GetPositionX(), obj->GetPositionY(), p.x_coord, p.y_coord);
573        return;
574    }
575
576    Cell cell(p);
577    cell.data.Part.reserved = ALL_DISTRICT;
578    cell.SetNoCreate();
579
580    if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
581        return;
582
583    Trinity::ObjectMessageDistDeliverer post_man(*obj, msg, to_possessor, dist);
584    TypeContainerVisitor<Trinity::ObjectMessageDistDeliverer, WorldTypeMapContainer > message(post_man);
585    CellLock<ReadGuard> cell_lock(cell, p);
586    cell_lock->Visit(cell_lock, message, *this);
587}
588
589bool Map::loaded(const GridPair &p) const
590{
591    return ( getNGrid(p.x_coord, p.y_coord) && isGridObjectDataLoaded(p.x_coord, p.y_coord) );
592}
593
594void Map::Update(const uint32 &t_diff)
595{
596    // Don't unload grids if it's battleground, since we may have manually added GOs,creatures, those doesn't load from DB at grid re-load !
597    // This isn't really bother us, since as soon as we have instanced BG-s, the whole map unloads as the BG gets ended
598    if (IsBattleGroundOrArena())
599        return;
600
601    for (GridRefManager<NGridType>::iterator i = GridRefManager<NGridType>::begin(); i != GridRefManager<NGridType>::end(); )
602    {
603        NGridType *grid = i->getSource();
604        GridInfo *info = i->getSource()->getGridInfoRef();
605        ++i;                                                // The update might delete the map and we need the next map before the iterator gets invalid
606        assert(grid->GetGridState() >= 0 && grid->GetGridState() < MAX_GRID_STATE);
607        si_GridStates[grid->GetGridState()]->Update(*this, *grid, *info, grid->getX(), grid->getY(), t_diff);
608    }
609}
610
611void Map::Remove(Player *player, bool remove)
612{
613    CellPair p = Trinity::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
614    if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
615    {
616        // invalid coordinates
617        player->RemoveFromWorld();
618
619        if( remove )
620            DeleteFromWorld(player);
621
622        return;
623    }
624
625    Cell cell(p);
626
627    if( !getNGrid(cell.data.Part.grid_x, cell.data.Part.grid_y) )
628    {
629        sLog.outError("Map::Remove() i_grids was NULL x:%d, y:%d",cell.data.Part.grid_x,cell.data.Part.grid_y);
630        return;
631    }
632
633    DEBUG_LOG("Remove player %s from grid[%u,%u]", player->GetName(), cell.GridX(), cell.GridY());
634    NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
635    assert(grid != NULL);
636
637    player->RemoveFromWorld();
638    RemoveFromGrid(player,grid,cell);
639
640    SendRemoveTransports(player);
641
642    UpdateObjectsVisibilityFor(player,cell,p);
643
644    if( remove )
645        DeleteFromWorld(player);
646}
647
648bool Map::RemoveBones(uint64 guid, float x, float y)
649{
650    if (IsRemovalGrid(x, y))
651    {
652        Corpse * corpse = ObjectAccessor::Instance().GetObjectInWorld(GetId(), x, y, guid, (Corpse*)NULL);
653        if(corpse && corpse->GetTypeId() == TYPEID_CORPSE && corpse->GetType() == CORPSE_BONES)
654            corpse->DeleteBonesFromWorld();
655        else
656            return false;
657    }
658    return true;
659}
660
661template<class T>
662void
663Map::Remove(T *obj, bool remove)
664{
665    CellPair p = Trinity::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
666    if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
667    {
668        sLog.outError("Map::Remove: Object " I64FMTD " have invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUID(), obj->GetPositionX(), obj->GetPositionY(), p.x_coord, p.y_coord);
669        return;
670    }
671
672    Cell cell(p);
673    if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
674        return;
675
676    DEBUG_LOG("Remove object " I64FMTD " from grid[%u,%u]", obj->GetGUID(), cell.data.Part.grid_x, cell.data.Part.grid_y);
677    NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
678    assert( grid != NULL );
679
680    obj->RemoveFromWorld();
681    RemoveFromGrid(obj,grid,cell);
682
683    UpdateObjectVisibility(obj,cell,p);
684
685    if( remove )
686    {
687        // if option set then object already saved at this moment
688        if(!sWorld.getConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATELY))
689            obj->SaveRespawnTime();
690        DeleteFromWorld(obj);
691    }
692}
693
694void
695Map::PlayerRelocation(Player *player, float x, float y, float z, float orientation)
696{
697    assert(player);
698
699    CellPair old_val = Trinity::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
700    CellPair new_val = Trinity::ComputeCellPair(x, y);
701
702    Cell old_cell(old_val);
703    Cell new_cell(new_val);
704    new_cell |= old_cell;
705    bool same_cell = (new_cell == old_cell);
706
707    player->Relocate(x, y, z, orientation);
708
709    if( old_cell.DiffGrid(new_cell) || old_cell.DiffCell(new_cell) )
710    {
711        DEBUG_LOG("Player %s relocation grid[%u,%u]cell[%u,%u]->grid[%u,%u]cell[%u,%u]", player->GetName(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY(), new_cell.GridX(), new_cell.GridY(), new_cell.CellX(), new_cell.CellY());
712
713        // update player position for group at taxi flight
714        if(player->GetGroup() && player->isInFlight())
715            player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
716
717        NGridType* oldGrid = getNGrid(old_cell.GridX(), old_cell.GridY());
718        RemoveFromGrid(player, oldGrid,old_cell);
719        if( !old_cell.DiffGrid(new_cell) )
720            AddToGrid(player, oldGrid,new_cell);
721
722        if( old_cell.DiffGrid(new_cell) )
723            EnsureGridLoadedForPlayer(new_cell, player, true);
724    }
725
726    // if move then update what player see and who seen
727    UpdatePlayerVisibility(player,new_cell,new_val);
728    UpdateObjectsVisibilityFor(player,new_cell,new_val);
729
730    // also update what possessing player sees
731    if(player->isPossessedByPlayer())
732        UpdateObjectsVisibilityFor((Player*)player->GetCharmer(), new_cell, new_val);
733
734    PlayerRelocationNotify(player,new_cell,new_val);
735    NGridType* newGrid = getNGrid(new_cell.GridX(), new_cell.GridY());
736    if( !same_cell && newGrid->GetGridState()!= GRID_STATE_ACTIVE )
737    {
738        ResetGridExpiry(*newGrid, 0.1f);
739        newGrid->SetGridState(GRID_STATE_ACTIVE);
740    }
741}
742
743void
744Map::CreatureRelocation(Creature *creature, float x, float y, float z, float ang)
745{
746    assert(CheckGridIntegrity(creature,false));
747
748    Cell old_cell = creature->GetCurrentCell();
749
750    CellPair new_val = Trinity::ComputeCellPair(x, y);
751    Cell new_cell(new_val);
752
753    // delay creature move for grid/cell to grid/cell moves
754    if( old_cell.DiffCell(new_cell) || old_cell.DiffGrid(new_cell) )
755    {
756        #ifdef TRINITY_DEBUG
757        if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
758            sLog.outDebug("Creature (GUID: %u Entry: %u) added to moving list from grid[%u,%u]cell[%u,%u] to grid[%u,%u]cell[%u,%u].", creature->GetGUIDLow(), creature->GetEntry(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY(), new_cell.GridX(), new_cell.GridY(), new_cell.CellX(), new_cell.CellY());
759        #endif
760        AddCreatureToMoveList(creature,x,y,z,ang);
761        // in diffcell/diffgrid case notifiers called at finishing move creature in Map::MoveAllCreaturesInMoveList
762        if(creature->isPossessedByPlayer())
763            EnsureGridLoadedForPlayer(new_cell, (Player*)creature->GetCharmer(), false);
764    }
765    else
766    {
767        creature->Relocate(x, y, z, ang);
768        // Update visibility back to player who is controlling the creature
769        if(creature->isPossessedByPlayer())
770            UpdateObjectsVisibilityFor((Player*)creature->GetCharmer(), new_cell, new_val);
771
772        CreatureRelocationNotify(creature,new_cell,new_val);
773    }
774    assert(CheckGridIntegrity(creature,true));
775}
776
777void Map::AddCreatureToMoveList(Creature *c, float x, float y, float z, float ang)
778{
779    if(!c)
780        return;
781
782    i_creaturesToMove[c] = CreatureMover(x,y,z,ang);
783}
784
785void Map::MoveAllCreaturesInMoveList()
786{
787    while(!i_creaturesToMove.empty())
788    {
789        // get data and remove element;
790        CreatureMoveList::iterator iter = i_creaturesToMove.begin();
791        Creature* c = iter->first;
792        CreatureMover cm = iter->second;
793        i_creaturesToMove.erase(iter);
794
795        // calculate cells
796        CellPair new_val = Trinity::ComputeCellPair(cm.x, cm.y);
797        Cell new_cell(new_val);
798
799        // do move or do move to respawn or remove creature if previous all fail
800        if(CreatureCellRelocation(c,new_cell))
801        {
802            // update pos
803            c->Relocate(cm.x, cm.y, cm.z, cm.ang);
804            CreatureRelocationNotify(c,new_cell,new_cell.cellPair());
805        }
806        else
807        {
808            // if creature can't be move in new cell/grid (not loaded) move it to repawn cell/grid
809            // creature coordinates will be updated and notifiers send
810            if(!CreatureRespawnRelocation(c))
811            {
812                // ... or unload (if respawn grid also not loaded)
813                #ifdef TRINITY_DEBUG
814                if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
815                    sLog.outDebug("Creature (GUID: %u Entry: %u ) can't be move to unloaded respawn grid.",c->GetGUIDLow(),c->GetEntry());
816                #endif
817                c->CleanupsBeforeDelete();
818                AddObjectToRemoveList(c);
819            }
820        }
821    }
822}
823
824bool Map::CreatureCellRelocation(Creature *c, Cell new_cell)
825{
826    Cell const& old_cell = c->GetCurrentCell();
827    if(!old_cell.DiffGrid(new_cell) )                       // in same grid
828    {
829        // if in same cell then none do
830        if(old_cell.DiffCell(new_cell))
831        {
832            #ifdef TRINITY_DEBUG
833            if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
834                sLog.outDebug("Creature (GUID: %u Entry: %u) moved in grid[%u,%u] from cell[%u,%u] to cell[%u,%u].", c->GetGUIDLow(), c->GetEntry(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY(), new_cell.CellX(), new_cell.CellY());
835            #endif
836
837            if( !old_cell.DiffGrid(new_cell) )
838            {
839                RemoveFromGrid(c,getNGrid(old_cell.GridX(), old_cell.GridY()),old_cell);
840                AddToGrid(c,getNGrid(new_cell.GridX(), new_cell.GridY()),new_cell);
841                c->SetCurrentCell(new_cell);
842            }
843        }
844        else
845        {
846            #ifdef TRINITY_DEBUG
847            if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
848                sLog.outDebug("Creature (GUID: %u Entry: %u) move in same grid[%u,%u]cell[%u,%u].", c->GetGUIDLow(), c->GetEntry(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY());
849            #endif
850        }
851    }
852    else                                                    // in diff. grids
853    if(loaded(GridPair(new_cell.GridX(), new_cell.GridY())))
854    {
855        #ifdef TRINITY_DEBUG
856        if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
857            sLog.outDebug("Creature (GUID: %u Entry: %u) moved from grid[%u,%u]cell[%u,%u] to grid[%u,%u]cell[%u,%u].", c->GetGUIDLow(), c->GetEntry(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY(), new_cell.GridX(), new_cell.GridY(), new_cell.CellX(), new_cell.CellY());
858        #endif
859
860        RemoveFromGrid(c,getNGrid(old_cell.GridX(), old_cell.GridY()),old_cell);
861        {
862            EnsureGridCreated(GridPair(new_cell.GridX(), new_cell.GridY()));
863            AddToGrid(c,getNGrid(new_cell.GridX(), new_cell.GridY()),new_cell);
864        }
865    }
866    else
867    {
868        #ifdef TRINITY_DEBUG
869        if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
870            sLog.outDebug("Creature (GUID: %u Entry: %u) attempt move from grid[%u,%u]cell[%u,%u] to unloaded grid[%u,%u]cell[%u,%u].", c->GetGUIDLow(), c->GetEntry(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY(), new_cell.GridX(), new_cell.GridY(), new_cell.CellX(), new_cell.CellY());
871        #endif
872        return false;
873    }
874
875    return true;
876}
877
878bool Map::CreatureRespawnRelocation(Creature *c)
879{
880    float resp_x, resp_y, resp_z, resp_o;
881    c->GetRespawnCoord(resp_x, resp_y, resp_z, &resp_o);
882
883    CellPair resp_val = Trinity::ComputeCellPair(resp_x, resp_y);
884    Cell resp_cell(resp_val);
885
886    c->CombatStop();
887    c->GetMotionMaster()->Clear();
888
889    #ifdef TRINITY_DEBUG
890    if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
891        sLog.outDebug("Creature (GUID: %u Entry: %u) will moved from grid[%u,%u]cell[%u,%u] to respawn grid[%u,%u]cell[%u,%u].", c->GetGUIDLow(), c->GetEntry(), c->GetCurrentCell().GridX(), c->GetCurrentCell().GridY(), c->GetCurrentCell().CellX(), c->GetCurrentCell().CellY(), resp_cell.GridX(), resp_cell.GridY(), resp_cell.CellX(), resp_cell.CellY());
892    #endif
893
894    // teleport it to respawn point (like normal respawn if player see)
895    if(CreatureCellRelocation(c,resp_cell))
896    {
897        c->Relocate(resp_x, resp_y, resp_z, resp_o);
898        c->GetMotionMaster()->Initialize();                 // prevent possible problems with default move generators
899        CreatureRelocationNotify(c,resp_cell,resp_cell.cellPair());
900        return true;
901    }
902    else
903        return false;
904}
905
906bool Map::UnloadGrid(const uint32 &x, const uint32 &y, bool pForce)
907{
908    NGridType *grid = getNGrid(x, y);
909    assert( grid != NULL);
910
911    {
912        if(!pForce && ObjectAccessor::Instance().ActiveObjectsNearGrid(x, y, i_id, i_InstanceId) )
913            return false;
914
915        DEBUG_LOG("Unloading grid[%u,%u] for map %u", x,y, i_id);
916        ObjectGridUnloader unloader(*grid);
917
918        // Finish creature moves, remove and delete all creatures with delayed remove before moving to respawn grids
919        // Must know real mob position before move
920        DoDelayedMovesAndRemoves();
921
922        // move creatures to respawn grids if this is diff.grid or to remove list
923        unloader.MoveToRespawnN();
924
925        // Finish creature moves, remove and delete all creatures with delayed remove before unload
926        DoDelayedMovesAndRemoves();
927
928        unloader.UnloadN();
929        delete getNGrid(x, y);
930        setNGrid(NULL, x, y);
931    }
932    int gx=63-x;
933    int gy=63-y;
934
935    // delete grid map, but don't delete if it is from parent map (and thus only reference)
936    //+++if (GridMaps[gx][gy]) don't check for GridMaps[gx][gy], we might have to unload vmaps
937    {
938        if (i_InstanceId == 0)
939        {
940            if(GridMaps[gx][gy]) delete (GridMaps[gx][gy]);
941            // x and y are swaped
942            VMAP::VMapFactory::createOrGetVMapManager()->unloadMap(GetId(), gy, gx);
943        }
944        else
945            ((MapInstanced*)(MapManager::Instance().GetBaseMap(i_id)))->RemoveGridMapReference(GridPair(gx, gy));
946        GridMaps[gx][gy] = NULL;
947    }
948    DEBUG_LOG("Unloading grid[%u,%u] for map %u finished", x,y, i_id);
949    return true;
950}
951
952void Map::UnloadAll(bool pForce)
953{
954    // clear all delayed moves, useless anyway do this moves before map unload.
955    i_creaturesToMove.clear();
956
957    for (GridRefManager<NGridType>::iterator i = GridRefManager<NGridType>::begin(); i != GridRefManager<NGridType>::end(); )
958    {
959        NGridType &grid(*i->getSource());
960        ++i;
961        UnloadGrid(grid.getX(), grid.getY(), pForce);       // deletes the grid and removes it from the GridRefManager
962    }
963}
964
965float Map::GetHeight(float x, float y, float z, bool pUseVmaps) const
966{
967    GridPair p = Trinity::ComputeGridPair(x, y);
968
969    // half opt method
970    int gx=(int)(32-x/SIZE_OF_GRIDS);                       //grid x
971    int gy=(int)(32-y/SIZE_OF_GRIDS);                       //grid y
972
973    float lx=MAP_RESOLUTION*(32 -x/SIZE_OF_GRIDS - gx);
974    float ly=MAP_RESOLUTION*(32 -y/SIZE_OF_GRIDS - gy);
975
976    // ensure GridMap is loaded
977    const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
978
979    // find raw .map surface under Z coordinates
980    float mapHeight;
981    if(GridMap* gmap = GridMaps[gx][gy])
982    {
983        int lx_int = (int)lx;
984        int ly_int = (int)ly;
985
986        float zi[4];
987        // Probe 4 nearest points (except border cases)
988        zi[0] = gmap->Z[lx_int][ly_int];
989        zi[1] = lx < MAP_RESOLUTION-1 ? gmap->Z[lx_int+1][ly_int] : zi[0];
990        zi[2] = ly < MAP_RESOLUTION-1 ? gmap->Z[lx_int][ly_int+1] : zi[0];
991        zi[3] = lx < MAP_RESOLUTION-1 && ly < MAP_RESOLUTION-1 ? gmap->Z[lx_int+1][ly_int+1] : zi[0];
992        // Recalculate them like if their x,y positions were in the range 0,1
993        float b[4];
994        b[0] = zi[0];
995        b[1] = zi[1]-zi[0];
996        b[2] = zi[2]-zi[0];
997        b[3] = zi[0]-zi[1]-zi[2]+zi[3];
998        // Normalize the dx and dy to be in range 0..1
999        float fact_x = lx - lx_int;
1000        float fact_y = ly - ly_int;
1001        // Use the simplified bilinear equation, as described in [url="http://en.wikipedia.org/wiki/Bilinear_interpolation"]http://en.wikipedia.org/wiki/Bilinear_interpolation[/url]
1002        float _mapheight = b[0] + (b[1]*fact_x) + (b[2]*fact_y) + (b[3]*fact_x*fact_y);
1003
1004        // look from a bit higher pos to find the floor, ignore under surface case
1005        if(z + 2.0f > _mapheight)
1006            mapHeight = _mapheight;
1007        else
1008            mapHeight = VMAP_INVALID_HEIGHT_VALUE;
1009    }
1010    else
1011        mapHeight = VMAP_INVALID_HEIGHT_VALUE;
1012
1013    float vmapHeight;
1014    if(pUseVmaps)
1015    {
1016        VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager();
1017        if(vmgr->isHeightCalcEnabled())
1018        {
1019            // look from a bit higher pos to find the floor
1020            vmapHeight = vmgr->getHeight(GetId(), x, y, z + 2.0f);
1021        }
1022        else
1023            vmapHeight = VMAP_INVALID_HEIGHT_VALUE;
1024    }
1025    else
1026        vmapHeight = VMAP_INVALID_HEIGHT_VALUE;
1027
1028    // mapHeight set for any above raw ground Z or <= INVALID_HEIGHT
1029    // vmapheight set for any under Z value or <= INVALID_HEIGHT
1030
1031    if( vmapHeight > INVALID_HEIGHT )
1032    {
1033        if( mapHeight > INVALID_HEIGHT )
1034        {
1035            // we have mapheight and vmapheight and must select more appropriate
1036
1037            // we are already under the surface or vmap height above map heigt
1038            // or if the distance of the vmap height is less the land height distance
1039            if( z < mapHeight || vmapHeight > mapHeight || fabs(mapHeight-z) > fabs(vmapHeight-z) )
1040                return vmapHeight;
1041            else
1042                return mapHeight;                           // better use .map surface height
1043
1044        }
1045        else
1046            return vmapHeight;                              // we have only vmapHeight (if have)
1047    }
1048    else
1049    {
1050        if(!pUseVmaps)
1051            return mapHeight;                               // explicitly use map data (if have)
1052        else if(mapHeight > INVALID_HEIGHT && (z < mapHeight + 2 || z == MAX_HEIGHT))
1053            return mapHeight;                               // explicitly use map data if original z < mapHeight but map found (z+2 > mapHeight)
1054        else
1055            return VMAP_INVALID_HEIGHT_VALUE;               // we not have any height
1056    }
1057}
1058
1059uint16 Map::GetAreaFlag(float x, float y ) const
1060{
1061    //local x,y coords
1062    float lx,ly;
1063    int gx,gy;
1064    GridPair p = Trinity::ComputeGridPair(x, y);
1065
1066    // half opt method
1067    gx=(int)(32-x/SIZE_OF_GRIDS) ;                          //grid x
1068    gy=(int)(32-y/SIZE_OF_GRIDS);                           //grid y
1069
1070    lx=16*(32 -x/SIZE_OF_GRIDS - gx);
1071    ly=16*(32 -y/SIZE_OF_GRIDS - gy);
1072    //DEBUG_LOG("my %d %d si %d %d",gx,gy,p.x_coord,p.y_coord);
1073
1074    // ensure GridMap is loaded
1075    const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
1076
1077    if(GridMaps[gx][gy])
1078        return GridMaps[gx][gy]->area_flag[(int)(lx)][(int)(ly)];
1079    // this used while not all *.map files generated (instances)
1080    else
1081        return GetAreaFlagByMapId(i_id);
1082}
1083
1084uint8 Map::GetTerrainType(float x, float y ) const
1085{
1086    //local x,y coords
1087    float lx,ly;
1088    int gx,gy;
1089
1090    // half opt method
1091    gx=(int)(32-x/SIZE_OF_GRIDS) ;                          //grid x
1092    gy=(int)(32-y/SIZE_OF_GRIDS);                           //grid y
1093
1094    lx=16*(32 -x/SIZE_OF_GRIDS - gx);
1095    ly=16*(32 -y/SIZE_OF_GRIDS - gy);
1096
1097    // ensure GridMap is loaded
1098    const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
1099
1100    if(GridMaps[gx][gy])
1101        return GridMaps[gx][gy]->terrain_type[(int)(lx)][(int)(ly)];
1102    else
1103        return 0;
1104
1105}
1106
1107float Map::GetWaterLevel(float x, float y ) const
1108{
1109    //local x,y coords
1110    float lx,ly;
1111    int gx,gy;
1112
1113    // half opt method
1114    gx=(int)(32-x/SIZE_OF_GRIDS) ;                          //grid x
1115    gy=(int)(32-y/SIZE_OF_GRIDS);                           //grid y
1116
1117    lx=128*(32 -x/SIZE_OF_GRIDS - gx);
1118    ly=128*(32 -y/SIZE_OF_GRIDS - gy);
1119
1120    // ensure GridMap is loaded
1121    const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
1122
1123    if(GridMaps[gx][gy])
1124        return GridMaps[gx][gy]->liquid_level[(int)(lx)][(int)(ly)];
1125    else
1126        return 0;
1127}
1128
1129uint32 Map::GetAreaId(uint16 areaflag,uint32 map_id)
1130{
1131    AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
1132
1133    if (entry)
1134        return entry->ID;
1135    else
1136        return 0;
1137}
1138
1139uint32 Map::GetZoneId(uint16 areaflag,uint32 map_id)
1140{
1141    AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
1142
1143    if( entry )
1144        return ( entry->zone != 0 ) ? entry->zone : entry->ID;
1145    else
1146        return 0;
1147}
1148
1149bool Map::IsInWater(float x, float y, float pZ) const
1150{
1151    // This method is called too often to use vamps for that (4. parameter = false).
1152    // The pZ pos is taken anyway for future use
1153    float z = GetHeight(x,y,pZ,false);                      // use .map base surface height
1154
1155    // underground or instance without vmap
1156    if(z <= INVALID_HEIGHT)
1157        return false;
1158
1159    float water_z = GetWaterLevel(x,y);
1160    uint8 flag = GetTerrainType(x,y);
1161    return (z < (water_z-2)) && (flag & 0x01);
1162}
1163
1164bool Map::IsUnderWater(float x, float y, float z) const
1165{
1166    float water_z = GetWaterLevel(x,y);
1167    uint8 flag = GetTerrainType(x,y);
1168    return (z < (water_z-2)) && (flag & 0x01);
1169}
1170
1171bool Map::CheckGridIntegrity(Creature* c, bool moved) const
1172{
1173    Cell const& cur_cell = c->GetCurrentCell();
1174
1175    CellPair xy_val = Trinity::ComputeCellPair(c->GetPositionX(), c->GetPositionY());
1176    Cell xy_cell(xy_val);
1177    if(xy_cell != cur_cell)
1178    {
1179        sLog.outError("ERROR: %s (GUID: %u) X: %f Y: %f (%s) in grid[%u,%u]cell[%u,%u] instead grid[%u,%u]cell[%u,%u]",
1180            (c->GetTypeId()==TYPEID_PLAYER ? "Player" : "Creature"),c->GetGUIDLow(),
1181            c->GetPositionX(),c->GetPositionY(),(moved ? "final" : "original"),
1182            cur_cell.GridX(), cur_cell.GridY(), cur_cell.CellX(), cur_cell.CellY(),
1183            xy_cell.GridX(),  xy_cell.GridY(),  xy_cell.CellX(),  xy_cell.CellY());
1184        return true;                                        // not crash at error, just output error in debug mode
1185    }
1186
1187    return true;
1188}
1189
1190const char* Map::GetMapName() const
1191{
1192    return i_mapEntry ? i_mapEntry->name[sWorld.GetDefaultDbcLocale()] : "UNNAMEDMAP\x0";
1193}
1194
1195void Map::UpdateObjectVisibility( WorldObject* obj, Cell cell, CellPair cellpair)
1196{
1197    cell.data.Part.reserved = ALL_DISTRICT;
1198    cell.SetNoCreate();
1199    Trinity::VisibleChangesNotifier notifier(*obj);
1200    TypeContainerVisitor<Trinity::VisibleChangesNotifier, WorldTypeMapContainer > player_notifier(notifier);
1201    CellLock<GridReadGuard> cell_lock(cell, cellpair);
1202    cell_lock->Visit(cell_lock, player_notifier, *this);
1203}
1204
1205void Map::UpdatePlayerVisibility( Player* player, Cell cell, CellPair cellpair )
1206{
1207    cell.data.Part.reserved = ALL_DISTRICT;
1208
1209    Trinity::PlayerNotifier pl_notifier(*player);
1210    TypeContainerVisitor<Trinity::PlayerNotifier, WorldTypeMapContainer > player_notifier(pl_notifier);
1211
1212    CellLock<ReadGuard> cell_lock(cell, cellpair);
1213    cell_lock->Visit(cell_lock, player_notifier, *this);
1214}
1215
1216void Map::UpdateObjectsVisibilityFor( Player* player, Cell cell, CellPair cellpair )
1217{
1218    Trinity::VisibleNotifier notifier(*player);
1219
1220    cell.data.Part.reserved = ALL_DISTRICT;
1221    cell.SetNoCreate();
1222    TypeContainerVisitor<Trinity::VisibleNotifier, WorldTypeMapContainer > world_notifier(notifier);
1223    TypeContainerVisitor<Trinity::VisibleNotifier, GridTypeMapContainer  > grid_notifier(notifier);
1224    CellLock<GridReadGuard> cell_lock(cell, cellpair);
1225    cell_lock->Visit(cell_lock, world_notifier, *this);
1226    cell_lock->Visit(cell_lock, grid_notifier,  *this);
1227
1228    // send data
1229    notifier.Notify();
1230}
1231
1232void Map::PlayerRelocationNotify( Player* player, Cell cell, CellPair cellpair )
1233{
1234    CellLock<ReadGuard> cell_lock(cell, cellpair);
1235    Trinity::PlayerRelocationNotifier relocationNotifier(*player);
1236    cell.data.Part.reserved = ALL_DISTRICT;
1237
1238    TypeContainerVisitor<Trinity::PlayerRelocationNotifier, GridTypeMapContainer >  p2grid_relocation(relocationNotifier);
1239    TypeContainerVisitor<Trinity::PlayerRelocationNotifier, WorldTypeMapContainer > p2world_relocation(relocationNotifier);
1240
1241    cell_lock->Visit(cell_lock, p2grid_relocation, *this);
1242    cell_lock->Visit(cell_lock, p2world_relocation, *this);
1243}
1244
1245void Map::CreatureRelocationNotify(Creature *creature, Cell cell, CellPair cellpair)
1246{
1247    CellLock<ReadGuard> cell_lock(cell, cellpair);
1248    Trinity::CreatureRelocationNotifier relocationNotifier(*creature);
1249    cell.data.Part.reserved = ALL_DISTRICT;
1250    cell.SetNoCreate();                                     // not trigger load unloaded grids at notifier call
1251
1252    TypeContainerVisitor<Trinity::CreatureRelocationNotifier, WorldTypeMapContainer > c2world_relocation(relocationNotifier);
1253    TypeContainerVisitor<Trinity::CreatureRelocationNotifier, GridTypeMapContainer >  c2grid_relocation(relocationNotifier);
1254
1255    cell_lock->Visit(cell_lock, c2world_relocation, *this);
1256    cell_lock->Visit(cell_lock, c2grid_relocation, *this);
1257}
1258
1259void Map::SendInitSelf( Player * player )
1260{
1261    sLog.outDetail("Creating player data for himself %u", player->GetGUIDLow());
1262
1263    UpdateData data;
1264
1265    bool hasTransport = false;
1266
1267    // attach to player data current transport data
1268    if(Transport* transport = player->GetTransport())
1269    {
1270        hasTransport = true;
1271        transport->BuildCreateUpdateBlockForPlayer(&data, player);
1272    }
1273
1274    // build data for self presence in world at own client (one time for map)
1275    player->BuildCreateUpdateBlockForPlayer(&data, player);
1276
1277    // build other passengers at transport also (they always visible and marked as visible and will not send at visibility update at add to map
1278    if(Transport* transport = player->GetTransport())
1279    {
1280        for(Transport::PlayerSet::const_iterator itr = transport->GetPassengers().begin();itr!=transport->GetPassengers().end();++itr)
1281        {
1282            if(player!=(*itr) && player->HaveAtClient(*itr))
1283            {
1284                hasTransport = true;
1285                (*itr)->BuildCreateUpdateBlockForPlayer(&data, player);
1286            }
1287        }
1288    }
1289
1290    WorldPacket packet;
1291    data.BuildPacket(&packet, hasTransport);
1292    player->GetSession()->SendPacket(&packet);
1293}
1294
1295void Map::SendInitTransports( Player * player )
1296{
1297    // Hack to send out transports
1298    MapManager::TransportMap& tmap = MapManager::Instance().m_TransportsByMap;
1299
1300    // no transports at map
1301    if (tmap.find(player->GetMapId()) == tmap.end())
1302        return;
1303
1304    UpdateData transData;
1305
1306    MapManager::TransportSet& tset = tmap[player->GetMapId()];
1307
1308    bool hasTransport = false;
1309
1310    for (MapManager::TransportSet::iterator i = tset.begin(); i != tset.end(); ++i)
1311    {
1312        if((*i) != player->GetTransport())                  // send data for current transport in other place
1313        {
1314            hasTransport = true;
1315            (*i)->BuildCreateUpdateBlockForPlayer(&transData, player);
1316        }
1317    }
1318
1319    WorldPacket packet;
1320    transData.BuildPacket(&packet, hasTransport);
1321    player->GetSession()->SendPacket(&packet);
1322}
1323
1324void Map::SendRemoveTransports( Player * player )
1325{
1326    // Hack to send out transports
1327    MapManager::TransportMap& tmap = MapManager::Instance().m_TransportsByMap;
1328
1329    // no transports at map
1330    if (tmap.find(player->GetMapId()) == tmap.end())
1331        return;
1332
1333    UpdateData transData;
1334
1335    MapManager::TransportSet& tset = tmap[player->GetMapId()];
1336
1337    // except used transport
1338    for (MapManager::TransportSet::iterator i = tset.begin(); i != tset.end(); ++i)
1339        if(player->GetTransport() != (*i))
1340            (*i)->BuildOutOfRangeUpdateBlock(&transData);
1341
1342    WorldPacket packet;
1343    transData.BuildPacket(&packet);
1344    player->GetSession()->SendPacket(&packet);
1345}
1346
1347inline void Map::setNGrid(NGridType *grid, uint32 x, uint32 y)
1348{
1349    if(x >= MAX_NUMBER_OF_GRIDS || y >= MAX_NUMBER_OF_GRIDS)
1350    {
1351        sLog.outError("map::setNGrid() Invalid grid coordinates found: %d, %d!",x,y);
1352        assert(false);
1353    }
1354    i_grids[x][y] = grid;
1355}
1356
1357void Map::DoDelayedMovesAndRemoves()
1358{
1359    MoveAllCreaturesInMoveList();
1360    RemoveAllObjectsInRemoveList();
1361}
1362
1363void Map::AddObjectToRemoveList(WorldObject *obj)
1364{
1365    assert(obj->GetMapId()==GetId() && obj->GetInstanceId()==GetInstanceId());
1366
1367    i_objectsToRemove.insert(obj);
1368    //sLog.outDebug("Object (GUID: %u TypeId: %u ) added to removing list.",obj->GetGUIDLow(),obj->GetTypeId());
1369}
1370
1371void Map::RemoveAllObjectsInRemoveList()
1372{
1373    if(i_objectsToRemove.empty())
1374        return;
1375
1376    //sLog.outDebug("Object remover 1 check.");
1377    while(!i_objectsToRemove.empty())
1378    {
1379        WorldObject* obj = *i_objectsToRemove.begin();
1380        i_objectsToRemove.erase(i_objectsToRemove.begin());
1381
1382        switch(obj->GetTypeId())
1383        {
1384            case TYPEID_CORPSE:
1385            {
1386                Corpse* corpse = ObjectAccessor::Instance().GetCorpse(*obj, obj->GetGUID());
1387                if (!corpse)
1388                    sLog.outError("ERROR: Try delete corpse/bones %u that not in map", obj->GetGUIDLow());
1389                else
1390                    Remove(corpse,true);
1391                break;
1392            }
1393        case TYPEID_DYNAMICOBJECT:
1394            Remove((DynamicObject*)obj,true);
1395            break;
1396        case TYPEID_GAMEOBJECT:
1397            Remove((GameObject*)obj,true);
1398            break;
1399        case TYPEID_UNIT:
1400            // in case triggered sequence some spell can continue casting after prev CleanupsBeforeDelete call
1401            // make sure that like sources auras/etc removed before destructor start
1402            ((Creature*)obj)->CleanupsBeforeDelete ();
1403            Remove((Creature*)obj,true);
1404            break;
1405        default:
1406            sLog.outError("Non-grid object (TypeId: %u) in grid object removing list, ignored.",obj->GetTypeId());
1407            break;
1408        }
1409    }
1410    //sLog.outDebug("Object remover 2 check.");
1411}
1412
1413bool Map::CanUnload(const uint32 &diff)
1414{
1415    if(!m_unloadTimer) return false;
1416    if(m_unloadTimer < diff) return true;
1417    m_unloadTimer -= diff;
1418    return false;
1419}
1420
1421template void Map::Add(Corpse *);
1422template void Map::Add(Creature *);
1423template void Map::Add(GameObject *);
1424template void Map::Add(DynamicObject *);
1425
1426template void Map::Remove(Corpse *,bool);
1427template void Map::Remove(Creature *,bool);
1428template void Map::Remove(GameObject *, bool);
1429template void Map::Remove(DynamicObject *, bool);
1430
1431/* ******* Dungeon Instance Maps ******* */
1432
1433InstanceMap::InstanceMap(uint32 id, time_t expiry, uint32 InstanceId, uint8 SpawnMode)
1434  : Map(id, expiry, InstanceId, SpawnMode), i_data(NULL),
1435    m_resetAfterUnload(false), m_unloadWhenEmpty(false)
1436{
1437    // the timer is started by default, and stopped when the first player joins
1438    // this make sure it gets unloaded if for some reason no player joins
1439    m_unloadTimer = std::max(sWorld.getConfig(CONFIG_INSTANCE_UNLOAD_DELAY), (uint32)MIN_UNLOAD_DELAY);
1440}
1441
1442InstanceMap::~InstanceMap()
1443{
1444    if(i_data)
1445    {
1446        delete i_data;
1447        i_data = NULL;
1448    }
1449}
1450
1451/*
1452    Do map specific checks to see if the player can enter
1453*/
1454bool InstanceMap::CanEnter(Player *player)
1455{
1456    if(std::find(i_Players.begin(),i_Players.end(),player)!=i_Players.end())
1457    {
1458        sLog.outError("InstanceMap::CanEnter - player %s(%u) already in map %d,%d,%d!", player->GetName(), player->GetGUIDLow(), GetId(), GetInstanceId(), GetSpawnMode());
1459        assert(false);
1460        return false;
1461    }
1462
1463    // cannot enter if the instance is full (player cap), GMs don't count
1464    InstanceTemplate const* iTemplate = objmgr.GetInstanceTemplate(GetId());
1465    if (!player->isGameMaster() && GetPlayersCountExceptGMs() >= iTemplate->maxPlayers)
1466    {
1467        sLog.outDetail("MAP: Instance '%u' of map '%s' cannot have more than '%u' players. Player '%s' rejected", GetInstanceId(), GetMapName(), iTemplate->maxPlayers, player->GetName());
1468        player->SendTransferAborted(GetId(), TRANSFER_ABORT_MAX_PLAYERS);
1469        return false;
1470    }
1471
1472    // cannot enter while players in the instance are in combat
1473    Group *pGroup = player->GetGroup();
1474    if(!player->isGameMaster() && pGroup && pGroup->InCombatToInstance(GetInstanceId()) && player->isAlive() && player->GetMapId() != GetId())
1475    {
1476        player->SendTransferAborted(GetId(), TRANSFER_ABORT_ZONE_IN_COMBAT);
1477        return false;
1478    }
1479
1480    return Map::CanEnter(player);
1481}
1482
1483/*
1484    Do map specific checks and add the player to the map if successful.
1485*/
1486bool InstanceMap::Add(Player *player)
1487{
1488    // TODO: Not sure about checking player level: already done in HandleAreaTriggerOpcode
1489    // GMs still can teleport player in instance.
1490    // Is it needed?
1491
1492    {
1493        Guard guard(*this);
1494        if(!CanEnter(player))
1495            return false;
1496
1497        // get or create an instance save for the map
1498        InstanceSave *mapSave = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1499        if(!mapSave)
1500        {
1501            sLog.outDetail("InstanceMap::Add: creating instance save for map %d spawnmode %d with instance id %d", GetId(), GetSpawnMode(), GetInstanceId());
1502            mapSave = sInstanceSaveManager.AddInstanceSave(GetId(), GetInstanceId(), GetSpawnMode(), 0, true);
1503        }
1504
1505        // check for existing instance binds
1506        InstancePlayerBind *playerBind = player->GetBoundInstance(GetId(), GetSpawnMode());
1507        if(playerBind && playerBind->perm)
1508        {
1509            // cannot enter other instances if bound permanently
1510            if(playerBind->save != mapSave)
1511            {
1512                sLog.outError("InstanceMap::Add: player %s(%d) is permanently bound to instance %d,%d,%d,%d,%d,%d but he is being put in instance %d,%d,%d,%d,%d,%d", player->GetName(), player->GetGUIDLow(), playerBind->save->GetMapId(), playerBind->save->GetInstanceId(), playerBind->save->GetDifficulty(), playerBind->save->GetPlayerCount(), playerBind->save->GetGroupCount(), playerBind->save->CanReset(), mapSave->GetMapId(), mapSave->GetInstanceId(), mapSave->GetDifficulty(), mapSave->GetPlayerCount(), mapSave->GetGroupCount(), mapSave->CanReset());
1513                assert(false);
1514            }
1515        }
1516        else
1517        {
1518            Group *pGroup = player->GetGroup();
1519            if(pGroup)
1520            {
1521                // solo saves should be reset when entering a group
1522                InstanceGroupBind *groupBind = pGroup->GetBoundInstance(GetId(), GetSpawnMode());
1523                if(playerBind)
1524                {
1525                    sLog.outError("InstanceMap::Add: player %s(%d) is being put in instance %d,%d,%d,%d,%d,%d but he is in group %d and is bound to instance %d,%d,%d,%d,%d,%d!", player->GetName(), player->GetGUIDLow(), mapSave->GetMapId(), mapSave->GetInstanceId(), mapSave->GetDifficulty(), mapSave->GetPlayerCount(), mapSave->GetGroupCount(), mapSave->CanReset(), GUID_LOPART(pGroup->GetLeaderGUID()), playerBind->save->GetMapId(), playerBind->save->GetInstanceId(), playerBind->save->GetDifficulty(), playerBind->save->GetPlayerCount(), playerBind->save->GetGroupCount(), playerBind->save->CanReset());
1526                    if(groupBind) sLog.outError("InstanceMap::Add: the group is bound to instance %d,%d,%d,%d,%d,%d", groupBind->save->GetMapId(), groupBind->save->GetInstanceId(), groupBind->save->GetDifficulty(), groupBind->save->GetPlayerCount(), groupBind->save->GetGroupCount(), groupBind->save->CanReset());
1527                    assert(false);
1528                }
1529                // bind to the group or keep using the group save
1530                if(!groupBind)
1531                    pGroup->BindToInstance(mapSave, false);
1532                else
1533                {
1534                    // cannot jump to a different instance without resetting it
1535                    if(groupBind->save != mapSave)
1536                    {
1537                        sLog.outError("InstanceMap::Add: player %s(%d) is being put in instance %d,%d,%d but he is in group %d which is bound to instance %d,%d,%d!", player->GetName(), player->GetGUIDLow(), mapSave->GetMapId(), mapSave->GetInstanceId(), mapSave->GetDifficulty(), GUID_LOPART(pGroup->GetLeaderGUID()), groupBind->save->GetMapId(), groupBind->save->GetInstanceId(), groupBind->save->GetDifficulty());
1538                        if(mapSave)
1539                            sLog.outError("MapSave players: %d, group count: %d", mapSave->GetPlayerCount(), mapSave->GetGroupCount());
1540                        else
1541                            sLog.outError("MapSave NULL");
1542                        if(groupBind->save)
1543                            sLog.outError("GroupBind save players: %d, group count: %d", groupBind->save->GetPlayerCount(), groupBind->save->GetGroupCount());
1544                        else
1545                            sLog.outError("GroupBind save NULL");
1546                        assert(false);
1547                    }
1548                    // if the group/leader is permanently bound to the instance
1549                    // players also become permanently bound when they enter
1550                    if(groupBind->perm)
1551                    {
1552                        WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
1553                        data << uint32(0);
1554                        player->GetSession()->SendPacket(&data);
1555                        player->BindToInstance(mapSave, true);
1556                    }
1557                }
1558            }
1559            else
1560            {
1561                // set up a solo bind or continue using it
1562                if(!playerBind)
1563                    player->BindToInstance(mapSave, false);
1564                else
1565                    // cannot jump to a different instance without resetting it
1566                    assert(playerBind->save == mapSave);
1567            }
1568        }
1569
1570        if(i_data) i_data->OnPlayerEnter(player);
1571        SetResetSchedule(false);
1572
1573        i_Players.push_back(player);
1574        player->SendInitWorldStates();
1575        sLog.outDetail("MAP: Player '%s' entered the instance '%u' of map '%s'", player->GetName(), GetInstanceId(), GetMapName());
1576        // initialize unload state
1577        m_unloadTimer = 0;
1578        m_resetAfterUnload = false;
1579        m_unloadWhenEmpty = false;
1580    }
1581
1582    // this will acquire the same mutex so it cannot be in the previous block
1583    Map::Add(player);
1584    return true;
1585}
1586
1587void InstanceMap::Update(const uint32& t_diff)
1588{
1589    Map::Update(t_diff);
1590
1591    if(i_data)
1592        i_data->Update(t_diff);
1593}
1594
1595void InstanceMap::Remove(Player *player, bool remove)
1596{
1597    sLog.outDetail("MAP: Removing player '%s' from instance '%u' of map '%s' before relocating to other map", player->GetName(), GetInstanceId(), GetMapName());
1598    i_Players.remove(player);
1599    SetResetSchedule(true);
1600    if(!m_unloadTimer && i_Players.empty())
1601        m_unloadTimer = m_unloadWhenEmpty ? MIN_UNLOAD_DELAY : std::max(sWorld.getConfig(CONFIG_INSTANCE_UNLOAD_DELAY), (uint32)MIN_UNLOAD_DELAY);
1602    Map::Remove(player, remove);
1603}
1604
1605Creature * Map::GetCreatureInMap(uint64 guid)
1606{
1607    Creature * obj = HashMapHolder<Creature>::Find(guid);
1608    if(obj && obj->GetInstanceId() != GetInstanceId()) obj = NULL;
1609    return obj;
1610}
1611
1612GameObject * Map::GetGameObjectInMap(uint64 guid)
1613{
1614    GameObject * obj = HashMapHolder<GameObject>::Find(guid);
1615    if(obj && obj->GetInstanceId() != GetInstanceId()) obj = NULL;
1616    return obj;
1617}
1618
1619void InstanceMap::CreateInstanceData(bool load)
1620{
1621    if(i_data != NULL)
1622        return;
1623
1624    InstanceTemplate const* mInstance = objmgr.GetInstanceTemplate(GetId());
1625    if (mInstance)
1626    {
1627        i_script = mInstance->script;
1628        i_data = Script->CreateInstanceData(this);
1629    }
1630
1631    if(!i_data)
1632        return;
1633
1634    if(load)
1635    {
1636        // TODO: make a global storage for this
1637        QueryResult* result = CharacterDatabase.PQuery("SELECT data FROM instance WHERE map = '%u' AND id = '%u'", GetId(), i_InstanceId);
1638        if (result)
1639        {
1640            Field* fields = result->Fetch();
1641            const char* data = fields[0].GetString();
1642            if(data)
1643            {
1644                sLog.outDebug("Loading instance data for `%s` with id %u", i_script.c_str(), i_InstanceId);
1645                i_data->Load(data);
1646            }
1647            delete result;
1648        }
1649    }
1650    else
1651    {
1652        sLog.outDebug("New instance data, \"%s\" ,initialized!",i_script.c_str());
1653        i_data->Initialize();
1654    }
1655}
1656
1657/*
1658    Returns true if there are no players in the instance
1659*/
1660bool InstanceMap::Reset(uint8 method)
1661{
1662    // note: since the map may not be loaded when the instance needs to be reset
1663    // the instance must be deleted from the DB by InstanceSaveManager
1664
1665    if(!i_Players.empty())
1666    {
1667        if(method == INSTANCE_RESET_ALL)
1668        {
1669            // notify the players to leave the instance so it can be reset
1670            for(PlayerList::iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1671                (*itr)->SendResetFailedNotify(GetId());
1672        }
1673        else
1674        {
1675            if(method == INSTANCE_RESET_GLOBAL)
1676            {
1677                // set the homebind timer for players inside (1 minute)
1678                for(PlayerList::iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1679                    (*itr)->m_InstanceValid = false;
1680            }
1681
1682            // the unload timer is not started
1683            // instead the map will unload immediately after the players have left
1684            m_unloadWhenEmpty = true;
1685            m_resetAfterUnload = true;
1686        }
1687    }
1688    else
1689    {
1690        // unloaded at next update
1691        m_unloadTimer = MIN_UNLOAD_DELAY;
1692        m_resetAfterUnload = true;
1693    }
1694
1695    return i_Players.empty();
1696}
1697
1698uint32 InstanceMap::GetPlayersCountExceptGMs() const
1699{
1700    uint32 count = 0;
1701    for(PlayerList::const_iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1702        if(!(*itr)->isGameMaster())
1703            ++count;
1704    return count;
1705}
1706
1707void InstanceMap::PermBindAllPlayers(Player *player)
1708{
1709    InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1710    if(!save)
1711    {
1712        sLog.outError("Cannot bind players, no instance save available for map!\n");
1713        return;
1714    }
1715
1716    Group *group = player->GetGroup();
1717    // group members outside the instance group don't get bound
1718    for(PlayerList::iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1719    {
1720        if(*itr)
1721        {
1722            // players inside an instance cannot be bound to other instances
1723            // some players may already be permanently bound, in this case nothing happens
1724            InstancePlayerBind *bind = (*itr)->GetBoundInstance(save->GetMapId(), save->GetDifficulty());
1725            if(!bind || !bind->perm)
1726            {
1727                (*itr)->BindToInstance(save, true);
1728                WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
1729                data << uint32(0);
1730                (*itr)->GetSession()->SendPacket(&data);
1731            }
1732
1733            // if the leader is not in the instance the group will not get a perm bind
1734            if(group && group->GetLeaderGUID() == (*itr)->GetGUID())
1735                group->BindToInstance(save, true);
1736        }
1737    }
1738}
1739
1740time_t InstanceMap::GetResetTime()
1741{
1742    InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1743    return save ? save->GetDifficulty() : DIFFICULTY_NORMAL;
1744}
1745
1746void InstanceMap::UnloadAll(bool pForce)
1747{
1748    if(!i_Players.empty())
1749    {
1750        sLog.outError("InstanceMap::UnloadAll: there are still players in the instance at unload, should not happen!");
1751        for(PlayerList::iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1752            if(*itr) (*itr)->TeleportTo((*itr)->m_homebindMapId, (*itr)->m_homebindX, (*itr)->m_homebindY, (*itr)->m_homebindZ, (*itr)->GetOrientation());
1753    }
1754
1755    if(m_resetAfterUnload == true)
1756        objmgr.DeleteRespawnTimeForInstance(GetInstanceId());
1757
1758    Map::UnloadAll(pForce);
1759}
1760
1761void InstanceMap::SendResetWarnings(uint32 timeLeft)
1762{
1763    for(PlayerList::iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1764        (*itr)->SendInstanceResetWarning(GetId(), timeLeft);
1765}
1766
1767void InstanceMap::SetResetSchedule(bool on)
1768{
1769    // only for normal instances
1770    // the reset time is only scheduled when there are no payers inside
1771    // it is assumed that the reset time will rarely (if ever) change while the reset is scheduled
1772    if(i_Players.empty() && !IsRaid() && !IsHeroic())
1773    {
1774        InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1775        if(!save) sLog.outError("InstanceMap::SetResetSchedule: cannot turn schedule %s, no save available for instance %d of %d", on ? "on" : "off", GetInstanceId(), GetId());
1776        else sInstanceSaveManager.ScheduleReset(on, save->GetResetTime(), InstanceSaveManager::InstResetEvent(0, GetId(), GetInstanceId()));
1777    }
1778}
1779
1780void InstanceMap::SendToPlayers(WorldPacket const* data) const
1781{
1782    for(PlayerList::const_iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1783        (*itr)->GetSession()->SendPacket(data);
1784}
1785
1786/* ******* Battleground Instance Maps ******* */
1787
1788BattleGroundMap::BattleGroundMap(uint32 id, time_t expiry, uint32 InstanceId)
1789  : Map(id, expiry, InstanceId, DIFFICULTY_NORMAL)
1790{
1791}
1792
1793BattleGroundMap::~BattleGroundMap()
1794{
1795}
1796
1797bool BattleGroundMap::CanEnter(Player * player)
1798{
1799    if(std::find(i_Players.begin(),i_Players.end(),player)!=i_Players.end())
1800    {
1801        sLog.outError("BGMap::CanEnter - player %u already in map!", player->GetGUIDLow());
1802        assert(false);
1803        return false;
1804    }
1805
1806    if(player->GetBattleGroundId() != GetInstanceId())
1807        return false;
1808
1809    // player number limit is checked in bgmgr, no need to do it here
1810
1811    return Map::CanEnter(player);
1812}
1813
1814bool BattleGroundMap::Add(Player * player)
1815{
1816    {
1817        Guard guard(*this);
1818        if(!CanEnter(player))
1819            return false;
1820        i_Players.push_back(player);
1821        // reset instance validity, battleground maps do not homebind
1822        player->m_InstanceValid = true;
1823    }
1824    return Map::Add(player);
1825}
1826
1827void BattleGroundMap::Remove(Player *player, bool remove)
1828{
1829    sLog.outDetail("MAP: Removing player '%s' from bg '%u' of map '%s' before relocating to other map", player->GetName(), GetInstanceId(), GetMapName());
1830    i_Players.remove(player);
1831    Map::Remove(player, remove);
1832}
1833
1834void BattleGroundMap::SetUnload()
1835{
1836    m_unloadTimer = MIN_UNLOAD_DELAY;
1837}
1838
1839void BattleGroundMap::UnloadAll(bool pForce)
1840{
1841    while(!i_Players.empty())
1842    {
1843        PlayerList::iterator itr = i_Players.begin();
1844        Player * plr = *itr;
1845        if(plr) (plr)->TeleportTo((*itr)->m_homebindMapId, (*itr)->m_homebindX, (*itr)->m_homebindY, (*itr)->m_homebindZ, (*itr)->GetOrientation());
1846        // TeleportTo removes the player from this map (if the map exists) -> calls BattleGroundMap::Remove -> invalidates the iterator.
1847        // just in case, remove the player from the list explicitly here as well to prevent a possible infinite loop
1848        // note that this remove is not needed if the code works well in other places
1849        i_Players.remove(plr);
1850    }
1851
1852    Map::UnloadAll(pForce);
1853}
Note: See TracBrowser for help on using the browser.