[7297] Fixed profession spells sorting in trainer spell list at client.
[getmangos.git] / src / game / Map.cpp
blobf5c2bd636a7ea6c1905ea3510c515223e2093d60
1 /*
2 * Copyright (C) 2005-2009 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_3.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() || obj->isVehicle())
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() || obj->isVehicle())
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(*obj,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;
1005 lx -= lx_int;
1006 ly -= ly_int;
1008 // Height stored as: h5 - its v8 grid, h1-h4 - its v9 grid
1009 // +--------------> X
1010 // | h1-------h2 Coordinates is:
1011 // | | \ 1 / | h1 0,0
1012 // | | \ / | h2 0,1
1013 // | | 2 h5 3 | h3 1,0
1014 // | | / \ | h4 1,1
1015 // | | / 4 \ | h5 1/2,1/2
1016 // | h3-------h4
1017 // V Y
1018 // For find height need
1019 // 1 - detect triangle
1020 // 2 - solve linear equation from triangle points
1022 // Calculate coefficients for solve h = a*x + b*y + c
1023 float a,b,c;
1024 // Select triangle:
1025 if (lx+ly < 1)
1027 if (lx > ly)
1029 // 1 triangle (h1, h2, h5 points)
1030 float h1 = gmap->v9[lx_int][ly_int];
1031 float h2 = gmap->v9[lx_int+1][ly_int];
1032 float h5 = 2 * gmap->v8[lx_int][ly_int];
1033 a = h2-h1;
1034 b = h5-h1-h2;
1035 c = h1;
1037 else
1039 // 2 triangle (h1, h3, h5 points)
1040 float h1 = gmap->v9[lx_int][ly_int];
1041 float h3 = gmap->v9[lx_int][ly_int+1];
1042 float h5 = 2 * gmap->v8[lx_int][ly_int];
1043 a = h5 - h1 - h3;
1044 b = h3 - h1;
1045 c = h1;
1048 else
1050 if (lx > ly)
1052 // 3 triangle (h2, h4, h5 points)
1053 float h2 = gmap->v9[lx_int+1][ly_int];
1054 float h4 = gmap->v9[lx_int+1][ly_int+1];
1055 float h5 = 2 * gmap->v8[lx_int][ly_int];
1056 a = h2 + h4 - h5;
1057 b = h4 - h2;
1058 c = h5 - h4;
1060 else
1062 // 4 triangle (h3, h4, h5 points)
1063 float h3 = gmap->v9[lx_int][ly_int+1];
1064 float h4 = gmap->v9[lx_int+1][ly_int+1];
1065 float h5 = 2 * gmap->v8[lx_int][ly_int];
1066 a = h4 - h3;
1067 b = h3 + h4 - h5;
1068 c = h5 - h4;
1071 // Calculate height
1072 float _mapheight = a * lx + b * ly + c;
1074 // look from a bit higher pos to find the floor, ignore under surface case
1075 if(z + 2.0f > _mapheight)
1076 mapHeight = _mapheight;
1077 else
1078 mapHeight = VMAP_INVALID_HEIGHT_VALUE;
1080 else
1081 mapHeight = VMAP_INVALID_HEIGHT_VALUE;
1083 float vmapHeight;
1084 if(pUseVmaps)
1086 VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager();
1087 if(vmgr->isHeightCalcEnabled())
1089 // look from a bit higher pos to find the floor
1090 vmapHeight = vmgr->getHeight(GetId(), x, y, z + 2.0f);
1092 else
1093 vmapHeight = VMAP_INVALID_HEIGHT_VALUE;
1095 else
1096 vmapHeight = VMAP_INVALID_HEIGHT_VALUE;
1098 // mapHeight set for any above raw ground Z or <= INVALID_HEIGHT
1099 // vmapheight set for any under Z value or <= INVALID_HEIGHT
1101 if( vmapHeight > INVALID_HEIGHT )
1103 if( mapHeight > INVALID_HEIGHT )
1105 // we have mapheight and vmapheight and must select more appropriate
1107 // we are already under the surface or vmap height above map heigt
1108 // or if the distance of the vmap height is less the land height distance
1109 if( z < mapHeight || vmapHeight > mapHeight || fabs(mapHeight-z) > fabs(vmapHeight-z) )
1110 return vmapHeight;
1111 else
1112 return mapHeight; // better use .map surface height
1115 else
1116 return vmapHeight; // we have only vmapHeight (if have)
1118 else
1120 if(!pUseVmaps)
1121 return mapHeight; // explicitly use map data (if have)
1122 else if(mapHeight > INVALID_HEIGHT && (z < mapHeight + 2 || z == MAX_HEIGHT))
1123 return mapHeight; // explicitly use map data if original z < mapHeight but map found (z+2 > mapHeight)
1124 else
1125 return VMAP_INVALID_HEIGHT_VALUE; // we not have any height
1129 uint16 Map::GetAreaFlag(float x, float y, float z) const
1131 //local x,y coords
1132 float lx,ly;
1133 int gx,gy;
1134 GridPair p = MaNGOS::ComputeGridPair(x, y);
1136 // half opt method
1137 gx=(int)(32-x/SIZE_OF_GRIDS) ; //grid x
1138 gy=(int)(32-y/SIZE_OF_GRIDS); //grid y
1140 lx=16*(32 -x/SIZE_OF_GRIDS - gx);
1141 ly=16*(32 -y/SIZE_OF_GRIDS - gy);
1142 //DEBUG_LOG("my %d %d si %d %d",gx,gy,p.x_coord,p.y_coord);
1144 // ensure GridMap is loaded
1145 const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
1147 uint16 areaflag;
1148 if(GridMaps[gx][gy])
1149 areaflag = GridMaps[gx][gy]->area_flag[(int)(lx)][(int)(ly)];
1150 // this used while not all *.map files generated (instances)
1151 else
1152 areaflag = GetAreaFlagByMapId(i_id);
1154 //FIXME: some hacks for areas above or underground for ground area
1155 // required for area specific spells/etc, until map/vmap data
1156 // not provided correct areaflag with this hacks
1157 switch(areaflag)
1159 // Acherus: The Ebon Hold (Plaguelands: The Scarlet Enclave)
1160 case 1984: // Plaguelands: The Scarlet Enclave
1161 case 2076: // Death's Breach (Plaguelands: The Scarlet Enclave)
1162 case 2745: // The Noxious Pass (Plaguelands: The Scarlet Enclave)
1163 if(z > 350.0f) areaflag = 2048; break;
1164 // Acherus: The Ebon Hold (Eastern Plaguelands)
1165 case 856: // The Noxious Glade (Eastern Plaguelands)
1166 case 2456: // Death's Breach (Eastern Plaguelands)
1167 if(z > 350.0f) areaflag = 1950; break;
1170 return areaflag;
1173 uint8 Map::GetTerrainType(float x, float y ) const
1175 //local x,y coords
1176 float lx,ly;
1177 int gx,gy;
1179 // half opt method
1180 gx=(int)(32-x/SIZE_OF_GRIDS) ; //grid x
1181 gy=(int)(32-y/SIZE_OF_GRIDS); //grid y
1183 lx=16*(32 -x/SIZE_OF_GRIDS - gx);
1184 ly=16*(32 -y/SIZE_OF_GRIDS - gy);
1186 // ensure GridMap is loaded
1187 const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
1189 if(GridMaps[gx][gy])
1190 return GridMaps[gx][gy]->terrain_type[(int)(lx)][(int)(ly)];
1191 else
1192 return 0;
1195 float Map::GetWaterLevel(float x, float y ) const
1197 //local x,y coords
1198 float lx,ly;
1199 int gx,gy;
1201 // half opt method
1202 gx=(int)(32-x/SIZE_OF_GRIDS) ; //grid x
1203 gy=(int)(32-y/SIZE_OF_GRIDS); //grid y
1205 lx=128*(32 -x/SIZE_OF_GRIDS - gx);
1206 ly=128*(32 -y/SIZE_OF_GRIDS - gy);
1208 // ensure GridMap is loaded
1209 const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
1211 if(GridMaps[gx][gy])
1212 return GridMaps[gx][gy]->liquid_level[(int)(lx)][(int)(ly)];
1213 else
1214 return 0;
1217 uint32 Map::GetAreaId(uint16 areaflag,uint32 map_id)
1219 AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
1221 if (entry)
1222 return entry->ID;
1223 else
1224 return 0;
1227 uint32 Map::GetZoneId(uint16 areaflag,uint32 map_id)
1229 AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
1231 if( entry )
1232 return ( entry->zone != 0 ) ? entry->zone : entry->ID;
1233 else
1234 return 0;
1237 bool Map::IsInWater(float x, float y, float pZ) const
1239 // This method is called too often to use vamps for that (4. parameter = false).
1240 // The pZ pos is taken anyway for future use
1241 float z = GetHeight(x,y,pZ,false); // use .map base surface height
1243 // underground or instance without vmap
1244 if(z <= INVALID_HEIGHT)
1245 return false;
1247 float water_z = GetWaterLevel(x,y);
1248 uint8 flag = GetTerrainType(x,y);
1249 return (z < (water_z-2)) && (flag & 0x01);
1252 bool Map::IsUnderWater(float x, float y, float z) const
1254 float water_z = GetWaterLevel(x,y);
1255 uint8 flag = GetTerrainType(x,y);
1256 return (z < (water_z-2)) && (flag & 0x01);
1259 bool Map::CheckGridIntegrity(Creature* c, bool moved) const
1261 Cell const& cur_cell = c->GetCurrentCell();
1263 CellPair xy_val = MaNGOS::ComputeCellPair(c->GetPositionX(), c->GetPositionY());
1264 Cell xy_cell(xy_val);
1265 if(xy_cell != cur_cell)
1267 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]",
1268 (c->GetTypeId()==TYPEID_PLAYER ? "Player" : "Creature"),c->GetGUIDLow(),
1269 c->GetPositionX(),c->GetPositionY(),(moved ? "final" : "original"),
1270 cur_cell.GridX(), cur_cell.GridY(), cur_cell.CellX(), cur_cell.CellY(),
1271 xy_cell.GridX(), xy_cell.GridY(), xy_cell.CellX(), xy_cell.CellY());
1272 return true; // not crash at error, just output error in debug mode
1275 return true;
1278 const char* Map::GetMapName() const
1280 return i_mapEntry ? i_mapEntry->name[sWorld.GetDefaultDbcLocale()] : "UNNAMEDMAP\x0";
1283 void Map::UpdateObjectVisibility( WorldObject* obj, Cell cell, CellPair cellpair)
1285 cell.data.Part.reserved = ALL_DISTRICT;
1286 cell.SetNoCreate();
1287 MaNGOS::VisibleChangesNotifier notifier(*obj);
1288 TypeContainerVisitor<MaNGOS::VisibleChangesNotifier, WorldTypeMapContainer > player_notifier(notifier);
1289 CellLock<GridReadGuard> cell_lock(cell, cellpair);
1290 cell_lock->Visit(cell_lock, player_notifier, *this);
1293 void Map::UpdatePlayerVisibility( Player* player, Cell cell, CellPair cellpair )
1295 cell.data.Part.reserved = ALL_DISTRICT;
1297 MaNGOS::PlayerNotifier pl_notifier(*player);
1298 TypeContainerVisitor<MaNGOS::PlayerNotifier, WorldTypeMapContainer > player_notifier(pl_notifier);
1300 CellLock<ReadGuard> cell_lock(cell, cellpair);
1301 cell_lock->Visit(cell_lock, player_notifier, *this);
1304 void Map::UpdateObjectsVisibilityFor( Player* player, Cell cell, CellPair cellpair )
1306 MaNGOS::VisibleNotifier notifier(*player);
1308 cell.data.Part.reserved = ALL_DISTRICT;
1309 cell.SetNoCreate();
1310 TypeContainerVisitor<MaNGOS::VisibleNotifier, WorldTypeMapContainer > world_notifier(notifier);
1311 TypeContainerVisitor<MaNGOS::VisibleNotifier, GridTypeMapContainer > grid_notifier(notifier);
1312 CellLock<GridReadGuard> cell_lock(cell, cellpair);
1313 cell_lock->Visit(cell_lock, world_notifier, *this);
1314 cell_lock->Visit(cell_lock, grid_notifier, *this);
1316 // send data
1317 notifier.Notify();
1320 void Map::PlayerRelocationNotify( Player* player, Cell cell, CellPair cellpair )
1322 CellLock<ReadGuard> cell_lock(cell, cellpair);
1323 MaNGOS::PlayerRelocationNotifier relocationNotifier(*player);
1324 cell.data.Part.reserved = ALL_DISTRICT;
1326 TypeContainerVisitor<MaNGOS::PlayerRelocationNotifier, GridTypeMapContainer > p2grid_relocation(relocationNotifier);
1327 TypeContainerVisitor<MaNGOS::PlayerRelocationNotifier, WorldTypeMapContainer > p2world_relocation(relocationNotifier);
1329 cell_lock->Visit(cell_lock, p2grid_relocation, *this);
1330 cell_lock->Visit(cell_lock, p2world_relocation, *this);
1333 void Map::CreatureRelocationNotify(Creature *creature, Cell cell, CellPair cellpair)
1335 CellLock<ReadGuard> cell_lock(cell, cellpair);
1336 MaNGOS::CreatureRelocationNotifier relocationNotifier(*creature);
1337 cell.data.Part.reserved = ALL_DISTRICT;
1338 cell.SetNoCreate(); // not trigger load unloaded grids at notifier call
1340 TypeContainerVisitor<MaNGOS::CreatureRelocationNotifier, WorldTypeMapContainer > c2world_relocation(relocationNotifier);
1341 TypeContainerVisitor<MaNGOS::CreatureRelocationNotifier, GridTypeMapContainer > c2grid_relocation(relocationNotifier);
1343 cell_lock->Visit(cell_lock, c2world_relocation, *this);
1344 cell_lock->Visit(cell_lock, c2grid_relocation, *this);
1347 void Map::SendInitSelf( Player * player )
1349 sLog.outDetail("Creating player data for himself %u", player->GetGUIDLow());
1351 UpdateData data;
1353 bool hasTransport = false;
1355 // attach to player data current transport data
1356 if(Transport* transport = player->GetTransport())
1358 hasTransport = true;
1359 transport->BuildCreateUpdateBlockForPlayer(&data, player);
1362 // build data for self presence in world at own client (one time for map)
1363 player->BuildCreateUpdateBlockForPlayer(&data, player);
1365 // build other passengers at transport also (they always visible and marked as visible and will not send at visibility update at add to map
1366 if(Transport* transport = player->GetTransport())
1368 for(Transport::PlayerSet::const_iterator itr = transport->GetPassengers().begin();itr!=transport->GetPassengers().end();++itr)
1370 if(player!=(*itr) && player->HaveAtClient(*itr))
1372 hasTransport = true;
1373 (*itr)->BuildCreateUpdateBlockForPlayer(&data, player);
1378 WorldPacket packet;
1379 data.BuildPacket(&packet, hasTransport);
1380 player->GetSession()->SendPacket(&packet);
1383 void Map::SendInitTransports( Player * player )
1385 // Hack to send out transports
1386 MapManager::TransportMap& tmap = MapManager::Instance().m_TransportsByMap;
1388 // no transports at map
1389 if (tmap.find(player->GetMapId()) == tmap.end())
1390 return;
1392 UpdateData transData;
1394 MapManager::TransportSet& tset = tmap[player->GetMapId()];
1396 bool hasTransport = false;
1398 for (MapManager::TransportSet::iterator i = tset.begin(); i != tset.end(); ++i)
1400 if((*i) != player->GetTransport()) // send data for current transport in other place
1402 hasTransport = true;
1403 (*i)->BuildCreateUpdateBlockForPlayer(&transData, player);
1407 WorldPacket packet;
1408 transData.BuildPacket(&packet, hasTransport);
1409 player->GetSession()->SendPacket(&packet);
1412 void Map::SendRemoveTransports( Player * player )
1414 // Hack to send out transports
1415 MapManager::TransportMap& tmap = MapManager::Instance().m_TransportsByMap;
1417 // no transports at map
1418 if (tmap.find(player->GetMapId()) == tmap.end())
1419 return;
1421 UpdateData transData;
1423 MapManager::TransportSet& tset = tmap[player->GetMapId()];
1425 // except used transport
1426 for (MapManager::TransportSet::iterator i = tset.begin(); i != tset.end(); ++i)
1427 if(player->GetTransport() != (*i))
1428 (*i)->BuildOutOfRangeUpdateBlock(&transData);
1430 WorldPacket packet;
1431 transData.BuildPacket(&packet);
1432 player->GetSession()->SendPacket(&packet);
1435 inline void Map::setNGrid(NGridType *grid, uint32 x, uint32 y)
1437 if(x >= MAX_NUMBER_OF_GRIDS || y >= MAX_NUMBER_OF_GRIDS)
1439 sLog.outError("map::setNGrid() Invalid grid coordinates found: %d, %d!",x,y);
1440 assert(false);
1442 i_grids[x][y] = grid;
1445 void Map::DoDelayedMovesAndRemoves()
1447 MoveAllCreaturesInMoveList();
1448 RemoveAllObjectsInRemoveList();
1451 void Map::AddObjectToRemoveList(WorldObject *obj)
1453 assert(obj->GetMapId()==GetId() && obj->GetInstanceId()==GetInstanceId());
1455 i_objectsToRemove.insert(obj);
1456 //sLog.outDebug("Object (GUID: %u TypeId: %u ) added to removing list.",obj->GetGUIDLow(),obj->GetTypeId());
1459 void Map::RemoveAllObjectsInRemoveList()
1461 if(i_objectsToRemove.empty())
1462 return;
1464 //sLog.outDebug("Object remover 1 check.");
1465 while(!i_objectsToRemove.empty())
1467 WorldObject* obj = *i_objectsToRemove.begin();
1468 i_objectsToRemove.erase(i_objectsToRemove.begin());
1470 switch(obj->GetTypeId())
1472 case TYPEID_CORPSE:
1474 Corpse* corpse = ObjectAccessor::Instance().GetCorpse(*obj, obj->GetGUID());
1475 if (!corpse)
1476 sLog.outError("ERROR: Try delete corpse/bones %u that not in map", obj->GetGUIDLow());
1477 else
1478 Remove(corpse,true);
1479 break;
1481 case TYPEID_DYNAMICOBJECT:
1482 Remove((DynamicObject*)obj,true);
1483 break;
1484 case TYPEID_GAMEOBJECT:
1485 Remove((GameObject*)obj,true);
1486 break;
1487 case TYPEID_UNIT:
1488 // in case triggered sequence some spell can continue casting after prev CleanupsBeforeDelete call
1489 // make sure that like sources auras/etc removed before destructor start
1490 ((Creature*)obj)->CleanupsBeforeDelete ();
1491 Remove((Creature*)obj,true);
1492 break;
1493 default:
1494 sLog.outError("Non-grid object (TypeId: %u) in grid object removing list, ignored.",obj->GetTypeId());
1495 break;
1498 //sLog.outDebug("Object remover 2 check.");
1501 uint32 Map::GetPlayersCountExceptGMs() const
1503 uint32 count = 0;
1504 for(MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
1505 if(!itr->getSource()->isGameMaster())
1506 ++count;
1507 return count;
1510 void Map::SendToPlayers(WorldPacket const* data) const
1512 for(MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
1513 itr->getSource()->GetSession()->SendPacket(data);
1516 bool Map::PlayersNearGrid(uint32 x, uint32 y) const
1518 CellPair cell_min(x*MAX_NUMBER_OF_CELLS, y*MAX_NUMBER_OF_CELLS);
1519 CellPair cell_max(cell_min.x_coord + MAX_NUMBER_OF_CELLS, cell_min.y_coord+MAX_NUMBER_OF_CELLS);
1520 cell_min << 2;
1521 cell_min -= 2;
1522 cell_max >> 2;
1523 cell_max += 2;
1525 for(MapRefManager::const_iterator iter = m_mapRefManager.begin(); iter != m_mapRefManager.end(); ++iter)
1527 Player* plr = iter->getSource();
1529 CellPair p = MaNGOS::ComputeCellPair(plr->GetPositionX(), plr->GetPositionY());
1530 if( (cell_min.x_coord <= p.x_coord && p.x_coord <= cell_max.x_coord) &&
1531 (cell_min.y_coord <= p.y_coord && p.y_coord <= cell_max.y_coord) )
1532 return true;
1535 return false;
1538 template void Map::Add(Corpse *);
1539 template void Map::Add(Creature *);
1540 template void Map::Add(GameObject *);
1541 template void Map::Add(DynamicObject *);
1543 template void Map::Remove(Corpse *,bool);
1544 template void Map::Remove(Creature *,bool);
1545 template void Map::Remove(GameObject *, bool);
1546 template void Map::Remove(DynamicObject *, bool);
1548 /* ******* Dungeon Instance Maps ******* */
1550 InstanceMap::InstanceMap(uint32 id, time_t expiry, uint32 InstanceId, uint8 SpawnMode)
1551 : Map(id, expiry, InstanceId, SpawnMode), i_data(NULL),
1552 m_resetAfterUnload(false), m_unloadWhenEmpty(false)
1554 // the timer is started by default, and stopped when the first player joins
1555 // this make sure it gets unloaded if for some reason no player joins
1556 m_unloadTimer = std::max(sWorld.getConfig(CONFIG_INSTANCE_UNLOAD_DELAY), (uint32)MIN_UNLOAD_DELAY);
1559 InstanceMap::~InstanceMap()
1561 if(i_data)
1563 delete i_data;
1564 i_data = NULL;
1569 Do map specific checks to see if the player can enter
1571 bool InstanceMap::CanEnter(Player *player)
1573 if(player->GetMapRef().getTarget() == this)
1575 sLog.outError("InstanceMap::CanEnter - player %s(%u) already in map %d,%d,%d!", player->GetName(), player->GetGUIDLow(), GetId(), GetInstanceId(), GetSpawnMode());
1576 assert(false);
1577 return false;
1580 // cannot enter if the instance is full (player cap), GMs don't count
1581 uint32 maxPlayers = GetMaxPlayers();
1582 if (!player->isGameMaster() && GetPlayersCountExceptGMs() >= maxPlayers)
1584 sLog.outDetail("MAP: Instance '%u' of map '%s' cannot have more than '%u' players. Player '%s' rejected", GetInstanceId(), GetMapName(), maxPlayers, player->GetName());
1585 player->SendTransferAborted(GetId(), TRANSFER_ABORT_MAX_PLAYERS);
1586 return false;
1589 // cannot enter while players in the instance are in combat
1590 Group *pGroup = player->GetGroup();
1591 if(pGroup && pGroup->InCombatToInstance(GetInstanceId()) && player->isAlive() && player->GetMapId() != GetId())
1593 player->SendTransferAborted(GetId(), TRANSFER_ABORT_ZONE_IN_COMBAT);
1594 return false;
1597 return Map::CanEnter(player);
1601 Do map specific checks and add the player to the map if successful.
1603 bool InstanceMap::Add(Player *player)
1605 // TODO: Not sure about checking player level: already done in HandleAreaTriggerOpcode
1606 // GMs still can teleport player in instance.
1607 // Is it needed?
1610 Guard guard(*this);
1611 if(!CanEnter(player))
1612 return false;
1614 // get or create an instance save for the map
1615 InstanceSave *mapSave = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1616 if(!mapSave)
1618 sLog.outDetail("InstanceMap::Add: creating instance save for map %d spawnmode %d with instance id %d", GetId(), GetSpawnMode(), GetInstanceId());
1619 mapSave = sInstanceSaveManager.AddInstanceSave(GetId(), GetInstanceId(), GetSpawnMode(), 0, true);
1622 // check for existing instance binds
1623 InstancePlayerBind *playerBind = player->GetBoundInstance(GetId(), GetSpawnMode());
1624 if(playerBind && playerBind->perm)
1626 // cannot enter other instances if bound permanently
1627 if(playerBind->save != mapSave)
1629 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());
1630 assert(false);
1633 else
1635 Group *pGroup = player->GetGroup();
1636 if(pGroup)
1638 // solo saves should be reset when entering a group
1639 InstanceGroupBind *groupBind = pGroup->GetBoundInstance(GetId(), GetSpawnMode());
1640 if(playerBind)
1642 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());
1643 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());
1644 assert(false);
1646 // bind to the group or keep using the group save
1647 if(!groupBind)
1648 pGroup->BindToInstance(mapSave, false);
1649 else
1651 // cannot jump to a different instance without resetting it
1652 if(groupBind->save != mapSave)
1654 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());
1655 if(mapSave)
1656 sLog.outError("MapSave players: %d, group count: %d", mapSave->GetPlayerCount(), mapSave->GetGroupCount());
1657 else
1658 sLog.outError("MapSave NULL");
1659 if(groupBind->save)
1660 sLog.outError("GroupBind save players: %d, group count: %d", groupBind->save->GetPlayerCount(), groupBind->save->GetGroupCount());
1661 else
1662 sLog.outError("GroupBind save NULL");
1663 assert(false);
1665 // if the group/leader is permanently bound to the instance
1666 // players also become permanently bound when they enter
1667 if(groupBind->perm)
1669 WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
1670 data << uint32(0);
1671 player->GetSession()->SendPacket(&data);
1672 player->BindToInstance(mapSave, true);
1676 else
1678 // set up a solo bind or continue using it
1679 if(!playerBind)
1680 player->BindToInstance(mapSave, false);
1681 else
1682 // cannot jump to a different instance without resetting it
1683 assert(playerBind->save == mapSave);
1687 if(i_data) i_data->OnPlayerEnter(player);
1688 // for normal instances cancel the reset schedule when the
1689 // first player enters (no players yet)
1690 SetResetSchedule(false);
1692 player->SendInitWorldStates();
1693 sLog.outDetail("MAP: Player '%s' entered the instance '%u' of map '%s'", player->GetName(), GetInstanceId(), GetMapName());
1694 // initialize unload state
1695 m_unloadTimer = 0;
1696 m_resetAfterUnload = false;
1697 m_unloadWhenEmpty = false;
1700 // this will acquire the same mutex so it cannot be in the previous block
1701 Map::Add(player);
1702 return true;
1705 void InstanceMap::Update(const uint32& t_diff)
1707 Map::Update(t_diff);
1709 if(i_data)
1710 i_data->Update(t_diff);
1713 void InstanceMap::Remove(Player *player, bool remove)
1715 sLog.outDetail("MAP: Removing player '%s' from instance '%u' of map '%s' before relocating to other map", player->GetName(), GetInstanceId(), GetMapName());
1716 //if last player set unload timer
1717 if(!m_unloadTimer && m_mapRefManager.getSize() == 1)
1718 m_unloadTimer = m_unloadWhenEmpty ? MIN_UNLOAD_DELAY : std::max(sWorld.getConfig(CONFIG_INSTANCE_UNLOAD_DELAY), (uint32)MIN_UNLOAD_DELAY);
1719 Map::Remove(player, remove);
1720 // for normal instances schedule the reset after all players have left
1721 SetResetSchedule(true);
1724 void InstanceMap::CreateInstanceData(bool load)
1726 if(i_data != NULL)
1727 return;
1729 InstanceTemplate const* mInstance = objmgr.GetInstanceTemplate(GetId());
1730 if (mInstance)
1732 i_script_id = mInstance->script_id;
1733 i_data = Script->CreateInstanceData(this);
1736 if(!i_data)
1737 return;
1739 if(load)
1741 // TODO: make a global storage for this
1742 QueryResult* result = CharacterDatabase.PQuery("SELECT data FROM instance WHERE map = '%u' AND id = '%u'", GetId(), i_InstanceId);
1743 if (result)
1745 Field* fields = result->Fetch();
1746 const char* data = fields[0].GetString();
1747 if(data)
1749 sLog.outDebug("Loading instance data for `%s` with id %u", objmgr.GetScriptName(i_script_id), i_InstanceId);
1750 i_data->Load(data);
1752 delete result;
1755 else
1757 sLog.outDebug("New instance data, \"%s\" ,initialized!", objmgr.GetScriptName(i_script_id));
1758 i_data->Initialize();
1763 Returns true if there are no players in the instance
1765 bool InstanceMap::Reset(uint8 method)
1767 // note: since the map may not be loaded when the instance needs to be reset
1768 // the instance must be deleted from the DB by InstanceSaveManager
1770 if(HavePlayers())
1772 if(method == INSTANCE_RESET_ALL)
1774 // notify the players to leave the instance so it can be reset
1775 for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
1776 itr->getSource()->SendResetFailedNotify(GetId());
1778 else
1780 if(method == INSTANCE_RESET_GLOBAL)
1782 // set the homebind timer for players inside (1 minute)
1783 for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
1784 itr->getSource()->m_InstanceValid = false;
1787 // the unload timer is not started
1788 // instead the map will unload immediately after the players have left
1789 m_unloadWhenEmpty = true;
1790 m_resetAfterUnload = true;
1793 else
1795 // unloaded at next update
1796 m_unloadTimer = MIN_UNLOAD_DELAY;
1797 m_resetAfterUnload = true;
1800 return m_mapRefManager.isEmpty();
1803 void InstanceMap::PermBindAllPlayers(Player *player)
1805 InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1806 if(!save)
1808 sLog.outError("Cannot bind players, no instance save available for map!\n");
1809 return;
1812 Group *group = player->GetGroup();
1813 // group members outside the instance group don't get bound
1814 for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
1816 Player* plr = itr->getSource();
1817 // players inside an instance cannot be bound to other instances
1818 // some players may already be permanently bound, in this case nothing happens
1819 InstancePlayerBind *bind = plr->GetBoundInstance(save->GetMapId(), save->GetDifficulty());
1820 if(!bind || !bind->perm)
1822 plr->BindToInstance(save, true);
1823 WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
1824 data << uint32(0);
1825 plr->GetSession()->SendPacket(&data);
1828 // if the leader is not in the instance the group will not get a perm bind
1829 if(group && group->GetLeaderGUID() == plr->GetGUID())
1830 group->BindToInstance(save, true);
1834 time_t InstanceMap::GetResetTime()
1836 InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1837 return save ? save->GetDifficulty() : DIFFICULTY_NORMAL;
1840 void InstanceMap::UnloadAll(bool pForce)
1842 if(HavePlayers())
1844 sLog.outError("InstanceMap::UnloadAll: there are still players in the instance at unload, should not happen!");
1845 for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
1847 Player* plr = itr->getSource();
1848 plr->TeleportTo(plr->m_homebindMapId, plr->m_homebindX, plr->m_homebindY, plr->m_homebindZ, plr->GetOrientation());
1852 if(m_resetAfterUnload == true)
1853 objmgr.DeleteRespawnTimeForInstance(GetInstanceId());
1855 Map::UnloadAll(pForce);
1858 void InstanceMap::SendResetWarnings(uint32 timeLeft) const
1860 for(MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
1861 itr->getSource()->SendInstanceResetWarning(GetId(), timeLeft);
1864 void InstanceMap::SetResetSchedule(bool on)
1866 // only for normal instances
1867 // the reset time is only scheduled when there are no payers inside
1868 // it is assumed that the reset time will rarely (if ever) change while the reset is scheduled
1869 if(!HavePlayers() && !IsRaid() && !IsHeroic())
1871 InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1872 if(!save) sLog.outError("InstanceMap::SetResetSchedule: cannot turn schedule %s, no save available for instance %d of %d", on ? "on" : "off", GetInstanceId(), GetId());
1873 else sInstanceSaveManager.ScheduleReset(on, save->GetResetTime(), InstanceSaveManager::InstResetEvent(0, GetId(), GetInstanceId()));
1877 uint32 InstanceMap::GetMaxPlayers() const
1879 InstanceTemplate const* iTemplate = objmgr.GetInstanceTemplate(GetId());
1880 if(!iTemplate)
1881 return 0;
1882 return IsHeroic() ? iTemplate->maxPlayersHeroic : iTemplate->maxPlayers;
1885 /* ******* Battleground Instance Maps ******* */
1887 BattleGroundMap::BattleGroundMap(uint32 id, time_t expiry, uint32 InstanceId)
1888 : Map(id, expiry, InstanceId, DIFFICULTY_NORMAL)
1892 BattleGroundMap::~BattleGroundMap()
1896 bool BattleGroundMap::CanEnter(Player * player)
1898 if(player->GetMapRef().getTarget() == this)
1900 sLog.outError("BGMap::CanEnter - player %u already in map!", player->GetGUIDLow());
1901 assert(false);
1902 return false;
1905 if(player->GetBattleGroundId() != GetInstanceId())
1906 return false;
1908 // player number limit is checked in bgmgr, no need to do it here
1910 return Map::CanEnter(player);
1913 bool BattleGroundMap::Add(Player * player)
1916 Guard guard(*this);
1917 if(!CanEnter(player))
1918 return false;
1919 // reset instance validity, battleground maps do not homebind
1920 player->m_InstanceValid = true;
1922 return Map::Add(player);
1925 void BattleGroundMap::Remove(Player *player, bool remove)
1927 sLog.outDetail("MAP: Removing player '%s' from bg '%u' of map '%s' before relocating to other map", player->GetName(), GetInstanceId(), GetMapName());
1928 Map::Remove(player, remove);
1931 void BattleGroundMap::SetUnload()
1933 m_unloadTimer = MIN_UNLOAD_DELAY;
1936 void BattleGroundMap::UnloadAll(bool pForce)
1938 while(HavePlayers())
1940 if(Player * plr = m_mapRefManager.getFirst()->getSource())
1942 plr->TeleportTo(plr->GetBattleGroundEntryPoint());
1943 // TeleportTo removes the player from this map (if the map exists) -> calls BattleGroundMap::Remove -> invalidates the iterator.
1944 // just in case, remove the player from the list explicitly here as well to prevent a possible infinite loop
1945 // note that this remove is not needed if the code works well in other places
1946 plr->GetMapRef().unlink();
1950 Map::UnloadAll(pForce);