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

Revision 2, 62.6 kB (checked in by yumileroy, 17 years ago)

[svn] * Proper SVN structure

Original author: Neo2003
Date: 2008-10-02 16:23:55-05:00

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