[6922] Whitespace and newline fixes
[getmangos.git] / src / game / Map.cpp
blobb1cb127207191722bc7c9e6874fd891410ced8a3
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 // the player iterator is stored in the map object
577 // to make sure calls to Map::Remove don't invalidate it
578 for(m_mapRefIter = m_mapRefManager.begin(); m_mapRefIter != m_mapRefManager.end(); ++m_mapRefIter)
580 Player* plr = m_mapRefIter->getSource();
582 if(!plr->IsInWorld())
583 continue;
585 CellPair standing_cell(MaNGOS::ComputeCellPair(plr->GetPositionX(), plr->GetPositionY()));
587 // Check for correctness of standing_cell, it also avoids problems with update_cell
588 if (standing_cell.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || standing_cell.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
589 continue;
591 // the overloaded operators handle range checking
592 // so ther's no need for range checking inside the loop
593 CellPair begin_cell(standing_cell), end_cell(standing_cell);
594 begin_cell << 1; begin_cell -= 1; // upper left
595 end_cell >> 1; end_cell += 1; // lower right
597 for(uint32 x = begin_cell.x_coord; x <= end_cell.x_coord; ++x)
599 for(uint32 y = begin_cell.y_coord; y <= end_cell.y_coord; ++y)
601 // marked cells are those that have been visited
602 // don't visit the same cell twice
603 uint32 cell_id = (y * TOTAL_NUMBER_OF_CELLS_PER_MAP) + x;
604 if(!isCellMarked(cell_id))
606 markCell(cell_id);
607 CellPair pair(x,y);
608 Cell cell(pair);
609 cell.data.Part.reserved = CENTER_DISTRICT;
610 cell.SetNoCreate();
611 CellLock<NullGuard> cell_lock(cell, pair);
612 cell_lock->Visit(cell_lock, grid_object_update, *this);
613 cell_lock->Visit(cell_lock, world_object_update, *this);
619 // 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 !
620 // This isn't really bother us, since as soon as we have instanced BG-s, the whole map unloads as the BG gets ended
621 if (IsBattleGroundOrArena())
622 return;
624 for (GridRefManager<NGridType>::iterator i = GridRefManager<NGridType>::begin(); i != GridRefManager<NGridType>::end(); )
626 NGridType *grid = i->getSource();
627 GridInfo *info = i->getSource()->getGridInfoRef();
628 ++i; // The update might delete the map and we need the next map before the iterator gets invalid
629 assert(grid->GetGridState() >= 0 && grid->GetGridState() < MAX_GRID_STATE);
630 si_GridStates[grid->GetGridState()]->Update(*this, *grid, *info, grid->getX(), grid->getY(), t_diff);
634 void Map::Remove(Player *player, bool remove)
636 // this may be called during Map::Update
637 // after decrement+unlink, ++m_mapRefIter will continue correctly
638 // when the first element of the list is being removed
639 // nocheck_prev will return the padding element of the RefManager
640 // instead of NULL in the case of prev
641 if(m_mapRefIter == player->GetMapRef())
642 m_mapRefIter = m_mapRefIter->nocheck_prev();
643 player->GetMapRef().unlink();
644 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
645 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
647 // invalid coordinates
648 player->RemoveFromWorld();
650 if( remove )
651 DeleteFromWorld(player);
653 return;
656 Cell cell(p);
658 if( !getNGrid(cell.data.Part.grid_x, cell.data.Part.grid_y) )
660 sLog.outError("Map::Remove() i_grids was NULL x:%d, y:%d",cell.data.Part.grid_x,cell.data.Part.grid_y);
661 return;
664 DEBUG_LOG("Remove player %s from grid[%u,%u]", player->GetName(), cell.GridX(), cell.GridY());
665 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
666 assert(grid != NULL);
668 player->RemoveFromWorld();
669 RemoveFromGrid(player,grid,cell);
671 SendRemoveTransports(player);
673 UpdateObjectsVisibilityFor(player,cell,p);
675 if( remove )
676 DeleteFromWorld(player);
679 bool Map::RemoveBones(uint64 guid, float x, float y)
681 if (IsRemovalGrid(x, y))
683 Corpse * corpse = ObjectAccessor::Instance().GetObjectInWorld(GetId(), x, y, guid, (Corpse*)NULL);
684 if(corpse && corpse->GetTypeId() == TYPEID_CORPSE && corpse->GetType() == CORPSE_BONES)
685 corpse->DeleteBonesFromWorld();
686 else
687 return false;
689 return true;
692 template<class T>
693 void
694 Map::Remove(T *obj, bool remove)
696 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
697 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
699 sLog.outError("Map::Remove: Object " I64FMT " have invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUID(), obj->GetPositionX(), obj->GetPositionY(), p.x_coord, p.y_coord);
700 return;
703 Cell cell(p);
704 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
705 return;
707 DEBUG_LOG("Remove object " I64FMT " from grid[%u,%u]", obj->GetGUID(), cell.data.Part.grid_x, cell.data.Part.grid_y);
708 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
709 assert( grid != NULL );
711 obj->RemoveFromWorld();
712 RemoveFromGrid(obj,grid,cell);
714 UpdateObjectVisibility(obj,cell,p);
716 if( remove )
718 // if option set then object already saved at this moment
719 if(!sWorld.getConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY))
720 obj->SaveRespawnTime();
721 DeleteFromWorld(obj);
725 void
726 Map::PlayerRelocation(Player *player, float x, float y, float z, float orientation)
728 assert(player);
730 CellPair old_val = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
731 CellPair new_val = MaNGOS::ComputeCellPair(x, y);
733 Cell old_cell(old_val);
734 Cell new_cell(new_val);
735 new_cell |= old_cell;
736 bool same_cell = (new_cell == old_cell);
738 player->Relocate(x, y, z, orientation);
740 if( old_cell.DiffGrid(new_cell) || old_cell.DiffCell(new_cell) )
742 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());
744 // update player position for group at taxi flight
745 if(player->GetGroup() && player->isInFlight())
746 player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
748 NGridType* oldGrid = getNGrid(old_cell.GridX(), old_cell.GridY());
749 RemoveFromGrid(player, oldGrid,old_cell);
750 if( !old_cell.DiffGrid(new_cell) )
751 AddToGrid(player, oldGrid,new_cell);
753 if( old_cell.DiffGrid(new_cell) )
754 EnsureGridLoadedForPlayer(new_cell, player, true);
757 // if move then update what player see and who seen
758 UpdatePlayerVisibility(player,new_cell,new_val);
759 UpdateObjectsVisibilityFor(player,new_cell,new_val);
760 PlayerRelocationNotify(player,new_cell,new_val);
761 NGridType* newGrid = getNGrid(new_cell.GridX(), new_cell.GridY());
762 if( !same_cell && newGrid->GetGridState()!= GRID_STATE_ACTIVE )
764 ResetGridExpiry(*newGrid, 0.1f);
765 newGrid->SetGridState(GRID_STATE_ACTIVE);
769 void
770 Map::CreatureRelocation(Creature *creature, float x, float y, float z, float ang)
772 assert(CheckGridIntegrity(creature,false));
774 Cell old_cell = creature->GetCurrentCell();
776 CellPair new_val = MaNGOS::ComputeCellPair(x, y);
777 Cell new_cell(new_val);
779 // delay creature move for grid/cell to grid/cell moves
780 if( old_cell.DiffCell(new_cell) || old_cell.DiffGrid(new_cell) )
782 #ifdef MANGOS_DEBUG
783 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
784 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());
785 #endif
786 AddCreatureToMoveList(creature,x,y,z,ang);
787 // in diffcell/diffgrid case notifiers called at finishing move creature in Map::MoveAllCreaturesInMoveList
789 else
791 creature->Relocate(x, y, z, ang);
792 CreatureRelocationNotify(creature,new_cell,new_val);
794 assert(CheckGridIntegrity(creature,true));
797 void Map::AddCreatureToMoveList(Creature *c, float x, float y, float z, float ang)
799 if(!c)
800 return;
802 i_creaturesToMove[c] = CreatureMover(x,y,z,ang);
805 void Map::MoveAllCreaturesInMoveList()
807 while(!i_creaturesToMove.empty())
809 // get data and remove element;
810 CreatureMoveList::iterator iter = i_creaturesToMove.begin();
811 Creature* c = iter->first;
812 CreatureMover cm = iter->second;
813 i_creaturesToMove.erase(iter);
815 // calculate cells
816 CellPair new_val = MaNGOS::ComputeCellPair(cm.x, cm.y);
817 Cell new_cell(new_val);
819 // do move or do move to respawn or remove creature if previous all fail
820 if(CreatureCellRelocation(c,new_cell))
822 // update pos
823 c->Relocate(cm.x, cm.y, cm.z, cm.ang);
824 CreatureRelocationNotify(c,new_cell,new_cell.cellPair());
826 else
828 // if creature can't be move in new cell/grid (not loaded) move it to repawn cell/grid
829 // creature coordinates will be updated and notifiers send
830 if(!CreatureRespawnRelocation(c))
832 // ... or unload (if respawn grid also not loaded)
833 #ifdef MANGOS_DEBUG
834 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
835 sLog.outDebug("Creature (GUID: %u Entry: %u ) can't be move to unloaded respawn grid.",c->GetGUIDLow(),c->GetEntry());
836 #endif
837 c->CleanupsBeforeDelete();
838 AddObjectToRemoveList(c);
844 bool Map::CreatureCellRelocation(Creature *c, Cell new_cell)
846 Cell const& old_cell = c->GetCurrentCell();
847 if(!old_cell.DiffGrid(new_cell) ) // in same grid
849 // if in same cell then none do
850 if(old_cell.DiffCell(new_cell))
852 #ifdef MANGOS_DEBUG
853 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
854 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());
855 #endif
857 if( !old_cell.DiffGrid(new_cell) )
859 RemoveFromGrid(c,getNGrid(old_cell.GridX(), old_cell.GridY()),old_cell);
860 AddToGrid(c,getNGrid(new_cell.GridX(), new_cell.GridY()),new_cell);
861 c->SetCurrentCell(new_cell);
864 else
866 #ifdef MANGOS_DEBUG
867 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
868 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());
869 #endif
872 else // in diff. grids
873 if(loaded(GridPair(new_cell.GridX(), new_cell.GridY())))
875 #ifdef MANGOS_DEBUG
876 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
877 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());
878 #endif
880 RemoveFromGrid(c,getNGrid(old_cell.GridX(), old_cell.GridY()),old_cell);
882 EnsureGridCreated(GridPair(new_cell.GridX(), new_cell.GridY()));
883 AddToGrid(c,getNGrid(new_cell.GridX(), new_cell.GridY()),new_cell);
886 else
888 #ifdef MANGOS_DEBUG
889 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
890 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());
891 #endif
892 return false;
895 return true;
898 bool Map::CreatureRespawnRelocation(Creature *c)
900 float resp_x, resp_y, resp_z, resp_o;
901 c->GetRespawnCoord(resp_x, resp_y, resp_z, &resp_o);
903 CellPair resp_val = MaNGOS::ComputeCellPair(resp_x, resp_y);
904 Cell resp_cell(resp_val);
906 c->CombatStop();
907 c->GetMotionMaster()->Clear();
909 #ifdef MANGOS_DEBUG
910 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
911 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());
912 #endif
914 // teleport it to respawn point (like normal respawn if player see)
915 if(CreatureCellRelocation(c,resp_cell))
917 c->Relocate(resp_x, resp_y, resp_z, resp_o);
918 c->GetMotionMaster()->Initialize(); // prevent possible problems with default move generators
919 CreatureRelocationNotify(c,resp_cell,resp_cell.cellPair());
920 return true;
922 else
923 return false;
926 bool Map::UnloadGrid(const uint32 &x, const uint32 &y, bool pForce)
928 NGridType *grid = getNGrid(x, y);
929 assert( grid != NULL);
932 if(!pForce && PlayersNearGrid(x, y) )
933 return false;
935 DEBUG_LOG("Unloading grid[%u,%u] for map %u", x,y, i_id);
936 ObjectGridUnloader unloader(*grid);
938 // Finish creature moves, remove and delete all creatures with delayed remove before moving to respawn grids
939 // Must know real mob position before move
940 DoDelayedMovesAndRemoves();
942 // move creatures to respawn grids if this is diff.grid or to remove list
943 unloader.MoveToRespawnN();
945 // Finish creature moves, remove and delete all creatures with delayed remove before unload
946 DoDelayedMovesAndRemoves();
948 unloader.UnloadN();
949 delete getNGrid(x, y);
950 setNGrid(NULL, x, y);
952 int gx=63-x;
953 int gy=63-y;
955 // delete grid map, but don't delete if it is from parent map (and thus only reference)
956 //+++if (GridMaps[gx][gy]) don't check for GridMaps[gx][gy], we might have to unload vmaps
958 if (i_InstanceId == 0)
960 if(GridMaps[gx][gy]) delete (GridMaps[gx][gy]);
961 // x and y are swapped
962 VMAP::VMapFactory::createOrGetVMapManager()->unloadMap(GetId(), gy, gx);
964 else
965 ((MapInstanced*)(MapManager::Instance().GetBaseMap(i_id)))->RemoveGridMapReference(GridPair(gx, gy));
966 GridMaps[gx][gy] = NULL;
968 DEBUG_LOG("Unloading grid[%u,%u] for map %u finished", x,y, i_id);
969 return true;
972 void Map::UnloadAll(bool pForce)
974 // clear all delayed moves, useless anyway do this moves before map unload.
975 i_creaturesToMove.clear();
977 for (GridRefManager<NGridType>::iterator i = GridRefManager<NGridType>::begin(); i != GridRefManager<NGridType>::end(); )
979 NGridType &grid(*i->getSource());
980 ++i;
981 UnloadGrid(grid.getX(), grid.getY(), pForce); // deletes the grid and removes it from the GridRefManager
985 float Map::GetHeight(float x, float y, float z, bool pUseVmaps) const
987 GridPair p = MaNGOS::ComputeGridPair(x, y);
989 // half opt method
990 int gx=(int)(32-x/SIZE_OF_GRIDS); //grid x
991 int gy=(int)(32-y/SIZE_OF_GRIDS); //grid y
993 float lx=MAP_RESOLUTION*(32 -x/SIZE_OF_GRIDS - gx);
994 float ly=MAP_RESOLUTION*(32 -y/SIZE_OF_GRIDS - gy);
996 // ensure GridMap is loaded
997 const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
999 // find raw .map surface under Z coordinates
1000 float mapHeight;
1001 if(GridMap* gmap = GridMaps[gx][gy])
1003 int lx_int = (int)lx;
1004 int ly_int = (int)ly;
1006 float zi[4];
1007 // Probe 4 nearest points (except border cases)
1008 zi[0] = gmap->Z[lx_int][ly_int];
1009 zi[1] = lx < MAP_RESOLUTION-1 ? gmap->Z[lx_int+1][ly_int] : zi[0];
1010 zi[2] = ly < MAP_RESOLUTION-1 ? gmap->Z[lx_int][ly_int+1] : zi[0];
1011 zi[3] = lx < MAP_RESOLUTION-1 && ly < MAP_RESOLUTION-1 ? gmap->Z[lx_int+1][ly_int+1] : zi[0];
1012 // Recalculate them like if their x,y positions were in the range 0,1
1013 float b[4];
1014 b[0] = zi[0];
1015 b[1] = zi[1]-zi[0];
1016 b[2] = zi[2]-zi[0];
1017 b[3] = zi[0]-zi[1]-zi[2]+zi[3];
1018 // Normalize the dx and dy to be in range 0..1
1019 float fact_x = lx - lx_int;
1020 float fact_y = ly - ly_int;
1021 // Use the simplified bilinear equation, as described in [url="http://en.wikipedia.org/wiki/Bilinear_interpolation"]http://en.wikipedia.org/wiki/Bilinear_interpolation[/url]
1022 float _mapheight = b[0] + (b[1]*fact_x) + (b[2]*fact_y) + (b[3]*fact_x*fact_y);
1024 // look from a bit higher pos to find the floor, ignore under surface case
1025 if(z + 2.0f > _mapheight)
1026 mapHeight = _mapheight;
1027 else
1028 mapHeight = VMAP_INVALID_HEIGHT_VALUE;
1030 else
1031 mapHeight = VMAP_INVALID_HEIGHT_VALUE;
1033 float vmapHeight;
1034 if(pUseVmaps)
1036 VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager();
1037 if(vmgr->isHeightCalcEnabled())
1039 // look from a bit higher pos to find the floor
1040 vmapHeight = vmgr->getHeight(GetId(), x, y, z + 2.0f);
1042 else
1043 vmapHeight = VMAP_INVALID_HEIGHT_VALUE;
1045 else
1046 vmapHeight = VMAP_INVALID_HEIGHT_VALUE;
1048 // mapHeight set for any above raw ground Z or <= INVALID_HEIGHT
1049 // vmapheight set for any under Z value or <= INVALID_HEIGHT
1051 if( vmapHeight > INVALID_HEIGHT )
1053 if( mapHeight > INVALID_HEIGHT )
1055 // we have mapheight and vmapheight and must select more appropriate
1057 // we are already under the surface or vmap height above map heigt
1058 // or if the distance of the vmap height is less the land height distance
1059 if( z < mapHeight || vmapHeight > mapHeight || fabs(mapHeight-z) > fabs(vmapHeight-z) )
1060 return vmapHeight;
1061 else
1062 return mapHeight; // better use .map surface height
1065 else
1066 return vmapHeight; // we have only vmapHeight (if have)
1068 else
1070 if(!pUseVmaps)
1071 return mapHeight; // explicitly use map data (if have)
1072 else if(mapHeight > INVALID_HEIGHT && (z < mapHeight + 2 || z == MAX_HEIGHT))
1073 return mapHeight; // explicitly use map data if original z < mapHeight but map found (z+2 > mapHeight)
1074 else
1075 return VMAP_INVALID_HEIGHT_VALUE; // we not have any height
1079 uint16 Map::GetAreaFlag(float x, float y ) const
1081 //local x,y coords
1082 float lx,ly;
1083 int gx,gy;
1084 GridPair p = MaNGOS::ComputeGridPair(x, y);
1086 // half opt method
1087 gx=(int)(32-x/SIZE_OF_GRIDS) ; //grid x
1088 gy=(int)(32-y/SIZE_OF_GRIDS); //grid y
1090 lx=16*(32 -x/SIZE_OF_GRIDS - gx);
1091 ly=16*(32 -y/SIZE_OF_GRIDS - gy);
1092 //DEBUG_LOG("my %d %d si %d %d",gx,gy,p.x_coord,p.y_coord);
1094 // ensure GridMap is loaded
1095 const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
1097 if(GridMaps[gx][gy])
1098 return GridMaps[gx][gy]->area_flag[(int)(lx)][(int)(ly)];
1099 // this used while not all *.map files generated (instances)
1100 else
1101 return GetAreaFlagByMapId(i_id);
1104 uint8 Map::GetTerrainType(float x, float y ) const
1106 //local x,y coords
1107 float lx,ly;
1108 int gx,gy;
1110 // half opt method
1111 gx=(int)(32-x/SIZE_OF_GRIDS) ; //grid x
1112 gy=(int)(32-y/SIZE_OF_GRIDS); //grid y
1114 lx=16*(32 -x/SIZE_OF_GRIDS - gx);
1115 ly=16*(32 -y/SIZE_OF_GRIDS - gy);
1117 // ensure GridMap is loaded
1118 const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
1120 if(GridMaps[gx][gy])
1121 return GridMaps[gx][gy]->terrain_type[(int)(lx)][(int)(ly)];
1122 else
1123 return 0;
1126 float Map::GetWaterLevel(float x, float y ) const
1128 //local x,y coords
1129 float lx,ly;
1130 int gx,gy;
1132 // half opt method
1133 gx=(int)(32-x/SIZE_OF_GRIDS) ; //grid x
1134 gy=(int)(32-y/SIZE_OF_GRIDS); //grid y
1136 lx=128*(32 -x/SIZE_OF_GRIDS - gx);
1137 ly=128*(32 -y/SIZE_OF_GRIDS - gy);
1139 // ensure GridMap is loaded
1140 const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
1142 if(GridMaps[gx][gy])
1143 return GridMaps[gx][gy]->liquid_level[(int)(lx)][(int)(ly)];
1144 else
1145 return 0;
1148 uint32 Map::GetAreaId(uint16 areaflag,uint32 map_id)
1150 AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
1152 if (entry)
1153 return entry->ID;
1154 else
1155 return 0;
1158 uint32 Map::GetZoneId(uint16 areaflag,uint32 map_id)
1160 AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
1162 if( entry )
1163 return ( entry->zone != 0 ) ? entry->zone : entry->ID;
1164 else
1165 return 0;
1168 bool Map::IsInWater(float x, float y, float pZ) const
1170 // This method is called too often to use vamps for that (4. parameter = false).
1171 // The pZ pos is taken anyway for future use
1172 float z = GetHeight(x,y,pZ,false); // use .map base surface height
1174 // underground or instance without vmap
1175 if(z <= INVALID_HEIGHT)
1176 return false;
1178 float water_z = GetWaterLevel(x,y);
1179 uint8 flag = GetTerrainType(x,y);
1180 return (z < (water_z-2)) && (flag & 0x01);
1183 bool Map::IsUnderWater(float x, float y, float z) const
1185 float water_z = GetWaterLevel(x,y);
1186 uint8 flag = GetTerrainType(x,y);
1187 return (z < (water_z-2)) && (flag & 0x01);
1190 bool Map::CheckGridIntegrity(Creature* c, bool moved) const
1192 Cell const& cur_cell = c->GetCurrentCell();
1194 CellPair xy_val = MaNGOS::ComputeCellPair(c->GetPositionX(), c->GetPositionY());
1195 Cell xy_cell(xy_val);
1196 if(xy_cell != cur_cell)
1198 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]",
1199 (c->GetTypeId()==TYPEID_PLAYER ? "Player" : "Creature"),c->GetGUIDLow(),
1200 c->GetPositionX(),c->GetPositionY(),(moved ? "final" : "original"),
1201 cur_cell.GridX(), cur_cell.GridY(), cur_cell.CellX(), cur_cell.CellY(),
1202 xy_cell.GridX(), xy_cell.GridY(), xy_cell.CellX(), xy_cell.CellY());
1203 return true; // not crash at error, just output error in debug mode
1206 return true;
1209 const char* Map::GetMapName() const
1211 return i_mapEntry ? i_mapEntry->name[sWorld.GetDefaultDbcLocale()] : "UNNAMEDMAP\x0";
1214 void Map::UpdateObjectVisibility( WorldObject* obj, Cell cell, CellPair cellpair)
1216 cell.data.Part.reserved = ALL_DISTRICT;
1217 cell.SetNoCreate();
1218 MaNGOS::VisibleChangesNotifier notifier(*obj);
1219 TypeContainerVisitor<MaNGOS::VisibleChangesNotifier, WorldTypeMapContainer > player_notifier(notifier);
1220 CellLock<GridReadGuard> cell_lock(cell, cellpair);
1221 cell_lock->Visit(cell_lock, player_notifier, *this);
1224 void Map::UpdatePlayerVisibility( Player* player, Cell cell, CellPair cellpair )
1226 cell.data.Part.reserved = ALL_DISTRICT;
1228 MaNGOS::PlayerNotifier pl_notifier(*player);
1229 TypeContainerVisitor<MaNGOS::PlayerNotifier, WorldTypeMapContainer > player_notifier(pl_notifier);
1231 CellLock<ReadGuard> cell_lock(cell, cellpair);
1232 cell_lock->Visit(cell_lock, player_notifier, *this);
1235 void Map::UpdateObjectsVisibilityFor( Player* player, Cell cell, CellPair cellpair )
1237 MaNGOS::VisibleNotifier notifier(*player);
1239 cell.data.Part.reserved = ALL_DISTRICT;
1240 cell.SetNoCreate();
1241 TypeContainerVisitor<MaNGOS::VisibleNotifier, WorldTypeMapContainer > world_notifier(notifier);
1242 TypeContainerVisitor<MaNGOS::VisibleNotifier, GridTypeMapContainer > grid_notifier(notifier);
1243 CellLock<GridReadGuard> cell_lock(cell, cellpair);
1244 cell_lock->Visit(cell_lock, world_notifier, *this);
1245 cell_lock->Visit(cell_lock, grid_notifier, *this);
1247 // send data
1248 notifier.Notify();
1251 void Map::PlayerRelocationNotify( Player* player, Cell cell, CellPair cellpair )
1253 CellLock<ReadGuard> cell_lock(cell, cellpair);
1254 MaNGOS::PlayerRelocationNotifier relocationNotifier(*player);
1255 cell.data.Part.reserved = ALL_DISTRICT;
1257 TypeContainerVisitor<MaNGOS::PlayerRelocationNotifier, GridTypeMapContainer > p2grid_relocation(relocationNotifier);
1258 TypeContainerVisitor<MaNGOS::PlayerRelocationNotifier, WorldTypeMapContainer > p2world_relocation(relocationNotifier);
1260 cell_lock->Visit(cell_lock, p2grid_relocation, *this);
1261 cell_lock->Visit(cell_lock, p2world_relocation, *this);
1264 void Map::CreatureRelocationNotify(Creature *creature, Cell cell, CellPair cellpair)
1266 CellLock<ReadGuard> cell_lock(cell, cellpair);
1267 MaNGOS::CreatureRelocationNotifier relocationNotifier(*creature);
1268 cell.data.Part.reserved = ALL_DISTRICT;
1269 cell.SetNoCreate(); // not trigger load unloaded grids at notifier call
1271 TypeContainerVisitor<MaNGOS::CreatureRelocationNotifier, WorldTypeMapContainer > c2world_relocation(relocationNotifier);
1272 TypeContainerVisitor<MaNGOS::CreatureRelocationNotifier, GridTypeMapContainer > c2grid_relocation(relocationNotifier);
1274 cell_lock->Visit(cell_lock, c2world_relocation, *this);
1275 cell_lock->Visit(cell_lock, c2grid_relocation, *this);
1278 void Map::SendInitSelf( Player * player )
1280 sLog.outDetail("Creating player data for himself %u", player->GetGUIDLow());
1282 UpdateData data;
1284 bool hasTransport = false;
1286 // attach to player data current transport data
1287 if(Transport* transport = player->GetTransport())
1289 hasTransport = true;
1290 transport->BuildCreateUpdateBlockForPlayer(&data, player);
1293 // build data for self presence in world at own client (one time for map)
1294 player->BuildCreateUpdateBlockForPlayer(&data, player);
1296 // build other passengers at transport also (they always visible and marked as visible and will not send at visibility update at add to map
1297 if(Transport* transport = player->GetTransport())
1299 for(Transport::PlayerSet::const_iterator itr = transport->GetPassengers().begin();itr!=transport->GetPassengers().end();++itr)
1301 if(player!=(*itr) && player->HaveAtClient(*itr))
1303 hasTransport = true;
1304 (*itr)->BuildCreateUpdateBlockForPlayer(&data, player);
1309 WorldPacket packet;
1310 data.BuildPacket(&packet, hasTransport);
1311 player->GetSession()->SendPacket(&packet);
1314 void Map::SendInitTransports( Player * player )
1316 // Hack to send out transports
1317 MapManager::TransportMap& tmap = MapManager::Instance().m_TransportsByMap;
1319 // no transports at map
1320 if (tmap.find(player->GetMapId()) == tmap.end())
1321 return;
1323 UpdateData transData;
1325 MapManager::TransportSet& tset = tmap[player->GetMapId()];
1327 bool hasTransport = false;
1329 for (MapManager::TransportSet::iterator i = tset.begin(); i != tset.end(); ++i)
1331 if((*i) != player->GetTransport()) // send data for current transport in other place
1333 hasTransport = true;
1334 (*i)->BuildCreateUpdateBlockForPlayer(&transData, player);
1338 WorldPacket packet;
1339 transData.BuildPacket(&packet, hasTransport);
1340 player->GetSession()->SendPacket(&packet);
1343 void Map::SendRemoveTransports( Player * player )
1345 // Hack to send out transports
1346 MapManager::TransportMap& tmap = MapManager::Instance().m_TransportsByMap;
1348 // no transports at map
1349 if (tmap.find(player->GetMapId()) == tmap.end())
1350 return;
1352 UpdateData transData;
1354 MapManager::TransportSet& tset = tmap[player->GetMapId()];
1356 // except used transport
1357 for (MapManager::TransportSet::iterator i = tset.begin(); i != tset.end(); ++i)
1358 if(player->GetTransport() != (*i))
1359 (*i)->BuildOutOfRangeUpdateBlock(&transData);
1361 WorldPacket packet;
1362 transData.BuildPacket(&packet);
1363 player->GetSession()->SendPacket(&packet);
1366 inline void Map::setNGrid(NGridType *grid, uint32 x, uint32 y)
1368 if(x >= MAX_NUMBER_OF_GRIDS || y >= MAX_NUMBER_OF_GRIDS)
1370 sLog.outError("map::setNGrid() Invalid grid coordinates found: %d, %d!",x,y);
1371 assert(false);
1373 i_grids[x][y] = grid;
1376 void Map::DoDelayedMovesAndRemoves()
1378 MoveAllCreaturesInMoveList();
1379 RemoveAllObjectsInRemoveList();
1382 void Map::AddObjectToRemoveList(WorldObject *obj)
1384 assert(obj->GetMapId()==GetId() && obj->GetInstanceId()==GetInstanceId());
1386 i_objectsToRemove.insert(obj);
1387 //sLog.outDebug("Object (GUID: %u TypeId: %u ) added to removing list.",obj->GetGUIDLow(),obj->GetTypeId());
1390 void Map::RemoveAllObjectsInRemoveList()
1392 if(i_objectsToRemove.empty())
1393 return;
1395 //sLog.outDebug("Object remover 1 check.");
1396 while(!i_objectsToRemove.empty())
1398 WorldObject* obj = *i_objectsToRemove.begin();
1399 i_objectsToRemove.erase(i_objectsToRemove.begin());
1401 switch(obj->GetTypeId())
1403 case TYPEID_CORPSE:
1405 Corpse* corpse = ObjectAccessor::Instance().GetCorpse(*obj, obj->GetGUID());
1406 if (!corpse)
1407 sLog.outError("ERROR: Try delete corpse/bones %u that not in map", obj->GetGUIDLow());
1408 else
1409 Remove(corpse,true);
1410 break;
1412 case TYPEID_DYNAMICOBJECT:
1413 Remove((DynamicObject*)obj,true);
1414 break;
1415 case TYPEID_GAMEOBJECT:
1416 Remove((GameObject*)obj,true);
1417 break;
1418 case TYPEID_UNIT:
1419 // in case triggered sequence some spell can continue casting after prev CleanupsBeforeDelete call
1420 // make sure that like sources auras/etc removed before destructor start
1421 ((Creature*)obj)->CleanupsBeforeDelete ();
1422 Remove((Creature*)obj,true);
1423 break;
1424 default:
1425 sLog.outError("Non-grid object (TypeId: %u) in grid object removing list, ignored.",obj->GetTypeId());
1426 break;
1429 //sLog.outDebug("Object remover 2 check.");
1432 bool Map::CanUnload(const uint32 &diff)
1434 if(!m_unloadTimer) return false;
1435 if(m_unloadTimer < diff) return true;
1436 m_unloadTimer -= diff;
1437 return false;
1440 uint32 Map::GetPlayersCountExceptGMs() const
1442 uint32 count = 0;
1443 for(MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
1444 if(!itr->getSource()->isGameMaster())
1445 ++count;
1446 return count;
1449 void Map::SendToPlayers(WorldPacket const* data) const
1451 for(MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
1452 itr->getSource()->GetSession()->SendPacket(data);
1455 bool Map::PlayersNearGrid(uint32 x, uint32 y) const
1457 CellPair cell_min(x*MAX_NUMBER_OF_CELLS, y*MAX_NUMBER_OF_CELLS);
1458 CellPair cell_max(cell_min.x_coord + MAX_NUMBER_OF_CELLS, cell_min.y_coord+MAX_NUMBER_OF_CELLS);
1459 cell_min << 2;
1460 cell_min -= 2;
1461 cell_max >> 2;
1462 cell_max += 2;
1464 for(MapRefManager::const_iterator iter = m_mapRefManager.begin(); iter != m_mapRefManager.end(); ++iter)
1466 Player* plr = iter->getSource();
1468 CellPair p = MaNGOS::ComputeCellPair(plr->GetPositionX(), plr->GetPositionY());
1469 if( (cell_min.x_coord <= p.x_coord && p.x_coord <= cell_max.x_coord) &&
1470 (cell_min.y_coord <= p.y_coord && p.y_coord <= cell_max.y_coord) )
1471 return true;
1474 return false;
1477 template void Map::Add(Corpse *);
1478 template void Map::Add(Creature *);
1479 template void Map::Add(GameObject *);
1480 template void Map::Add(DynamicObject *);
1482 template void Map::Remove(Corpse *,bool);
1483 template void Map::Remove(Creature *,bool);
1484 template void Map::Remove(GameObject *, bool);
1485 template void Map::Remove(DynamicObject *, bool);
1487 /* ******* Dungeon Instance Maps ******* */
1489 InstanceMap::InstanceMap(uint32 id, time_t expiry, uint32 InstanceId, uint8 SpawnMode)
1490 : Map(id, expiry, InstanceId, SpawnMode), i_data(NULL),
1491 m_resetAfterUnload(false), m_unloadWhenEmpty(false)
1493 // the timer is started by default, and stopped when the first player joins
1494 // this make sure it gets unloaded if for some reason no player joins
1495 m_unloadTimer = std::max(sWorld.getConfig(CONFIG_INSTANCE_UNLOAD_DELAY), (uint32)MIN_UNLOAD_DELAY);
1498 InstanceMap::~InstanceMap()
1500 if(i_data)
1502 delete i_data;
1503 i_data = NULL;
1508 Do map specific checks to see if the player can enter
1510 bool InstanceMap::CanEnter(Player *player)
1512 if(player->GetMapRef().getTarget() == this)
1514 sLog.outError("InstanceMap::CanEnter - player %s(%u) already in map %d,%d,%d!", player->GetName(), player->GetGUIDLow(), GetId(), GetInstanceId(), GetSpawnMode());
1515 assert(false);
1516 return false;
1519 // cannot enter if the instance is full (player cap), GMs don't count
1520 InstanceTemplate const* iTemplate = objmgr.GetInstanceTemplate(GetId());
1521 if (!player->isGameMaster() && GetPlayersCountExceptGMs() >= iTemplate->maxPlayers)
1523 sLog.outDetail("MAP: Instance '%u' of map '%s' cannot have more than '%u' players. Player '%s' rejected", GetInstanceId(), GetMapName(), iTemplate->maxPlayers, player->GetName());
1524 player->SendTransferAborted(GetId(), TRANSFER_ABORT_MAX_PLAYERS);
1525 return false;
1528 // cannot enter while players in the instance are in combat
1529 Group *pGroup = player->GetGroup();
1530 if(pGroup && pGroup->InCombatToInstance(GetInstanceId()) && player->isAlive() && player->GetMapId() != GetId())
1532 player->SendTransferAborted(GetId(), TRANSFER_ABORT_ZONE_IN_COMBAT);
1533 return false;
1536 return Map::CanEnter(player);
1540 Do map specific checks and add the player to the map if successful.
1542 bool InstanceMap::Add(Player *player)
1544 // TODO: Not sure about checking player level: already done in HandleAreaTriggerOpcode
1545 // GMs still can teleport player in instance.
1546 // Is it needed?
1549 Guard guard(*this);
1550 if(!CanEnter(player))
1551 return false;
1553 // get or create an instance save for the map
1554 InstanceSave *mapSave = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1555 if(!mapSave)
1557 sLog.outDetail("InstanceMap::Add: creating instance save for map %d spawnmode %d with instance id %d", GetId(), GetSpawnMode(), GetInstanceId());
1558 mapSave = sInstanceSaveManager.AddInstanceSave(GetId(), GetInstanceId(), GetSpawnMode(), 0, true);
1561 // check for existing instance binds
1562 InstancePlayerBind *playerBind = player->GetBoundInstance(GetId(), GetSpawnMode());
1563 if(playerBind && playerBind->perm)
1565 // cannot enter other instances if bound permanently
1566 if(playerBind->save != mapSave)
1568 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());
1569 assert(false);
1572 else
1574 Group *pGroup = player->GetGroup();
1575 if(pGroup)
1577 // solo saves should be reset when entering a group
1578 InstanceGroupBind *groupBind = pGroup->GetBoundInstance(GetId(), GetSpawnMode());
1579 if(playerBind)
1581 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());
1582 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());
1583 assert(false);
1585 // bind to the group or keep using the group save
1586 if(!groupBind)
1587 pGroup->BindToInstance(mapSave, false);
1588 else
1590 // cannot jump to a different instance without resetting it
1591 if(groupBind->save != mapSave)
1593 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());
1594 if(mapSave)
1595 sLog.outError("MapSave players: %d, group count: %d", mapSave->GetPlayerCount(), mapSave->GetGroupCount());
1596 else
1597 sLog.outError("MapSave NULL");
1598 if(groupBind->save)
1599 sLog.outError("GroupBind save players: %d, group count: %d", groupBind->save->GetPlayerCount(), groupBind->save->GetGroupCount());
1600 else
1601 sLog.outError("GroupBind save NULL");
1602 assert(false);
1604 // if the group/leader is permanently bound to the instance
1605 // players also become permanently bound when they enter
1606 if(groupBind->perm)
1608 WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
1609 data << uint32(0);
1610 player->GetSession()->SendPacket(&data);
1611 player->BindToInstance(mapSave, true);
1615 else
1617 // set up a solo bind or continue using it
1618 if(!playerBind)
1619 player->BindToInstance(mapSave, false);
1620 else
1621 // cannot jump to a different instance without resetting it
1622 assert(playerBind->save == mapSave);
1626 if(i_data) i_data->OnPlayerEnter(player);
1627 // for normal instances cancel the reset schedule when the
1628 // first player enters (no players yet)
1629 SetResetSchedule(false);
1631 player->SendInitWorldStates();
1632 sLog.outDetail("MAP: Player '%s' entered the instance '%u' of map '%s'", player->GetName(), GetInstanceId(), GetMapName());
1633 // initialize unload state
1634 m_unloadTimer = 0;
1635 m_resetAfterUnload = false;
1636 m_unloadWhenEmpty = false;
1639 // this will acquire the same mutex so it cannot be in the previous block
1640 Map::Add(player);
1641 return true;
1644 void InstanceMap::Update(const uint32& t_diff)
1646 Map::Update(t_diff);
1648 if(i_data)
1649 i_data->Update(t_diff);
1652 void InstanceMap::Remove(Player *player, bool remove)
1654 sLog.outDetail("MAP: Removing player '%s' from instance '%u' of map '%s' before relocating to other map", player->GetName(), GetInstanceId(), GetMapName());
1655 //if last player set unload timer
1656 if(!m_unloadTimer && m_mapRefManager.getSize() == 1)
1657 m_unloadTimer = m_unloadWhenEmpty ? MIN_UNLOAD_DELAY : std::max(sWorld.getConfig(CONFIG_INSTANCE_UNLOAD_DELAY), (uint32)MIN_UNLOAD_DELAY);
1658 Map::Remove(player, remove);
1659 // for normal instances schedule the reset after all players have left
1660 SetResetSchedule(true);
1663 void InstanceMap::CreateInstanceData(bool load)
1665 if(i_data != NULL)
1666 return;
1668 InstanceTemplate const* mInstance = objmgr.GetInstanceTemplate(GetId());
1669 if (mInstance)
1671 i_script_id = mInstance->script_id;
1672 i_data = Script->CreateInstanceData(this);
1675 if(!i_data)
1676 return;
1678 if(load)
1680 // TODO: make a global storage for this
1681 QueryResult* result = CharacterDatabase.PQuery("SELECT data FROM instance WHERE map = '%u' AND id = '%u'", GetId(), i_InstanceId);
1682 if (result)
1684 Field* fields = result->Fetch();
1685 const char* data = fields[0].GetString();
1686 if(data)
1688 sLog.outDebug("Loading instance data for `%s` with id %u", objmgr.GetScriptName(i_script_id), i_InstanceId);
1689 i_data->Load(data);
1691 delete result;
1694 else
1696 sLog.outDebug("New instance data, \"%s\" ,initialized!", objmgr.GetScriptName(i_script_id));
1697 i_data->Initialize();
1702 Returns true if there are no players in the instance
1704 bool InstanceMap::Reset(uint8 method)
1706 // note: since the map may not be loaded when the instance needs to be reset
1707 // the instance must be deleted from the DB by InstanceSaveManager
1709 if(HavePlayers())
1711 if(method == INSTANCE_RESET_ALL)
1713 // notify the players to leave the instance so it can be reset
1714 for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
1715 itr->getSource()->SendResetFailedNotify(GetId());
1717 else
1719 if(method == INSTANCE_RESET_GLOBAL)
1721 // set the homebind timer for players inside (1 minute)
1722 for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
1723 itr->getSource()->m_InstanceValid = false;
1726 // the unload timer is not started
1727 // instead the map will unload immediately after the players have left
1728 m_unloadWhenEmpty = true;
1729 m_resetAfterUnload = true;
1732 else
1734 // unloaded at next update
1735 m_unloadTimer = MIN_UNLOAD_DELAY;
1736 m_resetAfterUnload = true;
1739 return m_mapRefManager.isEmpty();
1742 void InstanceMap::PermBindAllPlayers(Player *player)
1744 InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1745 if(!save)
1747 sLog.outError("Cannot bind players, no instance save available for map!\n");
1748 return;
1751 Group *group = player->GetGroup();
1752 // group members outside the instance group don't get bound
1753 for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
1755 Player* plr = itr->getSource();
1756 // players inside an instance cannot be bound to other instances
1757 // some players may already be permanently bound, in this case nothing happens
1758 InstancePlayerBind *bind = plr->GetBoundInstance(save->GetMapId(), save->GetDifficulty());
1759 if(!bind || !bind->perm)
1761 plr->BindToInstance(save, true);
1762 WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
1763 data << uint32(0);
1764 plr->GetSession()->SendPacket(&data);
1767 // if the leader is not in the instance the group will not get a perm bind
1768 if(group && group->GetLeaderGUID() == plr->GetGUID())
1769 group->BindToInstance(save, true);
1773 time_t InstanceMap::GetResetTime()
1775 InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1776 return save ? save->GetDifficulty() : DIFFICULTY_NORMAL;
1779 void InstanceMap::UnloadAll(bool pForce)
1781 if(HavePlayers())
1783 sLog.outError("InstanceMap::UnloadAll: there are still players in the instance at unload, should not happen!");
1784 for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
1786 Player* plr = itr->getSource();
1787 plr->TeleportTo(plr->m_homebindMapId, plr->m_homebindX, plr->m_homebindY, plr->m_homebindZ, plr->GetOrientation());
1791 if(m_resetAfterUnload == true)
1792 objmgr.DeleteRespawnTimeForInstance(GetInstanceId());
1794 Map::UnloadAll(pForce);
1797 void InstanceMap::SendResetWarnings(uint32 timeLeft) const
1799 for(MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
1800 itr->getSource()->SendInstanceResetWarning(GetId(), timeLeft);
1803 void InstanceMap::SetResetSchedule(bool on)
1805 // only for normal instances
1806 // the reset time is only scheduled when there are no payers inside
1807 // it is assumed that the reset time will rarely (if ever) change while the reset is scheduled
1808 if(!HavePlayers() && !IsRaid() && !IsHeroic())
1810 InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1811 if(!save) sLog.outError("InstanceMap::SetResetSchedule: cannot turn schedule %s, no save available for instance %d of %d", on ? "on" : "off", GetInstanceId(), GetId());
1812 else sInstanceSaveManager.ScheduleReset(on, save->GetResetTime(), InstanceSaveManager::InstResetEvent(0, GetId(), GetInstanceId()));
1816 /* ******* Battleground Instance Maps ******* */
1818 BattleGroundMap::BattleGroundMap(uint32 id, time_t expiry, uint32 InstanceId)
1819 : Map(id, expiry, InstanceId, DIFFICULTY_NORMAL)
1823 BattleGroundMap::~BattleGroundMap()
1827 bool BattleGroundMap::CanEnter(Player * player)
1829 if(player->GetMapRef().getTarget() == this)
1831 sLog.outError("BGMap::CanEnter - player %u already in map!", player->GetGUIDLow());
1832 assert(false);
1833 return false;
1836 if(player->GetBattleGroundId() != GetInstanceId())
1837 return false;
1839 // player number limit is checked in bgmgr, no need to do it here
1841 return Map::CanEnter(player);
1844 bool BattleGroundMap::Add(Player * player)
1847 Guard guard(*this);
1848 if(!CanEnter(player))
1849 return false;
1850 // reset instance validity, battleground maps do not homebind
1851 player->m_InstanceValid = true;
1853 return Map::Add(player);
1856 void BattleGroundMap::Remove(Player *player, bool remove)
1858 sLog.outDetail("MAP: Removing player '%s' from bg '%u' of map '%s' before relocating to other map", player->GetName(), GetInstanceId(), GetMapName());
1859 Map::Remove(player, remove);
1862 void BattleGroundMap::SetUnload()
1864 m_unloadTimer = MIN_UNLOAD_DELAY;
1867 void BattleGroundMap::UnloadAll(bool pForce)
1869 while(HavePlayers())
1871 Player * plr = m_mapRefManager.getFirst()->getSource();
1872 if(plr) (plr)->TeleportTo(plr->m_homebindMapId, plr->m_homebindX, plr->m_homebindY, plr->m_homebindZ, plr->GetOrientation());
1873 // TeleportTo removes the player from this map (if the map exists) -> calls BattleGroundMap::Remove -> invalidates the iterator.
1874 // just in case, remove the player from the list explicitly here as well to prevent a possible infinite loop
1875 // note that this remove is not needed if the code works well in other places
1876 plr->GetMapRef().unlink();
1879 Map::UnloadAll(pForce);