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

Revision 279, 67.8 kB (checked in by yumileroy, 17 years ago)

Merged commit 269 (5f0e38da128a).

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