Move object update from ObjectAccessor to Map update.
[getmangos.git] / src / game / Map.cpp
blob601a69e86951de6a4edf65901bc640828ec27218
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"
37 #include "MapInstanced.h"
38 #include "InstanceSaveMgr.h"
39 #include "VMapFactory.h"
41 #define DEFAULT_GRID_EXPIRY 300
42 #define MAX_GRID_LOAD_TIME 50
44 // magic *.map header
45 const char MAP_MAGIC[] = "MAP_2.00";
47 GridState* si_GridStates[MAX_GRID_STATE];
49 Map::~Map()
51 UnloadAll(true);
54 bool Map::ExistMap(uint32 mapid,int x,int y)
56 int len = sWorld.GetDataPath().length()+strlen("maps/%03u%02u%02u.map")+1;
57 char* tmp = new char[len];
58 snprintf(tmp, len, (char *)(sWorld.GetDataPath()+"maps/%03u%02u%02u.map").c_str(),mapid,x,y);
60 FILE *pf=fopen(tmp,"rb");
62 if(!pf)
64 sLog.outError("Check existing of map file '%s': not exist!",tmp);
65 delete[] tmp;
66 return false;
69 char magic[8];
70 fread(magic,1,8,pf);
71 if(strncmp(MAP_MAGIC,magic,8))
73 sLog.outError("Map file '%s' is non-compatible version (outdated?). Please, create new using ad.exe program.",tmp);
74 delete [] tmp;
75 fclose(pf); //close file before return
76 return false;
79 delete [] tmp;
80 fclose(pf);
82 return true;
85 bool Map::ExistVMap(uint32 mapid,int x,int y)
87 if(VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager())
89 if(vmgr->isMapLoadingEnabled())
91 // x and y are swapped !! => fixed now
92 bool exists = vmgr->existsMap((sWorld.GetDataPath()+ "vmaps").c_str(), mapid, x,y);
93 if(!exists)
95 std::string name = vmgr->getDirFileName(mapid,x,y);
96 sLog.outError("VMap file '%s' is missing or point to wrong version vmap file, redo vmaps with latest vmap_assembler.exe program", (sWorld.GetDataPath()+"vmaps/"+name).c_str());
97 return false;
102 return true;
105 void Map::LoadVMap(int x,int y)
107 // x and y are swapped !!
108 int vmapLoadResult = VMAP::VMapFactory::createOrGetVMapManager()->loadMap((sWorld.GetDataPath()+ "vmaps").c_str(), GetId(), x,y);
109 switch(vmapLoadResult)
111 case VMAP::VMAP_LOAD_RESULT_OK:
112 sLog.outDetail("VMAP loaded name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", GetMapName(), GetId(), x,y, x,y);
113 break;
114 case VMAP::VMAP_LOAD_RESULT_ERROR:
115 sLog.outDetail("Could not load VMAP name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", GetMapName(), GetId(), x,y, x,y);
116 break;
117 case VMAP::VMAP_LOAD_RESULT_IGNORED:
118 DEBUG_LOG("Ignored VMAP name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", GetMapName(), GetId(), x,y, x,y);
119 break;
123 void Map::LoadMap(uint32 mapid, uint32 instanceid, int x,int y)
125 if( instanceid != 0 )
127 if(GridMaps[x][y])
128 return;
130 Map* baseMap = const_cast<Map*>(MapManager::Instance().GetBaseMap(mapid));
132 // load gridmap for base map
133 if (!baseMap->GridMaps[x][y])
134 baseMap->EnsureGridCreated(GridPair(63-x,63-y));
136 //+++ if (!baseMap->GridMaps[x][y]) don't check for GridMaps[gx][gy], we need the management for vmaps
137 // return;
139 ((MapInstanced*)(baseMap))->AddGridMapReference(GridPair(x,y));
140 baseMap->SetUnloadFlag(GridPair(63-x,63-y), false);
141 GridMaps[x][y] = baseMap->GridMaps[x][y];
142 return;
145 //map already load, delete it before reloading (Is it necessary? Do we really need the ability the reload maps during runtime?)
146 if(GridMaps[x][y])
148 sLog.outDetail("Unloading already loaded map %u before reloading.",mapid);
149 delete (GridMaps[x][y]);
150 GridMaps[x][y]=NULL;
153 // map file name
154 char *tmp=NULL;
155 // Pihhan: dataPath length + "maps/" + 3+2+2+ ".map" length may be > 32 !
156 int len = sWorld.GetDataPath().length()+strlen("maps/%03u%02u%02u.map")+1;
157 tmp = new char[len];
158 snprintf(tmp, len, (char *)(sWorld.GetDataPath()+"maps/%03u%02u%02u.map").c_str(),mapid,x,y);
159 sLog.outDetail("Loading map %s",tmp);
160 // loading data
161 FILE *pf=fopen(tmp,"rb");
162 if(!pf)
164 delete [] tmp;
165 return;
168 char magic[8];
169 fread(magic,1,8,pf);
170 if(strncmp(MAP_MAGIC,magic,8))
172 sLog.outError("Map file '%s' is non-compatible version (outdated?). Please, create new using ad.exe program.",tmp);
173 delete [] tmp;
174 fclose(pf); //close file before return
175 return;
177 delete [] tmp;
179 GridMap * buf= new GridMap;
180 fread(buf,1,sizeof(GridMap),pf);
181 fclose(pf);
183 GridMaps[x][y] = buf;
186 void Map::LoadMapAndVMap(uint32 mapid, uint32 instanceid, int x,int y)
188 LoadMap(mapid,instanceid,x,y);
189 if(instanceid == 0)
190 LoadVMap(x, y); // Only load the data for the base map
193 void Map::InitStateMachine()
195 si_GridStates[GRID_STATE_INVALID] = new InvalidState;
196 si_GridStates[GRID_STATE_ACTIVE] = new ActiveState;
197 si_GridStates[GRID_STATE_IDLE] = new IdleState;
198 si_GridStates[GRID_STATE_REMOVAL] = new RemovalState;
201 void Map::DeleteStateMachine()
203 delete si_GridStates[GRID_STATE_INVALID];
204 delete si_GridStates[GRID_STATE_ACTIVE];
205 delete si_GridStates[GRID_STATE_IDLE];
206 delete si_GridStates[GRID_STATE_REMOVAL];
209 Map::Map(uint32 id, time_t expiry, uint32 InstanceId, uint8 SpawnMode)
210 : i_id(id), i_gridExpiry(expiry), i_mapEntry (sMapStore.LookupEntry(id)),
211 i_InstanceId(InstanceId), i_spawnMode(SpawnMode), m_unloadTimer(0)
213 for(unsigned int idx=0; idx < MAX_NUMBER_OF_GRIDS; ++idx)
215 for(unsigned int j=0; j < MAX_NUMBER_OF_GRIDS; ++j)
217 //z code
218 GridMaps[idx][j] =NULL;
219 setNGrid(NULL, idx, j);
224 // Template specialization of utility methods
225 template<class T>
226 void Map::AddToGrid(T* obj, NGridType *grid, Cell const& cell)
228 (*grid)(cell.CellX(), cell.CellY()).template AddGridObject<T>(obj, obj->GetGUID());
231 template<>
232 void Map::AddToGrid(Player* obj, NGridType *grid, Cell const& cell)
234 (*grid)(cell.CellX(), cell.CellY()).AddWorldObject(obj, obj->GetGUID());
237 template<>
238 void Map::AddToGrid(Corpse *obj, NGridType *grid, Cell const& cell)
240 // add to world object registry in grid
241 if(obj->GetType()!=CORPSE_BONES)
243 (*grid)(cell.CellX(), cell.CellY()).AddWorldObject(obj, obj->GetGUID());
245 // add to grid object store
246 else
248 (*grid)(cell.CellX(), cell.CellY()).AddGridObject(obj, obj->GetGUID());
252 template<>
253 void Map::AddToGrid(Creature* obj, NGridType *grid, Cell const& cell)
255 // add to world object registry in grid
256 if(obj->isPet())
258 (*grid)(cell.CellX(), cell.CellY()).AddWorldObject<Creature>(obj, obj->GetGUID());
259 obj->SetCurrentCell(cell);
261 // add to grid object store
262 else
264 (*grid)(cell.CellX(), cell.CellY()).AddGridObject<Creature>(obj, obj->GetGUID());
265 obj->SetCurrentCell(cell);
269 template<class T>
270 void Map::RemoveFromGrid(T* obj, NGridType *grid, Cell const& cell)
272 (*grid)(cell.CellX(), cell.CellY()).template RemoveGridObject<T>(obj, obj->GetGUID());
275 template<>
276 void Map::RemoveFromGrid(Player* obj, NGridType *grid, Cell const& cell)
278 (*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject(obj, obj->GetGUID());
281 template<>
282 void Map::RemoveFromGrid(Corpse *obj, NGridType *grid, Cell const& cell)
284 // remove from world object registry in grid
285 if(obj->GetType()!=CORPSE_BONES)
287 (*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject(obj, obj->GetGUID());
289 // remove from grid object store
290 else
292 (*grid)(cell.CellX(), cell.CellY()).RemoveGridObject(obj, obj->GetGUID());
296 template<>
297 void Map::RemoveFromGrid(Creature* obj, NGridType *grid, Cell const& cell)
299 // remove from world object registry in grid
300 if(obj->isPet())
302 (*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject<Creature>(obj, obj->GetGUID());
304 // remove from grid object store
305 else
307 (*grid)(cell.CellX(), cell.CellY()).RemoveGridObject<Creature>(obj, obj->GetGUID());
311 template<class T>
312 void Map::DeleteFromWorld(T* obj)
314 // Note: In case resurrectable corpse and pet its removed from global lists in own destructor
315 delete obj;
318 template<class T>
319 void Map::AddNotifier(T* , Cell const& , CellPair const& )
323 template<>
324 void Map::AddNotifier(Player* obj, Cell const& cell, CellPair const& cellpair)
326 PlayerRelocationNotify(obj,cell,cellpair);
329 template<>
330 void Map::AddNotifier(Creature* obj, Cell const& cell, CellPair const& cellpair)
332 CreatureRelocationNotify(obj,cell,cellpair);
335 void
336 Map::EnsureGridCreated(const GridPair &p)
338 if(!getNGrid(p.x_coord, p.y_coord))
340 Guard guard(*this);
341 if(!getNGrid(p.x_coord, p.y_coord))
343 setNGrid(new NGridType(p.x_coord*MAX_NUMBER_OF_GRIDS + p.y_coord, p.x_coord, p.y_coord, i_gridExpiry, sWorld.getConfig(CONFIG_GRID_UNLOAD)),
344 p.x_coord, p.y_coord);
346 // build a linkage between this map and NGridType
347 buildNGridLinkage(getNGrid(p.x_coord, p.y_coord));
349 getNGrid(p.x_coord, p.y_coord)->SetGridState(GRID_STATE_IDLE);
351 //z coord
352 int gx=63-p.x_coord;
353 int gy=63-p.y_coord;
355 if(!GridMaps[gx][gy])
356 Map::LoadMapAndVMap(i_id,i_InstanceId,gx,gy);
361 void
362 Map::EnsureGridLoadedForPlayer(const Cell &cell, Player *player, bool add_player)
364 EnsureGridCreated(GridPair(cell.GridX(), cell.GridY()));
365 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
367 assert(grid != NULL);
368 if( !isGridObjectDataLoaded(cell.GridX(), cell.GridY()) )
370 if( player != NULL )
372 player->SendDelayResponse(MAX_GRID_LOAD_TIME);
373 DEBUG_LOG("Player %s enter cell[%u,%u] triggers of loading grid[%u,%u] on map %u", player->GetName(), cell.CellX(), cell.CellY(), cell.GridX(), cell.GridY(), i_id);
375 else
377 DEBUG_LOG("Player nearby triggers of loading grid [%u,%u] on map %u", cell.GridX(), cell.GridY(), i_id);
380 ObjectGridLoader loader(*grid, this, cell);
381 loader.LoadN();
382 setGridObjectDataLoaded(true, cell.GridX(), cell.GridY());
384 // Add resurrectable corpses to world object list in grid
385 ObjectAccessor::Instance().AddCorpsesToGrid(GridPair(cell.GridX(),cell.GridY()),(*grid)(cell.CellX(), cell.CellY()), this);
387 ResetGridExpiry(*getNGrid(cell.GridX(), cell.GridY()), 0.1f);
388 grid->SetGridState(GRID_STATE_ACTIVE);
390 if( add_player && player != NULL )
391 (*grid)(cell.CellX(), cell.CellY()).AddWorldObject(player, player->GetGUID());
393 else if( player && add_player )
394 AddToGrid(player,grid,cell);
397 void
398 Map::LoadGrid(const Cell& cell, bool no_unload)
400 EnsureGridCreated(GridPair(cell.GridX(), cell.GridY()));
401 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
403 assert(grid != NULL);
404 if( !isGridObjectDataLoaded(cell.GridX(), cell.GridY()) )
406 ObjectGridLoader loader(*grid, this, cell);
407 loader.LoadN();
409 // Add resurrectable corpses to world object list in grid
410 ObjectAccessor::Instance().AddCorpsesToGrid(GridPair(cell.GridX(),cell.GridY()),(*grid)(cell.CellX(), cell.CellY()), this);
412 setGridObjectDataLoaded(true,cell.GridX(), cell.GridY());
413 if(no_unload)
414 getNGrid(cell.GridX(), cell.GridY())->setUnloadFlag(false);
416 LoadVMap(63-cell.GridX(),63-cell.GridY());
419 bool Map::Add(Player *player)
421 player->SetInstanceId(GetInstanceId());
423 // update player state for other player and visa-versa
424 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
425 Cell cell(p);
426 EnsureGridLoadedForPlayer(cell, player, true);
427 player->AddToWorld();
429 SendInitSelf(player);
430 SendInitTransports(player);
432 UpdatePlayerVisibility(player,cell,p);
433 UpdateObjectsVisibilityFor(player,cell,p);
435 AddNotifier(player,cell,p);
436 return true;
439 template<class T>
440 void
441 Map::Add(T *obj)
443 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
445 assert(obj);
447 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
449 sLog.outError("Map::Add: Object " I64FMTD " have invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUID(), obj->GetPositionX(), obj->GetPositionY(), p.x_coord, p.y_coord);
450 return;
453 Cell cell(p);
454 EnsureGridCreated(GridPair(cell.GridX(), cell.GridY()));
455 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
456 assert( grid != NULL );
458 AddToGrid(obj,grid,cell);
459 obj->AddToWorld();
461 DEBUG_LOG("Object %u enters grid[%u,%u]", GUID_LOPART(obj->GetGUID()), cell.GridX(), cell.GridY());
463 UpdateObjectVisibility(obj,cell,p);
465 AddNotifier(obj,cell,p);
468 void Map::MessageBroadcast(Player *player, WorldPacket *msg, bool to_self)
470 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
472 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
474 sLog.outError("Map::MessageBroadcast: Player (GUID: %u) have invalid coordinates X:%f Y:%f grid cell [%u:%u]", player->GetGUIDLow(), player->GetPositionX(), player->GetPositionY(), p.x_coord, p.y_coord);
475 return;
478 Cell cell(p);
479 cell.data.Part.reserved = ALL_DISTRICT;
481 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
482 return;
484 MaNGOS::MessageDeliverer post_man(*player, msg, to_self);
485 TypeContainerVisitor<MaNGOS::MessageDeliverer, WorldTypeMapContainer > message(post_man);
486 CellLock<ReadGuard> cell_lock(cell, p);
487 cell_lock->Visit(cell_lock, message, *this);
490 void Map::MessageBroadcast(WorldObject *obj, WorldPacket *msg)
492 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
494 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
496 sLog.outError("Map::MessageBroadcast: Object " I64FMTD " have invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUID(), obj->GetPositionX(), obj->GetPositionY(), p.x_coord, p.y_coord);
497 return;
500 Cell cell(p);
501 cell.data.Part.reserved = ALL_DISTRICT;
502 cell.SetNoCreate();
504 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
505 return;
507 MaNGOS::ObjectMessageDeliverer post_man(msg);
508 TypeContainerVisitor<MaNGOS::ObjectMessageDeliverer, WorldTypeMapContainer > message(post_man);
509 CellLock<ReadGuard> cell_lock(cell, p);
510 cell_lock->Visit(cell_lock, message, *this);
513 void Map::MessageDistBroadcast(Player *player, WorldPacket *msg, float dist, bool to_self, bool own_team_only)
515 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
517 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
519 sLog.outError("Map::MessageBroadcast: Player (GUID: %u) have invalid coordinates X:%f Y:%f grid cell [%u:%u]", player->GetGUIDLow(), player->GetPositionX(), player->GetPositionY(), p.x_coord, p.y_coord);
520 return;
523 Cell cell(p);
524 cell.data.Part.reserved = ALL_DISTRICT;
526 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
527 return;
529 MaNGOS::MessageDistDeliverer post_man(*player, msg, dist, to_self, own_team_only);
530 TypeContainerVisitor<MaNGOS::MessageDistDeliverer , WorldTypeMapContainer > message(post_man);
531 CellLock<ReadGuard> cell_lock(cell, p);
532 cell_lock->Visit(cell_lock, message, *this);
535 void Map::MessageDistBroadcast(WorldObject *obj, WorldPacket *msg, float dist)
537 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
539 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
541 sLog.outError("Map::MessageBroadcast: Object " I64FMTD " have invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUID(), obj->GetPositionX(), obj->GetPositionY(), p.x_coord, p.y_coord);
542 return;
545 Cell cell(p);
546 cell.data.Part.reserved = ALL_DISTRICT;
547 cell.SetNoCreate();
549 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
550 return;
552 MaNGOS::ObjectMessageDistDeliverer post_man(*obj, msg,dist);
553 TypeContainerVisitor<MaNGOS::ObjectMessageDistDeliverer, WorldTypeMapContainer > message(post_man);
554 CellLock<ReadGuard> cell_lock(cell, p);
555 cell_lock->Visit(cell_lock, message, *this);
558 bool Map::loaded(const GridPair &p) const
560 return ( getNGrid(p.x_coord, p.y_coord) && isGridObjectDataLoaded(p.x_coord, p.y_coord) );
563 void Map::Update(const uint32 &t_diff)
565 resetMarkedCells();
567 //TODO: Player guard
568 HashMapHolder<Player>::MapType& playerMap = HashMapHolder<Player>::GetContainer();
569 for(HashMapHolder<Player>::MapType::iterator iter = playerMap.begin(); iter != playerMap.end(); ++iter)
571 WorldObject* obj = iter->second;
573 if(!obj->IsInWorld())
574 continue;
576 if(obj->GetMapId() != GetId())
577 continue;
579 if(obj->GetInstanceId() != GetInstanceId())
580 continue;
582 CellPair standing_cell(MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->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)
595 for(uint32 y = begin_cell.y_coord; y <= end_cell.y_coord; ++y)
596 markCell(x,y);
599 MaNGOS::ObjectUpdater updater(t_diff);
600 // for creature
601 TypeContainerVisitor<MaNGOS::ObjectUpdater, GridTypeMapContainer > grid_object_update(updater);
602 // for pets
603 TypeContainerVisitor<MaNGOS::ObjectUpdater, WorldTypeMapContainer > world_object_update(updater);
605 for(int x = 0; x < TOTAL_NUMBER_OF_CELLS_PER_MAP; ++x)
607 for(int y = 0; y < TOTAL_NUMBER_OF_CELLS_PER_MAP; ++y)
609 if(isCellMarked(x,y))
611 CellPair pair(x,y);
612 Cell cell(pair);
613 cell.data.Part.reserved = CENTER_DISTRICT;
614 cell.SetNoCreate();
615 CellLock<NullGuard> cell_lock(cell, pair);
616 cell_lock->Visit(cell_lock, grid_object_update, *this);
617 cell_lock->Visit(cell_lock, world_object_update, *this);
622 // 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 !
623 // This isn't really bother us, since as soon as we have instanced BG-s, the whole map unloads as the BG gets ended
624 if (IsBattleGroundOrArena())
625 return;
627 for (GridRefManager<NGridType>::iterator i = GridRefManager<NGridType>::begin(); i != GridRefManager<NGridType>::end(); )
629 NGridType *grid = i->getSource();
630 GridInfo *info = i->getSource()->getGridInfoRef();
631 ++i; // The update might delete the map and we need the next map before the iterator gets invalid
632 assert(grid->GetGridState() >= 0 && grid->GetGridState() < MAX_GRID_STATE);
633 si_GridStates[grid->GetGridState()]->Update(*this, *grid, *info, grid->getX(), grid->getY(), t_diff);
637 void Map::Remove(Player *player, bool remove)
639 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
640 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
642 // invalid coordinates
643 player->RemoveFromWorld();
645 if( remove )
646 DeleteFromWorld(player);
648 return;
651 Cell cell(p);
653 if( !getNGrid(cell.data.Part.grid_x, cell.data.Part.grid_y) )
655 sLog.outError("Map::Remove() i_grids was NULL x:%d, y:%d",cell.data.Part.grid_x,cell.data.Part.grid_y);
656 return;
659 DEBUG_LOG("Remove player %s from grid[%u,%u]", player->GetName(), cell.GridX(), cell.GridY());
660 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
661 assert(grid != NULL);
663 player->RemoveFromWorld();
664 RemoveFromGrid(player,grid,cell);
666 SendRemoveTransports(player);
668 UpdateObjectsVisibilityFor(player,cell,p);
670 if( remove )
671 DeleteFromWorld(player);
674 bool Map::RemoveBones(uint64 guid, float x, float y)
676 if (IsRemovalGrid(x, y))
678 Corpse * corpse = ObjectAccessor::Instance().GetObjectInWorld(GetId(), x, y, guid, (Corpse*)NULL);
679 if(corpse && corpse->GetTypeId() == TYPEID_CORPSE && corpse->GetType() == CORPSE_BONES)
680 corpse->DeleteBonesFromWorld();
681 else
682 return false;
684 return true;
687 template<class T>
688 void
689 Map::Remove(T *obj, bool remove)
691 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
692 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
694 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);
695 return;
698 Cell cell(p);
699 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
700 return;
702 DEBUG_LOG("Remove object " I64FMTD " from grid[%u,%u]", obj->GetGUID(), cell.data.Part.grid_x, cell.data.Part.grid_y);
703 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
704 assert( grid != NULL );
706 obj->RemoveFromWorld();
707 RemoveFromGrid(obj,grid,cell);
709 UpdateObjectVisibility(obj,cell,p);
711 if( remove )
713 // if option set then object already saved at this moment
714 if(!sWorld.getConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY))
715 obj->SaveRespawnTime();
716 DeleteFromWorld(obj);
720 void
721 Map::PlayerRelocation(Player *player, float x, float y, float z, float orientation)
723 assert(player);
725 CellPair old_val = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
726 CellPair new_val = MaNGOS::ComputeCellPair(x, y);
728 Cell old_cell(old_val);
729 Cell new_cell(new_val);
730 new_cell |= old_cell;
731 bool same_cell = (new_cell == old_cell);
733 player->Relocate(x, y, z, orientation);
735 if( old_cell.DiffGrid(new_cell) || old_cell.DiffCell(new_cell) )
737 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());
739 // update player position for group at taxi flight
740 if(player->GetGroup() && player->isInFlight())
741 player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
743 NGridType* oldGrid = getNGrid(old_cell.GridX(), old_cell.GridY());
744 RemoveFromGrid(player, oldGrid,old_cell);
745 if( !old_cell.DiffGrid(new_cell) )
746 AddToGrid(player, oldGrid,new_cell);
748 if( old_cell.DiffGrid(new_cell) )
749 EnsureGridLoadedForPlayer(new_cell, player, true);
752 // if move then update what player see and who seen
753 UpdatePlayerVisibility(player,new_cell,new_val);
754 UpdateObjectsVisibilityFor(player,new_cell,new_val);
755 PlayerRelocationNotify(player,new_cell,new_val);
756 NGridType* newGrid = getNGrid(new_cell.GridX(), new_cell.GridY());
757 if( !same_cell && newGrid->GetGridState()!= GRID_STATE_ACTIVE )
759 ResetGridExpiry(*newGrid, 0.1f);
760 newGrid->SetGridState(GRID_STATE_ACTIVE);
764 void
765 Map::CreatureRelocation(Creature *creature, float x, float y, float z, float ang)
767 assert(CheckGridIntegrity(creature,false));
769 Cell old_cell = creature->GetCurrentCell();
771 CellPair new_val = MaNGOS::ComputeCellPair(x, y);
772 Cell new_cell(new_val);
774 // delay creature move for grid/cell to grid/cell moves
775 if( old_cell.DiffCell(new_cell) || old_cell.DiffGrid(new_cell) )
777 #ifdef MANGOS_DEBUG
778 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
779 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());
780 #endif
781 AddCreatureToMoveList(creature,x,y,z,ang);
782 // in diffcell/diffgrid case notifiers called at finishing move creature in Map::MoveAllCreaturesInMoveList
784 else
786 creature->Relocate(x, y, z, ang);
787 CreatureRelocationNotify(creature,new_cell,new_val);
789 assert(CheckGridIntegrity(creature,true));
792 void Map::AddCreatureToMoveList(Creature *c, float x, float y, float z, float ang)
794 if(!c)
795 return;
797 i_creaturesToMove[c] = CreatureMover(x,y,z,ang);
800 void Map::MoveAllCreaturesInMoveList()
802 while(!i_creaturesToMove.empty())
804 // get data and remove element;
805 CreatureMoveList::iterator iter = i_creaturesToMove.begin();
806 Creature* c = iter->first;
807 CreatureMover cm = iter->second;
808 i_creaturesToMove.erase(iter);
810 // calculate cells
811 CellPair new_val = MaNGOS::ComputeCellPair(cm.x, cm.y);
812 Cell new_cell(new_val);
814 // do move or do move to respawn or remove creature if previous all fail
815 if(CreatureCellRelocation(c,new_cell))
817 // update pos
818 c->Relocate(cm.x, cm.y, cm.z, cm.ang);
819 CreatureRelocationNotify(c,new_cell,new_cell.cellPair());
821 else
823 // if creature can't be move in new cell/grid (not loaded) move it to repawn cell/grid
824 // creature coordinates will be updated and notifiers send
825 if(!CreatureRespawnRelocation(c))
827 // ... or unload (if respawn grid also not loaded)
828 #ifdef MANGOS_DEBUG
829 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
830 sLog.outDebug("Creature (GUID: %u Entry: %u ) can't be move to unloaded respawn grid.",c->GetGUIDLow(),c->GetEntry());
831 #endif
832 c->CleanupsBeforeDelete();
833 AddObjectToRemoveList(c);
839 bool Map::CreatureCellRelocation(Creature *c, Cell new_cell)
841 Cell const& old_cell = c->GetCurrentCell();
842 if(!old_cell.DiffGrid(new_cell) ) // in same grid
844 // if in same cell then none do
845 if(old_cell.DiffCell(new_cell))
847 #ifdef MANGOS_DEBUG
848 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
849 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());
850 #endif
852 if( !old_cell.DiffGrid(new_cell) )
854 RemoveFromGrid(c,getNGrid(old_cell.GridX(), old_cell.GridY()),old_cell);
855 AddToGrid(c,getNGrid(new_cell.GridX(), new_cell.GridY()),new_cell);
856 c->SetCurrentCell(new_cell);
859 else
861 #ifdef MANGOS_DEBUG
862 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
863 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());
864 #endif
867 else // in diff. grids
868 if(loaded(GridPair(new_cell.GridX(), new_cell.GridY())))
870 #ifdef MANGOS_DEBUG
871 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
872 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());
873 #endif
875 RemoveFromGrid(c,getNGrid(old_cell.GridX(), old_cell.GridY()),old_cell);
877 EnsureGridCreated(GridPair(new_cell.GridX(), new_cell.GridY()));
878 AddToGrid(c,getNGrid(new_cell.GridX(), new_cell.GridY()),new_cell);
881 else
883 #ifdef MANGOS_DEBUG
884 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
885 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());
886 #endif
887 return false;
890 return true;
893 bool Map::CreatureRespawnRelocation(Creature *c)
895 float resp_x, resp_y, resp_z, resp_o;
896 c->GetRespawnCoord(resp_x, resp_y, resp_z, &resp_o);
898 CellPair resp_val = MaNGOS::ComputeCellPair(resp_x, resp_y);
899 Cell resp_cell(resp_val);
901 c->CombatStop();
902 c->GetMotionMaster()->Clear();
904 #ifdef MANGOS_DEBUG
905 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
906 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());
907 #endif
909 // teleport it to respawn point (like normal respawn if player see)
910 if(CreatureCellRelocation(c,resp_cell))
912 c->Relocate(resp_x, resp_y, resp_z, resp_o);
913 c->GetMotionMaster()->Initialize(); // prevent possible problems with default move generators
914 CreatureRelocationNotify(c,resp_cell,resp_cell.cellPair());
915 return true;
917 else
918 return false;
921 bool Map::UnloadGrid(const uint32 &x, const uint32 &y, bool pForce)
923 NGridType *grid = getNGrid(x, y);
924 assert( grid != NULL);
927 if(!pForce && ObjectAccessor::Instance().PlayersNearGrid(x, y, i_id, i_InstanceId) )
928 return false;
930 DEBUG_LOG("Unloading grid[%u,%u] for map %u", x,y, i_id);
931 ObjectGridUnloader unloader(*grid);
933 // Finish creature moves, remove and delete all creatures with delayed remove before moving to respawn grids
934 // Must know real mob position before move
935 DoDelayedMovesAndRemoves();
937 // move creatures to respawn grids if this is diff.grid or to remove list
938 unloader.MoveToRespawnN();
940 // Finish creature moves, remove and delete all creatures with delayed remove before unload
941 DoDelayedMovesAndRemoves();
943 unloader.UnloadN();
944 delete getNGrid(x, y);
945 setNGrid(NULL, x, y);
947 int gx=63-x;
948 int gy=63-y;
950 // delete grid map, but don't delete if it is from parent map (and thus only reference)
951 //+++if (GridMaps[gx][gy]) don't check for GridMaps[gx][gy], we might have to unload vmaps
953 if (i_InstanceId == 0)
955 if(GridMaps[gx][gy]) delete (GridMaps[gx][gy]);
956 // x and y are swaped
957 VMAP::VMapFactory::createOrGetVMapManager()->unloadMap(GetId(), gy, gx);
959 else
960 ((MapInstanced*)(MapManager::Instance().GetBaseMap(i_id)))->RemoveGridMapReference(GridPair(gx, gy));
961 GridMaps[gx][gy] = NULL;
963 DEBUG_LOG("Unloading grid[%u,%u] for map %u finished", x,y, i_id);
964 return true;
967 void Map::UnloadAll(bool pForce)
969 // clear all delayed moves, useless anyway do this moves before map unload.
970 i_creaturesToMove.clear();
972 for (GridRefManager<NGridType>::iterator i = GridRefManager<NGridType>::begin(); i != GridRefManager<NGridType>::end(); )
974 NGridType &grid(*i->getSource());
975 ++i;
976 UnloadGrid(grid.getX(), grid.getY(), pForce); // deletes the grid and removes it from the GridRefManager
980 float Map::GetHeight(float x, float y, float z, bool pUseVmaps) const
982 GridPair p = MaNGOS::ComputeGridPair(x, y);
984 // half opt method
985 int gx=(int)(32-x/SIZE_OF_GRIDS); //grid x
986 int gy=(int)(32-y/SIZE_OF_GRIDS); //grid y
988 float lx=MAP_RESOLUTION*(32 -x/SIZE_OF_GRIDS - gx);
989 float ly=MAP_RESOLUTION*(32 -y/SIZE_OF_GRIDS - gy);
991 // ensure GridMap is loaded
992 const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
994 // find raw .map surface under Z coordinates
995 float mapHeight;
996 if(GridMap* gmap = GridMaps[gx][gy])
998 int lx_int = (int)lx;
999 int ly_int = (int)ly;
1001 float zi[4];
1002 // Probe 4 nearest points (except border cases)
1003 zi[0] = gmap->Z[lx_int][ly_int];
1004 zi[1] = lx < MAP_RESOLUTION-1 ? gmap->Z[lx_int+1][ly_int] : zi[0];
1005 zi[2] = ly < MAP_RESOLUTION-1 ? gmap->Z[lx_int][ly_int+1] : zi[0];
1006 zi[3] = lx < MAP_RESOLUTION-1 && ly < MAP_RESOLUTION-1 ? gmap->Z[lx_int+1][ly_int+1] : zi[0];
1007 // Recalculate them like if their x,y positions were in the range 0,1
1008 float b[4];
1009 b[0] = zi[0];
1010 b[1] = zi[1]-zi[0];
1011 b[2] = zi[2]-zi[0];
1012 b[3] = zi[0]-zi[1]-zi[2]+zi[3];
1013 // Normalize the dx and dy to be in range 0..1
1014 float fact_x = lx - lx_int;
1015 float fact_y = ly - ly_int;
1016 // Use the simplified bilinear equation, as described in [url="http://en.wikipedia.org/wiki/Bilinear_interpolation"]http://en.wikipedia.org/wiki/Bilinear_interpolation[/url]
1017 float _mapheight = b[0] + (b[1]*fact_x) + (b[2]*fact_y) + (b[3]*fact_x*fact_y);
1019 // look from a bit higher pos to find the floor, ignore under surface case
1020 if(z + 2.0f > _mapheight)
1021 mapHeight = _mapheight;
1022 else
1023 mapHeight = VMAP_INVALID_HEIGHT_VALUE;
1025 else
1026 mapHeight = VMAP_INVALID_HEIGHT_VALUE;
1028 float vmapHeight;
1029 if(pUseVmaps)
1031 VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager();
1032 if(vmgr->isHeightCalcEnabled())
1034 // look from a bit higher pos to find the floor
1035 vmapHeight = vmgr->getHeight(GetId(), x, y, z + 2.0f);
1037 else
1038 vmapHeight = VMAP_INVALID_HEIGHT_VALUE;
1040 else
1041 vmapHeight = VMAP_INVALID_HEIGHT_VALUE;
1043 // mapHeight set for any above raw ground Z or <= INVALID_HEIGHT
1044 // vmapheight set for any under Z value or <= INVALID_HEIGHT
1046 if( vmapHeight > INVALID_HEIGHT )
1048 if( mapHeight > INVALID_HEIGHT )
1050 // we have mapheight and vmapheight and must select more appropriate
1052 // we are already under the surface or vmap height above map heigt
1053 // or if the distance of the vmap height is less the land height distance
1054 if( z < mapHeight || vmapHeight > mapHeight || fabs(mapHeight-z) > fabs(vmapHeight-z) )
1055 return vmapHeight;
1056 else
1057 return mapHeight; // better use .map surface height
1060 else
1061 return vmapHeight; // we have only vmapHeight (if have)
1063 else
1065 if(!pUseVmaps)
1066 return mapHeight; // explicitly use map data (if have)
1067 else if(mapHeight > INVALID_HEIGHT && (z < mapHeight + 2 || z == MAX_HEIGHT))
1068 return mapHeight; // explicitly use map data if original z < mapHeight but map found (z+2 > mapHeight)
1069 else
1070 return VMAP_INVALID_HEIGHT_VALUE; // we not have any height
1074 uint16 Map::GetAreaFlag(float x, float y ) const
1076 //local x,y coords
1077 float lx,ly;
1078 int gx,gy;
1079 GridPair p = MaNGOS::ComputeGridPair(x, y);
1081 // half opt method
1082 gx=(int)(32-x/SIZE_OF_GRIDS) ; //grid x
1083 gy=(int)(32-y/SIZE_OF_GRIDS); //grid y
1085 lx=16*(32 -x/SIZE_OF_GRIDS - gx);
1086 ly=16*(32 -y/SIZE_OF_GRIDS - gy);
1087 //DEBUG_LOG("my %d %d si %d %d",gx,gy,p.x_coord,p.y_coord);
1089 // ensure GridMap is loaded
1090 const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
1092 if(GridMaps[gx][gy])
1093 return GridMaps[gx][gy]->area_flag[(int)(lx)][(int)(ly)];
1094 // this used while not all *.map files generated (instances)
1095 else
1096 return GetAreaFlagByMapId(i_id);
1099 uint8 Map::GetTerrainType(float x, float y ) const
1101 //local x,y coords
1102 float lx,ly;
1103 int gx,gy;
1105 // half opt method
1106 gx=(int)(32-x/SIZE_OF_GRIDS) ; //grid x
1107 gy=(int)(32-y/SIZE_OF_GRIDS); //grid y
1109 lx=16*(32 -x/SIZE_OF_GRIDS - gx);
1110 ly=16*(32 -y/SIZE_OF_GRIDS - gy);
1112 // ensure GridMap is loaded
1113 const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
1115 if(GridMaps[gx][gy])
1116 return GridMaps[gx][gy]->terrain_type[(int)(lx)][(int)(ly)];
1117 else
1118 return 0;
1122 float Map::GetWaterLevel(float x, float y ) const
1124 //local x,y coords
1125 float lx,ly;
1126 int gx,gy;
1128 // half opt method
1129 gx=(int)(32-x/SIZE_OF_GRIDS) ; //grid x
1130 gy=(int)(32-y/SIZE_OF_GRIDS); //grid y
1132 lx=128*(32 -x/SIZE_OF_GRIDS - gx);
1133 ly=128*(32 -y/SIZE_OF_GRIDS - gy);
1135 // ensure GridMap is loaded
1136 const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
1138 if(GridMaps[gx][gy])
1139 return GridMaps[gx][gy]->liquid_level[(int)(lx)][(int)(ly)];
1140 else
1141 return 0;
1144 uint32 Map::GetAreaId(uint16 areaflag,uint32 map_id)
1146 AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
1148 if (entry)
1149 return entry->ID;
1150 else
1151 return 0;
1154 uint32 Map::GetZoneId(uint16 areaflag,uint32 map_id)
1156 AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
1158 if( entry )
1159 return ( entry->zone != 0 ) ? entry->zone : entry->ID;
1160 else
1161 return 0;
1164 bool Map::IsInWater(float x, float y, float pZ) const
1166 // This method is called too often to use vamps for that (4. parameter = false).
1167 // The pZ pos is taken anyway for future use
1168 float z = GetHeight(x,y,pZ,false); // use .map base surface height
1170 // underground or instance without vmap
1171 if(z <= INVALID_HEIGHT)
1172 return false;
1174 float water_z = GetWaterLevel(x,y);
1175 uint8 flag = GetTerrainType(x,y);
1176 return (z < (water_z-2)) && (flag & 0x01);
1179 bool Map::IsUnderWater(float x, float y, float z) const
1181 float water_z = GetWaterLevel(x,y);
1182 uint8 flag = GetTerrainType(x,y);
1183 return (z < (water_z-2)) && (flag & 0x01);
1186 bool Map::CheckGridIntegrity(Creature* c, bool moved) const
1188 Cell const& cur_cell = c->GetCurrentCell();
1190 CellPair xy_val = MaNGOS::ComputeCellPair(c->GetPositionX(), c->GetPositionY());
1191 Cell xy_cell(xy_val);
1192 if(xy_cell != cur_cell)
1194 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]",
1195 (c->GetTypeId()==TYPEID_PLAYER ? "Player" : "Creature"),c->GetGUIDLow(),
1196 c->GetPositionX(),c->GetPositionY(),(moved ? "final" : "original"),
1197 cur_cell.GridX(), cur_cell.GridY(), cur_cell.CellX(), cur_cell.CellY(),
1198 xy_cell.GridX(), xy_cell.GridY(), xy_cell.CellX(), xy_cell.CellY());
1199 return true; // not crash at error, just output error in debug mode
1202 return true;
1205 const char* Map::GetMapName() const
1207 return i_mapEntry ? i_mapEntry->name[sWorld.GetDefaultDbcLocale()] : "UNNAMEDMAP\x0";
1210 void Map::UpdateObjectVisibility( WorldObject* obj, Cell cell, CellPair cellpair)
1212 cell.data.Part.reserved = ALL_DISTRICT;
1213 cell.SetNoCreate();
1214 MaNGOS::VisibleChangesNotifier notifier(*obj);
1215 TypeContainerVisitor<MaNGOS::VisibleChangesNotifier, WorldTypeMapContainer > player_notifier(notifier);
1216 CellLock<GridReadGuard> cell_lock(cell, cellpair);
1217 cell_lock->Visit(cell_lock, player_notifier, *this);
1220 void Map::UpdatePlayerVisibility( Player* player, Cell cell, CellPair cellpair )
1222 cell.data.Part.reserved = ALL_DISTRICT;
1224 MaNGOS::PlayerNotifier pl_notifier(*player);
1225 TypeContainerVisitor<MaNGOS::PlayerNotifier, WorldTypeMapContainer > player_notifier(pl_notifier);
1227 CellLock<ReadGuard> cell_lock(cell, cellpair);
1228 cell_lock->Visit(cell_lock, player_notifier, *this);
1231 void Map::UpdateObjectsVisibilityFor( Player* player, Cell cell, CellPair cellpair )
1233 MaNGOS::VisibleNotifier notifier(*player);
1235 cell.data.Part.reserved = ALL_DISTRICT;
1236 cell.SetNoCreate();
1237 TypeContainerVisitor<MaNGOS::VisibleNotifier, WorldTypeMapContainer > world_notifier(notifier);
1238 TypeContainerVisitor<MaNGOS::VisibleNotifier, GridTypeMapContainer > grid_notifier(notifier);
1239 CellLock<GridReadGuard> cell_lock(cell, cellpair);
1240 cell_lock->Visit(cell_lock, world_notifier, *this);
1241 cell_lock->Visit(cell_lock, grid_notifier, *this);
1243 // send data
1244 notifier.Notify();
1247 void Map::PlayerRelocationNotify( Player* player, Cell cell, CellPair cellpair )
1249 CellLock<ReadGuard> cell_lock(cell, cellpair);
1250 MaNGOS::PlayerRelocationNotifier relocationNotifier(*player);
1251 cell.data.Part.reserved = ALL_DISTRICT;
1253 TypeContainerVisitor<MaNGOS::PlayerRelocationNotifier, GridTypeMapContainer > p2grid_relocation(relocationNotifier);
1254 TypeContainerVisitor<MaNGOS::PlayerRelocationNotifier, WorldTypeMapContainer > p2world_relocation(relocationNotifier);
1256 cell_lock->Visit(cell_lock, p2grid_relocation, *this);
1257 cell_lock->Visit(cell_lock, p2world_relocation, *this);
1260 void Map::CreatureRelocationNotify(Creature *creature, Cell cell, CellPair cellpair)
1262 CellLock<ReadGuard> cell_lock(cell, cellpair);
1263 MaNGOS::CreatureRelocationNotifier relocationNotifier(*creature);
1264 cell.data.Part.reserved = ALL_DISTRICT;
1265 cell.SetNoCreate(); // not trigger load unloaded grids at notifier call
1267 TypeContainerVisitor<MaNGOS::CreatureRelocationNotifier, WorldTypeMapContainer > c2world_relocation(relocationNotifier);
1268 TypeContainerVisitor<MaNGOS::CreatureRelocationNotifier, GridTypeMapContainer > c2grid_relocation(relocationNotifier);
1270 cell_lock->Visit(cell_lock, c2world_relocation, *this);
1271 cell_lock->Visit(cell_lock, c2grid_relocation, *this);
1274 void Map::SendInitSelf( Player * player )
1276 sLog.outDetail("Creating player data for himself %u", player->GetGUIDLow());
1278 UpdateData data;
1280 bool hasTransport = false;
1282 // attach to player data current transport data
1283 if(Transport* transport = player->GetTransport())
1285 hasTransport = true;
1286 transport->BuildCreateUpdateBlockForPlayer(&data, player);
1289 // build data for self presence in world at own client (one time for map)
1290 player->BuildCreateUpdateBlockForPlayer(&data, player);
1292 // build other passengers at transport also (they always visible and marked as visible and will not send at visibility update at add to map
1293 if(Transport* transport = player->GetTransport())
1295 for(Transport::PlayerSet::const_iterator itr = transport->GetPassengers().begin();itr!=transport->GetPassengers().end();++itr)
1297 if(player!=(*itr) && player->HaveAtClient(*itr))
1299 hasTransport = true;
1300 (*itr)->BuildCreateUpdateBlockForPlayer(&data, player);
1305 WorldPacket packet;
1306 data.BuildPacket(&packet, hasTransport);
1307 player->GetSession()->SendPacket(&packet);
1310 void Map::SendInitTransports( Player * player )
1312 // Hack to send out transports
1313 MapManager::TransportMap& tmap = MapManager::Instance().m_TransportsByMap;
1315 // no transports at map
1316 if (tmap.find(player->GetMapId()) == tmap.end())
1317 return;
1319 UpdateData transData;
1321 MapManager::TransportSet& tset = tmap[player->GetMapId()];
1323 bool hasTransport = false;
1325 for (MapManager::TransportSet::iterator i = tset.begin(); i != tset.end(); ++i)
1327 if((*i) != player->GetTransport()) // send data for current transport in other place
1329 hasTransport = true;
1330 (*i)->BuildCreateUpdateBlockForPlayer(&transData, player);
1334 WorldPacket packet;
1335 transData.BuildPacket(&packet, hasTransport);
1336 player->GetSession()->SendPacket(&packet);
1339 void Map::SendRemoveTransports( Player * player )
1341 // Hack to send out transports
1342 MapManager::TransportMap& tmap = MapManager::Instance().m_TransportsByMap;
1344 // no transports at map
1345 if (tmap.find(player->GetMapId()) == tmap.end())
1346 return;
1348 UpdateData transData;
1350 MapManager::TransportSet& tset = tmap[player->GetMapId()];
1352 // except used transport
1353 for (MapManager::TransportSet::iterator i = tset.begin(); i != tset.end(); ++i)
1354 if(player->GetTransport() != (*i))
1355 (*i)->BuildOutOfRangeUpdateBlock(&transData);
1357 WorldPacket packet;
1358 transData.BuildPacket(&packet);
1359 player->GetSession()->SendPacket(&packet);
1362 inline void Map::setNGrid(NGridType *grid, uint32 x, uint32 y)
1364 if(x >= MAX_NUMBER_OF_GRIDS || y >= MAX_NUMBER_OF_GRIDS)
1366 sLog.outError("map::setNGrid() Invalid grid coordinates found: %d, %d!",x,y);
1367 assert(false);
1369 i_grids[x][y] = grid;
1372 void Map::DoDelayedMovesAndRemoves()
1374 MoveAllCreaturesInMoveList();
1375 RemoveAllObjectsInRemoveList();
1378 void Map::AddObjectToRemoveList(WorldObject *obj)
1380 assert(obj->GetMapId()==GetId() && obj->GetInstanceId()==GetInstanceId());
1382 i_objectsToRemove.insert(obj);
1383 //sLog.outDebug("Object (GUID: %u TypeId: %u ) added to removing list.",obj->GetGUIDLow(),obj->GetTypeId());
1386 void Map::RemoveAllObjectsInRemoveList()
1388 if(i_objectsToRemove.empty())
1389 return;
1391 //sLog.outDebug("Object remover 1 check.");
1392 while(!i_objectsToRemove.empty())
1394 WorldObject* obj = *i_objectsToRemove.begin();
1395 i_objectsToRemove.erase(i_objectsToRemove.begin());
1397 switch(obj->GetTypeId())
1399 case TYPEID_CORPSE:
1401 Corpse* corpse = ObjectAccessor::Instance().GetCorpse(*obj, obj->GetGUID());
1402 if (!corpse)
1403 sLog.outError("ERROR: Try delete corpse/bones %u that not in map", obj->GetGUIDLow());
1404 else
1405 Remove(corpse,true);
1406 break;
1408 case TYPEID_DYNAMICOBJECT:
1409 Remove((DynamicObject*)obj,true);
1410 break;
1411 case TYPEID_GAMEOBJECT:
1412 Remove((GameObject*)obj,true);
1413 break;
1414 case TYPEID_UNIT:
1415 // in case triggered sequence some spell can continue casting after prev CleanupsBeforeDelete call
1416 // make sure that like sources auras/etc removed before destructor start
1417 ((Creature*)obj)->CleanupsBeforeDelete ();
1418 Remove((Creature*)obj,true);
1419 break;
1420 default:
1421 sLog.outError("Non-grid object (TypeId: %u) in grid object removing list, ignored.",obj->GetTypeId());
1422 break;
1425 //sLog.outDebug("Object remover 2 check.");
1428 bool Map::CanUnload(const uint32 &diff)
1430 if(!m_unloadTimer) return false;
1431 if(m_unloadTimer < diff) return true;
1432 m_unloadTimer -= diff;
1433 return false;
1436 template void Map::Add(Corpse *);
1437 template void Map::Add(Creature *);
1438 template void Map::Add(GameObject *);
1439 template void Map::Add(DynamicObject *);
1441 template void Map::Remove(Corpse *,bool);
1442 template void Map::Remove(Creature *,bool);
1443 template void Map::Remove(GameObject *, bool);
1444 template void Map::Remove(DynamicObject *, bool);
1446 /* ******* Dungeon Instance Maps ******* */
1448 InstanceMap::InstanceMap(uint32 id, time_t expiry, uint32 InstanceId, uint8 SpawnMode)
1449 : Map(id, expiry, InstanceId, SpawnMode), i_data(NULL),
1450 m_resetAfterUnload(false), m_unloadWhenEmpty(false)
1452 // the timer is started by default, and stopped when the first player joins
1453 // this make sure it gets unloaded if for some reason no player joins
1454 m_unloadTimer = std::max(sWorld.getConfig(CONFIG_INSTANCE_UNLOAD_DELAY), (uint32)MIN_UNLOAD_DELAY);
1457 InstanceMap::~InstanceMap()
1459 if(i_data)
1461 delete i_data;
1462 i_data = NULL;
1467 Do map specific checks to see if the player can enter
1469 bool InstanceMap::CanEnter(Player *player)
1471 if(std::find(i_Players.begin(),i_Players.end(),player)!=i_Players.end())
1473 sLog.outError("InstanceMap::CanEnter - player %s(%u) already in map %d,%d,%d!", player->GetName(), player->GetGUIDLow(), GetId(), GetInstanceId(), GetSpawnMode());
1474 assert(false);
1475 return false;
1478 // cannot enter if the instance is full (player cap), GMs don't count
1479 InstanceTemplate const* iTemplate = objmgr.GetInstanceTemplate(GetId());
1480 if (!player->isGameMaster() && GetPlayersCountExceptGMs() >= iTemplate->maxPlayers)
1482 sLog.outDetail("MAP: Instance '%u' of map '%s' cannot have more than '%u' players. Player '%s' rejected", GetInstanceId(), GetMapName(), iTemplate->maxPlayers, player->GetName());
1483 player->SendTransferAborted(GetId(), TRANSFER_ABORT_MAX_PLAYERS);
1484 return false;
1487 // cannot enter while players in the instance are in combat
1488 Group *pGroup = player->GetGroup();
1489 if(pGroup && pGroup->InCombatToInstance(GetInstanceId()) && player->isAlive() && player->GetMapId() != GetId())
1491 player->SendTransferAborted(GetId(), TRANSFER_ABORT_ZONE_IN_COMBAT);
1492 return false;
1495 return Map::CanEnter(player);
1499 Do map specific checks and add the player to the map if successful.
1501 bool InstanceMap::Add(Player *player)
1503 // TODO: Not sure about checking player level: already done in HandleAreaTriggerOpcode
1504 // GMs still can teleport player in instance.
1505 // Is it needed?
1508 Guard guard(*this);
1509 if(!CanEnter(player))
1510 return false;
1512 // get or create an instance save for the map
1513 InstanceSave *mapSave = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1514 if(!mapSave)
1516 sLog.outDetail("InstanceMap::Add: creating instance save for map %d spawnmode %d with instance id %d", GetId(), GetSpawnMode(), GetInstanceId());
1517 mapSave = sInstanceSaveManager.AddInstanceSave(GetId(), GetInstanceId(), GetSpawnMode(), 0, true);
1520 // check for existing instance binds
1521 InstancePlayerBind *playerBind = player->GetBoundInstance(GetId(), GetSpawnMode());
1522 if(playerBind && playerBind->perm)
1524 // cannot enter other instances if bound permanently
1525 if(playerBind->save != mapSave)
1527 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());
1528 assert(false);
1531 else
1533 Group *pGroup = player->GetGroup();
1534 if(pGroup)
1536 // solo saves should be reset when entering a group
1537 InstanceGroupBind *groupBind = pGroup->GetBoundInstance(GetId(), GetSpawnMode());
1538 if(playerBind)
1540 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());
1541 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());
1542 assert(false);
1544 // bind to the group or keep using the group save
1545 if(!groupBind)
1546 pGroup->BindToInstance(mapSave, false);
1547 else
1549 // cannot jump to a different instance without resetting it
1550 if(groupBind->save != mapSave)
1552 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());
1553 if(mapSave)
1554 sLog.outError("MapSave players: %d, group count: %d", mapSave->GetPlayerCount(), mapSave->GetGroupCount());
1555 else
1556 sLog.outError("MapSave NULL");
1557 if(groupBind->save)
1558 sLog.outError("GroupBind save players: %d, group count: %d", groupBind->save->GetPlayerCount(), groupBind->save->GetGroupCount());
1559 else
1560 sLog.outError("GroupBind save NULL");
1561 assert(false);
1563 // if the group/leader is permanently bound to the instance
1564 // players also become permanently bound when they enter
1565 if(groupBind->perm)
1567 WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
1568 data << uint32(0);
1569 player->GetSession()->SendPacket(&data);
1570 player->BindToInstance(mapSave, true);
1574 else
1576 // set up a solo bind or continue using it
1577 if(!playerBind)
1578 player->BindToInstance(mapSave, false);
1579 else
1580 // cannot jump to a different instance without resetting it
1581 assert(playerBind->save == mapSave);
1585 if(i_data) i_data->OnPlayerEnter(player);
1586 SetResetSchedule(false);
1588 i_Players.push_back(player);
1589 player->SendInitWorldStates();
1590 sLog.outDetail("MAP: Player '%s' entered the instance '%u' of map '%s'", player->GetName(), GetInstanceId(), GetMapName());
1591 // initialize unload state
1592 m_unloadTimer = 0;
1593 m_resetAfterUnload = false;
1594 m_unloadWhenEmpty = false;
1597 // this will acquire the same mutex so it cannot be in the previous block
1598 Map::Add(player);
1599 return true;
1602 void InstanceMap::Update(const uint32& t_diff)
1604 Map::Update(t_diff);
1606 if(i_data)
1607 i_data->Update(t_diff);
1610 void InstanceMap::Remove(Player *player, bool remove)
1612 sLog.outDetail("MAP: Removing player '%s' from instance '%u' of map '%s' before relocating to other map", player->GetName(), GetInstanceId(), GetMapName());
1613 i_Players.remove(player);
1614 SetResetSchedule(true);
1615 if(!m_unloadTimer && i_Players.empty())
1616 m_unloadTimer = m_unloadWhenEmpty ? MIN_UNLOAD_DELAY : std::max(sWorld.getConfig(CONFIG_INSTANCE_UNLOAD_DELAY), (uint32)MIN_UNLOAD_DELAY);
1617 Map::Remove(player, remove);
1620 void InstanceMap::CreateInstanceData(bool load)
1622 if(i_data != NULL)
1623 return;
1625 InstanceTemplate const* mInstance = objmgr.GetInstanceTemplate(GetId());
1626 if (mInstance)
1628 i_script = mInstance->script;
1629 i_data = Script->CreateInstanceData(this);
1632 if(!i_data)
1633 return;
1635 if(load)
1637 // TODO: make a global storage for this
1638 QueryResult* result = CharacterDatabase.PQuery("SELECT data FROM instance WHERE map = '%u' AND id = '%u'", GetId(), i_InstanceId);
1639 if (result)
1641 Field* fields = result->Fetch();
1642 const char* data = fields[0].GetString();
1643 if(data)
1645 sLog.outDebug("Loading instance data for `%s` with id %u", i_script.c_str(), i_InstanceId);
1646 i_data->Load(data);
1648 delete result;
1651 else
1653 sLog.outDebug("New instance data, \"%s\" ,initialized!",i_script.c_str());
1654 i_data->Initialize();
1659 Returns true if there are no players in the instance
1661 bool InstanceMap::Reset(uint8 method)
1663 // note: since the map may not be loaded when the instance needs to be reset
1664 // the instance must be deleted from the DB by InstanceSaveManager
1666 if(!i_Players.empty())
1668 if(method == INSTANCE_RESET_ALL)
1670 // notify the players to leave the instance so it can be reset
1671 for(PlayerList::iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1672 (*itr)->SendResetFailedNotify(GetId());
1674 else
1676 if(method == INSTANCE_RESET_GLOBAL)
1678 // set the homebind timer for players inside (1 minute)
1679 for(PlayerList::iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1680 (*itr)->m_InstanceValid = false;
1683 // the unload timer is not started
1684 // instead the map will unload immediately after the players have left
1685 m_unloadWhenEmpty = true;
1686 m_resetAfterUnload = true;
1689 else
1691 // unloaded at next update
1692 m_unloadTimer = MIN_UNLOAD_DELAY;
1693 m_resetAfterUnload = true;
1696 return i_Players.empty();
1699 uint32 InstanceMap::GetPlayersCountExceptGMs() const
1701 uint32 count = 0;
1702 for(PlayerList::const_iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1703 if(!(*itr)->isGameMaster())
1704 ++count;
1705 return count;
1708 void InstanceMap::PermBindAllPlayers(Player *player)
1710 InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1711 if(!save)
1713 sLog.outError("Cannot bind players, no instance save available for map!\n");
1714 return;
1717 Group *group = player->GetGroup();
1718 // group members outside the instance group don't get bound
1719 for(PlayerList::iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1721 if(*itr)
1723 // players inside an instance cannot be bound to other instances
1724 // some players may already be permanently bound, in this case nothing happens
1725 InstancePlayerBind *bind = (*itr)->GetBoundInstance(save->GetMapId(), save->GetDifficulty());
1726 if(!bind || !bind->perm)
1728 (*itr)->BindToInstance(save, true);
1729 WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
1730 data << uint32(0);
1731 (*itr)->GetSession()->SendPacket(&data);
1734 // if the leader is not in the instance the group will not get a perm bind
1735 if(group && group->GetLeaderGUID() == (*itr)->GetGUID())
1736 group->BindToInstance(save, true);
1741 time_t InstanceMap::GetResetTime()
1743 InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1744 return save ? save->GetDifficulty() : DIFFICULTY_NORMAL;
1747 void InstanceMap::UnloadAll(bool pForce)
1749 if(!i_Players.empty())
1751 sLog.outError("InstanceMap::UnloadAll: there are still players in the instance at unload, should not happen!");
1752 for(PlayerList::iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1753 if(*itr) (*itr)->TeleportTo((*itr)->m_homebindMapId, (*itr)->m_homebindX, (*itr)->m_homebindY, (*itr)->m_homebindZ, (*itr)->GetOrientation());
1756 if(m_resetAfterUnload == true)
1757 objmgr.DeleteRespawnTimeForInstance(GetInstanceId());
1759 Map::UnloadAll(pForce);
1762 void InstanceMap::SendResetWarnings(uint32 timeLeft)
1764 for(PlayerList::iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1765 (*itr)->SendInstanceResetWarning(GetId(), timeLeft);
1768 void InstanceMap::SetResetSchedule(bool on)
1770 // only for normal instances
1771 // the reset time is only scheduled when there are no payers inside
1772 // it is assumed that the reset time will rarely (if ever) change while the reset is scheduled
1773 if(i_Players.empty() && !IsRaid() && !IsHeroic())
1775 InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1776 if(!save) sLog.outError("InstanceMap::SetResetSchedule: cannot turn schedule %s, no save available for instance %d of %d", on ? "on" : "off", GetInstanceId(), GetId());
1777 else sInstanceSaveManager.ScheduleReset(on, save->GetResetTime(), InstanceSaveManager::InstResetEvent(0, GetId(), GetInstanceId()));
1781 void InstanceMap::SendToPlayers(WorldPacket const* data) const
1783 for(PlayerList::const_iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1784 (*itr)->GetSession()->SendPacket(data);
1787 /* ******* Battleground Instance Maps ******* */
1789 BattleGroundMap::BattleGroundMap(uint32 id, time_t expiry, uint32 InstanceId)
1790 : Map(id, expiry, InstanceId, DIFFICULTY_NORMAL)
1794 BattleGroundMap::~BattleGroundMap()
1798 bool BattleGroundMap::CanEnter(Player * player)
1800 if(std::find(i_Players.begin(),i_Players.end(),player)!=i_Players.end())
1802 sLog.outError("BGMap::CanEnter - player %u already in map!", player->GetGUIDLow());
1803 assert(false);
1804 return false;
1807 if(player->GetBattleGroundId() != GetInstanceId())
1808 return false;
1810 // player number limit is checked in bgmgr, no need to do it here
1812 return Map::CanEnter(player);
1815 bool BattleGroundMap::Add(Player * player)
1818 Guard guard(*this);
1819 if(!CanEnter(player))
1820 return false;
1821 i_Players.push_back(player);
1822 // reset instance validity, battleground maps do not homebind
1823 player->m_InstanceValid = true;
1825 return Map::Add(player);
1828 void BattleGroundMap::Remove(Player *player, bool remove)
1830 sLog.outDetail("MAP: Removing player '%s' from bg '%u' of map '%s' before relocating to other map", player->GetName(), GetInstanceId(), GetMapName());
1831 i_Players.remove(player);
1832 Map::Remove(player, remove);
1835 void BattleGroundMap::SetUnload()
1837 m_unloadTimer = MIN_UNLOAD_DELAY;
1840 void BattleGroundMap::UnloadAll(bool pForce)
1842 while(!i_Players.empty())
1844 PlayerList::iterator itr = i_Players.begin();
1845 Player * plr = *itr;
1846 if(plr) (plr)->TeleportTo((*itr)->m_homebindMapId, (*itr)->m_homebindX, (*itr)->m_homebindY, (*itr)->m_homebindZ, (*itr)->GetOrientation());
1847 // TeleportTo removes the player from this map (if the map exists) -> calls BattleGroundMap::Remove -> invalidates the iterator.
1848 // just in case, remove the player from the list explicitly here as well to prevent a possible infinite loop
1849 // note that this remove is not needed if the code works well in other places
1850 i_Players.remove(plr);
1853 Map::UnloadAll(pForce);