[8449] Deprecate healing/damage item mods and merge internal data in to spell power.
[getmangos.git] / src / game / Map.cpp
bloba43712d25b30de0a80cb4ea837a3058c614c4c3a
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 "Vehicle.h"
22 #include "GridNotifiers.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 GridState* si_GridStates[MAX_GRID_STATE];
47 struct ScriptAction
49 uint64 sourceGUID;
50 uint64 targetGUID;
51 uint64 ownerGUID; // owner of source if source is item
52 ScriptInfo const* script; // pointer to static script data
55 Map::~Map()
57 UnloadAll(true);
59 if(!m_scriptSchedule.empty())
60 sWorld.DecreaseScheduledScriptCount(m_scriptSchedule.size());
63 bool Map::ExistMap(uint32 mapid,int gx,int gy)
65 int len = sWorld.GetDataPath().length()+strlen("maps/%03u%02u%02u.map")+1;
66 char* tmp = new char[len];
67 snprintf(tmp, len, (char *)(sWorld.GetDataPath()+"maps/%03u%02u%02u.map").c_str(),mapid,gx,gy);
69 FILE *pf=fopen(tmp,"rb");
71 if(!pf)
73 sLog.outError("Check existing of map file '%s': not exist!",tmp);
74 delete[] tmp;
75 return false;
78 map_fileheader header;
79 fread(&header, sizeof(header), 1, pf);
80 if (header.mapMagic != uint32(MAP_MAGIC) ||
81 header.versionMagic != uint32(MAP_VERSION_MAGIC))
83 sLog.outError("Map file '%s' is non-compatible version (outdated?). Please, create new using ad.exe program.",tmp);
84 delete [] tmp;
85 fclose(pf); //close file before return
86 return false;
89 delete [] tmp;
90 fclose(pf);
91 return true;
94 bool Map::ExistVMap(uint32 mapid,int gx,int gy)
96 if(VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager())
98 if(vmgr->isMapLoadingEnabled())
100 // x and y are swapped !! => fixed now
101 bool exists = vmgr->existsMap((sWorld.GetDataPath()+ "vmaps").c_str(), mapid, gx,gy);
102 if(!exists)
104 std::string name = vmgr->getDirFileName(mapid,gx,gy);
105 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());
106 return false;
111 return true;
114 void Map::LoadVMap(int gx,int gy)
116 // x and y are swapped !!
117 int vmapLoadResult = VMAP::VMapFactory::createOrGetVMapManager()->loadMap((sWorld.GetDataPath()+ "vmaps").c_str(), GetId(), gx,gy);
118 switch(vmapLoadResult)
120 case VMAP::VMAP_LOAD_RESULT_OK:
121 sLog.outDetail("VMAP loaded name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", GetMapName(), GetId(), gx,gy,gx,gy);
122 break;
123 case VMAP::VMAP_LOAD_RESULT_ERROR:
124 sLog.outDetail("Could not load VMAP name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", GetMapName(), GetId(), gx,gy,gx,gy);
125 break;
126 case VMAP::VMAP_LOAD_RESULT_IGNORED:
127 DEBUG_LOG("Ignored VMAP name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", GetMapName(), GetId(), gx,gy,gx,gy);
128 break;
132 void Map::LoadMap(int gx,int gy, bool reload)
134 if( i_InstanceId != 0 )
136 if(GridMaps[gx][gy])
137 return;
139 // load grid map for base map
140 if (!m_parentMap->GridMaps[gx][gy])
141 m_parentMap->EnsureGridCreated(GridPair(63-gx,63-gy));
143 ((MapInstanced*)(m_parentMap))->AddGridMapReference(GridPair(gx,gy));
144 GridMaps[gx][gy] = m_parentMap->GridMaps[gx][gy];
145 return;
148 if(GridMaps[gx][gy] && !reload)
149 return;
151 //map already load, delete it before reloading (Is it necessary? Do we really need the ability the reload maps during runtime?)
152 if(GridMaps[gx][gy])
154 sLog.outDetail("Unloading already loaded map %u before reloading.",i_id);
155 delete (GridMaps[gx][gy]);
156 GridMaps[gx][gy]=NULL;
159 // map file name
160 char *tmp=NULL;
161 int len = sWorld.GetDataPath().length()+strlen("maps/%03u%02u%02u.map")+1;
162 tmp = new char[len];
163 snprintf(tmp, len, (char *)(sWorld.GetDataPath()+"maps/%03u%02u%02u.map").c_str(),i_id,gx,gy);
164 sLog.outDetail("Loading map %s",tmp);
165 // loading data
166 GridMaps[gx][gy] = new GridMap();
167 if (!GridMaps[gx][gy]->loadData(tmp))
169 sLog.outError("Error load map file: \n %s\n", tmp);
171 delete [] tmp;
174 void Map::LoadMapAndVMap(int gx,int gy)
176 LoadMap(gx,gy);
177 if(i_InstanceId == 0)
178 LoadVMap(gx, gy); // Only load the data for the base map
181 void Map::InitStateMachine()
183 si_GridStates[GRID_STATE_INVALID] = new InvalidState;
184 si_GridStates[GRID_STATE_ACTIVE] = new ActiveState;
185 si_GridStates[GRID_STATE_IDLE] = new IdleState;
186 si_GridStates[GRID_STATE_REMOVAL] = new RemovalState;
189 void Map::DeleteStateMachine()
191 delete si_GridStates[GRID_STATE_INVALID];
192 delete si_GridStates[GRID_STATE_ACTIVE];
193 delete si_GridStates[GRID_STATE_IDLE];
194 delete si_GridStates[GRID_STATE_REMOVAL];
197 Map::Map(uint32 id, time_t expiry, uint32 InstanceId, uint8 SpawnMode, Map* _parent)
198 : i_mapEntry (sMapStore.LookupEntry(id)), i_spawnMode(SpawnMode),
199 i_id(id), i_InstanceId(InstanceId), m_unloadTimer(0),
200 m_activeNonPlayersIter(m_activeNonPlayers.end()),
201 i_gridExpiry(expiry), m_parentMap(_parent ? _parent : this)
203 for(unsigned int idx=0; idx < MAX_NUMBER_OF_GRIDS; ++idx)
205 for(unsigned int j=0; j < MAX_NUMBER_OF_GRIDS; ++j)
207 //z code
208 GridMaps[idx][j] =NULL;
209 setNGrid(NULL, idx, j);
214 // Template specialization of utility methods
215 template<class T>
216 void Map::AddToGrid(T* obj, NGridType *grid, Cell const& cell)
218 (*grid)(cell.CellX(), cell.CellY()).template AddGridObject<T>(obj, obj->GetGUID());
221 template<>
222 void Map::AddToGrid(Player* obj, NGridType *grid, Cell const& cell)
224 (*grid)(cell.CellX(), cell.CellY()).AddWorldObject(obj, obj->GetGUID());
227 template<>
228 void Map::AddToGrid(Corpse *obj, NGridType *grid, Cell const& cell)
230 // add to world object registry in grid
231 if(obj->GetType()!=CORPSE_BONES)
233 (*grid)(cell.CellX(), cell.CellY()).AddWorldObject(obj, obj->GetGUID());
235 // add to grid object store
236 else
238 (*grid)(cell.CellX(), cell.CellY()).AddGridObject(obj, obj->GetGUID());
242 template<>
243 void Map::AddToGrid(Creature* obj, NGridType *grid, Cell const& cell)
245 // add to world object registry in grid
246 if(obj->isPet() || obj->isVehicle())
248 (*grid)(cell.CellX(), cell.CellY()).AddWorldObject<Creature>(obj, obj->GetGUID());
249 obj->SetCurrentCell(cell);
251 // add to grid object store
252 else
254 (*grid)(cell.CellX(), cell.CellY()).AddGridObject<Creature>(obj, obj->GetGUID());
255 obj->SetCurrentCell(cell);
259 template<class T>
260 void Map::RemoveFromGrid(T* obj, NGridType *grid, Cell const& cell)
262 (*grid)(cell.CellX(), cell.CellY()).template RemoveGridObject<T>(obj, obj->GetGUID());
265 template<>
266 void Map::RemoveFromGrid(Player* obj, NGridType *grid, Cell const& cell)
268 (*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject(obj, obj->GetGUID());
271 template<>
272 void Map::RemoveFromGrid(Corpse *obj, NGridType *grid, Cell const& cell)
274 // remove from world object registry in grid
275 if(obj->GetType()!=CORPSE_BONES)
277 (*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject(obj, obj->GetGUID());
279 // remove from grid object store
280 else
282 (*grid)(cell.CellX(), cell.CellY()).RemoveGridObject(obj, obj->GetGUID());
286 template<>
287 void Map::RemoveFromGrid(Creature* obj, NGridType *grid, Cell const& cell)
289 // remove from world object registry in grid
290 if(obj->isPet() || obj->isVehicle())
292 (*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject<Creature>(obj, obj->GetGUID());
294 // remove from grid object store
295 else
297 (*grid)(cell.CellX(), cell.CellY()).RemoveGridObject<Creature>(obj, obj->GetGUID());
301 template<class T>
302 void Map::DeleteFromWorld(T* obj)
304 // Note: In case resurrectable corpse and pet its removed from global lists in own destructor
305 delete obj;
308 template<>
309 void Map::DeleteFromWorld(Player* pl)
311 ObjectAccessor::Instance().RemoveObject(pl);
312 delete pl;
315 template<class T>
316 void Map::AddNotifier(T* , Cell const& , CellPair const& )
320 template<>
321 void Map::AddNotifier(Player* obj, Cell const& cell, CellPair const& cellpair)
323 PlayerRelocationNotify(obj,cell,cellpair);
326 template<>
327 void Map::AddNotifier(Creature* obj, Cell const& cell, CellPair const& cellpair)
329 CreatureRelocationNotify(obj,cell,cellpair);
332 void
333 Map::EnsureGridCreated(const GridPair &p)
335 if(!getNGrid(p.x_coord, p.y_coord))
337 Guard guard(*this);
338 if(!getNGrid(p.x_coord, p.y_coord))
340 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)),
341 p.x_coord, p.y_coord);
343 // build a linkage between this map and NGridType
344 buildNGridLinkage(getNGrid(p.x_coord, p.y_coord));
346 getNGrid(p.x_coord, p.y_coord)->SetGridState(GRID_STATE_IDLE);
348 //z coord
349 int gx=63-p.x_coord;
350 int gy=63-p.y_coord;
352 if(!GridMaps[gx][gy])
353 LoadMapAndVMap(gx,gy);
358 void
359 Map::EnsureGridLoadedAtEnter(const Cell &cell, Player *player)
361 NGridType *grid;
363 if(EnsureGridLoaded(cell))
365 grid = getNGrid(cell.GridX(), cell.GridY());
367 if (player)
369 player->SendDelayResponse(MAX_GRID_LOAD_TIME);
370 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);
372 else
374 DEBUG_LOG("Active object nearby triggers of loading grid [%u,%u] on map %u", cell.GridX(), cell.GridY(), i_id);
377 ResetGridExpiry(*getNGrid(cell.GridX(), cell.GridY()), 0.1f);
378 grid->SetGridState(GRID_STATE_ACTIVE);
380 else
381 grid = getNGrid(cell.GridX(), cell.GridY());
383 if (player)
384 AddToGrid(player,grid,cell);
387 bool Map::EnsureGridLoaded(const Cell &cell)
389 EnsureGridCreated(GridPair(cell.GridX(), cell.GridY()));
390 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
392 assert(grid != NULL);
393 if( !isGridObjectDataLoaded(cell.GridX(), cell.GridY()) )
395 ObjectGridLoader loader(*grid, this, cell);
396 loader.LoadN();
398 // Add resurrectable corpses to world object list in grid
399 ObjectAccessor::Instance().AddCorpsesToGrid(GridPair(cell.GridX(),cell.GridY()),(*grid)(cell.CellX(), cell.CellY()), this);
401 setGridObjectDataLoaded(true,cell.GridX(), cell.GridY());
402 return true;
405 return false;
408 void Map::LoadGrid(const Cell& cell, bool no_unload)
410 EnsureGridLoaded(cell);
412 if(no_unload)
413 getNGrid(cell.GridX(), cell.GridY())->setUnloadExplicitLock(true);
416 bool Map::Add(Player *player)
418 player->GetMapRef().link(this, player);
419 player->SetMap(this);
421 // update player state for other player and visa-versa
422 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
423 Cell cell(p);
424 EnsureGridLoadedAtEnter(cell, player);
425 player->AddToWorld();
427 SendInitSelf(player);
428 SendInitTransports(player);
430 UpdatePlayerVisibility(player,cell,p);
431 UpdateObjectsVisibilityFor(player,cell,p);
433 AddNotifier(player,cell,p);
434 return true;
437 template<class T>
438 void
439 Map::Add(T *obj)
441 assert(obj);
443 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
444 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
446 sLog.outError("Map::Add: Object (GUID: %u TypeId: %u) have invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUIDLow(), obj->GetTypeId(), obj->GetPositionX(), obj->GetPositionY(), p.x_coord, p.y_coord);
447 return;
450 obj->SetMap(this);
452 Cell cell(p);
453 if(obj->isActiveObject())
454 EnsureGridLoadedAtEnter(cell);
455 else
456 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 if(obj->isActiveObject())
465 AddToActive(obj);
467 DEBUG_LOG("Object %u enters grid[%u,%u]", GUID_LOPART(obj->GetGUID()), cell.GridX(), cell.GridY());
469 UpdateObjectVisibility(obj,cell,p);
471 AddNotifier(obj,cell,p);
474 void Map::MessageBroadcast(Player *player, WorldPacket *msg, bool to_self)
476 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
478 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
480 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);
481 return;
484 Cell cell(p);
485 cell.data.Part.reserved = ALL_DISTRICT;
486 cell.SetNoCreate();
488 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
489 return;
491 MaNGOS::MessageDeliverer post_man(*player, msg, to_self);
492 TypeContainerVisitor<MaNGOS::MessageDeliverer, WorldTypeMapContainer > message(post_man);
493 CellLock<ReadGuard> cell_lock(cell, p);
494 cell_lock->Visit(cell_lock, message, *this);
497 void Map::MessageBroadcast(WorldObject *obj, WorldPacket *msg)
499 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
501 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
503 sLog.outError("Map::MessageBroadcast: Object (GUID: %u TypeId: %u) have invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUIDLow(), obj->GetTypeId(), obj->GetPositionX(), obj->GetPositionY(), p.x_coord, p.y_coord);
504 return;
507 Cell cell(p);
508 cell.data.Part.reserved = ALL_DISTRICT;
509 cell.SetNoCreate();
511 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
512 return;
514 MaNGOS::ObjectMessageDeliverer post_man(*obj,msg);
515 TypeContainerVisitor<MaNGOS::ObjectMessageDeliverer, WorldTypeMapContainer > message(post_man);
516 CellLock<ReadGuard> cell_lock(cell, p);
517 cell_lock->Visit(cell_lock, message, *this);
520 void Map::MessageDistBroadcast(Player *player, WorldPacket *msg, float dist, bool to_self, bool own_team_only)
522 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
524 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
526 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);
527 return;
530 Cell cell(p);
531 cell.data.Part.reserved = ALL_DISTRICT;
532 cell.SetNoCreate();
534 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
535 return;
537 MaNGOS::MessageDistDeliverer post_man(*player, msg, dist, to_self, own_team_only);
538 TypeContainerVisitor<MaNGOS::MessageDistDeliverer , WorldTypeMapContainer > message(post_man);
539 CellLock<ReadGuard> cell_lock(cell, p);
540 cell_lock->Visit(cell_lock, message, *this);
543 void Map::MessageDistBroadcast(WorldObject *obj, WorldPacket *msg, float dist)
545 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
547 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
549 sLog.outError("Map::MessageBroadcast: Object (GUID: %u TypeId: %u) have invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUIDLow(), obj->GetTypeId(), obj->GetPositionX(), obj->GetPositionY(), p.x_coord, p.y_coord);
550 return;
553 Cell cell(p);
554 cell.data.Part.reserved = ALL_DISTRICT;
555 cell.SetNoCreate();
557 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
558 return;
560 MaNGOS::ObjectMessageDistDeliverer post_man(*obj, msg,dist);
561 TypeContainerVisitor<MaNGOS::ObjectMessageDistDeliverer, WorldTypeMapContainer > message(post_man);
562 CellLock<ReadGuard> cell_lock(cell, p);
563 cell_lock->Visit(cell_lock, message, *this);
566 bool Map::loaded(const GridPair &p) const
568 return ( getNGrid(p.x_coord, p.y_coord) && isGridObjectDataLoaded(p.x_coord, p.y_coord) );
571 void Map::Update(const uint32 &t_diff)
573 /// update players at tick
574 for(m_mapRefIter = m_mapRefManager.begin(); m_mapRefIter != m_mapRefManager.end(); ++m_mapRefIter)
576 Player* plr = m_mapRefIter->getSource();
577 if(plr && plr->IsInWorld())
578 plr->Update(t_diff);
581 /// update active cells around players and active objects
582 resetMarkedCells();
584 MaNGOS::ObjectUpdater updater(t_diff);
585 // for creature
586 TypeContainerVisitor<MaNGOS::ObjectUpdater, GridTypeMapContainer > grid_object_update(updater);
587 // for pets
588 TypeContainerVisitor<MaNGOS::ObjectUpdater, WorldTypeMapContainer > world_object_update(updater);
590 // the player iterator is stored in the map object
591 // to make sure calls to Map::Remove don't invalidate it
592 for(m_mapRefIter = m_mapRefManager.begin(); m_mapRefIter != m_mapRefManager.end(); ++m_mapRefIter)
594 Player* plr = m_mapRefIter->getSource();
596 if(!plr->IsInWorld())
597 continue;
599 CellPair standing_cell(MaNGOS::ComputeCellPair(plr->GetPositionX(), plr->GetPositionY()));
601 // Check for correctness of standing_cell, it also avoids problems with update_cell
602 if (standing_cell.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || standing_cell.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
603 continue;
605 // the overloaded operators handle range checking
606 // so ther's no need for range checking inside the loop
607 CellPair begin_cell(standing_cell), end_cell(standing_cell);
608 begin_cell << 1; begin_cell -= 1; // upper left
609 end_cell >> 1; end_cell += 1; // lower right
611 for(uint32 x = begin_cell.x_coord; x <= end_cell.x_coord; ++x)
613 for(uint32 y = begin_cell.y_coord; y <= end_cell.y_coord; ++y)
615 // marked cells are those that have been visited
616 // don't visit the same cell twice
617 uint32 cell_id = (y * TOTAL_NUMBER_OF_CELLS_PER_MAP) + x;
618 if(!isCellMarked(cell_id))
620 markCell(cell_id);
621 CellPair pair(x,y);
622 Cell cell(pair);
623 cell.data.Part.reserved = CENTER_DISTRICT;
624 cell.SetNoCreate();
625 CellLock<NullGuard> cell_lock(cell, pair);
626 cell_lock->Visit(cell_lock, grid_object_update, *this);
627 cell_lock->Visit(cell_lock, world_object_update, *this);
633 // non-player active objects
634 if(!m_activeNonPlayers.empty())
636 for(m_activeNonPlayersIter = m_activeNonPlayers.begin(); m_activeNonPlayersIter != m_activeNonPlayers.end(); )
638 // skip not in world
639 WorldObject* obj = *m_activeNonPlayersIter;
641 // step before processing, in this case if Map::Remove remove next object we correctly
642 // step to next-next, and if we step to end() then newly added objects can wait next update.
643 ++m_activeNonPlayersIter;
645 if(!obj->IsInWorld())
646 continue;
648 CellPair standing_cell(MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY()));
650 // Check for correctness of standing_cell, it also avoids problems with update_cell
651 if (standing_cell.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || standing_cell.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
652 continue;
654 // the overloaded operators handle range checking
655 // so ther's no need for range checking inside the loop
656 CellPair begin_cell(standing_cell), end_cell(standing_cell);
657 begin_cell << 1; begin_cell -= 1; // upper left
658 end_cell >> 1; end_cell += 1; // lower right
660 for(uint32 x = begin_cell.x_coord; x <= end_cell.x_coord; ++x)
662 for(uint32 y = begin_cell.y_coord; y <= end_cell.y_coord; ++y)
664 // marked cells are those that have been visited
665 // don't visit the same cell twice
666 uint32 cell_id = (y * TOTAL_NUMBER_OF_CELLS_PER_MAP) + x;
667 if(!isCellMarked(cell_id))
669 markCell(cell_id);
670 CellPair pair(x,y);
671 Cell cell(pair);
672 cell.data.Part.reserved = CENTER_DISTRICT;
673 cell.SetNoCreate();
674 CellLock<NullGuard> cell_lock(cell, pair);
675 cell_lock->Visit(cell_lock, grid_object_update, *this);
676 cell_lock->Visit(cell_lock, world_object_update, *this);
683 // 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 !
684 // This isn't really bother us, since as soon as we have instanced BG-s, the whole map unloads as the BG gets ended
685 if (!IsBattleGroundOrArena())
687 for (GridRefManager<NGridType>::iterator i = GridRefManager<NGridType>::begin(); i != GridRefManager<NGridType>::end(); )
689 NGridType *grid = i->getSource();
690 GridInfo *info = i->getSource()->getGridInfoRef();
691 ++i; // The update might delete the map and we need the next map before the iterator gets invalid
692 assert(grid->GetGridState() >= 0 && grid->GetGridState() < MAX_GRID_STATE);
693 si_GridStates[grid->GetGridState()]->Update(*this, *grid, *info, grid->getX(), grid->getY(), t_diff);
697 ///- Process necessary scripts
698 if (!m_scriptSchedule.empty())
699 ScriptsProcess();
702 void Map::Remove(Player *player, bool remove)
704 // this may be called during Map::Update
705 // after decrement+unlink, ++m_mapRefIter will continue correctly
706 // when the first element of the list is being removed
707 // nocheck_prev will return the padding element of the RefManager
708 // instead of NULL in the case of prev
709 if(m_mapRefIter == player->GetMapRef())
710 m_mapRefIter = m_mapRefIter->nocheck_prev();
711 player->GetMapRef().unlink();
712 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
713 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
715 if(remove)
716 player->CleanupsBeforeDelete();
718 // invalid coordinates
719 player->RemoveFromWorld();
720 player->ResetMap();
722 if( remove )
723 DeleteFromWorld(player);
725 return;
728 Cell cell(p);
730 if( !getNGrid(cell.data.Part.grid_x, cell.data.Part.grid_y) )
732 sLog.outError("Map::Remove() i_grids was NULL x:%d, y:%d",cell.data.Part.grid_x,cell.data.Part.grid_y);
733 return;
736 DEBUG_LOG("Remove player %s from grid[%u,%u]", player->GetName(), cell.GridX(), cell.GridY());
737 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
738 assert(grid != NULL);
740 if(remove)
741 player->CleanupsBeforeDelete();
743 player->RemoveFromWorld();
744 RemoveFromGrid(player,grid,cell);
746 SendRemoveTransports(player);
747 UpdateObjectsVisibilityFor(player,cell,p);
749 player->ResetMap();
750 if( remove )
751 DeleteFromWorld(player);
754 bool Map::RemoveBones(uint64 guid, float x, float y)
756 if (IsRemovalGrid(x, y))
758 Corpse * corpse = ObjectAccessor::Instance().GetObjectInWorld(GetId(), x, y, guid, (Corpse*)NULL);
759 if(corpse && corpse->GetTypeId() == TYPEID_CORPSE && corpse->GetType() == CORPSE_BONES)
760 corpse->DeleteBonesFromWorld();
761 else
762 return false;
764 return true;
767 template<class T>
768 void
769 Map::Remove(T *obj, bool remove)
771 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
772 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
774 sLog.outError("Map::Remove: Object (GUID: %u TypeId:%u) have invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUIDLow(), obj->GetTypeId(), obj->GetPositionX(), obj->GetPositionY(), p.x_coord, p.y_coord);
775 return;
778 Cell cell(p);
779 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
780 return;
782 DEBUG_LOG("Remove object (GUID: %u TypeId:%u) from grid[%u,%u]", obj->GetGUIDLow(), obj->GetTypeId(), cell.data.Part.grid_x, cell.data.Part.grid_y);
783 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
784 assert( grid != NULL );
786 if(obj->isActiveObject())
787 RemoveFromActive(obj);
789 obj->RemoveFromWorld();
790 RemoveFromGrid(obj,grid,cell);
792 UpdateObjectVisibility(obj,cell,p);
794 obj->ResetMap();
795 if( remove )
797 // if option set then object already saved at this moment
798 if(!sWorld.getConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY))
799 obj->SaveRespawnTime();
800 DeleteFromWorld(obj);
804 void
805 Map::PlayerRelocation(Player *player, float x, float y, float z, float orientation)
807 assert(player);
809 CellPair old_val = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
810 CellPair new_val = MaNGOS::ComputeCellPair(x, y);
812 Cell old_cell(old_val);
813 Cell new_cell(new_val);
814 new_cell |= old_cell;
815 bool same_cell = (new_cell == old_cell);
817 player->Relocate(x, y, z, orientation);
819 if( old_cell.DiffGrid(new_cell) || old_cell.DiffCell(new_cell) )
821 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());
823 // update player position for group at taxi flight
824 if(player->GetGroup() && player->isInFlight())
825 player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
827 NGridType* oldGrid = getNGrid(old_cell.GridX(), old_cell.GridY());
828 RemoveFromGrid(player, oldGrid,old_cell);
829 if( !old_cell.DiffGrid(new_cell) )
830 AddToGrid(player, oldGrid,new_cell);
831 else
832 EnsureGridLoadedAtEnter(new_cell, player);
835 // if move then update what player see and who seen
836 UpdatePlayerVisibility(player,new_cell,new_val);
837 UpdateObjectsVisibilityFor(player,new_cell,new_val);
838 PlayerRelocationNotify(player,new_cell,new_val);
839 NGridType* newGrid = getNGrid(new_cell.GridX(), new_cell.GridY());
840 if( !same_cell && newGrid->GetGridState()!= GRID_STATE_ACTIVE )
842 ResetGridExpiry(*newGrid, 0.1f);
843 newGrid->SetGridState(GRID_STATE_ACTIVE);
847 void
848 Map::CreatureRelocation(Creature *creature, float x, float y, float z, float ang)
850 assert(CheckGridIntegrity(creature,false));
852 Cell old_cell = creature->GetCurrentCell();
854 CellPair new_val = MaNGOS::ComputeCellPair(x, y);
855 Cell new_cell(new_val);
857 // delay creature move for grid/cell to grid/cell moves
858 if( old_cell.DiffCell(new_cell) || old_cell.DiffGrid(new_cell) )
860 #ifdef MANGOS_DEBUG
861 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
862 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());
863 #endif
864 AddCreatureToMoveList(creature,x,y,z,ang);
865 // in diffcell/diffgrid case notifiers called at finishing move creature in Map::MoveAllCreaturesInMoveList
867 else
869 creature->Relocate(x, y, z, ang);
870 CreatureRelocationNotify(creature,new_cell,new_val);
872 assert(CheckGridIntegrity(creature,true));
875 void Map::AddCreatureToMoveList(Creature *c, float x, float y, float z, float ang)
877 if(!c)
878 return;
880 i_creaturesToMove[c] = CreatureMover(x,y,z,ang);
883 void Map::MoveAllCreaturesInMoveList()
885 while(!i_creaturesToMove.empty())
887 // get data and remove element;
888 CreatureMoveList::iterator iter = i_creaturesToMove.begin();
889 Creature* c = iter->first;
890 CreatureMover cm = iter->second;
891 i_creaturesToMove.erase(iter);
893 // calculate cells
894 CellPair new_val = MaNGOS::ComputeCellPair(cm.x, cm.y);
895 Cell new_cell(new_val);
897 // do move or do move to respawn or remove creature if previous all fail
898 if(CreatureCellRelocation(c,new_cell))
900 // update pos
901 c->Relocate(cm.x, cm.y, cm.z, cm.ang);
902 CreatureRelocationNotify(c,new_cell,new_cell.cellPair());
904 else
906 // if creature can't be move in new cell/grid (not loaded) move it to repawn cell/grid
907 // creature coordinates will be updated and notifiers send
908 if(!CreatureRespawnRelocation(c))
910 // ... or unload (if respawn grid also not loaded)
911 #ifdef MANGOS_DEBUG
912 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
913 sLog.outDebug("Creature (GUID: %u Entry: %u ) can't be move to unloaded respawn grid.",c->GetGUIDLow(),c->GetEntry());
914 #endif
915 AddObjectToRemoveList(c);
921 bool Map::CreatureCellRelocation(Creature *c, Cell new_cell)
923 Cell const& old_cell = c->GetCurrentCell();
924 if(!old_cell.DiffGrid(new_cell) ) // in same grid
926 // if in same cell then none do
927 if(old_cell.DiffCell(new_cell))
929 #ifdef MANGOS_DEBUG
930 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
931 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());
932 #endif
934 if( !old_cell.DiffGrid(new_cell) )
936 RemoveFromGrid(c,getNGrid(old_cell.GridX(), old_cell.GridY()),old_cell);
937 AddToGrid(c,getNGrid(new_cell.GridX(), new_cell.GridY()),new_cell);
938 c->SetCurrentCell(new_cell);
941 else
943 #ifdef MANGOS_DEBUG
944 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
945 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());
946 #endif
949 return true;
952 // in diff. grids but active creature
953 if(c->isActiveObject())
955 EnsureGridLoadedAtEnter(new_cell);
957 #ifdef MANGOS_DEBUG
958 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
959 sLog.outDebug("Active 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());
960 #endif
962 RemoveFromGrid(c,getNGrid(old_cell.GridX(), old_cell.GridY()),old_cell);
963 AddToGrid(c,getNGrid(new_cell.GridX(), new_cell.GridY()),new_cell);
965 return true;
968 // in diff. loaded grid normal creature
969 if(loaded(GridPair(new_cell.GridX(), new_cell.GridY())))
971 #ifdef MANGOS_DEBUG
972 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
973 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());
974 #endif
976 RemoveFromGrid(c,getNGrid(old_cell.GridX(), old_cell.GridY()),old_cell);
978 EnsureGridCreated(GridPair(new_cell.GridX(), new_cell.GridY()));
979 AddToGrid(c,getNGrid(new_cell.GridX(), new_cell.GridY()),new_cell);
982 return true;
985 // fail to move: normal creature attempt move to unloaded grid
986 #ifdef MANGOS_DEBUG
987 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
988 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());
989 #endif
990 return false;
993 bool Map::CreatureRespawnRelocation(Creature *c)
995 float resp_x, resp_y, resp_z, resp_o;
996 c->GetRespawnCoord(resp_x, resp_y, resp_z, &resp_o);
998 CellPair resp_val = MaNGOS::ComputeCellPair(resp_x, resp_y);
999 Cell resp_cell(resp_val);
1001 c->CombatStop();
1002 c->GetMotionMaster()->Clear();
1004 #ifdef MANGOS_DEBUG
1005 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
1006 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());
1007 #endif
1009 // teleport it to respawn point (like normal respawn if player see)
1010 if(CreatureCellRelocation(c,resp_cell))
1012 c->Relocate(resp_x, resp_y, resp_z, resp_o);
1013 c->GetMotionMaster()->Initialize(); // prevent possible problems with default move generators
1014 CreatureRelocationNotify(c,resp_cell,resp_cell.cellPair());
1015 return true;
1017 else
1018 return false;
1021 bool Map::UnloadGrid(const uint32 &x, const uint32 &y, bool pForce)
1023 NGridType *grid = getNGrid(x, y);
1024 assert( grid != NULL);
1027 if(!pForce && ActiveObjectsNearGrid(x, y) )
1028 return false;
1030 DEBUG_LOG("Unloading grid[%u,%u] for map %u", x,y, i_id);
1031 ObjectGridUnloader unloader(*grid);
1033 // Finish creature moves, remove and delete all creatures with delayed remove before moving to respawn grids
1034 // Must know real mob position before move
1035 DoDelayedMovesAndRemoves();
1037 // move creatures to respawn grids if this is diff.grid or to remove list
1038 unloader.MoveToRespawnN();
1040 // Finish creature moves, remove and delete all creatures with delayed remove before unload
1041 DoDelayedMovesAndRemoves();
1043 unloader.UnloadN();
1044 delete getNGrid(x, y);
1045 setNGrid(NULL, x, y);
1047 int gx=63-x;
1048 int gy=63-y;
1050 // delete grid map, but don't delete if it is from parent map (and thus only reference)
1051 //+++if (GridMaps[gx][gy]) don't check for GridMaps[gx][gy], we might have to unload vmaps
1053 if (i_InstanceId == 0)
1055 if(GridMaps[gx][gy])
1057 GridMaps[gx][gy]->unloadData();
1058 delete GridMaps[gx][gy];
1060 // x and y are swapped
1061 VMAP::VMapFactory::createOrGetVMapManager()->unloadMap(GetId(), gy, gx);
1063 else
1064 ((MapInstanced*)m_parentMap)->RemoveGridMapReference(GridPair(gx, gy));
1066 GridMaps[gx][gy] = NULL;
1068 DEBUG_LOG("Unloading grid[%u,%u] for map %u finished", x,y, i_id);
1069 return true;
1072 void Map::UnloadAll(bool pForce)
1074 // clear all delayed moves, useless anyway do this moves before map unload.
1075 i_creaturesToMove.clear();
1077 for (GridRefManager<NGridType>::iterator i = GridRefManager<NGridType>::begin(); i != GridRefManager<NGridType>::end(); )
1079 NGridType &grid(*i->getSource());
1080 ++i;
1081 UnloadGrid(grid.getX(), grid.getY(), pForce); // deletes the grid and removes it from the GridRefManager
1085 //*****************************
1086 // Grid function
1087 //*****************************
1088 GridMap::GridMap()
1090 m_flags = 0;
1091 // Area data
1092 m_gridArea = 0;
1093 m_area_map = NULL;
1094 // Height level data
1095 m_gridHeight = INVALID_HEIGHT;
1096 m_gridGetHeight = &GridMap::getHeightFromFlat;
1097 m_V9 = NULL;
1098 m_V8 = NULL;
1099 // Liquid data
1100 m_liquidType = 0;
1101 m_liquid_offX = 0;
1102 m_liquid_offY = 0;
1103 m_liquid_width = 0;
1104 m_liquid_height = 0;
1105 m_liquidLevel = INVALID_HEIGHT;
1106 m_liquid_type = NULL;
1107 m_liquid_map = NULL;
1110 GridMap::~GridMap()
1112 unloadData();
1115 bool GridMap::loadData(char *filename)
1117 // Unload old data if exist
1118 unloadData();
1120 map_fileheader header;
1121 // Not return error if file not found
1122 FILE *in = fopen(filename, "rb");
1123 if (!in)
1124 return true;
1125 fread(&header, sizeof(header),1,in);
1126 if (header.mapMagic == uint32(MAP_MAGIC) &&
1127 header.versionMagic == uint32(MAP_VERSION_MAGIC))
1129 // loadup area data
1130 if (header.areaMapOffset && !loadAreaData(in, header.areaMapOffset, header.areaMapSize))
1132 sLog.outError("Error loading map area data\n");
1133 fclose(in);
1134 return false;
1136 // loadup height data
1137 if (header.heightMapOffset && !loadHeihgtData(in, header.heightMapOffset, header.heightMapSize))
1139 sLog.outError("Error loading map height data\n");
1140 fclose(in);
1141 return false;
1143 // loadup liquid data
1144 if (header.liquidMapOffset && !loadLiquidData(in, header.liquidMapOffset, header.liquidMapSize))
1146 sLog.outError("Error loading map liquids data\n");
1147 fclose(in);
1148 return false;
1150 fclose(in);
1151 return true;
1153 sLog.outError("Map file '%s' is non-compatible version (outdated?). Please, create new using ad.exe program.", filename);
1154 fclose(in);
1155 return false;
1158 void GridMap::unloadData()
1160 if (m_area_map) delete[] m_area_map;
1161 if (m_V9) delete[] m_V9;
1162 if (m_V8) delete[] m_V8;
1163 if (m_liquid_type) delete[] m_liquid_type;
1164 if (m_liquid_map) delete[] m_liquid_map;
1165 m_area_map = NULL;
1166 m_V9 = NULL;
1167 m_V8 = NULL;
1168 m_liquid_type = NULL;
1169 m_liquid_map = NULL;
1170 m_gridGetHeight = &GridMap::getHeightFromFlat;
1173 bool GridMap::loadAreaData(FILE *in, uint32 offset, uint32 size)
1175 map_areaHeader header;
1176 fseek(in, offset, SEEK_SET);
1177 fread(&header, sizeof(header), 1, in);
1178 if (header.fourcc != uint32(MAP_AREA_MAGIC))
1179 return false;
1181 m_gridArea = header.gridArea;
1182 if (!(header.flags & MAP_AREA_NO_AREA))
1184 m_area_map = new uint16 [16*16];
1185 fread(m_area_map, sizeof(uint16), 16*16, in);
1187 return true;
1190 bool GridMap::loadHeihgtData(FILE *in, uint32 offset, uint32 size)
1192 map_heightHeader header;
1193 fseek(in, offset, SEEK_SET);
1194 fread(&header, sizeof(header), 1, in);
1195 if (header.fourcc != uint32(MAP_HEIGHT_MAGIC))
1196 return false;
1198 m_gridHeight = header.gridHeight;
1199 if (!(header.flags & MAP_HEIGHT_NO_HEIGHT))
1201 if ((header.flags & MAP_HEIGHT_AS_INT16))
1203 m_uint16_V9 = new uint16 [129*129];
1204 m_uint16_V8 = new uint16 [128*128];
1205 fread(m_uint16_V9, sizeof(uint16), 129*129, in);
1206 fread(m_uint16_V8, sizeof(uint16), 128*128, in);
1207 m_gridIntHeightMultiplier = (header.gridMaxHeight - header.gridHeight) / 65535;
1208 m_gridGetHeight = &GridMap::getHeightFromUint16;
1210 else if ((header.flags & MAP_HEIGHT_AS_INT8))
1212 m_uint8_V9 = new uint8 [129*129];
1213 m_uint8_V8 = new uint8 [128*128];
1214 fread(m_uint8_V9, sizeof(uint8), 129*129, in);
1215 fread(m_uint8_V8, sizeof(uint8), 128*128, in);
1216 m_gridIntHeightMultiplier = (header.gridMaxHeight - header.gridHeight) / 255;
1217 m_gridGetHeight = &GridMap::getHeightFromUint8;
1219 else
1221 m_V9 = new float [129*129];
1222 m_V8 = new float [128*128];
1223 fread(m_V9, sizeof(float), 129*129, in);
1224 fread(m_V8, sizeof(float), 128*128, in);
1225 m_gridGetHeight = &GridMap::getHeightFromFloat;
1228 else
1229 m_gridGetHeight = &GridMap::getHeightFromFlat;
1230 return true;
1233 bool GridMap::loadLiquidData(FILE *in, uint32 offset, uint32 size)
1235 map_liquidHeader header;
1236 fseek(in, offset, SEEK_SET);
1237 fread(&header, sizeof(header), 1, in);
1238 if (header.fourcc != uint32(MAP_LIQUID_MAGIC))
1239 return false;
1241 m_liquidType = header.liquidType;
1242 m_liquid_offX = header.offsetX;
1243 m_liquid_offY = header.offsetY;
1244 m_liquid_width = header.width;
1245 m_liquid_height= header.height;
1246 m_liquidLevel = header.liquidLevel;
1248 if (!(header.flags & MAP_LIQUID_NO_TYPE))
1250 m_liquid_type = new uint8 [16*16];
1251 fread(m_liquid_type, sizeof(uint8), 16*16, in);
1253 if (!(header.flags & MAP_LIQUID_NO_HEIGHT))
1255 m_liquid_map = new float [m_liquid_width*m_liquid_height];
1256 fread(m_liquid_map, sizeof(float), m_liquid_width*m_liquid_height, in);
1258 return true;
1261 uint16 GridMap::getArea(float x, float y)
1263 if (!m_area_map)
1264 return m_gridArea;
1266 x = 16 * (32 - x/SIZE_OF_GRIDS);
1267 y = 16 * (32 - y/SIZE_OF_GRIDS);
1268 int lx = (int)x & 15;
1269 int ly = (int)y & 15;
1270 return m_area_map[lx*16 + ly];
1273 float GridMap::getHeightFromFlat(float /*x*/, float /*y*/) const
1275 return m_gridHeight;
1278 float GridMap::getHeightFromFloat(float x, float y) const
1280 if (!m_V8 || !m_V9)
1281 return m_gridHeight;
1283 x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
1284 y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
1286 int x_int = (int)x;
1287 int y_int = (int)y;
1288 x -= x_int;
1289 y -= y_int;
1290 x_int&=(MAP_RESOLUTION - 1);
1291 y_int&=(MAP_RESOLUTION - 1);
1293 // Height stored as: h5 - its v8 grid, h1-h4 - its v9 grid
1294 // +--------------> X
1295 // | h1-------h2 Coordinates is:
1296 // | | \ 1 / | h1 0,0
1297 // | | \ / | h2 0,1
1298 // | | 2 h5 3 | h3 1,0
1299 // | | / \ | h4 1,1
1300 // | | / 4 \ | h5 1/2,1/2
1301 // | h3-------h4
1302 // V Y
1303 // For find height need
1304 // 1 - detect triangle
1305 // 2 - solve linear equation from triangle points
1306 // Calculate coefficients for solve h = a*x + b*y + c
1308 float a,b,c;
1309 // Select triangle:
1310 if (x+y < 1)
1312 if (x > y)
1314 // 1 triangle (h1, h2, h5 points)
1315 float h1 = m_V9[(x_int )*129 + y_int];
1316 float h2 = m_V9[(x_int+1)*129 + y_int];
1317 float h5 = 2 * m_V8[x_int*128 + y_int];
1318 a = h2-h1;
1319 b = h5-h1-h2;
1320 c = h1;
1322 else
1324 // 2 triangle (h1, h3, h5 points)
1325 float h1 = m_V9[x_int*129 + y_int ];
1326 float h3 = m_V9[x_int*129 + y_int+1];
1327 float h5 = 2 * m_V8[x_int*128 + y_int];
1328 a = h5 - h1 - h3;
1329 b = h3 - h1;
1330 c = h1;
1333 else
1335 if (x > y)
1337 // 3 triangle (h2, h4, h5 points)
1338 float h2 = m_V9[(x_int+1)*129 + y_int ];
1339 float h4 = m_V9[(x_int+1)*129 + y_int+1];
1340 float h5 = 2 * m_V8[x_int*128 + y_int];
1341 a = h2 + h4 - h5;
1342 b = h4 - h2;
1343 c = h5 - h4;
1345 else
1347 // 4 triangle (h3, h4, h5 points)
1348 float h3 = m_V9[(x_int )*129 + y_int+1];
1349 float h4 = m_V9[(x_int+1)*129 + y_int+1];
1350 float h5 = 2 * m_V8[x_int*128 + y_int];
1351 a = h4 - h3;
1352 b = h3 + h4 - h5;
1353 c = h5 - h4;
1356 // Calculate height
1357 return a * x + b * y + c;
1360 float GridMap::getHeightFromUint8(float x, float y) const
1362 if (!m_uint8_V8 || !m_uint8_V9)
1363 return m_gridHeight;
1365 x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
1366 y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
1368 int x_int = (int)x;
1369 int y_int = (int)y;
1370 x -= x_int;
1371 y -= y_int;
1372 x_int&=(MAP_RESOLUTION - 1);
1373 y_int&=(MAP_RESOLUTION - 1);
1375 int32 a, b, c;
1376 uint8 *V9_h1_ptr = &m_uint8_V9[x_int*128 + x_int + y_int];
1377 if (x+y < 1)
1379 if (x > y)
1381 // 1 triangle (h1, h2, h5 points)
1382 int32 h1 = V9_h1_ptr[ 0];
1383 int32 h2 = V9_h1_ptr[129];
1384 int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int];
1385 a = h2-h1;
1386 b = h5-h1-h2;
1387 c = h1;
1389 else
1391 // 2 triangle (h1, h3, h5 points)
1392 int32 h1 = V9_h1_ptr[0];
1393 int32 h3 = V9_h1_ptr[1];
1394 int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int];
1395 a = h5 - h1 - h3;
1396 b = h3 - h1;
1397 c = h1;
1400 else
1402 if (x > y)
1404 // 3 triangle (h2, h4, h5 points)
1405 int32 h2 = V9_h1_ptr[129];
1406 int32 h4 = V9_h1_ptr[130];
1407 int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int];
1408 a = h2 + h4 - h5;
1409 b = h4 - h2;
1410 c = h5 - h4;
1412 else
1414 // 4 triangle (h3, h4, h5 points)
1415 int32 h3 = V9_h1_ptr[ 1];
1416 int32 h4 = V9_h1_ptr[130];
1417 int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int];
1418 a = h4 - h3;
1419 b = h3 + h4 - h5;
1420 c = h5 - h4;
1423 // Calculate height
1424 return (float)((a * x) + (b * y) + c)*m_gridIntHeightMultiplier + m_gridHeight;
1427 float GridMap::getHeightFromUint16(float x, float y) const
1429 if (!m_uint16_V8 || !m_uint16_V9)
1430 return m_gridHeight;
1432 x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
1433 y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
1435 int x_int = (int)x;
1436 int y_int = (int)y;
1437 x -= x_int;
1438 y -= y_int;
1439 x_int&=(MAP_RESOLUTION - 1);
1440 y_int&=(MAP_RESOLUTION - 1);
1442 int32 a, b, c;
1443 uint16 *V9_h1_ptr = &m_uint16_V9[x_int*128 + x_int + y_int];
1444 if (x+y < 1)
1446 if (x > y)
1448 // 1 triangle (h1, h2, h5 points)
1449 int32 h1 = V9_h1_ptr[ 0];
1450 int32 h2 = V9_h1_ptr[129];
1451 int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int];
1452 a = h2-h1;
1453 b = h5-h1-h2;
1454 c = h1;
1456 else
1458 // 2 triangle (h1, h3, h5 points)
1459 int32 h1 = V9_h1_ptr[0];
1460 int32 h3 = V9_h1_ptr[1];
1461 int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int];
1462 a = h5 - h1 - h3;
1463 b = h3 - h1;
1464 c = h1;
1467 else
1469 if (x > y)
1471 // 3 triangle (h2, h4, h5 points)
1472 int32 h2 = V9_h1_ptr[129];
1473 int32 h4 = V9_h1_ptr[130];
1474 int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int];
1475 a = h2 + h4 - h5;
1476 b = h4 - h2;
1477 c = h5 - h4;
1479 else
1481 // 4 triangle (h3, h4, h5 points)
1482 int32 h3 = V9_h1_ptr[ 1];
1483 int32 h4 = V9_h1_ptr[130];
1484 int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int];
1485 a = h4 - h3;
1486 b = h3 + h4 - h5;
1487 c = h5 - h4;
1490 // Calculate height
1491 return (float)((a * x) + (b * y) + c)*m_gridIntHeightMultiplier + m_gridHeight;
1494 float GridMap::getLiquidLevel(float x, float y)
1496 if (!m_liquid_map)
1497 return m_liquidLevel;
1499 x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
1500 y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
1502 int cx_int = ((int)x & (MAP_RESOLUTION-1)) - m_liquid_offY;
1503 int cy_int = ((int)y & (MAP_RESOLUTION-1)) - m_liquid_offX;
1505 if (cx_int < 0 || cx_int >=m_liquid_height)
1506 return INVALID_HEIGHT;
1507 if (cy_int < 0 || cy_int >=m_liquid_width )
1508 return INVALID_HEIGHT;
1510 return m_liquid_map[cx_int*m_liquid_width + cy_int];
1513 uint8 GridMap::getTerrainType(float x, float y)
1515 if (!m_liquid_type)
1516 return m_liquidType;
1518 x = 16 * (32 - x/SIZE_OF_GRIDS);
1519 y = 16 * (32 - y/SIZE_OF_GRIDS);
1520 int lx = (int)x & 15;
1521 int ly = (int)y & 15;
1522 return m_liquid_type[lx*16 + ly];
1525 // Get water state on map
1526 inline ZLiquidStatus GridMap::getLiquidStatus(float x, float y, float z, uint8 ReqLiquidType, LiquidData *data)
1528 // Check water type (if no water return)
1529 if (!m_liquid_type && !m_liquidType)
1530 return LIQUID_MAP_NO_WATER;
1532 // Get cell
1533 float cx = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
1534 float cy = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
1536 int x_int = (int)cx & (MAP_RESOLUTION-1);
1537 int y_int = (int)cy & (MAP_RESOLUTION-1);
1539 // Check water type in cell
1540 uint8 type = m_liquid_type ? m_liquid_type[(x_int>>3)*16 + (y_int>>3)] : m_liquidType;
1541 if (type == 0)
1542 return LIQUID_MAP_NO_WATER;
1544 // Check req liquid type mask
1545 if (ReqLiquidType && !(ReqLiquidType&type))
1546 return LIQUID_MAP_NO_WATER;
1548 // Check water level:
1549 // Check water height map
1550 int lx_int = x_int - m_liquid_offY;
1551 int ly_int = y_int - m_liquid_offX;
1552 if (lx_int < 0 || lx_int >=m_liquid_height)
1553 return LIQUID_MAP_NO_WATER;
1554 if (ly_int < 0 || ly_int >=m_liquid_width )
1555 return LIQUID_MAP_NO_WATER;
1557 // Get water level
1558 float liquid_level = m_liquid_map ? m_liquid_map[lx_int*m_liquid_width + ly_int] : m_liquidLevel;
1559 // Get ground level (sub 0.2 for fix some errors)
1560 float ground_level = getHeight(x, y);
1562 // Check water level and ground level
1563 if (liquid_level < ground_level || z < ground_level - 2)
1564 return LIQUID_MAP_NO_WATER;
1566 // All ok in water -> store data
1567 if (data)
1569 data->type = type;
1570 data->level = liquid_level;
1571 data->depth_level = ground_level;
1574 // For speed check as int values
1575 int delta = int((liquid_level - z) * 10);
1577 // Get position delta
1578 if (delta > 20) // Under water
1579 return LIQUID_MAP_UNDER_WATER;
1580 if (delta > 0 ) // In water
1581 return LIQUID_MAP_IN_WATER;
1582 if (delta > -1) // Walk on water
1583 return LIQUID_MAP_WATER_WALK;
1584 // Above water
1585 return LIQUID_MAP_ABOVE_WATER;
1588 inline GridMap *Map::GetGrid(float x, float y)
1590 // half opt method
1591 int gx=(int)(32-x/SIZE_OF_GRIDS); //grid x
1592 int gy=(int)(32-y/SIZE_OF_GRIDS); //grid y
1594 // ensure GridMap is loaded
1595 EnsureGridCreated(GridPair(63-gx,63-gy));
1597 return GridMaps[gx][gy];
1600 float Map::GetHeight(float x, float y, float z, bool pUseVmaps) const
1602 // find raw .map surface under Z coordinates
1603 float mapHeight;
1604 if(GridMap *gmap = const_cast<Map*>(this)->GetGrid(x, y))
1606 float _mapheight = gmap->getHeight(x,y);
1608 // look from a bit higher pos to find the floor, ignore under surface case
1609 if(z + 2.0f > _mapheight)
1610 mapHeight = _mapheight;
1611 else
1612 mapHeight = VMAP_INVALID_HEIGHT_VALUE;
1614 else
1615 mapHeight = VMAP_INVALID_HEIGHT_VALUE;
1617 float vmapHeight;
1618 if(pUseVmaps)
1620 VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager();
1621 if(vmgr->isHeightCalcEnabled())
1623 // look from a bit higher pos to find the floor
1624 vmapHeight = vmgr->getHeight(GetId(), x, y, z + 2.0f);
1626 else
1627 vmapHeight = VMAP_INVALID_HEIGHT_VALUE;
1629 else
1630 vmapHeight = VMAP_INVALID_HEIGHT_VALUE;
1632 // mapHeight set for any above raw ground Z or <= INVALID_HEIGHT
1633 // vmapheight set for any under Z value or <= INVALID_HEIGHT
1635 if( vmapHeight > INVALID_HEIGHT )
1637 if( mapHeight > INVALID_HEIGHT )
1639 // we have mapheight and vmapheight and must select more appropriate
1641 // we are already under the surface or vmap height above map heigt
1642 // or if the distance of the vmap height is less the land height distance
1643 if( z < mapHeight || vmapHeight > mapHeight || fabs(mapHeight-z) > fabs(vmapHeight-z) )
1644 return vmapHeight;
1645 else
1646 return mapHeight; // better use .map surface height
1649 else
1650 return vmapHeight; // we have only vmapHeight (if have)
1652 else
1654 if(!pUseVmaps)
1655 return mapHeight; // explicitly use map data (if have)
1656 else if(mapHeight > INVALID_HEIGHT && (z < mapHeight + 2 || z == MAX_HEIGHT))
1657 return mapHeight; // explicitly use map data if original z < mapHeight but map found (z+2 > mapHeight)
1658 else
1659 return VMAP_INVALID_HEIGHT_VALUE; // we not have any height
1663 uint16 Map::GetAreaFlag(float x, float y, float z) const
1665 uint16 areaflag;
1666 if(GridMap *gmap = const_cast<Map*>(this)->GetGrid(x, y))
1667 areaflag = gmap->getArea(x, y);
1668 // this used while not all *.map files generated (instances)
1669 else
1670 areaflag = GetAreaFlagByMapId(i_id);
1672 //FIXME: some hacks for areas above or underground for ground area
1673 // required for area specific spells/etc, until map/vmap data
1674 // not provided correct areaflag with this hacks
1675 switch(areaflag)
1677 // Acherus: The Ebon Hold (Plaguelands: The Scarlet Enclave)
1678 case 1984: // Plaguelands: The Scarlet Enclave
1679 case 2076: // Death's Breach (Plaguelands: The Scarlet Enclave)
1680 case 2745: // The Noxious Pass (Plaguelands: The Scarlet Enclave)
1681 if(z > 350.0f) areaflag = 2048; break;
1682 // Acherus: The Ebon Hold (Eastern Plaguelands)
1683 case 856: // The Noxious Glade (Eastern Plaguelands)
1684 case 2456: // Death's Breach (Eastern Plaguelands)
1685 if(z > 350.0f) areaflag = 1950; break;
1686 // Dalaran
1687 case 2492: // Forlorn Woods (Crystalsong Forest)
1688 if (x > 5568.0f && x < 6116.0f && y > 282.0f && y < 982.0f && z > 563.0f)
1690 // Krasus' Landing (Dalaran), fast check
1691 if (x > 5758.77f && x < 5869.03f && y < 510.46f)
1693 // Krasus' Landing (Dalaran), with open east side
1694 if (y < 449.33f || (x-5813.9f)*(x-5813.9f)+(y-449.33f)*(y-449.33f) < 1864.0f)
1696 areaflag = 2533; // Note: also 2633, possible one flight allowed and other not allowed case
1697 break;
1701 // Dalaran
1702 areaflag = 2153;
1704 break;
1705 // The Violet Citadel (Dalaran) or Dalaran
1706 case 2484: // The Twilight Rivulet (Crystalsong Forest)
1707 case 1593: // Crystalsong Forest
1708 // Dalaran
1709 if (x > 5568.0f && x < 6116.0f && y > 282.0f && y < 982.0f && z > 563.0f)
1711 // The Violet Citadel (Dalaran), fast check
1712 if (x > 5721.1f && x < 5884.66f && y > 764.4f && y < 948.0f)
1714 // The Violet Citadel (Dalaran)
1715 if ((x-5803.0f)*(x-5803.0f)+(y-846.18f)*(y-846.18f) < 6690.0f)
1717 areaflag = 2696;
1718 break;
1722 // Dalaran
1723 areaflag = 2153;
1725 break;
1726 // Vargoth's Retreat (Dalaran) or The Violet Citadel (Dalaran) or Dalaran
1727 case 2504: // Violet Stand (Crystalsong Forest)
1728 // Dalaran
1729 if (x > 5568.0f && x < 6116.0f && y > 282.0f && y < 982.0f && z > 563.0f)
1731 // The Violet Citadel (Dalaran), fast check
1732 if (x > 5721.1f && x < 5884.66f && y > 764.4f && y < 948.0f)
1734 // Vargoth's Retreat (Dalaran), nice slow circle with upper limit
1735 if (z < 898.0f && (x-5765.0f)*(x-5765.0f)+(y-862.4f)*(y-862.4f) < 262.0f)
1737 areaflag = 2748;
1738 break;
1741 // The Violet Citadel (Dalaran)
1742 if ((x-5803.0f)*(x-5803.0f)+(y-846.18f)*(y-846.18f) < 6690.0f)
1744 areaflag = 2696;
1745 break;
1749 // Dalaran
1750 areaflag = 2153;
1752 break;
1753 // Maw of Neltharion (cave)
1754 case 164: // Dragonblight
1755 case 1797: // Obsidian Dragonshrine (Dragonblight)
1756 case 1827: // Wintergrasp
1757 case 2591: // The Cauldron of Flames (Wintergrasp)
1758 if (x > 4364.0f && x < 4632.0f && y > 1545.0f && y < 1886.0f && z < 200.0f) areaflag = 1853; break;
1759 // Undercity (sewers enter and path)
1760 case 179: // Tirisfal Glades
1761 if (x > 1595.0f && x < 1699.0f && y > 535.0f && y < 643.5f && z < 30.5f) areaflag = 685; break;
1762 // Undercity (Royal Quarter)
1763 case 210: // Silverpine Forest
1764 case 316: // The Shining Strand (Silverpine Forest)
1765 case 438: // Lordamere Lake (Silverpine Forest)
1766 if (x > 1237.0f && x < 1401.0f && y > 284.0f && y < 440.0f && z < -40.0f) areaflag = 685; break;
1767 // Undercity (cave and ground zone, part of royal quarter)
1768 case 607: // Ruins of Lordaeron (Tirisfal Glades)
1769 // ground and near to ground (by city walls)
1770 if(z > 0.0f)
1772 if (x > 1510.0f && x < 1839.0f && y > 29.77f && y < 433.0f) areaflag = 685;
1774 // more wide underground, part of royal quarter
1775 else
1777 if (x > 1299.0f && x < 1839.0f && y > 10.0f && y < 440.0f) areaflag = 685;
1779 break;
1780 // The Makers' Perch (ground) and Makers' Overlook (ground and cave)
1781 case 1335: // Sholazar Basin
1782 // The Makers' Perch ground (fast box)
1783 if (x > 6100.0f && x < 6250.0f && y > 5650.0f && y < 5800.0f)
1785 // nice slow circle
1786 if ((x-6183.0f)*(x-6183.0f)+(y-5717.0f)*(y-5717.0f) < 2500.0f)
1787 areaflag = 2189;
1789 // Makers' Overlook (ground and cave)
1790 else if (x > 5634.48f && x < 5774.53f && y < 3475.0f && z > 300.0f)
1792 if(y > 3380.26f || y > 3265.0f && z < 360.0f) areaflag = 2187;
1794 break;
1795 // The Makers' Perch (underground)
1796 case 2147: // The Stormwright's Shelf (Sholazar Basin)
1797 if (x > 6199.0f && x < 6283.0f && y > 5705.0f && y < 5817.0f && z < 38.0f) areaflag = 2189; break;
1798 // Makers' Overlook (deep cave)
1799 case 267: // Icecrown
1800 if (x > 5684.0f && x < 5798.0f && y > 3035.0f && y < 3367.0f && z < 358.0f) areaflag = 2187; break;
1801 // Wyrmrest Temple (Dragonblight)
1802 case 1814: // Path of the Titans (Dragonblight)
1803 case 1897: // The Dragon Wastes (Dragonblight)
1804 // fast box
1805 if (x > 3400.0f && x < 3700.0f && y > 130.0f && y < 420.0f)
1807 // nice slow circle
1808 if ((x-3546.87f)*(x-3546.87f)+(y-272.71f)*(y-272.71f) < 19600.0f) areaflag = 1791;
1810 break;
1813 return areaflag;
1816 uint8 Map::GetTerrainType(float x, float y ) const
1818 if(GridMap *gmap = const_cast<Map*>(this)->GetGrid(x, y))
1819 return gmap->getTerrainType(x, y);
1820 else
1821 return 0;
1824 ZLiquidStatus Map::getLiquidStatus(float x, float y, float z, uint8 ReqLiquidType, LiquidData *data) const
1826 if(GridMap* gmap = const_cast<Map*>(this)->GetGrid(x, y))
1827 return gmap->getLiquidStatus(x, y, z, ReqLiquidType, data);
1828 else
1829 return LIQUID_MAP_NO_WATER;
1832 float Map::GetWaterLevel(float x, float y ) const
1834 if(GridMap* gmap = const_cast<Map*>(this)->GetGrid(x, y))
1835 return gmap->getLiquidLevel(x, y);
1836 else
1837 return 0;
1840 uint32 Map::GetAreaIdByAreaFlag(uint16 areaflag,uint32 map_id)
1842 AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
1844 if (entry)
1845 return entry->ID;
1846 else
1847 return 0;
1850 uint32 Map::GetZoneIdByAreaFlag(uint16 areaflag,uint32 map_id)
1852 AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
1854 if( entry )
1855 return ( entry->zone != 0 ) ? entry->zone : entry->ID;
1856 else
1857 return 0;
1860 void Map::GetZoneAndAreaIdByAreaFlag(uint32& zoneid, uint32& areaid, uint16 areaflag,uint32 map_id)
1862 AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
1864 areaid = entry ? entry->ID : 0;
1865 zoneid = entry ? (( entry->zone != 0 ) ? entry->zone : entry->ID) : 0;
1868 bool Map::IsInWater(float x, float y, float pZ) const
1870 // Check surface in x, y point for liquid
1871 if (GridMap* gmap = const_cast<Map*>(this)->GetGrid(x, y))
1873 LiquidData liquid_status;
1874 if (getLiquidStatus(x, y, pZ, MAP_ALL_LIQUIDS, &liquid_status))
1876 if (liquid_status.level - liquid_status.depth_level > 2)
1877 return true;
1880 return false;
1883 bool Map::IsUnderWater(float x, float y, float z) const
1885 if (GridMap* gmap = const_cast<Map*>(this)->GetGrid(x, y))
1887 if (getLiquidStatus(x, y, z, MAP_LIQUID_TYPE_WATER|MAP_LIQUID_TYPE_OCEAN)&LIQUID_MAP_UNDER_WATER)
1888 return true;
1890 return false;
1893 bool Map::CheckGridIntegrity(Creature* c, bool moved) const
1895 Cell const& cur_cell = c->GetCurrentCell();
1897 CellPair xy_val = MaNGOS::ComputeCellPair(c->GetPositionX(), c->GetPositionY());
1898 Cell xy_cell(xy_val);
1899 if(xy_cell != cur_cell)
1901 sLog.outError("Creature (GUIDLow: %u) X: %f Y: %f (%s) in grid[%u,%u]cell[%u,%u] instead grid[%u,%u]cell[%u,%u]",
1902 c->GetGUIDLow(),
1903 c->GetPositionX(),c->GetPositionY(),(moved ? "final" : "original"),
1904 cur_cell.GridX(), cur_cell.GridY(), cur_cell.CellX(), cur_cell.CellY(),
1905 xy_cell.GridX(), xy_cell.GridY(), xy_cell.CellX(), xy_cell.CellY());
1906 return true; // not crash at error, just output error in debug mode
1909 return true;
1912 const char* Map::GetMapName() const
1914 return i_mapEntry ? i_mapEntry->name[sWorld.GetDefaultDbcLocale()] : "UNNAMEDMAP\x0";
1917 void Map::UpdateObjectVisibility( WorldObject* obj, Cell cell, CellPair cellpair)
1919 cell.data.Part.reserved = ALL_DISTRICT;
1920 cell.SetNoCreate();
1921 MaNGOS::VisibleChangesNotifier notifier(*obj);
1922 TypeContainerVisitor<MaNGOS::VisibleChangesNotifier, WorldTypeMapContainer > player_notifier(notifier);
1923 CellLock<GridReadGuard> cell_lock(cell, cellpair);
1924 cell_lock->Visit(cell_lock, player_notifier, *this);
1927 void Map::UpdatePlayerVisibility( Player* player, Cell cell, CellPair cellpair )
1929 cell.data.Part.reserved = ALL_DISTRICT;
1931 MaNGOS::PlayerNotifier pl_notifier(*player);
1932 TypeContainerVisitor<MaNGOS::PlayerNotifier, WorldTypeMapContainer > player_notifier(pl_notifier);
1934 CellLock<ReadGuard> cell_lock(cell, cellpair);
1935 cell_lock->Visit(cell_lock, player_notifier, *this);
1938 void Map::UpdateObjectsVisibilityFor( Player* player, Cell cell, CellPair cellpair )
1940 MaNGOS::VisibleNotifier notifier(*player);
1942 cell.data.Part.reserved = ALL_DISTRICT;
1943 cell.SetNoCreate();
1944 TypeContainerVisitor<MaNGOS::VisibleNotifier, WorldTypeMapContainer > world_notifier(notifier);
1945 TypeContainerVisitor<MaNGOS::VisibleNotifier, GridTypeMapContainer > grid_notifier(notifier);
1946 CellLock<GridReadGuard> cell_lock(cell, cellpair);
1947 cell_lock->Visit(cell_lock, world_notifier, *this);
1948 cell_lock->Visit(cell_lock, grid_notifier, *this);
1950 // send data
1951 notifier.Notify();
1954 void Map::PlayerRelocationNotify( Player* player, Cell cell, CellPair cellpair )
1956 CellLock<ReadGuard> cell_lock(cell, cellpair);
1957 MaNGOS::PlayerRelocationNotifier relocationNotifier(*player);
1958 cell.data.Part.reserved = ALL_DISTRICT;
1960 TypeContainerVisitor<MaNGOS::PlayerRelocationNotifier, GridTypeMapContainer > p2grid_relocation(relocationNotifier);
1961 TypeContainerVisitor<MaNGOS::PlayerRelocationNotifier, WorldTypeMapContainer > p2world_relocation(relocationNotifier);
1963 cell_lock->Visit(cell_lock, p2grid_relocation, *this);
1964 cell_lock->Visit(cell_lock, p2world_relocation, *this);
1967 void Map::CreatureRelocationNotify(Creature *creature, Cell cell, CellPair cellpair)
1969 CellLock<ReadGuard> cell_lock(cell, cellpair);
1970 MaNGOS::CreatureRelocationNotifier relocationNotifier(*creature);
1971 cell.data.Part.reserved = ALL_DISTRICT;
1972 cell.SetNoCreate(); // not trigger load unloaded grids at notifier call
1974 TypeContainerVisitor<MaNGOS::CreatureRelocationNotifier, WorldTypeMapContainer > c2world_relocation(relocationNotifier);
1975 TypeContainerVisitor<MaNGOS::CreatureRelocationNotifier, GridTypeMapContainer > c2grid_relocation(relocationNotifier);
1977 cell_lock->Visit(cell_lock, c2world_relocation, *this);
1978 cell_lock->Visit(cell_lock, c2grid_relocation, *this);
1981 void Map::SendInitSelf( Player * player )
1983 sLog.outDetail("Creating player data for himself %u", player->GetGUIDLow());
1985 UpdateData data;
1987 // attach to player data current transport data
1988 if(Transport* transport = player->GetTransport())
1990 transport->BuildCreateUpdateBlockForPlayer(&data, player);
1993 // build data for self presence in world at own client (one time for map)
1994 player->BuildCreateUpdateBlockForPlayer(&data, player);
1996 // build other passengers at transport also (they always visible and marked as visible and will not send at visibility update at add to map
1997 if(Transport* transport = player->GetTransport())
1999 for(Transport::PlayerSet::const_iterator itr = transport->GetPassengers().begin();itr!=transport->GetPassengers().end();++itr)
2001 if(player!=(*itr) && player->HaveAtClient(*itr))
2003 (*itr)->BuildCreateUpdateBlockForPlayer(&data, player);
2008 WorldPacket packet;
2009 data.BuildPacket(&packet);
2010 player->GetSession()->SendPacket(&packet);
2013 void Map::SendInitTransports( Player * player )
2015 // Hack to send out transports
2016 MapManager::TransportMap& tmap = MapManager::Instance().m_TransportsByMap;
2018 // no transports at map
2019 if (tmap.find(player->GetMapId()) == tmap.end())
2020 return;
2022 UpdateData transData;
2024 MapManager::TransportSet& tset = tmap[player->GetMapId()];
2026 for (MapManager::TransportSet::const_iterator i = tset.begin(); i != tset.end(); ++i)
2028 // send data for current transport in other place
2029 if((*i) != player->GetTransport() && (*i)->GetMapId()==i_id)
2031 (*i)->BuildCreateUpdateBlockForPlayer(&transData, player);
2035 WorldPacket packet;
2036 transData.BuildPacket(&packet);
2037 player->GetSession()->SendPacket(&packet);
2040 void Map::SendRemoveTransports( Player * player )
2042 // Hack to send out transports
2043 MapManager::TransportMap& tmap = MapManager::Instance().m_TransportsByMap;
2045 // no transports at map
2046 if (tmap.find(player->GetMapId()) == tmap.end())
2047 return;
2049 UpdateData transData;
2051 MapManager::TransportSet& tset = tmap[player->GetMapId()];
2053 // except used transport
2054 for (MapManager::TransportSet::const_iterator i = tset.begin(); i != tset.end(); ++i)
2055 if((*i) != player->GetTransport() && (*i)->GetMapId()!=i_id)
2056 (*i)->BuildOutOfRangeUpdateBlock(&transData);
2058 WorldPacket packet;
2059 transData.BuildPacket(&packet);
2060 player->GetSession()->SendPacket(&packet);
2063 inline void Map::setNGrid(NGridType *grid, uint32 x, uint32 y)
2065 if(x >= MAX_NUMBER_OF_GRIDS || y >= MAX_NUMBER_OF_GRIDS)
2067 sLog.outError("map::setNGrid() Invalid grid coordinates found: %d, %d!",x,y);
2068 assert(false);
2070 i_grids[x][y] = grid;
2073 void Map::DoDelayedMovesAndRemoves()
2075 MoveAllCreaturesInMoveList();
2076 RemoveAllObjectsInRemoveList();
2079 void Map::AddObjectToRemoveList(WorldObject *obj)
2081 assert(obj->GetMapId()==GetId() && obj->GetInstanceId()==GetInstanceId());
2083 obj->CleanupsBeforeDelete(); // remove or simplify at least cross referenced links
2085 i_objectsToRemove.insert(obj);
2086 //sLog.outDebug("Object (GUID: %u TypeId: %u ) added to removing list.",obj->GetGUIDLow(),obj->GetTypeId());
2089 void Map::RemoveAllObjectsInRemoveList()
2091 if(i_objectsToRemove.empty())
2092 return;
2094 //sLog.outDebug("Object remover 1 check.");
2095 while(!i_objectsToRemove.empty())
2097 WorldObject* obj = *i_objectsToRemove.begin();
2098 i_objectsToRemove.erase(i_objectsToRemove.begin());
2100 switch(obj->GetTypeId())
2102 case TYPEID_CORPSE:
2104 Corpse* corpse = ObjectAccessor::Instance().GetCorpse(*obj, obj->GetGUID());
2105 if (!corpse)
2106 sLog.outError("Try delete corpse/bones %u that not in map", obj->GetGUIDLow());
2107 else
2108 Remove(corpse,true);
2109 break;
2111 case TYPEID_DYNAMICOBJECT:
2112 Remove((DynamicObject*)obj,true);
2113 break;
2114 case TYPEID_GAMEOBJECT:
2115 Remove((GameObject*)obj,true);
2116 break;
2117 case TYPEID_UNIT:
2118 // in case triggered sequence some spell can continue casting after prev CleanupsBeforeDelete call
2119 // make sure that like sources auras/etc removed before destructor start
2120 ((Creature*)obj)->CleanupsBeforeDelete ();
2121 Remove((Creature*)obj,true);
2122 break;
2123 default:
2124 sLog.outError("Non-grid object (TypeId: %u) in grid object removing list, ignored.",obj->GetTypeId());
2125 break;
2128 //sLog.outDebug("Object remover 2 check.");
2131 uint32 Map::GetPlayersCountExceptGMs() const
2133 uint32 count = 0;
2134 for(MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
2135 if(!itr->getSource()->isGameMaster())
2136 ++count;
2137 return count;
2140 void Map::SendToPlayers(WorldPacket const* data) const
2142 for(MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
2143 itr->getSource()->GetSession()->SendPacket(data);
2146 bool Map::ActiveObjectsNearGrid(uint32 x, uint32 y) const
2148 CellPair cell_min(x*MAX_NUMBER_OF_CELLS, y*MAX_NUMBER_OF_CELLS);
2149 CellPair cell_max(cell_min.x_coord + MAX_NUMBER_OF_CELLS, cell_min.y_coord+MAX_NUMBER_OF_CELLS);
2150 cell_min << 2;
2151 cell_min -= 2;
2152 cell_max >> 2;
2153 cell_max += 2;
2155 for(MapRefManager::const_iterator iter = m_mapRefManager.begin(); iter != m_mapRefManager.end(); ++iter)
2157 Player* plr = iter->getSource();
2159 CellPair p = MaNGOS::ComputeCellPair(plr->GetPositionX(), plr->GetPositionY());
2160 if( (cell_min.x_coord <= p.x_coord && p.x_coord <= cell_max.x_coord) &&
2161 (cell_min.y_coord <= p.y_coord && p.y_coord <= cell_max.y_coord) )
2162 return true;
2165 for(ActiveNonPlayers::const_iterator iter = m_activeNonPlayers.begin(); iter != m_activeNonPlayers.end(); ++iter)
2167 WorldObject* obj = *iter;
2169 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
2170 if( (cell_min.x_coord <= p.x_coord && p.x_coord <= cell_max.x_coord) &&
2171 (cell_min.y_coord <= p.y_coord && p.y_coord <= cell_max.y_coord) )
2172 return true;
2175 return false;
2178 void Map::AddToActive( Creature* c )
2180 AddToActiveHelper(c);
2182 // also not allow unloading spawn grid to prevent creating creature clone at load
2183 if(!c->isPet() && c->GetDBTableGUIDLow())
2185 float x,y,z;
2186 c->GetRespawnCoord(x,y,z);
2187 GridPair p = MaNGOS::ComputeGridPair(x, y);
2188 if(getNGrid(p.x_coord, p.y_coord))
2189 getNGrid(p.x_coord, p.y_coord)->incUnloadActiveLock();
2190 else
2192 GridPair p2 = MaNGOS::ComputeGridPair(c->GetPositionX(), c->GetPositionY());
2193 sLog.outError("Active creature (GUID: %u Entry: %u) added to grid[%u,%u] but spawn grid[%u,%u] not loaded.",
2194 c->GetGUIDLow(), c->GetEntry(), p.x_coord, p.y_coord, p2.x_coord, p2.y_coord);
2199 void Map::RemoveFromActive( Creature* c )
2201 RemoveFromActiveHelper(c);
2203 // also allow unloading spawn grid
2204 if(!c->isPet() && c->GetDBTableGUIDLow())
2206 float x,y,z;
2207 c->GetRespawnCoord(x,y,z);
2208 GridPair p = MaNGOS::ComputeGridPair(x, y);
2209 if(getNGrid(p.x_coord, p.y_coord))
2210 getNGrid(p.x_coord, p.y_coord)->decUnloadActiveLock();
2211 else
2213 GridPair p2 = MaNGOS::ComputeGridPair(c->GetPositionX(), c->GetPositionY());
2214 sLog.outError("Active creature (GUID: %u Entry: %u) removed from grid[%u,%u] but spawn grid[%u,%u] not loaded.",
2215 c->GetGUIDLow(), c->GetEntry(), p.x_coord, p.y_coord, p2.x_coord, p2.y_coord);
2220 template void Map::Add(Corpse *);
2221 template void Map::Add(Creature *);
2222 template void Map::Add(GameObject *);
2223 template void Map::Add(DynamicObject *);
2225 template void Map::Remove(Corpse *,bool);
2226 template void Map::Remove(Creature *,bool);
2227 template void Map::Remove(GameObject *, bool);
2228 template void Map::Remove(DynamicObject *, bool);
2230 /* ******* Dungeon Instance Maps ******* */
2232 InstanceMap::InstanceMap(uint32 id, time_t expiry, uint32 InstanceId, uint8 SpawnMode, Map* _parent)
2233 : Map(id, expiry, InstanceId, SpawnMode, _parent),
2234 m_resetAfterUnload(false), m_unloadWhenEmpty(false),
2235 i_data(NULL), i_script_id(0)
2237 // the timer is started by default, and stopped when the first player joins
2238 // this make sure it gets unloaded if for some reason no player joins
2239 m_unloadTimer = std::max(sWorld.getConfig(CONFIG_INSTANCE_UNLOAD_DELAY), (uint32)MIN_UNLOAD_DELAY);
2242 InstanceMap::~InstanceMap()
2244 if(i_data)
2246 delete i_data;
2247 i_data = NULL;
2252 Do map specific checks to see if the player can enter
2254 bool InstanceMap::CanEnter(Player *player)
2256 if(player->GetMapRef().getTarget() == this)
2258 sLog.outError("InstanceMap::CanEnter - player %s(%u) already in map %d,%d,%d!", player->GetName(), player->GetGUIDLow(), GetId(), GetInstanceId(), GetSpawnMode());
2259 assert(false);
2260 return false;
2263 // cannot enter if the instance is full (player cap), GMs don't count
2264 uint32 maxPlayers = GetMaxPlayers();
2265 if (!player->isGameMaster() && GetPlayersCountExceptGMs() >= maxPlayers)
2267 sLog.outDetail("MAP: Instance '%u' of map '%s' cannot have more than '%u' players. Player '%s' rejected", GetInstanceId(), GetMapName(), maxPlayers, player->GetName());
2268 player->SendTransferAborted(GetId(), TRANSFER_ABORT_MAX_PLAYERS);
2269 return false;
2272 // cannot enter while players in the instance are in combat
2273 Group *pGroup = player->GetGroup();
2274 if(pGroup && pGroup->InCombatToInstance(GetInstanceId()) && player->isAlive() && player->GetMapId() != GetId())
2276 player->SendTransferAborted(GetId(), TRANSFER_ABORT_ZONE_IN_COMBAT);
2277 return false;
2280 return Map::CanEnter(player);
2284 Do map specific checks and add the player to the map if successful.
2286 bool InstanceMap::Add(Player *player)
2288 // TODO: Not sure about checking player level: already done in HandleAreaTriggerOpcode
2289 // GMs still can teleport player in instance.
2290 // Is it needed?
2293 Guard guard(*this);
2294 if(!CanEnter(player))
2295 return false;
2297 // Dungeon only code
2298 if(IsDungeon())
2300 // get or create an instance save for the map
2301 InstanceSave *mapSave = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
2302 if(!mapSave)
2304 sLog.outDetail("InstanceMap::Add: creating instance save for map %d spawnmode %d with instance id %d", GetId(), GetSpawnMode(), GetInstanceId());
2305 mapSave = sInstanceSaveManager.AddInstanceSave(GetId(), GetInstanceId(), GetSpawnMode(), 0, true);
2308 // check for existing instance binds
2309 InstancePlayerBind *playerBind = player->GetBoundInstance(GetId(), GetSpawnMode());
2310 if(playerBind && playerBind->perm)
2312 // cannot enter other instances if bound permanently
2313 if(playerBind->save != mapSave)
2315 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());
2316 assert(false);
2319 else
2321 Group *pGroup = player->GetGroup();
2322 if(pGroup)
2324 // solo saves should be reset when entering a group
2325 InstanceGroupBind *groupBind = pGroup->GetBoundInstance(GetId(), GetSpawnMode());
2326 if(playerBind)
2328 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());
2329 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());
2330 assert(false);
2332 // bind to the group or keep using the group save
2333 if(!groupBind)
2334 pGroup->BindToInstance(mapSave, false);
2335 else
2337 // cannot jump to a different instance without resetting it
2338 if(groupBind->save != mapSave)
2340 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());
2341 if(mapSave)
2342 sLog.outError("MapSave players: %d, group count: %d", mapSave->GetPlayerCount(), mapSave->GetGroupCount());
2343 else
2344 sLog.outError("MapSave NULL");
2345 if(groupBind->save)
2346 sLog.outError("GroupBind save players: %d, group count: %d", groupBind->save->GetPlayerCount(), groupBind->save->GetGroupCount());
2347 else
2348 sLog.outError("GroupBind save NULL");
2349 assert(false);
2351 // if the group/leader is permanently bound to the instance
2352 // players also become permanently bound when they enter
2353 if(groupBind->perm)
2355 WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
2356 data << uint32(0);
2357 player->GetSession()->SendPacket(&data);
2358 player->BindToInstance(mapSave, true);
2362 else
2364 // set up a solo bind or continue using it
2365 if(!playerBind)
2366 player->BindToInstance(mapSave, false);
2367 else
2368 // cannot jump to a different instance without resetting it
2369 assert(playerBind->save == mapSave);
2374 if(i_data) i_data->OnPlayerEnter(player);
2375 // for normal instances cancel the reset schedule when the
2376 // first player enters (no players yet)
2377 SetResetSchedule(false);
2379 sLog.outDetail("MAP: Player '%s' entered the instance '%u' of map '%s'", player->GetName(), GetInstanceId(), GetMapName());
2380 // initialize unload state
2381 m_unloadTimer = 0;
2382 m_resetAfterUnload = false;
2383 m_unloadWhenEmpty = false;
2386 // this will acquire the same mutex so it cannot be in the previous block
2387 Map::Add(player);
2388 return true;
2391 void InstanceMap::Update(const uint32& t_diff)
2393 Map::Update(t_diff);
2395 if(i_data)
2396 i_data->Update(t_diff);
2399 void InstanceMap::Remove(Player *player, bool remove)
2401 sLog.outDetail("MAP: Removing player '%s' from instance '%u' of map '%s' before relocating to other map", player->GetName(), GetInstanceId(), GetMapName());
2402 //if last player set unload timer
2403 if(!m_unloadTimer && m_mapRefManager.getSize() == 1)
2404 m_unloadTimer = m_unloadWhenEmpty ? MIN_UNLOAD_DELAY : std::max(sWorld.getConfig(CONFIG_INSTANCE_UNLOAD_DELAY), (uint32)MIN_UNLOAD_DELAY);
2405 Map::Remove(player, remove);
2406 // for normal instances schedule the reset after all players have left
2407 SetResetSchedule(true);
2410 void InstanceMap::CreateInstanceData(bool load)
2412 if(i_data != NULL)
2413 return;
2415 InstanceTemplate const* mInstance = objmgr.GetInstanceTemplate(GetId());
2416 if (mInstance)
2418 i_script_id = mInstance->script_id;
2419 i_data = Script->CreateInstanceData(this);
2422 if(!i_data)
2423 return;
2425 if(load)
2427 // TODO: make a global storage for this
2428 QueryResult* result = CharacterDatabase.PQuery("SELECT data FROM instance WHERE map = '%u' AND id = '%u'", GetId(), i_InstanceId);
2429 if (result)
2431 Field* fields = result->Fetch();
2432 const char* data = fields[0].GetString();
2433 if(data)
2435 sLog.outDebug("Loading instance data for `%s` with id %u", objmgr.GetScriptName(i_script_id), i_InstanceId);
2436 i_data->Load(data);
2438 delete result;
2441 else
2443 sLog.outDebug("New instance data, \"%s\" ,initialized!", objmgr.GetScriptName(i_script_id));
2444 i_data->Initialize();
2449 Returns true if there are no players in the instance
2451 bool InstanceMap::Reset(uint8 method)
2453 // note: since the map may not be loaded when the instance needs to be reset
2454 // the instance must be deleted from the DB by InstanceSaveManager
2456 if(HavePlayers())
2458 if(method == INSTANCE_RESET_ALL)
2460 // notify the players to leave the instance so it can be reset
2461 for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
2462 itr->getSource()->SendResetFailedNotify(GetId());
2464 else
2466 if(method == INSTANCE_RESET_GLOBAL)
2468 // set the homebind timer for players inside (1 minute)
2469 for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
2470 itr->getSource()->m_InstanceValid = false;
2473 // the unload timer is not started
2474 // instead the map will unload immediately after the players have left
2475 m_unloadWhenEmpty = true;
2476 m_resetAfterUnload = true;
2479 else
2481 // unloaded at next update
2482 m_unloadTimer = MIN_UNLOAD_DELAY;
2483 m_resetAfterUnload = true;
2486 return m_mapRefManager.isEmpty();
2489 void InstanceMap::PermBindAllPlayers(Player *player)
2491 if(!IsDungeon())
2492 return;
2494 InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
2495 if(!save)
2497 sLog.outError("Cannot bind players, no instance save available for map!");
2498 return;
2501 Group *group = player->GetGroup();
2502 // group members outside the instance group don't get bound
2503 for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
2505 Player* plr = itr->getSource();
2506 // players inside an instance cannot be bound to other instances
2507 // some players may already be permanently bound, in this case nothing happens
2508 InstancePlayerBind *bind = plr->GetBoundInstance(save->GetMapId(), save->GetDifficulty());
2509 if(!bind || !bind->perm)
2511 plr->BindToInstance(save, true);
2512 WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
2513 data << uint32(0);
2514 plr->GetSession()->SendPacket(&data);
2517 // if the leader is not in the instance the group will not get a perm bind
2518 if(group && group->GetLeaderGUID() == plr->GetGUID())
2519 group->BindToInstance(save, true);
2523 void InstanceMap::UnloadAll(bool pForce)
2525 if(HavePlayers())
2527 sLog.outError("InstanceMap::UnloadAll: there are still players in the instance at unload, should not happen!");
2528 for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
2530 Player* plr = itr->getSource();
2531 plr->TeleportTo(plr->m_homebindMapId, plr->m_homebindX, plr->m_homebindY, plr->m_homebindZ, plr->GetOrientation());
2535 if(m_resetAfterUnload == true)
2536 objmgr.DeleteRespawnTimeForInstance(GetInstanceId());
2538 Map::UnloadAll(pForce);
2541 void InstanceMap::SendResetWarnings(uint32 timeLeft) const
2543 for(MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
2544 itr->getSource()->SendInstanceResetWarning(GetId(), itr->getSource()->GetDifficulty(), timeLeft);
2547 void InstanceMap::SetResetSchedule(bool on)
2549 // only for normal instances
2550 // the reset time is only scheduled when there are no payers inside
2551 // it is assumed that the reset time will rarely (if ever) change while the reset is scheduled
2552 if(IsDungeon() && !HavePlayers() && !IsRaid() && !IsHeroic())
2554 InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
2555 if(!save) sLog.outError("InstanceMap::SetResetSchedule: cannot turn schedule %s, no save available for instance %d of %d", on ? "on" : "off", GetInstanceId(), GetId());
2556 else sInstanceSaveManager.ScheduleReset(on, save->GetResetTime(), InstanceSaveManager::InstResetEvent(0, GetId(), GetInstanceId()));
2560 uint32 InstanceMap::GetMaxPlayers() const
2562 InstanceTemplate const* iTemplate = objmgr.GetInstanceTemplate(GetId());
2563 if(!iTemplate)
2564 return 0;
2565 return IsHeroic() ? iTemplate->maxPlayersHeroic : iTemplate->maxPlayers;
2568 /* ******* Battleground Instance Maps ******* */
2570 BattleGroundMap::BattleGroundMap(uint32 id, time_t expiry, uint32 InstanceId, Map* _parent)
2571 : Map(id, expiry, InstanceId, DIFFICULTY_NORMAL, _parent)
2575 BattleGroundMap::~BattleGroundMap()
2579 bool BattleGroundMap::CanEnter(Player * player)
2581 if(player->GetMapRef().getTarget() == this)
2583 sLog.outError("BGMap::CanEnter - player %u already in map!", player->GetGUIDLow());
2584 assert(false);
2585 return false;
2588 if(player->GetBattleGroundId() != GetInstanceId())
2589 return false;
2591 // player number limit is checked in bgmgr, no need to do it here
2593 return Map::CanEnter(player);
2596 bool BattleGroundMap::Add(Player * player)
2599 Guard guard(*this);
2600 if(!CanEnter(player))
2601 return false;
2602 // reset instance validity, battleground maps do not homebind
2603 player->m_InstanceValid = true;
2605 return Map::Add(player);
2608 void BattleGroundMap::Remove(Player *player, bool remove)
2610 sLog.outDetail("MAP: Removing player '%s' from bg '%u' of map '%s' before relocating to other map", player->GetName(), GetInstanceId(), GetMapName());
2611 Map::Remove(player, remove);
2614 void BattleGroundMap::SetUnload()
2616 m_unloadTimer = MIN_UNLOAD_DELAY;
2619 void BattleGroundMap::UnloadAll(bool pForce)
2621 while(HavePlayers())
2623 if(Player * plr = m_mapRefManager.getFirst()->getSource())
2625 plr->TeleportTo(plr->GetBattleGroundEntryPoint());
2626 // TeleportTo removes the player from this map (if the map exists) -> calls BattleGroundMap::Remove -> invalidates the iterator.
2627 // just in case, remove the player from the list explicitly here as well to prevent a possible infinite loop
2628 // note that this remove is not needed if the code works well in other places
2629 plr->GetMapRef().unlink();
2633 Map::UnloadAll(pForce);
2636 /// Put scripts in the execution queue
2637 void Map::ScriptsStart(ScriptMapMap const& scripts, uint32 id, Object* source, Object* target)
2639 ///- Find the script map
2640 ScriptMapMap::const_iterator s = scripts.find(id);
2641 if (s == scripts.end())
2642 return;
2644 // prepare static data
2645 uint64 sourceGUID = source->GetGUID();
2646 uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
2647 uint64 ownerGUID = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
2649 ///- Schedule script execution for all scripts in the script map
2650 ScriptMap const *s2 = &(s->second);
2651 bool immedScript = false;
2652 for (ScriptMap::const_iterator iter = s2->begin(); iter != s2->end(); ++iter)
2654 ScriptAction sa;
2655 sa.sourceGUID = sourceGUID;
2656 sa.targetGUID = targetGUID;
2657 sa.ownerGUID = ownerGUID;
2659 sa.script = &iter->second;
2660 m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(time_t(sWorld.GetGameTime() + iter->first), sa));
2661 if (iter->first == 0)
2662 immedScript = true;
2664 sWorld.IncreaseScheduledScriptsCount();
2666 ///- If one of the effects should be immediate, launch the script execution
2667 if (immedScript)
2668 ScriptsProcess();
2671 void Map::ScriptCommandStart(ScriptInfo const& script, uint32 delay, Object* source, Object* target)
2673 // NOTE: script record _must_ exist until command executed
2675 // prepare static data
2676 uint64 sourceGUID = source->GetGUID();
2677 uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
2678 uint64 ownerGUID = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
2680 ScriptAction sa;
2681 sa.sourceGUID = sourceGUID;
2682 sa.targetGUID = targetGUID;
2683 sa.ownerGUID = ownerGUID;
2685 sa.script = &script;
2686 m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(time_t(sWorld.GetGameTime() + delay), sa));
2688 sWorld.IncreaseScheduledScriptsCount();
2690 ///- If effects should be immediate, launch the script execution
2691 if(delay == 0)
2692 ScriptsProcess();
2695 /// Process queued scripts
2696 void Map::ScriptsProcess()
2698 if (m_scriptSchedule.empty())
2699 return;
2701 ///- Process overdue queued scripts
2702 std::multimap<time_t, ScriptAction>::iterator iter = m_scriptSchedule.begin();
2703 // ok as multimap is a *sorted* associative container
2704 while (!m_scriptSchedule.empty() && (iter->first <= sWorld.GetGameTime()))
2706 ScriptAction const& step = iter->second;
2708 Object* source = NULL;
2710 if(step.sourceGUID)
2712 switch(GUID_HIPART(step.sourceGUID))
2714 case HIGHGUID_ITEM:
2715 // case HIGHGUID_CONTAINER: ==HIGHGUID_ITEM
2717 Player* player = HashMapHolder<Player>::Find(step.ownerGUID);
2718 if(player)
2719 source = player->GetItemByGuid(step.sourceGUID);
2720 break;
2722 case HIGHGUID_UNIT:
2723 source = HashMapHolder<Creature>::Find(step.sourceGUID);
2724 break;
2725 case HIGHGUID_PET:
2726 source = HashMapHolder<Pet>::Find(step.sourceGUID);
2727 break;
2728 case HIGHGUID_VEHICLE:
2729 source = HashMapHolder<Vehicle>::Find(step.sourceGUID);
2730 break;
2731 case HIGHGUID_PLAYER:
2732 source = HashMapHolder<Player>::Find(step.sourceGUID);
2733 break;
2734 case HIGHGUID_GAMEOBJECT:
2735 source = HashMapHolder<GameObject>::Find(step.sourceGUID);
2736 break;
2737 case HIGHGUID_CORPSE:
2738 source = HashMapHolder<Corpse>::Find(step.sourceGUID);
2739 break;
2740 default:
2741 sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.sourceGUID));
2742 break;
2746 if(source && !source->IsInWorld()) source = NULL;
2748 Object* target = NULL;
2750 if(step.targetGUID)
2752 switch(GUID_HIPART(step.targetGUID))
2754 case HIGHGUID_UNIT:
2755 target = HashMapHolder<Creature>::Find(step.targetGUID);
2756 break;
2757 case HIGHGUID_PET:
2758 target = HashMapHolder<Pet>::Find(step.targetGUID);
2759 break;
2760 case HIGHGUID_VEHICLE:
2761 target = HashMapHolder<Vehicle>::Find(step.targetGUID);
2762 break;
2763 case HIGHGUID_PLAYER: // empty GUID case also
2764 target = HashMapHolder<Player>::Find(step.targetGUID);
2765 break;
2766 case HIGHGUID_GAMEOBJECT:
2767 target = HashMapHolder<GameObject>::Find(step.targetGUID);
2768 break;
2769 case HIGHGUID_CORPSE:
2770 target = HashMapHolder<Corpse>::Find(step.targetGUID);
2771 break;
2772 default:
2773 sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.targetGUID));
2774 break;
2778 if(target && !target->IsInWorld()) target = NULL;
2780 switch (step.script->command)
2782 case SCRIPT_COMMAND_TALK:
2784 if(!source)
2786 sLog.outError("SCRIPT_COMMAND_TALK call for NULL creature.");
2787 break;
2790 if(source->GetTypeId()!=TYPEID_UNIT)
2792 sLog.outError("SCRIPT_COMMAND_TALK call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
2793 break;
2796 uint64 unit_target = target ? target->GetGUID() : 0;
2798 //datalong 0=normal say, 1=whisper, 2=yell, 3=emote text
2799 switch(step.script->datalong)
2801 case 0: // Say
2802 ((Creature *)source)->Say(step.script->dataint, LANG_UNIVERSAL, unit_target);
2803 break;
2804 case 1: // Whisper
2805 if(!unit_target)
2807 sLog.outError("SCRIPT_COMMAND_TALK attempt to whisper (%u) NULL, skipping.",step.script->datalong);
2808 break;
2810 ((Creature *)source)->Whisper(step.script->dataint,unit_target);
2811 break;
2812 case 2: // Yell
2813 ((Creature *)source)->Yell(step.script->dataint, LANG_UNIVERSAL, unit_target);
2814 break;
2815 case 3: // Emote text
2816 ((Creature *)source)->TextEmote(step.script->dataint, unit_target);
2817 break;
2818 default:
2819 break; // must be already checked at load
2821 break;
2824 case SCRIPT_COMMAND_EMOTE:
2825 if(!source)
2827 sLog.outError("SCRIPT_COMMAND_EMOTE call for NULL creature.");
2828 break;
2831 if(source->GetTypeId()!=TYPEID_UNIT)
2833 sLog.outError("SCRIPT_COMMAND_EMOTE call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
2834 break;
2837 ((Creature *)source)->HandleEmoteCommand(step.script->datalong);
2838 break;
2839 case SCRIPT_COMMAND_FIELD_SET:
2840 if(!source)
2842 sLog.outError("SCRIPT_COMMAND_FIELD_SET call for NULL object.");
2843 break;
2845 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
2847 sLog.outError("SCRIPT_COMMAND_FIELD_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
2848 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
2849 break;
2852 source->SetUInt32Value(step.script->datalong, step.script->datalong2);
2853 break;
2854 case SCRIPT_COMMAND_MOVE_TO:
2855 if(!source)
2857 sLog.outError("SCRIPT_COMMAND_MOVE_TO call for NULL creature.");
2858 break;
2861 if(source->GetTypeId()!=TYPEID_UNIT)
2863 sLog.outError("SCRIPT_COMMAND_MOVE_TO call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
2864 break;
2866 ((Creature*)source)->SendMonsterMoveWithSpeed(step.script->x, step.script->y, step.script->z, step.script->datalong2 );
2867 ((Creature*)source)->GetMap()->CreatureRelocation(((Creature*)source), step.script->x, step.script->y, step.script->z, 0);
2868 break;
2869 case SCRIPT_COMMAND_FLAG_SET:
2870 if(!source)
2872 sLog.outError("SCRIPT_COMMAND_FLAG_SET call for NULL object.");
2873 break;
2875 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
2877 sLog.outError("SCRIPT_COMMAND_FLAG_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
2878 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
2879 break;
2882 source->SetFlag(step.script->datalong, step.script->datalong2);
2883 break;
2884 case SCRIPT_COMMAND_FLAG_REMOVE:
2885 if(!source)
2887 sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for NULL object.");
2888 break;
2890 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
2892 sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for wrong field %u (max count: %u) in object (TypeId: %u).",
2893 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
2894 break;
2897 source->RemoveFlag(step.script->datalong, step.script->datalong2);
2898 break;
2900 case SCRIPT_COMMAND_TELEPORT_TO:
2902 // accept player in any one from target/source arg
2903 if (!target && !source)
2905 sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for NULL object.");
2906 break;
2909 // must be only Player
2910 if((!target || target->GetTypeId() != TYPEID_PLAYER) && (!source || source->GetTypeId() != TYPEID_PLAYER))
2912 sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for non-player (TypeIdSource: %u)(TypeIdTarget: %u), skipping.", source ? source->GetTypeId() : 0, target ? target->GetTypeId() : 0);
2913 break;
2916 Player* pSource = target && target->GetTypeId() == TYPEID_PLAYER ? (Player*)target : (Player*)source;
2918 pSource->TeleportTo(step.script->datalong, step.script->x, step.script->y, step.script->z, step.script->o);
2919 break;
2922 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
2924 if(!step.script->datalong) // creature not specified
2926 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL creature.");
2927 break;
2930 if(!source)
2932 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL world object.");
2933 break;
2936 WorldObject* summoner = dynamic_cast<WorldObject*>(source);
2938 if(!summoner)
2940 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
2941 break;
2944 float x = step.script->x;
2945 float y = step.script->y;
2946 float z = step.script->z;
2947 float o = step.script->o;
2949 Creature* pCreature = summoner->SummonCreature(step.script->datalong, x, y, z, o,TEMPSUMMON_TIMED_OR_DEAD_DESPAWN,step.script->datalong2);
2950 if (!pCreature)
2952 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON failed for creature (entry: %u).",step.script->datalong);
2953 break;
2956 break;
2959 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
2961 if(!step.script->datalong) // gameobject not specified
2963 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL gameobject.");
2964 break;
2967 if(!source)
2969 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL world object.");
2970 break;
2973 WorldObject* summoner = dynamic_cast<WorldObject*>(source);
2975 if(!summoner)
2977 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
2978 break;
2981 GameObject *go = NULL;
2982 int32 time_to_despawn = step.script->datalong2<5 ? 5 : (int32)step.script->datalong2;
2984 CellPair p(MaNGOS::ComputeCellPair(summoner->GetPositionX(), summoner->GetPositionY()));
2985 Cell cell(p);
2986 cell.data.Part.reserved = ALL_DISTRICT;
2988 MaNGOS::GameObjectWithDbGUIDCheck go_check(*summoner,step.script->datalong);
2989 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(summoner, go,go_check);
2991 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
2992 CellLock<GridReadGuard> cell_lock(cell, p);
2993 cell_lock->Visit(cell_lock, object_checker, *summoner->GetMap());
2995 if ( !go )
2997 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT failed for gameobject(guid: %u).", step.script->datalong);
2998 break;
3001 if( go->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE ||
3002 go->GetGoType()==GAMEOBJECT_TYPE_DOOR ||
3003 go->GetGoType()==GAMEOBJECT_TYPE_BUTTON ||
3004 go->GetGoType()==GAMEOBJECT_TYPE_TRAP )
3006 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT can not be used with gameobject of type %u (guid: %u).", uint32(go->GetGoType()), step.script->datalong);
3007 break;
3010 if( go->isSpawned() )
3011 break; //gameobject already spawned
3013 go->SetLootState(GO_READY);
3014 go->SetRespawnTime(time_to_despawn); //despawn object in ? seconds
3016 go->GetMap()->Add(go);
3017 break;
3019 case SCRIPT_COMMAND_OPEN_DOOR:
3021 if(!step.script->datalong) // door not specified
3023 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL door.");
3024 break;
3027 if(!source)
3029 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL unit.");
3030 break;
3033 if(!source->isType(TYPEMASK_UNIT)) // must be any Unit (creature or player)
3035 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
3036 break;
3039 Unit* caster = (Unit*)source;
3041 GameObject *door = NULL;
3042 int32 time_to_close = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
3044 CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
3045 Cell cell(p);
3046 cell.data.Part.reserved = ALL_DISTRICT;
3048 MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
3049 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(caster,door,go_check);
3051 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
3052 CellLock<GridReadGuard> cell_lock(cell, p);
3053 cell_lock->Visit(cell_lock, object_checker, *caster->GetMap());
3055 if (!door)
3057 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for gameobject(guid: %u).", step.script->datalong);
3058 break;
3060 if (door->GetGoType() != GAMEOBJECT_TYPE_DOOR)
3062 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for non-door(GoType: %u).", door->GetGoType());
3063 break;
3066 if (door->GetGoState() != GO_STATE_READY)
3067 break; //door already open
3069 door->UseDoorOrButton(time_to_close);
3071 if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
3072 ((GameObject*)target)->UseDoorOrButton(time_to_close);
3073 break;
3075 case SCRIPT_COMMAND_CLOSE_DOOR:
3077 if(!step.script->datalong) // guid for door not specified
3079 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL door.");
3080 break;
3083 if(!source)
3085 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL unit.");
3086 break;
3089 if(!source->isType(TYPEMASK_UNIT)) // must be any Unit (creature or player)
3091 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
3092 break;
3095 Unit* caster = (Unit*)source;
3097 GameObject *door = NULL;
3098 int32 time_to_open = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
3100 CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
3101 Cell cell(p);
3102 cell.data.Part.reserved = ALL_DISTRICT;
3104 MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
3105 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(caster,door,go_check);
3107 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
3108 CellLock<GridReadGuard> cell_lock(cell, p);
3109 cell_lock->Visit(cell_lock, object_checker, *caster->GetMap());
3111 if ( !door )
3113 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for gameobject(guid: %u).", step.script->datalong);
3114 break;
3116 if ( door->GetGoType() != GAMEOBJECT_TYPE_DOOR )
3118 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for non-door(GoType: %u).", door->GetGoType());
3119 break;
3122 if( door->GetGoState() == GO_STATE_READY )
3123 break; //door already closed
3125 door->UseDoorOrButton(time_to_open);
3127 if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
3128 ((GameObject*)target)->UseDoorOrButton(time_to_open);
3130 break;
3132 case SCRIPT_COMMAND_QUEST_EXPLORED:
3134 if(!source)
3136 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL source.");
3137 break;
3140 if(!target)
3142 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL target.");
3143 break;
3146 // when script called for item spell casting then target == (unit or GO) and source is player
3147 WorldObject* worldObject;
3148 Player* player;
3150 if(target->GetTypeId()==TYPEID_PLAYER)
3152 if(source->GetTypeId()!=TYPEID_UNIT && source->GetTypeId()!=TYPEID_GAMEOBJECT)
3154 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",source->GetTypeId());
3155 break;
3158 worldObject = (WorldObject*)source;
3159 player = (Player*)target;
3161 else
3163 if(target->GetTypeId()!=TYPEID_UNIT && target->GetTypeId()!=TYPEID_GAMEOBJECT)
3165 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
3166 break;
3169 if(source->GetTypeId()!=TYPEID_PLAYER)
3171 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-player(TypeId: %u), skipping.",source->GetTypeId());
3172 break;
3175 worldObject = (WorldObject*)target;
3176 player = (Player*)source;
3179 // quest id and flags checked at script loading
3180 if( (worldObject->GetTypeId()!=TYPEID_UNIT || ((Unit*)worldObject)->isAlive()) &&
3181 (step.script->datalong2==0 || worldObject->IsWithinDistInMap(player,float(step.script->datalong2))) )
3182 player->AreaExploredOrEventHappens(step.script->datalong);
3183 else
3184 player->FailQuest(step.script->datalong);
3186 break;
3189 case SCRIPT_COMMAND_ACTIVATE_OBJECT:
3191 if(!source)
3193 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT must have source caster.");
3194 break;
3197 if(!source->isType(TYPEMASK_UNIT))
3199 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
3200 break;
3203 if(!target)
3205 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for NULL gameobject.");
3206 break;
3209 if(target->GetTypeId()!=TYPEID_GAMEOBJECT)
3211 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
3212 break;
3215 Unit* caster = (Unit*)source;
3217 GameObject *go = (GameObject*)target;
3219 go->Use(caster);
3220 break;
3223 case SCRIPT_COMMAND_REMOVE_AURA:
3225 Object* cmdTarget = step.script->datalong2 ? source : target;
3227 if(!cmdTarget)
3229 sLog.outError("SCRIPT_COMMAND_REMOVE_AURA call for NULL %s.",step.script->datalong2 ? "source" : "target");
3230 break;
3233 if(!cmdTarget->isType(TYPEMASK_UNIT))
3235 sLog.outError("SCRIPT_COMMAND_REMOVE_AURA %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 ? "source" : "target",cmdTarget->GetTypeId());
3236 break;
3239 ((Unit*)cmdTarget)->RemoveAurasDueToSpell(step.script->datalong);
3240 break;
3243 case SCRIPT_COMMAND_CAST_SPELL:
3245 if(!source)
3247 sLog.outError("SCRIPT_COMMAND_CAST_SPELL must have source caster.");
3248 break;
3251 Object* cmdTarget = step.script->datalong2 & 0x01 ? source : target;
3253 if(!cmdTarget)
3255 sLog.outError("SCRIPT_COMMAND_CAST_SPELL call for NULL %s.",step.script->datalong2 & 0x01 ? "source" : "target");
3256 break;
3259 if(!cmdTarget->isType(TYPEMASK_UNIT))
3261 sLog.outError("SCRIPT_COMMAND_CAST_SPELL %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 & 0x01 ? "source" : "target",cmdTarget->GetTypeId());
3262 break;
3265 Unit* spellTarget = (Unit*)cmdTarget;
3267 Object* cmdSource = step.script->datalong2 & 0x02 ? target : source;
3269 if(!cmdSource)
3271 sLog.outError("SCRIPT_COMMAND_CAST_SPELL call for NULL %s.",step.script->datalong2 & 0x02 ? "target" : "source");
3272 break;
3275 if(!cmdSource->isType(TYPEMASK_UNIT))
3277 sLog.outError("SCRIPT_COMMAND_CAST_SPELL %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 & 0x02 ? "target" : "source", cmdSource->GetTypeId());
3278 break;
3281 Unit* spellSource = (Unit*)cmdSource;
3283 //TODO: when GO cast implemented, code below must be updated accordingly to also allow GO spell cast
3284 spellSource->CastSpell(spellTarget,step.script->datalong,false);
3286 break;
3289 case SCRIPT_COMMAND_PLAY_SOUND:
3291 if(!source)
3293 sLog.outError("SCRIPT_COMMAND_PLAY_SOUND call for NULL creature.");
3294 break;
3297 WorldObject* pSource = dynamic_cast<WorldObject*>(source);
3298 if(!pSource)
3300 sLog.outError("SCRIPT_COMMAND_PLAY_SOUND call for non-world object (TypeId: %u), skipping.",source->GetTypeId());
3301 break;
3304 // bitmask: 0/1=anyone/target, 0/2=with distance dependent
3305 Player* pTarget = NULL;
3306 if(step.script->datalong2 & 1)
3308 if(!target)
3310 sLog.outError("SCRIPT_COMMAND_PLAY_SOUND in targeted mode call for NULL target.");
3311 break;
3314 if(target->GetTypeId()!=TYPEID_PLAYER)
3316 sLog.outError("SCRIPT_COMMAND_PLAY_SOUND in targeted mode call for non-player (TypeId: %u), skipping.",target->GetTypeId());
3317 break;
3320 pTarget = (Player*)target;
3323 // bitmask: 0/1=anyone/target, 0/2=with distance dependent
3324 if(step.script->datalong2 & 2)
3325 pSource->PlayDistanceSound(step.script->datalong,pTarget);
3326 else
3327 pSource->PlayDirectSound(step.script->datalong,pTarget);
3328 break;
3330 default:
3331 sLog.outError("Unknown script command %u called.",step.script->command);
3332 break;
3335 m_scriptSchedule.erase(iter);
3336 sWorld.DecreaseScheduledScriptCount();
3338 iter = m_scriptSchedule.begin();
3340 return;
3343 Creature*
3344 Map::GetCreature(uint64 guid)
3346 Creature * ret = ObjectAccessor::GetObjectInWorld(guid, (Creature*)NULL);
3347 if(!ret)
3348 return NULL;
3350 if(ret->GetMapId() != GetId())
3351 return NULL;
3353 if(ret->GetInstanceId() != GetInstanceId())
3354 return NULL;
3356 return ret;
3359 GameObject*
3360 Map::GetGameObject(uint64 guid)
3362 GameObject * ret = ObjectAccessor::GetObjectInWorld(guid, (GameObject*)NULL);
3363 if(!ret)
3364 return NULL;
3365 if(ret->GetMapId() != GetId())
3366 return NULL;
3367 if(ret->GetInstanceId() != GetInstanceId())
3368 return NULL;
3369 return ret;
3372 DynamicObject*
3373 Map::GetDynamicObject(uint64 guid)
3375 DynamicObject * ret = ObjectAccessor::GetObjectInWorld(guid, (DynamicObject*)NULL);
3376 if(!ret)
3377 return NULL;
3378 if(ret->GetMapId() != GetId())
3379 return NULL;
3380 if(ret->GetInstanceId() != GetInstanceId())
3381 return NULL;
3382 return ret;