Allow constant only access to m_mapRefManager using Map::GetPlayers()
[getmangos.git] / src / game / Map.cpp
blob606d53df606b4db2a8d5ec6df2f0a56fb8cb8850
1 /*
2 * Copyright (C) 2005-2008 MaNGOS <http://getmangos.com/>
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.
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.
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
19 #include "MapManager.h"
20 #include "Player.h"
21 #include "GridNotifiers.h"
22 #include "WorldSession.h"
23 #include "Log.h"
24 #include "GridStates.h"
25 #include "CellImpl.h"
26 #include "InstanceData.h"
27 #include "Map.h"
28 #include "GridNotifiersImpl.h"
29 #include "Config/ConfigEnv.h"
30 #include "Transports.h"
31 #include "ObjectAccessor.h"
32 #include "ObjectMgr.h"
33 #include "World.h"
34 #include "ScriptCalls.h"
35 #include "Group.h"
36 #include "MapRefManager.h"
38 #include "MapInstanced.h"
39 #include "InstanceSaveMgr.h"
40 #include "VMapFactory.h"
42 #define DEFAULT_GRID_EXPIRY 300
43 #define MAX_GRID_LOAD_TIME 50
45 // magic *.map header
46 const char MAP_MAGIC[] = "MAP_2.00";
48 GridState* si_GridStates[MAX_GRID_STATE];
50 Map::~Map()
52 UnloadAll(true);
55 bool Map::ExistMap(uint32 mapid,int x,int y)
57 int len = sWorld.GetDataPath().length()+strlen("maps/%03u%02u%02u.map")+1;
58 char* tmp = new char[len];
59 snprintf(tmp, len, (char *)(sWorld.GetDataPath()+"maps/%03u%02u%02u.map").c_str(),mapid,x,y);
61 FILE *pf=fopen(tmp,"rb");
63 if(!pf)
65 sLog.outError("Check existing of map file '%s': not exist!",tmp);
66 delete[] tmp;
67 return false;
70 char magic[8];
71 fread(magic,1,8,pf);
72 if(strncmp(MAP_MAGIC,magic,8))
74 sLog.outError("Map file '%s' is non-compatible version (outdated?). Please, create new using ad.exe program.",tmp);
75 delete [] tmp;
76 fclose(pf); //close file before return
77 return false;
80 delete [] tmp;
81 fclose(pf);
83 return true;
86 bool Map::ExistVMap(uint32 mapid,int x,int y)
88 if(VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager())
90 if(vmgr->isMapLoadingEnabled())
92 // x and y are swapped !! => fixed now
93 bool exists = vmgr->existsMap((sWorld.GetDataPath()+ "vmaps").c_str(), mapid, x,y);
94 if(!exists)
96 std::string name = vmgr->getDirFileName(mapid,x,y);
97 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());
98 return false;
103 return true;
106 void Map::LoadVMap(int x,int y)
108 // x and y are swapped !!
109 int vmapLoadResult = VMAP::VMapFactory::createOrGetVMapManager()->loadMap((sWorld.GetDataPath()+ "vmaps").c_str(), GetId(), x,y);
110 switch(vmapLoadResult)
112 case VMAP::VMAP_LOAD_RESULT_OK:
113 sLog.outDetail("VMAP loaded name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", GetMapName(), GetId(), x,y, x,y);
114 break;
115 case VMAP::VMAP_LOAD_RESULT_ERROR:
116 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);
117 break;
118 case VMAP::VMAP_LOAD_RESULT_IGNORED:
119 DEBUG_LOG("Ignored VMAP name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", GetMapName(), GetId(), x,y, x,y);
120 break;
124 void Map::LoadMap(uint32 mapid, uint32 instanceid, int x,int y)
126 if( instanceid != 0 )
128 if(GridMaps[x][y])
129 return;
131 Map* baseMap = const_cast<Map*>(MapManager::Instance().GetBaseMap(mapid));
133 // load gridmap for base map
134 if (!baseMap->GridMaps[x][y])
135 baseMap->EnsureGridCreated(GridPair(63-x,63-y));
137 //+++ if (!baseMap->GridMaps[x][y]) don't check for GridMaps[gx][gy], we need the management for vmaps
138 // return;
140 ((MapInstanced*)(baseMap))->AddGridMapReference(GridPair(x,y));
141 baseMap->SetUnloadFlag(GridPair(63-x,63-y), false);
142 GridMaps[x][y] = baseMap->GridMaps[x][y];
143 return;
146 //map already load, delete it before reloading (Is it necessary? Do we really need the ability the reload maps during runtime?)
147 if(GridMaps[x][y])
149 sLog.outDetail("Unloading already loaded map %u before reloading.",mapid);
150 delete (GridMaps[x][y]);
151 GridMaps[x][y]=NULL;
154 // map file name
155 char *tmp=NULL;
156 // Pihhan: dataPath length + "maps/" + 3+2+2+ ".map" length may be > 32 !
157 int len = sWorld.GetDataPath().length()+strlen("maps/%03u%02u%02u.map")+1;
158 tmp = new char[len];
159 snprintf(tmp, len, (char *)(sWorld.GetDataPath()+"maps/%03u%02u%02u.map").c_str(),mapid,x,y);
160 sLog.outDetail("Loading map %s",tmp);
161 // loading data
162 FILE *pf=fopen(tmp,"rb");
163 if(!pf)
165 delete [] tmp;
166 return;
169 char magic[8];
170 fread(magic,1,8,pf);
171 if(strncmp(MAP_MAGIC,magic,8))
173 sLog.outError("Map file '%s' is non-compatible version (outdated?). Please, create new using ad.exe program.",tmp);
174 delete [] tmp;
175 fclose(pf); //close file before return
176 return;
178 delete [] tmp;
180 GridMap * buf= new GridMap;
181 fread(buf,1,sizeof(GridMap),pf);
182 fclose(pf);
184 GridMaps[x][y] = buf;
187 void Map::LoadMapAndVMap(uint32 mapid, uint32 instanceid, int x,int y)
189 LoadMap(mapid,instanceid,x,y);
190 if(instanceid == 0)
191 LoadVMap(x, y); // Only load the data for the base map
194 void Map::InitStateMachine()
196 si_GridStates[GRID_STATE_INVALID] = new InvalidState;
197 si_GridStates[GRID_STATE_ACTIVE] = new ActiveState;
198 si_GridStates[GRID_STATE_IDLE] = new IdleState;
199 si_GridStates[GRID_STATE_REMOVAL] = new RemovalState;
202 void Map::DeleteStateMachine()
204 delete si_GridStates[GRID_STATE_INVALID];
205 delete si_GridStates[GRID_STATE_ACTIVE];
206 delete si_GridStates[GRID_STATE_IDLE];
207 delete si_GridStates[GRID_STATE_REMOVAL];
210 Map::Map(uint32 id, time_t expiry, uint32 InstanceId, uint8 SpawnMode)
211 : i_id(id), i_gridExpiry(expiry), i_mapEntry (sMapStore.LookupEntry(id)),
212 i_InstanceId(InstanceId), i_spawnMode(SpawnMode), m_unloadTimer(0)
214 for(unsigned int idx=0; idx < MAX_NUMBER_OF_GRIDS; ++idx)
216 for(unsigned int j=0; j < MAX_NUMBER_OF_GRIDS; ++j)
218 //z code
219 GridMaps[idx][j] =NULL;
220 setNGrid(NULL, idx, j);
225 // Template specialization of utility methods
226 template<class T>
227 void Map::AddToGrid(T* obj, NGridType *grid, Cell const& cell)
229 (*grid)(cell.CellX(), cell.CellY()).template AddGridObject<T>(obj, obj->GetGUID());
232 template<>
233 void Map::AddToGrid(Player* obj, NGridType *grid, Cell const& cell)
235 (*grid)(cell.CellX(), cell.CellY()).AddWorldObject(obj, obj->GetGUID());
238 template<>
239 void Map::AddToGrid(Corpse *obj, NGridType *grid, Cell const& cell)
241 // add to world object registry in grid
242 if(obj->GetType()!=CORPSE_BONES)
244 (*grid)(cell.CellX(), cell.CellY()).AddWorldObject(obj, obj->GetGUID());
246 // add to grid object store
247 else
249 (*grid)(cell.CellX(), cell.CellY()).AddGridObject(obj, obj->GetGUID());
253 template<>
254 void Map::AddToGrid(Creature* obj, NGridType *grid, Cell const& cell)
256 // add to world object registry in grid
257 if(obj->isPet())
259 (*grid)(cell.CellX(), cell.CellY()).AddWorldObject<Creature>(obj, obj->GetGUID());
260 obj->SetCurrentCell(cell);
262 // add to grid object store
263 else
265 (*grid)(cell.CellX(), cell.CellY()).AddGridObject<Creature>(obj, obj->GetGUID());
266 obj->SetCurrentCell(cell);
270 template<class T>
271 void Map::RemoveFromGrid(T* obj, NGridType *grid, Cell const& cell)
273 (*grid)(cell.CellX(), cell.CellY()).template RemoveGridObject<T>(obj, obj->GetGUID());
276 template<>
277 void Map::RemoveFromGrid(Player* obj, NGridType *grid, Cell const& cell)
279 (*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject(obj, obj->GetGUID());
282 template<>
283 void Map::RemoveFromGrid(Corpse *obj, NGridType *grid, Cell const& cell)
285 // remove from world object registry in grid
286 if(obj->GetType()!=CORPSE_BONES)
288 (*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject(obj, obj->GetGUID());
290 // remove from grid object store
291 else
293 (*grid)(cell.CellX(), cell.CellY()).RemoveGridObject(obj, obj->GetGUID());
297 template<>
298 void Map::RemoveFromGrid(Creature* obj, NGridType *grid, Cell const& cell)
300 // remove from world object registry in grid
301 if(obj->isPet())
303 (*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject<Creature>(obj, obj->GetGUID());
305 // remove from grid object store
306 else
308 (*grid)(cell.CellX(), cell.CellY()).RemoveGridObject<Creature>(obj, obj->GetGUID());
312 template<class T>
313 void Map::DeleteFromWorld(T* obj)
315 // Note: In case resurrectable corpse and pet its removed from global lists in own destructor
316 delete obj;
319 template<class T>
320 void Map::AddNotifier(T* , Cell const& , CellPair const& )
324 template<>
325 void Map::AddNotifier(Player* obj, Cell const& cell, CellPair const& cellpair)
327 PlayerRelocationNotify(obj,cell,cellpair);
330 template<>
331 void Map::AddNotifier(Creature* obj, Cell const& cell, CellPair const& cellpair)
333 CreatureRelocationNotify(obj,cell,cellpair);
336 void
337 Map::EnsureGridCreated(const GridPair &p)
339 if(!getNGrid(p.x_coord, p.y_coord))
341 Guard guard(*this);
342 if(!getNGrid(p.x_coord, p.y_coord))
344 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)),
345 p.x_coord, p.y_coord);
347 // build a linkage between this map and NGridType
348 buildNGridLinkage(getNGrid(p.x_coord, p.y_coord));
350 getNGrid(p.x_coord, p.y_coord)->SetGridState(GRID_STATE_IDLE);
352 //z coord
353 int gx=63-p.x_coord;
354 int gy=63-p.y_coord;
356 if(!GridMaps[gx][gy])
357 Map::LoadMapAndVMap(i_id,i_InstanceId,gx,gy);
362 void
363 Map::EnsureGridLoadedForPlayer(const Cell &cell, Player *player, bool add_player)
365 EnsureGridCreated(GridPair(cell.GridX(), cell.GridY()));
366 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
368 assert(grid != NULL);
369 if( !isGridObjectDataLoaded(cell.GridX(), cell.GridY()) )
371 if( player != NULL )
373 player->SendDelayResponse(MAX_GRID_LOAD_TIME);
374 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);
376 else
378 DEBUG_LOG("Player nearby triggers of loading grid [%u,%u] on map %u", cell.GridX(), cell.GridY(), i_id);
381 ObjectGridLoader loader(*grid, this, cell);
382 loader.LoadN();
383 setGridObjectDataLoaded(true, cell.GridX(), cell.GridY());
385 // Add resurrectable corpses to world object list in grid
386 ObjectAccessor::Instance().AddCorpsesToGrid(GridPair(cell.GridX(),cell.GridY()),(*grid)(cell.CellX(), cell.CellY()), this);
388 ResetGridExpiry(*getNGrid(cell.GridX(), cell.GridY()), 0.1f);
389 grid->SetGridState(GRID_STATE_ACTIVE);
391 if( add_player && player != NULL )
392 (*grid)(cell.CellX(), cell.CellY()).AddWorldObject(player, player->GetGUID());
394 else if( player && add_player )
395 AddToGrid(player,grid,cell);
398 void
399 Map::LoadGrid(const Cell& cell, bool no_unload)
401 EnsureGridCreated(GridPair(cell.GridX(), cell.GridY()));
402 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
404 assert(grid != NULL);
405 if( !isGridObjectDataLoaded(cell.GridX(), cell.GridY()) )
407 ObjectGridLoader loader(*grid, this, cell);
408 loader.LoadN();
410 // Add resurrectable corpses to world object list in grid
411 ObjectAccessor::Instance().AddCorpsesToGrid(GridPair(cell.GridX(),cell.GridY()),(*grid)(cell.CellX(), cell.CellY()), this);
413 setGridObjectDataLoaded(true,cell.GridX(), cell.GridY());
414 if(no_unload)
415 getNGrid(cell.GridX(), cell.GridY())->setUnloadFlag(false);
417 LoadVMap(63-cell.GridX(),63-cell.GridY());
420 bool Map::Add(Player *player)
422 player->GetMapRef().link(this, player);
424 player->SetInstanceId(GetInstanceId());
426 // update player state for other player and visa-versa
427 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
428 Cell cell(p);
429 EnsureGridLoadedForPlayer(cell, player, true);
430 player->AddToWorld();
432 SendInitSelf(player);
433 SendInitTransports(player);
435 UpdatePlayerVisibility(player,cell,p);
436 UpdateObjectsVisibilityFor(player,cell,p);
438 AddNotifier(player,cell,p);
439 return true;
442 template<class T>
443 void
444 Map::Add(T *obj)
446 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
448 assert(obj);
450 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
452 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);
453 return;
456 Cell cell(p);
457 EnsureGridCreated(GridPair(cell.GridX(), cell.GridY()));
458 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
459 assert( grid != NULL );
461 AddToGrid(obj,grid,cell);
462 obj->AddToWorld();
464 DEBUG_LOG("Object %u enters grid[%u,%u]", GUID_LOPART(obj->GetGUID()), cell.GridX(), cell.GridY());
466 UpdateObjectVisibility(obj,cell,p);
468 AddNotifier(obj,cell,p);
471 void Map::MessageBroadcast(Player *player, WorldPacket *msg, bool to_self)
473 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
475 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
477 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);
478 return;
481 Cell cell(p);
482 cell.data.Part.reserved = ALL_DISTRICT;
484 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
485 return;
487 MaNGOS::MessageDeliverer post_man(*player, msg, to_self);
488 TypeContainerVisitor<MaNGOS::MessageDeliverer, WorldTypeMapContainer > message(post_man);
489 CellLock<ReadGuard> cell_lock(cell, p);
490 cell_lock->Visit(cell_lock, message, *this);
493 void Map::MessageBroadcast(WorldObject *obj, WorldPacket *msg)
495 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
497 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
499 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);
500 return;
503 Cell cell(p);
504 cell.data.Part.reserved = ALL_DISTRICT;
505 cell.SetNoCreate();
507 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
508 return;
510 MaNGOS::ObjectMessageDeliverer post_man(msg);
511 TypeContainerVisitor<MaNGOS::ObjectMessageDeliverer, WorldTypeMapContainer > message(post_man);
512 CellLock<ReadGuard> cell_lock(cell, p);
513 cell_lock->Visit(cell_lock, message, *this);
516 void Map::MessageDistBroadcast(Player *player, WorldPacket *msg, float dist, bool to_self, bool own_team_only)
518 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
520 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
522 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);
523 return;
526 Cell cell(p);
527 cell.data.Part.reserved = ALL_DISTRICT;
529 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
530 return;
532 MaNGOS::MessageDistDeliverer post_man(*player, msg, dist, to_self, own_team_only);
533 TypeContainerVisitor<MaNGOS::MessageDistDeliverer , WorldTypeMapContainer > message(post_man);
534 CellLock<ReadGuard> cell_lock(cell, p);
535 cell_lock->Visit(cell_lock, message, *this);
538 void Map::MessageDistBroadcast(WorldObject *obj, WorldPacket *msg, float dist)
540 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
542 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
544 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);
545 return;
548 Cell cell(p);
549 cell.data.Part.reserved = ALL_DISTRICT;
550 cell.SetNoCreate();
552 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
553 return;
555 MaNGOS::ObjectMessageDistDeliverer post_man(*obj, msg,dist);
556 TypeContainerVisitor<MaNGOS::ObjectMessageDistDeliverer, WorldTypeMapContainer > message(post_man);
557 CellLock<ReadGuard> cell_lock(cell, p);
558 cell_lock->Visit(cell_lock, message, *this);
561 bool Map::loaded(const GridPair &p) const
563 return ( getNGrid(p.x_coord, p.y_coord) && isGridObjectDataLoaded(p.x_coord, p.y_coord) );
566 void Map::Update(const uint32 &t_diff)
568 resetMarkedCells();
570 MaNGOS::ObjectUpdater updater(t_diff);
571 // for creature
572 TypeContainerVisitor<MaNGOS::ObjectUpdater, GridTypeMapContainer > grid_object_update(updater);
573 // for pets
574 TypeContainerVisitor<MaNGOS::ObjectUpdater, WorldTypeMapContainer > world_object_update(updater);
576 for(MapRefManager::iterator iter = m_mapRefManager.begin(); iter != m_mapRefManager.end(); ++iter)
578 Player* plr = iter->getSource();
579 if(!plr->IsInWorld())
580 continue;
582 CellPair standing_cell(MaNGOS::ComputeCellPair(plr->GetPositionX(), plr->GetPositionY()));
584 // Check for correctness of standing_cell, it also avoids problems with update_cell
585 if (standing_cell.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || standing_cell.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
586 continue;
588 // the overloaded operators handle range checking
589 // so ther's no need for range checking inside the loop
590 CellPair begin_cell(standing_cell), end_cell(standing_cell);
591 begin_cell << 1; begin_cell -= 1; // upper left
592 end_cell >> 1; end_cell += 1; // lower right
594 for(uint32 x = begin_cell.x_coord; x <= end_cell.x_coord; ++x)
596 for(uint32 y = begin_cell.y_coord; y <= end_cell.y_coord; ++y)
598 // marked cells are those that have been visited
599 // don't visit the same cell twice
600 uint32 cell_id = (y * TOTAL_NUMBER_OF_CELLS_PER_MAP) + x;
601 if(!isCellMarked(cell_id))
603 markCell(cell_id);
604 CellPair pair(x,y);
605 Cell cell(pair);
606 cell.data.Part.reserved = CENTER_DISTRICT;
607 cell.SetNoCreate();
608 CellLock<NullGuard> cell_lock(cell, pair);
609 cell_lock->Visit(cell_lock, grid_object_update, *this);
610 cell_lock->Visit(cell_lock, world_object_update, *this);
617 // 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 !
618 // This isn't really bother us, since as soon as we have instanced BG-s, the whole map unloads as the BG gets ended
619 if (IsBattleGroundOrArena())
620 return;
622 for (GridRefManager<NGridType>::iterator i = GridRefManager<NGridType>::begin(); i != GridRefManager<NGridType>::end(); )
624 NGridType *grid = i->getSource();
625 GridInfo *info = i->getSource()->getGridInfoRef();
626 ++i; // The update might delete the map and we need the next map before the iterator gets invalid
627 assert(grid->GetGridState() >= 0 && grid->GetGridState() < MAX_GRID_STATE);
628 si_GridStates[grid->GetGridState()]->Update(*this, *grid, *info, grid->getX(), grid->getY(), t_diff);
632 void Map::Remove(Player *player, bool remove)
634 player->GetMapRef().unlink();
635 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
636 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
638 // invalid coordinates
639 player->RemoveFromWorld();
641 if( remove )
642 DeleteFromWorld(player);
644 return;
647 Cell cell(p);
649 if( !getNGrid(cell.data.Part.grid_x, cell.data.Part.grid_y) )
651 sLog.outError("Map::Remove() i_grids was NULL x:%d, y:%d",cell.data.Part.grid_x,cell.data.Part.grid_y);
652 return;
655 DEBUG_LOG("Remove player %s from grid[%u,%u]", player->GetName(), cell.GridX(), cell.GridY());
656 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
657 assert(grid != NULL);
659 player->RemoveFromWorld();
660 RemoveFromGrid(player,grid,cell);
662 SendRemoveTransports(player);
664 UpdateObjectsVisibilityFor(player,cell,p);
666 if( remove )
667 DeleteFromWorld(player);
670 bool Map::RemoveBones(uint64 guid, float x, float y)
672 if (IsRemovalGrid(x, y))
674 Corpse * corpse = ObjectAccessor::Instance().GetObjectInWorld(GetId(), x, y, guid, (Corpse*)NULL);
675 if(corpse && corpse->GetTypeId() == TYPEID_CORPSE && corpse->GetType() == CORPSE_BONES)
676 corpse->DeleteBonesFromWorld();
677 else
678 return false;
680 return true;
683 template<class T>
684 void
685 Map::Remove(T *obj, bool remove)
687 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
688 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
690 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);
691 return;
694 Cell cell(p);
695 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
696 return;
698 DEBUG_LOG("Remove object " I64FMTD " from grid[%u,%u]", obj->GetGUID(), cell.data.Part.grid_x, cell.data.Part.grid_y);
699 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
700 assert( grid != NULL );
702 obj->RemoveFromWorld();
703 RemoveFromGrid(obj,grid,cell);
705 UpdateObjectVisibility(obj,cell,p);
707 if( remove )
709 // if option set then object already saved at this moment
710 if(!sWorld.getConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY))
711 obj->SaveRespawnTime();
712 DeleteFromWorld(obj);
716 void
717 Map::PlayerRelocation(Player *player, float x, float y, float z, float orientation)
719 assert(player);
721 CellPair old_val = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
722 CellPair new_val = MaNGOS::ComputeCellPair(x, y);
724 Cell old_cell(old_val);
725 Cell new_cell(new_val);
726 new_cell |= old_cell;
727 bool same_cell = (new_cell == old_cell);
729 player->Relocate(x, y, z, orientation);
731 if( old_cell.DiffGrid(new_cell) || old_cell.DiffCell(new_cell) )
733 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());
735 // update player position for group at taxi flight
736 if(player->GetGroup() && player->isInFlight())
737 player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
739 NGridType* oldGrid = getNGrid(old_cell.GridX(), old_cell.GridY());
740 RemoveFromGrid(player, oldGrid,old_cell);
741 if( !old_cell.DiffGrid(new_cell) )
742 AddToGrid(player, oldGrid,new_cell);
744 if( old_cell.DiffGrid(new_cell) )
745 EnsureGridLoadedForPlayer(new_cell, player, true);
748 // if move then update what player see and who seen
749 UpdatePlayerVisibility(player,new_cell,new_val);
750 UpdateObjectsVisibilityFor(player,new_cell,new_val);
751 PlayerRelocationNotify(player,new_cell,new_val);
752 NGridType* newGrid = getNGrid(new_cell.GridX(), new_cell.GridY());
753 if( !same_cell && newGrid->GetGridState()!= GRID_STATE_ACTIVE )
755 ResetGridExpiry(*newGrid, 0.1f);
756 newGrid->SetGridState(GRID_STATE_ACTIVE);
760 void
761 Map::CreatureRelocation(Creature *creature, float x, float y, float z, float ang)
763 assert(CheckGridIntegrity(creature,false));
765 Cell old_cell = creature->GetCurrentCell();
767 CellPair new_val = MaNGOS::ComputeCellPair(x, y);
768 Cell new_cell(new_val);
770 // delay creature move for grid/cell to grid/cell moves
771 if( old_cell.DiffCell(new_cell) || old_cell.DiffGrid(new_cell) )
773 #ifdef MANGOS_DEBUG
774 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
775 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());
776 #endif
777 AddCreatureToMoveList(creature,x,y,z,ang);
778 // in diffcell/diffgrid case notifiers called at finishing move creature in Map::MoveAllCreaturesInMoveList
780 else
782 creature->Relocate(x, y, z, ang);
783 CreatureRelocationNotify(creature,new_cell,new_val);
785 assert(CheckGridIntegrity(creature,true));
788 void Map::AddCreatureToMoveList(Creature *c, float x, float y, float z, float ang)
790 if(!c)
791 return;
793 i_creaturesToMove[c] = CreatureMover(x,y,z,ang);
796 void Map::MoveAllCreaturesInMoveList()
798 while(!i_creaturesToMove.empty())
800 // get data and remove element;
801 CreatureMoveList::iterator iter = i_creaturesToMove.begin();
802 Creature* c = iter->first;
803 CreatureMover cm = iter->second;
804 i_creaturesToMove.erase(iter);
806 // calculate cells
807 CellPair new_val = MaNGOS::ComputeCellPair(cm.x, cm.y);
808 Cell new_cell(new_val);
810 // do move or do move to respawn or remove creature if previous all fail
811 if(CreatureCellRelocation(c,new_cell))
813 // update pos
814 c->Relocate(cm.x, cm.y, cm.z, cm.ang);
815 CreatureRelocationNotify(c,new_cell,new_cell.cellPair());
817 else
819 // if creature can't be move in new cell/grid (not loaded) move it to repawn cell/grid
820 // creature coordinates will be updated and notifiers send
821 if(!CreatureRespawnRelocation(c))
823 // ... or unload (if respawn grid also not loaded)
824 #ifdef MANGOS_DEBUG
825 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
826 sLog.outDebug("Creature (GUID: %u Entry: %u ) can't be move to unloaded respawn grid.",c->GetGUIDLow(),c->GetEntry());
827 #endif
828 c->CleanupsBeforeDelete();
829 AddObjectToRemoveList(c);
835 bool Map::CreatureCellRelocation(Creature *c, Cell new_cell)
837 Cell const& old_cell = c->GetCurrentCell();
838 if(!old_cell.DiffGrid(new_cell) ) // in same grid
840 // if in same cell then none do
841 if(old_cell.DiffCell(new_cell))
843 #ifdef MANGOS_DEBUG
844 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
845 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());
846 #endif
848 if( !old_cell.DiffGrid(new_cell) )
850 RemoveFromGrid(c,getNGrid(old_cell.GridX(), old_cell.GridY()),old_cell);
851 AddToGrid(c,getNGrid(new_cell.GridX(), new_cell.GridY()),new_cell);
852 c->SetCurrentCell(new_cell);
855 else
857 #ifdef MANGOS_DEBUG
858 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
859 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());
860 #endif
863 else // in diff. grids
864 if(loaded(GridPair(new_cell.GridX(), new_cell.GridY())))
866 #ifdef MANGOS_DEBUG
867 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
868 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());
869 #endif
871 RemoveFromGrid(c,getNGrid(old_cell.GridX(), old_cell.GridY()),old_cell);
873 EnsureGridCreated(GridPair(new_cell.GridX(), new_cell.GridY()));
874 AddToGrid(c,getNGrid(new_cell.GridX(), new_cell.GridY()),new_cell);
877 else
879 #ifdef MANGOS_DEBUG
880 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
881 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());
882 #endif
883 return false;
886 return true;
889 bool Map::CreatureRespawnRelocation(Creature *c)
891 float resp_x, resp_y, resp_z, resp_o;
892 c->GetRespawnCoord(resp_x, resp_y, resp_z, &resp_o);
894 CellPair resp_val = MaNGOS::ComputeCellPair(resp_x, resp_y);
895 Cell resp_cell(resp_val);
897 c->CombatStop();
898 c->GetMotionMaster()->Clear();
900 #ifdef MANGOS_DEBUG
901 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
902 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());
903 #endif
905 // teleport it to respawn point (like normal respawn if player see)
906 if(CreatureCellRelocation(c,resp_cell))
908 c->Relocate(resp_x, resp_y, resp_z, resp_o);
909 c->GetMotionMaster()->Initialize(); // prevent possible problems with default move generators
910 CreatureRelocationNotify(c,resp_cell,resp_cell.cellPair());
911 return true;
913 else
914 return false;
917 bool Map::UnloadGrid(const uint32 &x, const uint32 &y, bool pForce)
919 NGridType *grid = getNGrid(x, y);
920 assert( grid != NULL);
923 if(!pForce && PlayersNearGrid(x, y) )
924 return false;
926 DEBUG_LOG("Unloading grid[%u,%u] for map %u", x,y, i_id);
927 ObjectGridUnloader unloader(*grid);
929 // Finish creature moves, remove and delete all creatures with delayed remove before moving to respawn grids
930 // Must know real mob position before move
931 DoDelayedMovesAndRemoves();
933 // move creatures to respawn grids if this is diff.grid or to remove list
934 unloader.MoveToRespawnN();
936 // Finish creature moves, remove and delete all creatures with delayed remove before unload
937 DoDelayedMovesAndRemoves();
939 unloader.UnloadN();
940 delete getNGrid(x, y);
941 setNGrid(NULL, x, y);
943 int gx=63-x;
944 int gy=63-y;
946 // delete grid map, but don't delete if it is from parent map (and thus only reference)
947 //+++if (GridMaps[gx][gy]) don't check for GridMaps[gx][gy], we might have to unload vmaps
949 if (i_InstanceId == 0)
951 if(GridMaps[gx][gy]) delete (GridMaps[gx][gy]);
952 // x and y are swaped
953 VMAP::VMapFactory::createOrGetVMapManager()->unloadMap(GetId(), gy, gx);
955 else
956 ((MapInstanced*)(MapManager::Instance().GetBaseMap(i_id)))->RemoveGridMapReference(GridPair(gx, gy));
957 GridMaps[gx][gy] = NULL;
959 DEBUG_LOG("Unloading grid[%u,%u] for map %u finished", x,y, i_id);
960 return true;
963 void Map::UnloadAll(bool pForce)
965 // clear all delayed moves, useless anyway do this moves before map unload.
966 i_creaturesToMove.clear();
968 for (GridRefManager<NGridType>::iterator i = GridRefManager<NGridType>::begin(); i != GridRefManager<NGridType>::end(); )
970 NGridType &grid(*i->getSource());
971 ++i;
972 UnloadGrid(grid.getX(), grid.getY(), pForce); // deletes the grid and removes it from the GridRefManager
976 float Map::GetHeight(float x, float y, float z, bool pUseVmaps) const
978 GridPair p = MaNGOS::ComputeGridPair(x, y);
980 // half opt method
981 int gx=(int)(32-x/SIZE_OF_GRIDS); //grid x
982 int gy=(int)(32-y/SIZE_OF_GRIDS); //grid y
984 float lx=MAP_RESOLUTION*(32 -x/SIZE_OF_GRIDS - gx);
985 float ly=MAP_RESOLUTION*(32 -y/SIZE_OF_GRIDS - gy);
987 // ensure GridMap is loaded
988 const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
990 // find raw .map surface under Z coordinates
991 float mapHeight;
992 if(GridMap* gmap = GridMaps[gx][gy])
994 int lx_int = (int)lx;
995 int ly_int = (int)ly;
997 float zi[4];
998 // Probe 4 nearest points (except border cases)
999 zi[0] = gmap->Z[lx_int][ly_int];
1000 zi[1] = lx < MAP_RESOLUTION-1 ? gmap->Z[lx_int+1][ly_int] : zi[0];
1001 zi[2] = ly < MAP_RESOLUTION-1 ? gmap->Z[lx_int][ly_int+1] : zi[0];
1002 zi[3] = lx < MAP_RESOLUTION-1 && ly < MAP_RESOLUTION-1 ? gmap->Z[lx_int+1][ly_int+1] : zi[0];
1003 // Recalculate them like if their x,y positions were in the range 0,1
1004 float b[4];
1005 b[0] = zi[0];
1006 b[1] = zi[1]-zi[0];
1007 b[2] = zi[2]-zi[0];
1008 b[3] = zi[0]-zi[1]-zi[2]+zi[3];
1009 // Normalize the dx and dy to be in range 0..1
1010 float fact_x = lx - lx_int;
1011 float fact_y = ly - ly_int;
1012 // Use the simplified bilinear equation, as described in [url="http://en.wikipedia.org/wiki/Bilinear_interpolation"]http://en.wikipedia.org/wiki/Bilinear_interpolation[/url]
1013 float _mapheight = b[0] + (b[1]*fact_x) + (b[2]*fact_y) + (b[3]*fact_x*fact_y);
1015 // look from a bit higher pos to find the floor, ignore under surface case
1016 if(z + 2.0f > _mapheight)
1017 mapHeight = _mapheight;
1018 else
1019 mapHeight = VMAP_INVALID_HEIGHT_VALUE;
1021 else
1022 mapHeight = VMAP_INVALID_HEIGHT_VALUE;
1024 float vmapHeight;
1025 if(pUseVmaps)
1027 VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager();
1028 if(vmgr->isHeightCalcEnabled())
1030 // look from a bit higher pos to find the floor
1031 vmapHeight = vmgr->getHeight(GetId(), x, y, z + 2.0f);
1033 else
1034 vmapHeight = VMAP_INVALID_HEIGHT_VALUE;
1036 else
1037 vmapHeight = VMAP_INVALID_HEIGHT_VALUE;
1039 // mapHeight set for any above raw ground Z or <= INVALID_HEIGHT
1040 // vmapheight set for any under Z value or <= INVALID_HEIGHT
1042 if( vmapHeight > INVALID_HEIGHT )
1044 if( mapHeight > INVALID_HEIGHT )
1046 // we have mapheight and vmapheight and must select more appropriate
1048 // we are already under the surface or vmap height above map heigt
1049 // or if the distance of the vmap height is less the land height distance
1050 if( z < mapHeight || vmapHeight > mapHeight || fabs(mapHeight-z) > fabs(vmapHeight-z) )
1051 return vmapHeight;
1052 else
1053 return mapHeight; // better use .map surface height
1056 else
1057 return vmapHeight; // we have only vmapHeight (if have)
1059 else
1061 if(!pUseVmaps)
1062 return mapHeight; // explicitly use map data (if have)
1063 else if(mapHeight > INVALID_HEIGHT && (z < mapHeight + 2 || z == MAX_HEIGHT))
1064 return mapHeight; // explicitly use map data if original z < mapHeight but map found (z+2 > mapHeight)
1065 else
1066 return VMAP_INVALID_HEIGHT_VALUE; // we not have any height
1070 uint16 Map::GetAreaFlag(float x, float y ) const
1072 //local x,y coords
1073 float lx,ly;
1074 int gx,gy;
1075 GridPair p = MaNGOS::ComputeGridPair(x, y);
1077 // half opt method
1078 gx=(int)(32-x/SIZE_OF_GRIDS) ; //grid x
1079 gy=(int)(32-y/SIZE_OF_GRIDS); //grid y
1081 lx=16*(32 -x/SIZE_OF_GRIDS - gx);
1082 ly=16*(32 -y/SIZE_OF_GRIDS - gy);
1083 //DEBUG_LOG("my %d %d si %d %d",gx,gy,p.x_coord,p.y_coord);
1085 // ensure GridMap is loaded
1086 const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
1088 if(GridMaps[gx][gy])
1089 return GridMaps[gx][gy]->area_flag[(int)(lx)][(int)(ly)];
1090 // this used while not all *.map files generated (instances)
1091 else
1092 return GetAreaFlagByMapId(i_id);
1095 uint8 Map::GetTerrainType(float x, float y ) const
1097 //local x,y coords
1098 float lx,ly;
1099 int gx,gy;
1101 // half opt method
1102 gx=(int)(32-x/SIZE_OF_GRIDS) ; //grid x
1103 gy=(int)(32-y/SIZE_OF_GRIDS); //grid y
1105 lx=16*(32 -x/SIZE_OF_GRIDS - gx);
1106 ly=16*(32 -y/SIZE_OF_GRIDS - gy);
1108 // ensure GridMap is loaded
1109 const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
1111 if(GridMaps[gx][gy])
1112 return GridMaps[gx][gy]->terrain_type[(int)(lx)][(int)(ly)];
1113 else
1114 return 0;
1118 float Map::GetWaterLevel(float x, float y ) const
1120 //local x,y coords
1121 float lx,ly;
1122 int gx,gy;
1124 // half opt method
1125 gx=(int)(32-x/SIZE_OF_GRIDS) ; //grid x
1126 gy=(int)(32-y/SIZE_OF_GRIDS); //grid y
1128 lx=128*(32 -x/SIZE_OF_GRIDS - gx);
1129 ly=128*(32 -y/SIZE_OF_GRIDS - gy);
1131 // ensure GridMap is loaded
1132 const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
1134 if(GridMaps[gx][gy])
1135 return GridMaps[gx][gy]->liquid_level[(int)(lx)][(int)(ly)];
1136 else
1137 return 0;
1140 uint32 Map::GetAreaId(uint16 areaflag,uint32 map_id)
1142 AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
1144 if (entry)
1145 return entry->ID;
1146 else
1147 return 0;
1150 uint32 Map::GetZoneId(uint16 areaflag,uint32 map_id)
1152 AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
1154 if( entry )
1155 return ( entry->zone != 0 ) ? entry->zone : entry->ID;
1156 else
1157 return 0;
1160 bool Map::IsInWater(float x, float y, float pZ) const
1162 // This method is called too often to use vamps for that (4. parameter = false).
1163 // The pZ pos is taken anyway for future use
1164 float z = GetHeight(x,y,pZ,false); // use .map base surface height
1166 // underground or instance without vmap
1167 if(z <= INVALID_HEIGHT)
1168 return false;
1170 float water_z = GetWaterLevel(x,y);
1171 uint8 flag = GetTerrainType(x,y);
1172 return (z < (water_z-2)) && (flag & 0x01);
1175 bool Map::IsUnderWater(float x, float y, float z) const
1177 float water_z = GetWaterLevel(x,y);
1178 uint8 flag = GetTerrainType(x,y);
1179 return (z < (water_z-2)) && (flag & 0x01);
1182 bool Map::CheckGridIntegrity(Creature* c, bool moved) const
1184 Cell const& cur_cell = c->GetCurrentCell();
1186 CellPair xy_val = MaNGOS::ComputeCellPair(c->GetPositionX(), c->GetPositionY());
1187 Cell xy_cell(xy_val);
1188 if(xy_cell != cur_cell)
1190 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]",
1191 (c->GetTypeId()==TYPEID_PLAYER ? "Player" : "Creature"),c->GetGUIDLow(),
1192 c->GetPositionX(),c->GetPositionY(),(moved ? "final" : "original"),
1193 cur_cell.GridX(), cur_cell.GridY(), cur_cell.CellX(), cur_cell.CellY(),
1194 xy_cell.GridX(), xy_cell.GridY(), xy_cell.CellX(), xy_cell.CellY());
1195 return true; // not crash at error, just output error in debug mode
1198 return true;
1201 const char* Map::GetMapName() const
1203 return i_mapEntry ? i_mapEntry->name[sWorld.GetDefaultDbcLocale()] : "UNNAMEDMAP\x0";
1206 void Map::UpdateObjectVisibility( WorldObject* obj, Cell cell, CellPair cellpair)
1208 cell.data.Part.reserved = ALL_DISTRICT;
1209 cell.SetNoCreate();
1210 MaNGOS::VisibleChangesNotifier notifier(*obj);
1211 TypeContainerVisitor<MaNGOS::VisibleChangesNotifier, WorldTypeMapContainer > player_notifier(notifier);
1212 CellLock<GridReadGuard> cell_lock(cell, cellpair);
1213 cell_lock->Visit(cell_lock, player_notifier, *this);
1216 void Map::UpdatePlayerVisibility( Player* player, Cell cell, CellPair cellpair )
1218 cell.data.Part.reserved = ALL_DISTRICT;
1220 MaNGOS::PlayerNotifier pl_notifier(*player);
1221 TypeContainerVisitor<MaNGOS::PlayerNotifier, WorldTypeMapContainer > player_notifier(pl_notifier);
1223 CellLock<ReadGuard> cell_lock(cell, cellpair);
1224 cell_lock->Visit(cell_lock, player_notifier, *this);
1227 void Map::UpdateObjectsVisibilityFor( Player* player, Cell cell, CellPair cellpair )
1229 MaNGOS::VisibleNotifier notifier(*player);
1231 cell.data.Part.reserved = ALL_DISTRICT;
1232 cell.SetNoCreate();
1233 TypeContainerVisitor<MaNGOS::VisibleNotifier, WorldTypeMapContainer > world_notifier(notifier);
1234 TypeContainerVisitor<MaNGOS::VisibleNotifier, GridTypeMapContainer > grid_notifier(notifier);
1235 CellLock<GridReadGuard> cell_lock(cell, cellpair);
1236 cell_lock->Visit(cell_lock, world_notifier, *this);
1237 cell_lock->Visit(cell_lock, grid_notifier, *this);
1239 // send data
1240 notifier.Notify();
1243 void Map::PlayerRelocationNotify( Player* player, Cell cell, CellPair cellpair )
1245 CellLock<ReadGuard> cell_lock(cell, cellpair);
1246 MaNGOS::PlayerRelocationNotifier relocationNotifier(*player);
1247 cell.data.Part.reserved = ALL_DISTRICT;
1249 TypeContainerVisitor<MaNGOS::PlayerRelocationNotifier, GridTypeMapContainer > p2grid_relocation(relocationNotifier);
1250 TypeContainerVisitor<MaNGOS::PlayerRelocationNotifier, WorldTypeMapContainer > p2world_relocation(relocationNotifier);
1252 cell_lock->Visit(cell_lock, p2grid_relocation, *this);
1253 cell_lock->Visit(cell_lock, p2world_relocation, *this);
1256 void Map::CreatureRelocationNotify(Creature *creature, Cell cell, CellPair cellpair)
1258 CellLock<ReadGuard> cell_lock(cell, cellpair);
1259 MaNGOS::CreatureRelocationNotifier relocationNotifier(*creature);
1260 cell.data.Part.reserved = ALL_DISTRICT;
1261 cell.SetNoCreate(); // not trigger load unloaded grids at notifier call
1263 TypeContainerVisitor<MaNGOS::CreatureRelocationNotifier, WorldTypeMapContainer > c2world_relocation(relocationNotifier);
1264 TypeContainerVisitor<MaNGOS::CreatureRelocationNotifier, GridTypeMapContainer > c2grid_relocation(relocationNotifier);
1266 cell_lock->Visit(cell_lock, c2world_relocation, *this);
1267 cell_lock->Visit(cell_lock, c2grid_relocation, *this);
1270 void Map::SendInitSelf( Player * player )
1272 sLog.outDetail("Creating player data for himself %u", player->GetGUIDLow());
1274 UpdateData data;
1276 bool hasTransport = false;
1278 // attach to player data current transport data
1279 if(Transport* transport = player->GetTransport())
1281 hasTransport = true;
1282 transport->BuildCreateUpdateBlockForPlayer(&data, player);
1285 // build data for self presence in world at own client (one time for map)
1286 player->BuildCreateUpdateBlockForPlayer(&data, player);
1288 // build other passengers at transport also (they always visible and marked as visible and will not send at visibility update at add to map
1289 if(Transport* transport = player->GetTransport())
1291 for(Transport::PlayerSet::const_iterator itr = transport->GetPassengers().begin();itr!=transport->GetPassengers().end();++itr)
1293 if(player!=(*itr) && player->HaveAtClient(*itr))
1295 hasTransport = true;
1296 (*itr)->BuildCreateUpdateBlockForPlayer(&data, player);
1301 WorldPacket packet;
1302 data.BuildPacket(&packet, hasTransport);
1303 player->GetSession()->SendPacket(&packet);
1306 void Map::SendInitTransports( Player * player )
1308 // Hack to send out transports
1309 MapManager::TransportMap& tmap = MapManager::Instance().m_TransportsByMap;
1311 // no transports at map
1312 if (tmap.find(player->GetMapId()) == tmap.end())
1313 return;
1315 UpdateData transData;
1317 MapManager::TransportSet& tset = tmap[player->GetMapId()];
1319 bool hasTransport = false;
1321 for (MapManager::TransportSet::iterator i = tset.begin(); i != tset.end(); ++i)
1323 if((*i) != player->GetTransport()) // send data for current transport in other place
1325 hasTransport = true;
1326 (*i)->BuildCreateUpdateBlockForPlayer(&transData, player);
1330 WorldPacket packet;
1331 transData.BuildPacket(&packet, hasTransport);
1332 player->GetSession()->SendPacket(&packet);
1335 void Map::SendRemoveTransports( Player * player )
1337 // Hack to send out transports
1338 MapManager::TransportMap& tmap = MapManager::Instance().m_TransportsByMap;
1340 // no transports at map
1341 if (tmap.find(player->GetMapId()) == tmap.end())
1342 return;
1344 UpdateData transData;
1346 MapManager::TransportSet& tset = tmap[player->GetMapId()];
1348 // except used transport
1349 for (MapManager::TransportSet::iterator i = tset.begin(); i != tset.end(); ++i)
1350 if(player->GetTransport() != (*i))
1351 (*i)->BuildOutOfRangeUpdateBlock(&transData);
1353 WorldPacket packet;
1354 transData.BuildPacket(&packet);
1355 player->GetSession()->SendPacket(&packet);
1358 inline void Map::setNGrid(NGridType *grid, uint32 x, uint32 y)
1360 if(x >= MAX_NUMBER_OF_GRIDS || y >= MAX_NUMBER_OF_GRIDS)
1362 sLog.outError("map::setNGrid() Invalid grid coordinates found: %d, %d!",x,y);
1363 assert(false);
1365 i_grids[x][y] = grid;
1368 void Map::DoDelayedMovesAndRemoves()
1370 MoveAllCreaturesInMoveList();
1371 RemoveAllObjectsInRemoveList();
1374 void Map::AddObjectToRemoveList(WorldObject *obj)
1376 assert(obj->GetMapId()==GetId() && obj->GetInstanceId()==GetInstanceId());
1378 i_objectsToRemove.insert(obj);
1379 //sLog.outDebug("Object (GUID: %u TypeId: %u ) added to removing list.",obj->GetGUIDLow(),obj->GetTypeId());
1382 void Map::RemoveAllObjectsInRemoveList()
1384 if(i_objectsToRemove.empty())
1385 return;
1387 //sLog.outDebug("Object remover 1 check.");
1388 while(!i_objectsToRemove.empty())
1390 WorldObject* obj = *i_objectsToRemove.begin();
1391 i_objectsToRemove.erase(i_objectsToRemove.begin());
1393 switch(obj->GetTypeId())
1395 case TYPEID_CORPSE:
1397 Corpse* corpse = ObjectAccessor::Instance().GetCorpse(*obj, obj->GetGUID());
1398 if (!corpse)
1399 sLog.outError("ERROR: Try delete corpse/bones %u that not in map", obj->GetGUIDLow());
1400 else
1401 Remove(corpse,true);
1402 break;
1404 case TYPEID_DYNAMICOBJECT:
1405 Remove((DynamicObject*)obj,true);
1406 break;
1407 case TYPEID_GAMEOBJECT:
1408 Remove((GameObject*)obj,true);
1409 break;
1410 case TYPEID_UNIT:
1411 // in case triggered sequence some spell can continue casting after prev CleanupsBeforeDelete call
1412 // make sure that like sources auras/etc removed before destructor start
1413 ((Creature*)obj)->CleanupsBeforeDelete ();
1414 Remove((Creature*)obj,true);
1415 break;
1416 default:
1417 sLog.outError("Non-grid object (TypeId: %u) in grid object removing list, ignored.",obj->GetTypeId());
1418 break;
1421 //sLog.outDebug("Object remover 2 check.");
1424 bool Map::CanUnload(const uint32 &diff)
1426 if(!m_unloadTimer) return false;
1427 if(m_unloadTimer < diff) return true;
1428 m_unloadTimer -= diff;
1429 return false;
1432 uint32 Map::GetPlayersCountExceptGMs() const
1434 uint32 count = 0;
1435 for(MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
1436 if(!itr->getSource()->isGameMaster())
1437 ++count;
1438 return count;
1441 void Map::SendToPlayers(WorldPacket const* data) const
1443 for(MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
1444 itr->getSource()->GetSession()->SendPacket(data);
1447 bool Map::PlayersNearGrid(uint32 x, uint32 y) const
1449 CellPair cell_min(x*MAX_NUMBER_OF_CELLS, y*MAX_NUMBER_OF_CELLS);
1450 CellPair cell_max(cell_min.x_coord + MAX_NUMBER_OF_CELLS, cell_min.y_coord+MAX_NUMBER_OF_CELLS);
1451 cell_min << 2;
1452 cell_min -= 2;
1453 cell_max >> 2;
1454 cell_max += 2;
1456 for(MapRefManager::const_iterator iter = m_mapRefManager.begin(); iter != m_mapRefManager.end(); ++iter)
1458 Player* plr = iter->getSource();
1460 CellPair p = MaNGOS::ComputeCellPair(plr->GetPositionX(), plr->GetPositionY());
1461 if( (cell_min.x_coord <= p.x_coord && p.x_coord <= cell_max.x_coord) &&
1462 (cell_min.y_coord <= p.y_coord && p.y_coord <= cell_max.y_coord) )
1463 return true;
1466 return false;
1469 template void Map::Add(Corpse *);
1470 template void Map::Add(Creature *);
1471 template void Map::Add(GameObject *);
1472 template void Map::Add(DynamicObject *);
1474 template void Map::Remove(Corpse *,bool);
1475 template void Map::Remove(Creature *,bool);
1476 template void Map::Remove(GameObject *, bool);
1477 template void Map::Remove(DynamicObject *, bool);
1479 /* ******* Dungeon Instance Maps ******* */
1481 InstanceMap::InstanceMap(uint32 id, time_t expiry, uint32 InstanceId, uint8 SpawnMode)
1482 : Map(id, expiry, InstanceId, SpawnMode), i_data(NULL),
1483 m_resetAfterUnload(false), m_unloadWhenEmpty(false)
1485 // the timer is started by default, and stopped when the first player joins
1486 // this make sure it gets unloaded if for some reason no player joins
1487 m_unloadTimer = std::max(sWorld.getConfig(CONFIG_INSTANCE_UNLOAD_DELAY), (uint32)MIN_UNLOAD_DELAY);
1490 InstanceMap::~InstanceMap()
1492 if(i_data)
1494 delete i_data;
1495 i_data = NULL;
1500 Do map specific checks to see if the player can enter
1502 bool InstanceMap::CanEnter(Player *player)
1504 if(player->GetMapRef().getTarget() == this)
1506 sLog.outError("InstanceMap::CanEnter - player %s(%u) already in map %d,%d,%d!", player->GetName(), player->GetGUIDLow(), GetId(), GetInstanceId(), GetSpawnMode());
1507 assert(false);
1508 return false;
1511 // cannot enter if the instance is full (player cap), GMs don't count
1512 InstanceTemplate const* iTemplate = objmgr.GetInstanceTemplate(GetId());
1513 if (!player->isGameMaster() && GetPlayersCountExceptGMs() >= iTemplate->maxPlayers)
1515 sLog.outDetail("MAP: Instance '%u' of map '%s' cannot have more than '%u' players. Player '%s' rejected", GetInstanceId(), GetMapName(), iTemplate->maxPlayers, player->GetName());
1516 player->SendTransferAborted(GetId(), TRANSFER_ABORT_MAX_PLAYERS);
1517 return false;
1520 // cannot enter while players in the instance are in combat
1521 Group *pGroup = player->GetGroup();
1522 if(pGroup && pGroup->InCombatToInstance(GetInstanceId()) && player->isAlive() && player->GetMapId() != GetId())
1524 player->SendTransferAborted(GetId(), TRANSFER_ABORT_ZONE_IN_COMBAT);
1525 return false;
1528 return Map::CanEnter(player);
1532 Do map specific checks and add the player to the map if successful.
1534 bool InstanceMap::Add(Player *player)
1536 // TODO: Not sure about checking player level: already done in HandleAreaTriggerOpcode
1537 // GMs still can teleport player in instance.
1538 // Is it needed?
1541 Guard guard(*this);
1542 if(!CanEnter(player))
1543 return false;
1545 // get or create an instance save for the map
1546 InstanceSave *mapSave = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1547 if(!mapSave)
1549 sLog.outDetail("InstanceMap::Add: creating instance save for map %d spawnmode %d with instance id %d", GetId(), GetSpawnMode(), GetInstanceId());
1550 mapSave = sInstanceSaveManager.AddInstanceSave(GetId(), GetInstanceId(), GetSpawnMode(), 0, true);
1553 // check for existing instance binds
1554 InstancePlayerBind *playerBind = player->GetBoundInstance(GetId(), GetSpawnMode());
1555 if(playerBind && playerBind->perm)
1557 // cannot enter other instances if bound permanently
1558 if(playerBind->save != mapSave)
1560 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());
1561 assert(false);
1564 else
1566 Group *pGroup = player->GetGroup();
1567 if(pGroup)
1569 // solo saves should be reset when entering a group
1570 InstanceGroupBind *groupBind = pGroup->GetBoundInstance(GetId(), GetSpawnMode());
1571 if(playerBind)
1573 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());
1574 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());
1575 assert(false);
1577 // bind to the group or keep using the group save
1578 if(!groupBind)
1579 pGroup->BindToInstance(mapSave, false);
1580 else
1582 // cannot jump to a different instance without resetting it
1583 if(groupBind->save != mapSave)
1585 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());
1586 if(mapSave)
1587 sLog.outError("MapSave players: %d, group count: %d", mapSave->GetPlayerCount(), mapSave->GetGroupCount());
1588 else
1589 sLog.outError("MapSave NULL");
1590 if(groupBind->save)
1591 sLog.outError("GroupBind save players: %d, group count: %d", groupBind->save->GetPlayerCount(), groupBind->save->GetGroupCount());
1592 else
1593 sLog.outError("GroupBind save NULL");
1594 assert(false);
1596 // if the group/leader is permanently bound to the instance
1597 // players also become permanently bound when they enter
1598 if(groupBind->perm)
1600 WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
1601 data << uint32(0);
1602 player->GetSession()->SendPacket(&data);
1603 player->BindToInstance(mapSave, true);
1607 else
1609 // set up a solo bind or continue using it
1610 if(!playerBind)
1611 player->BindToInstance(mapSave, false);
1612 else
1613 // cannot jump to a different instance without resetting it
1614 assert(playerBind->save == mapSave);
1618 if(i_data) i_data->OnPlayerEnter(player);
1619 SetResetSchedule(false);
1621 player->SendInitWorldStates();
1622 sLog.outDetail("MAP: Player '%s' entered the instance '%u' of map '%s'", player->GetName(), GetInstanceId(), GetMapName());
1623 // initialize unload state
1624 m_unloadTimer = 0;
1625 m_resetAfterUnload = false;
1626 m_unloadWhenEmpty = false;
1629 // this will acquire the same mutex so it cannot be in the previous block
1630 Map::Add(player);
1631 return true;
1634 void InstanceMap::Update(const uint32& t_diff)
1636 Map::Update(t_diff);
1638 if(i_data)
1639 i_data->Update(t_diff);
1642 void InstanceMap::Remove(Player *player, bool remove)
1644 sLog.outDetail("MAP: Removing player '%s' from instance '%u' of map '%s' before relocating to other map", player->GetName(), GetInstanceId(), GetMapName());
1645 SetResetSchedule(true);
1646 //if last player set unload timer
1647 if(!m_unloadTimer && m_mapRefManager.getSize() == 1)
1648 m_unloadTimer = m_unloadWhenEmpty ? MIN_UNLOAD_DELAY : std::max(sWorld.getConfig(CONFIG_INSTANCE_UNLOAD_DELAY), (uint32)MIN_UNLOAD_DELAY);
1649 Map::Remove(player, remove);
1652 void InstanceMap::CreateInstanceData(bool load)
1654 if(i_data != NULL)
1655 return;
1657 InstanceTemplate const* mInstance = objmgr.GetInstanceTemplate(GetId());
1658 if (mInstance)
1660 i_script_id = mInstance->script_id;
1661 i_data = Script->CreateInstanceData(this);
1664 if(!i_data)
1665 return;
1667 if(load)
1669 // TODO: make a global storage for this
1670 QueryResult* result = CharacterDatabase.PQuery("SELECT data FROM instance WHERE map = '%u' AND id = '%u'", GetId(), i_InstanceId);
1671 if (result)
1673 Field* fields = result->Fetch();
1674 const char* data = fields[0].GetString();
1675 if(data)
1677 sLog.outDebug("Loading instance data for `%s` with id %u", objmgr.GetScriptName(i_script_id), i_InstanceId);
1678 i_data->Load(data);
1680 delete result;
1683 else
1685 sLog.outDebug("New instance data, \"%s\" ,initialized!", objmgr.GetScriptName(i_script_id));
1686 i_data->Initialize();
1691 Returns true if there are no players in the instance
1693 bool InstanceMap::Reset(uint8 method)
1695 // note: since the map may not be loaded when the instance needs to be reset
1696 // the instance must be deleted from the DB by InstanceSaveManager
1698 if(HavePlayers())
1700 if(method == INSTANCE_RESET_ALL)
1702 // notify the players to leave the instance so it can be reset
1703 for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
1704 itr->getSource()->SendResetFailedNotify(GetId());
1706 else
1708 if(method == INSTANCE_RESET_GLOBAL)
1710 // set the homebind timer for players inside (1 minute)
1711 for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
1712 itr->getSource()->m_InstanceValid = false;
1715 // the unload timer is not started
1716 // instead the map will unload immediately after the players have left
1717 m_unloadWhenEmpty = true;
1718 m_resetAfterUnload = true;
1721 else
1723 // unloaded at next update
1724 m_unloadTimer = MIN_UNLOAD_DELAY;
1725 m_resetAfterUnload = true;
1728 return m_mapRefManager.isEmpty();
1731 void InstanceMap::PermBindAllPlayers(Player *player)
1733 InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1734 if(!save)
1736 sLog.outError("Cannot bind players, no instance save available for map!\n");
1737 return;
1740 Group *group = player->GetGroup();
1741 // group members outside the instance group don't get bound
1742 for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
1744 Player* plr = itr->getSource();
1745 // players inside an instance cannot be bound to other instances
1746 // some players may already be permanently bound, in this case nothing happens
1747 InstancePlayerBind *bind = plr->GetBoundInstance(save->GetMapId(), save->GetDifficulty());
1748 if(!bind || !bind->perm)
1750 plr->BindToInstance(save, true);
1751 WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
1752 data << uint32(0);
1753 plr->GetSession()->SendPacket(&data);
1756 // if the leader is not in the instance the group will not get a perm bind
1757 if(group && group->GetLeaderGUID() == plr->GetGUID())
1758 group->BindToInstance(save, true);
1762 time_t InstanceMap::GetResetTime()
1764 InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1765 return save ? save->GetDifficulty() : DIFFICULTY_NORMAL;
1768 void InstanceMap::UnloadAll(bool pForce)
1770 if(HavePlayers())
1772 sLog.outError("InstanceMap::UnloadAll: there are still players in the instance at unload, should not happen!");
1773 for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
1775 Player* plr = itr->getSource();
1776 plr->TeleportTo(plr->m_homebindMapId, plr->m_homebindX, plr->m_homebindY, plr->m_homebindZ, plr->GetOrientation());
1780 if(m_resetAfterUnload == true)
1781 objmgr.DeleteRespawnTimeForInstance(GetInstanceId());
1783 Map::UnloadAll(pForce);
1786 void InstanceMap::SendResetWarnings(uint32 timeLeft) const
1788 for(MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
1789 itr->getSource()->SendInstanceResetWarning(GetId(), timeLeft);
1792 void InstanceMap::SetResetSchedule(bool on)
1794 // only for normal instances
1795 // the reset time is only scheduled when there are no payers inside
1796 // it is assumed that the reset time will rarely (if ever) change while the reset is scheduled
1797 if(!HavePlayers() && !IsRaid() && !IsHeroic())
1799 InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1800 if(!save) sLog.outError("InstanceMap::SetResetSchedule: cannot turn schedule %s, no save available for instance %d of %d", on ? "on" : "off", GetInstanceId(), GetId());
1801 else sInstanceSaveManager.ScheduleReset(on, save->GetResetTime(), InstanceSaveManager::InstResetEvent(0, GetId(), GetInstanceId()));
1805 /* ******* Battleground Instance Maps ******* */
1807 BattleGroundMap::BattleGroundMap(uint32 id, time_t expiry, uint32 InstanceId)
1808 : Map(id, expiry, InstanceId, DIFFICULTY_NORMAL)
1812 BattleGroundMap::~BattleGroundMap()
1816 bool BattleGroundMap::CanEnter(Player * player)
1818 if(player->GetMapRef().getTarget() == this)
1820 sLog.outError("BGMap::CanEnter - player %u already in map!", player->GetGUIDLow());
1821 assert(false);
1822 return false;
1825 if(player->GetBattleGroundId() != GetInstanceId())
1826 return false;
1828 // player number limit is checked in bgmgr, no need to do it here
1830 return Map::CanEnter(player);
1833 bool BattleGroundMap::Add(Player * player)
1836 Guard guard(*this);
1837 if(!CanEnter(player))
1838 return false;
1839 // reset instance validity, battleground maps do not homebind
1840 player->m_InstanceValid = true;
1842 return Map::Add(player);
1845 void BattleGroundMap::Remove(Player *player, bool remove)
1847 sLog.outDetail("MAP: Removing player '%s' from bg '%u' of map '%s' before relocating to other map", player->GetName(), GetInstanceId(), GetMapName());
1848 Map::Remove(player, remove);
1851 void BattleGroundMap::SetUnload()
1853 m_unloadTimer = MIN_UNLOAD_DELAY;
1856 void BattleGroundMap::UnloadAll(bool pForce)
1858 while(HavePlayers())
1860 Player * plr = m_mapRefManager.getFirst()->getSource();
1861 if(plr) (plr)->TeleportTo(plr->m_homebindMapId, plr->m_homebindX, plr->m_homebindY, plr->m_homebindZ, plr->GetOrientation());
1862 // TeleportTo removes the player from this map (if the map exists) -> calls BattleGroundMap::Remove -> invalidates the iterator.
1863 // just in case, remove the player from the list explicitly here as well to prevent a possible infinite loop
1864 // note that this remove is not needed if the code works well in other places
1865 plr->GetMapRef().unlink();
1868 Map::UnloadAll(pForce);