[9184] Fixed unread packet tail spam for CMSG_LEAVE_BATTLEFIELD
[getmangos.git] / src / game / Map.cpp
blobb8fdd29168b47319652a6fafcaac37c01e2c1100
1 /*
2 * Copyright (C) 2005-2010 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"
37 #include "DBCEnums.h"
39 #include "MapInstanced.h"
40 #include "InstanceSaveMgr.h"
41 #include "VMapFactory.h"
43 #define MAX_CREATURE_ATTACK_RADIUS (45.0f * sWorld.getRate(RATE_CREATURE_AGGRO))
45 GridState* si_GridStates[MAX_GRID_STATE];
47 static char const* MAP_MAGIC = "MAPS";
48 static char const* MAP_VERSION_MAGIC = "w1.0";
49 static char const* MAP_AREA_MAGIC = "AREA";
50 static char const* MAP_HEIGHT_MAGIC = "MHGT";
51 static char const* MAP_LIQUID_MAGIC = "MLIQ";
53 struct ScriptAction
55 uint64 sourceGUID;
56 uint64 targetGUID;
57 uint64 ownerGUID; // owner of source if source is item
58 ScriptInfo const* script; // pointer to static script data
61 Map::~Map()
63 ObjectAccessor::DelinkMap(this);
64 UnloadAll(true);
66 if(!m_scriptSchedule.empty())
67 sWorld.DecreaseScheduledScriptCount(m_scriptSchedule.size());
70 bool Map::ExistMap(uint32 mapid,int gx,int gy)
72 int len = sWorld.GetDataPath().length()+strlen("maps/%03u%02u%02u.map")+1;
73 char* tmp = new char[len];
74 snprintf(tmp, len, (char *)(sWorld.GetDataPath()+"maps/%03u%02u%02u.map").c_str(),mapid,gx,gy);
76 FILE *pf=fopen(tmp,"rb");
78 if(!pf)
80 sLog.outError("Check existing of map file '%s': not exist!",tmp);
81 delete[] tmp;
82 return false;
85 map_fileheader header;
86 fread(&header, sizeof(header), 1, pf);
87 if (header.mapMagic != *((uint32 const*)(MAP_MAGIC)) ||
88 header.versionMagic != *((uint32 const*)(MAP_VERSION_MAGIC)))
90 sLog.outError("Map file '%s' is non-compatible version (outdated?). Please, create new using ad.exe program.",tmp);
91 delete [] tmp;
92 fclose(pf); //close file before return
93 return false;
96 delete [] tmp;
97 fclose(pf);
98 return true;
101 bool Map::ExistVMap(uint32 mapid,int gx,int gy)
103 if(VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager())
105 if(vmgr->isMapLoadingEnabled())
107 // x and y are swapped !! => fixed now
108 bool exists = vmgr->existsMap((sWorld.GetDataPath()+ "vmaps").c_str(), mapid, gx,gy);
109 if(!exists)
111 std::string name = vmgr->getDirFileName(mapid,gx,gy);
112 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());
113 return false;
118 return true;
121 void Map::LoadVMap(int gx,int gy)
123 // x and y are swapped !!
124 int vmapLoadResult = VMAP::VMapFactory::createOrGetVMapManager()->loadMap((sWorld.GetDataPath()+ "vmaps").c_str(), GetId(), gx,gy);
125 switch(vmapLoadResult)
127 case VMAP::VMAP_LOAD_RESULT_OK:
128 sLog.outDetail("VMAP loaded name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", GetMapName(), GetId(), gx,gy,gx,gy);
129 break;
130 case VMAP::VMAP_LOAD_RESULT_ERROR:
131 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);
132 break;
133 case VMAP::VMAP_LOAD_RESULT_IGNORED:
134 DEBUG_LOG("Ignored VMAP name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", GetMapName(), GetId(), gx,gy,gx,gy);
135 break;
139 void Map::LoadMap(int gx,int gy, bool reload)
141 if( i_InstanceId != 0 )
143 if(GridMaps[gx][gy])
144 return;
146 // load grid map for base map
147 if (!m_parentMap->GridMaps[gx][gy])
148 m_parentMap->EnsureGridCreated(GridPair(63-gx,63-gy));
150 ((MapInstanced*)(m_parentMap))->AddGridMapReference(GridPair(gx,gy));
151 GridMaps[gx][gy] = m_parentMap->GridMaps[gx][gy];
152 return;
155 if(GridMaps[gx][gy] && !reload)
156 return;
158 //map already load, delete it before reloading (Is it necessary? Do we really need the ability the reload maps during runtime?)
159 if(GridMaps[gx][gy])
161 sLog.outDetail("Unloading already loaded map %u before reloading.",i_id);
162 delete (GridMaps[gx][gy]);
163 GridMaps[gx][gy]=NULL;
166 // map file name
167 char *tmp=NULL;
168 int len = sWorld.GetDataPath().length()+strlen("maps/%03u%02u%02u.map")+1;
169 tmp = new char[len];
170 snprintf(tmp, len, (char *)(sWorld.GetDataPath()+"maps/%03u%02u%02u.map").c_str(),i_id,gx,gy);
171 sLog.outDetail("Loading map %s",tmp);
172 // loading data
173 GridMaps[gx][gy] = new GridMap();
174 if (!GridMaps[gx][gy]->loadData(tmp))
176 sLog.outError("Error load map file: \n %s\n", tmp);
178 delete [] tmp;
181 void Map::LoadMapAndVMap(int gx,int gy)
183 LoadMap(gx,gy);
184 if(i_InstanceId == 0)
185 LoadVMap(gx, gy); // Only load the data for the base map
188 void Map::InitStateMachine()
190 si_GridStates[GRID_STATE_INVALID] = new InvalidState;
191 si_GridStates[GRID_STATE_ACTIVE] = new ActiveState;
192 si_GridStates[GRID_STATE_IDLE] = new IdleState;
193 si_GridStates[GRID_STATE_REMOVAL] = new RemovalState;
196 void Map::DeleteStateMachine()
198 delete si_GridStates[GRID_STATE_INVALID];
199 delete si_GridStates[GRID_STATE_ACTIVE];
200 delete si_GridStates[GRID_STATE_IDLE];
201 delete si_GridStates[GRID_STATE_REMOVAL];
204 Map::Map(uint32 id, time_t expiry, uint32 InstanceId, uint8 SpawnMode, Map* _parent)
205 : i_mapEntry (sMapStore.LookupEntry(id)), i_spawnMode(SpawnMode),
206 i_id(id), i_InstanceId(InstanceId), m_unloadTimer(0),
207 m_VisibleDistance(DEFAULT_VISIBILITY_DISTANCE),
208 m_activeNonPlayersIter(m_activeNonPlayers.end()),
209 i_gridExpiry(expiry), m_parentMap(_parent ? _parent : this),
210 m_hiDynObjectGuid(1), m_hiPetGuid(1), m_hiVehicleGuid(1)
212 for(unsigned int idx=0; idx < MAX_NUMBER_OF_GRIDS; ++idx)
214 for(unsigned int j=0; j < MAX_NUMBER_OF_GRIDS; ++j)
216 //z code
217 GridMaps[idx][j] =NULL;
218 setNGrid(NULL, idx, j);
221 ObjectAccessor::LinkMap(this);
223 //lets initialize visibility distance for map
224 Map::InitVisibilityDistance();
227 void Map::InitVisibilityDistance()
229 //init visibility for continents
230 m_VisibleDistance = World::GetMaxVisibleDistanceOnContinents();
233 // Template specialization of utility methods
234 template<class T>
235 void Map::AddToGrid(T* obj, NGridType *grid, Cell const& cell)
237 (*grid)(cell.CellX(), cell.CellY()).template AddGridObject<T>(obj, obj->GetGUID());
240 template<>
241 void Map::AddToGrid(Player* obj, NGridType *grid, Cell const& cell)
243 (*grid)(cell.CellX(), cell.CellY()).AddWorldObject(obj, obj->GetGUID());
246 template<>
247 void Map::AddToGrid(Corpse *obj, NGridType *grid, Cell const& cell)
249 // add to world object registry in grid
250 if(obj->GetType()!=CORPSE_BONES)
252 (*grid)(cell.CellX(), cell.CellY()).AddWorldObject(obj, obj->GetGUID());
254 // add to grid object store
255 else
257 (*grid)(cell.CellX(), cell.CellY()).AddGridObject(obj, obj->GetGUID());
261 template<>
262 void Map::AddToGrid(Creature* obj, NGridType *grid, Cell const& cell)
264 // add to world object registry in grid
265 if(obj->isPet() || obj->isVehicle())
267 (*grid)(cell.CellX(), cell.CellY()).AddWorldObject<Creature>(obj, obj->GetGUID());
268 obj->SetCurrentCell(cell);
270 // add to grid object store
271 else
273 (*grid)(cell.CellX(), cell.CellY()).AddGridObject<Creature>(obj, obj->GetGUID());
274 obj->SetCurrentCell(cell);
278 template<class T>
279 void Map::RemoveFromGrid(T* obj, NGridType *grid, Cell const& cell)
281 (*grid)(cell.CellX(), cell.CellY()).template RemoveGridObject<T>(obj, obj->GetGUID());
284 template<>
285 void Map::RemoveFromGrid(Player* obj, NGridType *grid, Cell const& cell)
287 (*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject(obj, obj->GetGUID());
290 template<>
291 void Map::RemoveFromGrid(Corpse *obj, NGridType *grid, Cell const& cell)
293 // remove from world object registry in grid
294 if(obj->GetType()!=CORPSE_BONES)
296 (*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject(obj, obj->GetGUID());
298 // remove from grid object store
299 else
301 (*grid)(cell.CellX(), cell.CellY()).RemoveGridObject(obj, obj->GetGUID());
305 template<>
306 void Map::RemoveFromGrid(Creature* obj, NGridType *grid, Cell const& cell)
308 // remove from world object registry in grid
309 if(obj->isPet() || obj->isVehicle())
311 (*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject<Creature>(obj, obj->GetGUID());
313 // remove from grid object store
314 else
316 (*grid)(cell.CellX(), cell.CellY()).RemoveGridObject<Creature>(obj, obj->GetGUID());
320 template<class T>
321 void Map::DeleteFromWorld(T* obj)
323 // Note: In case resurrectable corpse and pet its removed from global lists in own destructor
324 delete obj;
327 template<>
328 void Map::DeleteFromWorld(Player* pl)
330 sObjectAccessor.RemoveObject(pl);
331 delete pl;
334 template<class T>
335 void Map::AddNotifier(T* , Cell const& , CellPair const& )
339 template<>
340 void Map::AddNotifier(Player* obj, Cell const& cell, CellPair const& cellpair)
342 PlayerRelocationNotify(obj,cell,cellpair);
345 template<>
346 void Map::AddNotifier(Creature* obj, Cell const& cell, CellPair const& cellpair)
348 CreatureRelocationNotify(obj,cell,cellpair);
351 void
352 Map::EnsureGridCreated(const GridPair &p)
354 if(!getNGrid(p.x_coord, p.y_coord))
356 Guard guard(*this);
357 if(!getNGrid(p.x_coord, p.y_coord))
359 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)),
360 p.x_coord, p.y_coord);
362 // build a linkage between this map and NGridType
363 buildNGridLinkage(getNGrid(p.x_coord, p.y_coord));
365 getNGrid(p.x_coord, p.y_coord)->SetGridState(GRID_STATE_IDLE);
367 //z coord
368 int gx = (MAX_NUMBER_OF_GRIDS - 1) - p.x_coord;
369 int gy = (MAX_NUMBER_OF_GRIDS - 1) - p.y_coord;
371 if(!GridMaps[gx][gy])
372 LoadMapAndVMap(gx,gy);
377 void
378 Map::EnsureGridLoadedAtEnter(const Cell &cell, Player *player)
380 NGridType *grid;
382 if(EnsureGridLoaded(cell))
384 grid = getNGrid(cell.GridX(), cell.GridY());
386 if (player)
388 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);
390 else
392 DEBUG_LOG("Active object nearby triggers of loading grid [%u,%u] on map %u", cell.GridX(), cell.GridY(), i_id);
395 ResetGridExpiry(*getNGrid(cell.GridX(), cell.GridY()), 0.1f);
396 grid->SetGridState(GRID_STATE_ACTIVE);
398 else
399 grid = getNGrid(cell.GridX(), cell.GridY());
401 if (player)
402 AddToGrid(player,grid,cell);
405 bool Map::EnsureGridLoaded(const Cell &cell)
407 EnsureGridCreated(GridPair(cell.GridX(), cell.GridY()));
408 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
410 assert(grid != NULL);
411 if( !isGridObjectDataLoaded(cell.GridX(), cell.GridY()) )
413 ObjectGridLoader loader(*grid, this, cell);
414 loader.LoadN();
416 // Add resurrectable corpses to world object list in grid
417 sObjectAccessor.AddCorpsesToGrid(GridPair(cell.GridX(),cell.GridY()),(*grid)(cell.CellX(), cell.CellY()), this);
419 setGridObjectDataLoaded(true,cell.GridX(), cell.GridY());
420 return true;
423 return false;
426 void Map::LoadGrid(const Cell& cell, bool no_unload)
428 EnsureGridLoaded(cell);
430 if(no_unload)
431 getNGrid(cell.GridX(), cell.GridY())->setUnloadExplicitLock(true);
434 bool Map::Add(Player *player)
436 player->GetMapRef().link(this, player);
437 player->SetMap(this);
439 // update player state for other player and visa-versa
440 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
441 Cell cell(p);
442 EnsureGridLoadedAtEnter(cell, player);
443 player->AddToWorld();
445 SendInitSelf(player);
446 SendInitTransports(player);
448 UpdatePlayerVisibility(player,cell,p);
449 UpdateObjectsVisibilityFor(player,cell,p);
451 AddNotifier(player,cell,p);
452 return true;
455 template<class T>
456 void
457 Map::Add(T *obj)
459 assert(obj);
461 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
462 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
464 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);
465 return;
468 obj->SetMap(this);
470 Cell cell(p);
471 if(obj->isActiveObject())
472 EnsureGridLoadedAtEnter(cell);
473 else
474 EnsureGridCreated(GridPair(cell.GridX(), cell.GridY()));
476 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
477 assert( grid != NULL );
479 AddToGrid(obj,grid,cell);
480 obj->AddToWorld();
482 if(obj->isActiveObject())
483 AddToActive(obj);
485 DEBUG_LOG("Object %u enters grid[%u,%u]", GUID_LOPART(obj->GetGUID()), cell.GridX(), cell.GridY());
487 UpdateObjectVisibility(obj,cell,p);
489 AddNotifier(obj,cell,p);
492 void Map::MessageBroadcast(Player *player, WorldPacket *msg, bool to_self)
494 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
496 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
498 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);
499 return;
502 Cell cell(p);
503 cell.data.Part.reserved = ALL_DISTRICT;
504 cell.SetNoCreate();
506 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
507 return;
509 MaNGOS::MessageDeliverer post_man(*player, msg, to_self);
510 TypeContainerVisitor<MaNGOS::MessageDeliverer, WorldTypeMapContainer > message(post_man);
511 CellLock<ReadGuard> cell_lock(cell, p);
512 cell_lock->Visit(cell_lock, message, *this, *player, GetVisibilityDistance());
515 void Map::MessageBroadcast(WorldObject *obj, WorldPacket *msg)
517 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
519 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
521 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);
522 return;
525 Cell cell(p);
526 cell.data.Part.reserved = ALL_DISTRICT;
527 cell.SetNoCreate();
529 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
530 return;
532 //TODO: currently on continents when Visibility.Distance.InFlight > Visibility.Distance.Continents
533 //we have alot of blinking mobs because monster move packet send is broken...
534 MaNGOS::ObjectMessageDeliverer post_man(*obj,msg);
535 TypeContainerVisitor<MaNGOS::ObjectMessageDeliverer, WorldTypeMapContainer > message(post_man);
536 CellLock<ReadGuard> cell_lock(cell, p);
537 cell_lock->Visit(cell_lock, message, *this, *obj, GetVisibilityDistance());
540 void Map::MessageDistBroadcast(Player *player, WorldPacket *msg, float dist, bool to_self, bool own_team_only)
542 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
544 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
546 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);
547 return;
550 Cell cell(p);
551 cell.data.Part.reserved = ALL_DISTRICT;
552 cell.SetNoCreate();
554 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
555 return;
557 MaNGOS::MessageDistDeliverer post_man(*player, msg, dist, to_self, own_team_only);
558 TypeContainerVisitor<MaNGOS::MessageDistDeliverer , WorldTypeMapContainer > message(post_man);
559 CellLock<ReadGuard> cell_lock(cell, p);
560 cell_lock->Visit(cell_lock, message, *this, *player, dist);
563 void Map::MessageDistBroadcast(WorldObject *obj, WorldPacket *msg, float dist)
565 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
567 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
569 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);
570 return;
573 Cell cell(p);
574 cell.data.Part.reserved = ALL_DISTRICT;
575 cell.SetNoCreate();
577 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
578 return;
580 MaNGOS::ObjectMessageDistDeliverer post_man(*obj, msg, dist);
581 TypeContainerVisitor<MaNGOS::ObjectMessageDistDeliverer, WorldTypeMapContainer > message(post_man);
582 CellLock<ReadGuard> cell_lock(cell, p);
583 cell_lock->Visit(cell_lock, message, *this, *obj, dist);
586 bool Map::loaded(const GridPair &p) const
588 return ( getNGrid(p.x_coord, p.y_coord) && isGridObjectDataLoaded(p.x_coord, p.y_coord) );
591 void Map::Update(const uint32 &t_diff)
593 /// update players at tick
594 for(m_mapRefIter = m_mapRefManager.begin(); m_mapRefIter != m_mapRefManager.end(); ++m_mapRefIter)
596 Player* plr = m_mapRefIter->getSource();
597 if(plr && plr->IsInWorld())
598 plr->Update(t_diff);
601 /// update active cells around players and active objects
602 resetMarkedCells();
604 MaNGOS::ObjectUpdater updater(t_diff);
605 // for creature
606 TypeContainerVisitor<MaNGOS::ObjectUpdater, GridTypeMapContainer > grid_object_update(updater);
607 // for pets
608 TypeContainerVisitor<MaNGOS::ObjectUpdater, WorldTypeMapContainer > world_object_update(updater);
610 // the player iterator is stored in the map object
611 // to make sure calls to Map::Remove don't invalidate it
612 for(m_mapRefIter = m_mapRefManager.begin(); m_mapRefIter != m_mapRefManager.end(); ++m_mapRefIter)
614 Player* plr = m_mapRefIter->getSource();
616 if(!plr->IsInWorld())
617 continue;
619 CellPair standing_cell(MaNGOS::ComputeCellPair(plr->GetPositionX(), plr->GetPositionY()));
621 // Check for correctness of standing_cell, it also avoids problems with update_cell
622 if (standing_cell.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || standing_cell.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
623 continue;
625 // the overloaded operators handle range checking
626 // so ther's no need for range checking inside the loop
627 CellPair begin_cell(standing_cell), end_cell(standing_cell);
628 //lets update mobs/objects in ALL visible cells around player!
629 CellArea area = Cell::CalculateCellArea(*plr, GetVisibilityDistance());
630 area.ResizeBorders(begin_cell, end_cell);
632 for(uint32 x = begin_cell.x_coord; x <= end_cell.x_coord; ++x)
634 for(uint32 y = begin_cell.y_coord; y <= end_cell.y_coord; ++y)
636 // marked cells are those that have been visited
637 // don't visit the same cell twice
638 uint32 cell_id = (y * TOTAL_NUMBER_OF_CELLS_PER_MAP) + x;
639 if(!isCellMarked(cell_id))
641 markCell(cell_id);
642 CellPair pair(x,y);
643 Cell cell(pair);
644 cell.data.Part.reserved = CENTER_DISTRICT;
645 cell.SetNoCreate();
646 CellLock<NullGuard> cell_lock(cell, pair);
647 cell_lock->Visit(cell_lock, grid_object_update, *this);
648 cell_lock->Visit(cell_lock, world_object_update, *this);
654 // non-player active objects
655 if(!m_activeNonPlayers.empty())
657 for(m_activeNonPlayersIter = m_activeNonPlayers.begin(); m_activeNonPlayersIter != m_activeNonPlayers.end(); )
659 // skip not in world
660 WorldObject* obj = *m_activeNonPlayersIter;
662 // step before processing, in this case if Map::Remove remove next object we correctly
663 // step to next-next, and if we step to end() then newly added objects can wait next update.
664 ++m_activeNonPlayersIter;
666 if(!obj->IsInWorld())
667 continue;
669 CellPair standing_cell(MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY()));
671 // Check for correctness of standing_cell, it also avoids problems with update_cell
672 if (standing_cell.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || standing_cell.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
673 continue;
675 // the overloaded operators handle range checking
676 // so ther's no need for range checking inside the loop
677 CellPair begin_cell(standing_cell), end_cell(standing_cell);
678 begin_cell << 1; begin_cell -= 1; // upper left
679 end_cell >> 1; end_cell += 1; // lower right
681 for(uint32 x = begin_cell.x_coord; x <= end_cell.x_coord; ++x)
683 for(uint32 y = begin_cell.y_coord; y <= end_cell.y_coord; ++y)
685 // marked cells are those that have been visited
686 // don't visit the same cell twice
687 uint32 cell_id = (y * TOTAL_NUMBER_OF_CELLS_PER_MAP) + x;
688 if(!isCellMarked(cell_id))
690 markCell(cell_id);
691 CellPair pair(x,y);
692 Cell cell(pair);
693 cell.data.Part.reserved = CENTER_DISTRICT;
694 cell.SetNoCreate();
695 CellLock<NullGuard> cell_lock(cell, pair);
696 cell_lock->Visit(cell_lock, grid_object_update, *this);
697 cell_lock->Visit(cell_lock, world_object_update, *this);
704 // Send world objects and item update field changes
705 SendObjectUpdates();
707 // 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 !
708 // This isn't really bother us, since as soon as we have instanced BG-s, the whole map unloads as the BG gets ended
709 if (!IsBattleGroundOrArena())
711 for (GridRefManager<NGridType>::iterator i = GridRefManager<NGridType>::begin(); i != GridRefManager<NGridType>::end(); )
713 NGridType *grid = i->getSource();
714 GridInfo *info = i->getSource()->getGridInfoRef();
715 ++i; // The update might delete the map and we need the next map before the iterator gets invalid
716 assert(grid->GetGridState() >= 0 && grid->GetGridState() < MAX_GRID_STATE);
717 si_GridStates[grid->GetGridState()]->Update(*this, *grid, *info, grid->getX(), grid->getY(), t_diff);
721 ///- Process necessary scripts
722 if (!m_scriptSchedule.empty())
723 ScriptsProcess();
726 void Map::Remove(Player *player, bool remove)
728 if(remove)
729 player->CleanupsBeforeDelete();
730 else
731 player->RemoveFromWorld();
733 // this may be called during Map::Update
734 // after decrement+unlink, ++m_mapRefIter will continue correctly
735 // when the first element of the list is being removed
736 // nocheck_prev will return the padding element of the RefManager
737 // instead of NULL in the case of prev
738 if(m_mapRefIter == player->GetMapRef())
739 m_mapRefIter = m_mapRefIter->nocheck_prev();
740 player->GetMapRef().unlink();
741 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
742 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
744 // invalid coordinates
745 player->ResetMap();
747 if( remove )
748 DeleteFromWorld(player);
750 return;
753 Cell cell(p);
755 if( !getNGrid(cell.data.Part.grid_x, cell.data.Part.grid_y) )
757 sLog.outError("Map::Remove() i_grids was NULL x:%d, y:%d",cell.data.Part.grid_x,cell.data.Part.grid_y);
758 return;
761 DEBUG_LOG("Remove player %s from grid[%u,%u]", player->GetName(), cell.GridX(), cell.GridY());
762 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
763 assert(grid != NULL);
765 RemoveFromGrid(player,grid,cell);
767 SendRemoveTransports(player);
768 UpdateObjectsVisibilityFor(player,cell,p);
770 player->ResetMap();
771 if( remove )
772 DeleteFromWorld(player);
775 bool Map::RemoveBones(uint64 guid, float x, float y)
777 if (IsRemovalGrid(x, y))
779 Corpse* corpse = ObjectAccessor::GetCorpseInMap(guid,GetId());
780 if (!corpse)
781 return false;
783 CellPair p = MaNGOS::ComputeCellPair(x,y);
784 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
786 sLog.outError("Map::RemoveBones: invalid coordinates supplied X:%f Y:%f grid cell [%u:%u]", x, y, p.x_coord, p.y_coord);
787 return false;
790 CellPair q = MaNGOS::ComputeCellPair(corpse->GetPositionX(),corpse->GetPositionY());
791 if(q.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || q.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
793 sLog.outError("Map::RemoveBones: object (GUID: %u TypeId: %u) has invalid coordinates X:%f Y:%f grid cell [%u:%u]", corpse->GetGUIDLow(), corpse->GetTypeId(), corpse->GetPositionX(), corpse->GetPositionY(), q.x_coord, q.y_coord);
794 return false;
797 int32 dx = int32(p.x_coord) - int32(q.x_coord);
798 int32 dy = int32(p.y_coord) - int32(q.y_coord);
800 if (dx <= -2 || dx >= 2 || dy <= -2 || dy >= 2)
801 return false;
803 if(corpse && corpse->GetTypeId() == TYPEID_CORPSE && corpse->GetType() == CORPSE_BONES)
804 corpse->DeleteBonesFromWorld();
805 else
806 return false;
808 return true;
811 template<class T>
812 void
813 Map::Remove(T *obj, bool remove)
815 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
816 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
818 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);
819 return;
822 Cell cell(p);
823 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
824 return;
826 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);
827 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
828 assert( grid != NULL );
830 if(obj->isActiveObject())
831 RemoveFromActive(obj);
833 if(remove)
834 obj->CleanupsBeforeDelete();
835 else
836 obj->RemoveFromWorld();
838 RemoveFromGrid(obj,grid,cell);
840 UpdateObjectVisibility(obj,cell,p);
842 obj->ResetMap();
843 if( remove )
845 // if option set then object already saved at this moment
846 if(!sWorld.getConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY))
847 obj->SaveRespawnTime();
848 DeleteFromWorld(obj);
852 void
853 Map::PlayerRelocation(Player *player, float x, float y, float z, float orientation)
855 assert(player);
857 CellPair old_val = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
858 CellPair new_val = MaNGOS::ComputeCellPair(x, y);
860 Cell old_cell(old_val);
861 Cell new_cell(new_val);
862 new_cell |= old_cell;
863 bool same_cell = (new_cell == old_cell);
865 player->Relocate(x, y, z, orientation);
867 if( old_cell.DiffGrid(new_cell) || old_cell.DiffCell(new_cell) )
869 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());
871 // update player position for group at taxi flight
872 if(player->GetGroup() && player->isInFlight())
873 player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
875 NGridType* oldGrid = getNGrid(old_cell.GridX(), old_cell.GridY());
876 RemoveFromGrid(player, oldGrid,old_cell);
877 if( !old_cell.DiffGrid(new_cell) )
878 AddToGrid(player, oldGrid,new_cell);
879 else
880 EnsureGridLoadedAtEnter(new_cell, player);
883 // if move then update what player see and who seen
884 UpdatePlayerVisibility(player,new_cell,new_val);
885 UpdateObjectsVisibilityFor(player,new_cell,new_val);
886 PlayerRelocationNotify(player,new_cell,new_val);
887 NGridType* newGrid = getNGrid(new_cell.GridX(), new_cell.GridY());
888 if( !same_cell && newGrid->GetGridState()!= GRID_STATE_ACTIVE )
890 ResetGridExpiry(*newGrid, 0.1f);
891 newGrid->SetGridState(GRID_STATE_ACTIVE);
895 void
896 Map::CreatureRelocation(Creature *creature, float x, float y, float z, float ang)
898 assert(CheckGridIntegrity(creature,false));
900 Cell old_cell = creature->GetCurrentCell();
902 CellPair new_val = MaNGOS::ComputeCellPair(x, y);
903 Cell new_cell(new_val);
905 // delay creature move for grid/cell to grid/cell moves
906 if( old_cell.DiffCell(new_cell) || old_cell.DiffGrid(new_cell) )
908 #ifdef MANGOS_DEBUG
909 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
910 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());
911 #endif
912 AddCreatureToMoveList(creature,x,y,z,ang);
913 // in diffcell/diffgrid case notifiers called at finishing move creature in Map::MoveAllCreaturesInMoveList
915 else
917 creature->Relocate(x, y, z, ang);
918 CreatureRelocationNotify(creature,new_cell,new_val);
920 assert(CheckGridIntegrity(creature,true));
923 void Map::AddCreatureToMoveList(Creature *c, float x, float y, float z, float ang)
925 if(!c)
926 return;
928 i_creaturesToMove[c] = CreatureMover(x,y,z,ang);
931 void Map::MoveAllCreaturesInMoveList()
933 while(!i_creaturesToMove.empty())
935 // get data and remove element;
936 CreatureMoveList::iterator iter = i_creaturesToMove.begin();
937 Creature* c = iter->first;
938 CreatureMover cm = iter->second;
939 i_creaturesToMove.erase(iter);
941 // calculate cells
942 CellPair new_val = MaNGOS::ComputeCellPair(cm.x, cm.y);
943 Cell new_cell(new_val);
945 // do move or do move to respawn or remove creature if previous all fail
946 if(CreatureCellRelocation(c,new_cell))
948 // update pos
949 c->Relocate(cm.x, cm.y, cm.z, cm.ang);
950 CreatureRelocationNotify(c,new_cell,new_cell.cellPair());
952 else
954 // if creature can't be move in new cell/grid (not loaded) move it to repawn cell/grid
955 // creature coordinates will be updated and notifiers send
956 if(!CreatureRespawnRelocation(c))
958 // ... or unload (if respawn grid also not loaded)
959 #ifdef MANGOS_DEBUG
960 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
961 sLog.outDebug("Creature (GUID: %u Entry: %u ) can't be move to unloaded respawn grid.",c->GetGUIDLow(),c->GetEntry());
962 #endif
963 AddObjectToRemoveList(c);
969 bool Map::CreatureCellRelocation(Creature *c, Cell new_cell)
971 Cell const& old_cell = c->GetCurrentCell();
972 if(!old_cell.DiffGrid(new_cell) ) // in same grid
974 // if in same cell then none do
975 if(old_cell.DiffCell(new_cell))
977 #ifdef MANGOS_DEBUG
978 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
979 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());
980 #endif
982 if( !old_cell.DiffGrid(new_cell) )
984 RemoveFromGrid(c,getNGrid(old_cell.GridX(), old_cell.GridY()),old_cell);
985 AddToGrid(c,getNGrid(new_cell.GridX(), new_cell.GridY()),new_cell);
986 c->SetCurrentCell(new_cell);
989 else
991 #ifdef MANGOS_DEBUG
992 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
993 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());
994 #endif
997 return true;
1000 // in diff. grids but active creature
1001 if(c->isActiveObject())
1003 EnsureGridLoadedAtEnter(new_cell);
1005 #ifdef MANGOS_DEBUG
1006 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
1007 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());
1008 #endif
1010 RemoveFromGrid(c,getNGrid(old_cell.GridX(), old_cell.GridY()),old_cell);
1011 AddToGrid(c,getNGrid(new_cell.GridX(), new_cell.GridY()),new_cell);
1013 return true;
1016 // in diff. loaded grid normal creature
1017 if(loaded(GridPair(new_cell.GridX(), new_cell.GridY())))
1019 #ifdef MANGOS_DEBUG
1020 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
1021 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());
1022 #endif
1024 RemoveFromGrid(c,getNGrid(old_cell.GridX(), old_cell.GridY()),old_cell);
1026 EnsureGridCreated(GridPair(new_cell.GridX(), new_cell.GridY()));
1027 AddToGrid(c,getNGrid(new_cell.GridX(), new_cell.GridY()),new_cell);
1030 return true;
1033 // fail to move: normal creature attempt move to unloaded grid
1034 #ifdef MANGOS_DEBUG
1035 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
1036 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());
1037 #endif
1038 return false;
1041 bool Map::CreatureRespawnRelocation(Creature *c)
1043 float resp_x, resp_y, resp_z, resp_o;
1044 c->GetRespawnCoord(resp_x, resp_y, resp_z, &resp_o);
1046 CellPair resp_val = MaNGOS::ComputeCellPair(resp_x, resp_y);
1047 Cell resp_cell(resp_val);
1049 c->CombatStop();
1050 c->GetMotionMaster()->Clear();
1052 #ifdef MANGOS_DEBUG
1053 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
1054 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());
1055 #endif
1057 // teleport it to respawn point (like normal respawn if player see)
1058 if(CreatureCellRelocation(c,resp_cell))
1060 c->Relocate(resp_x, resp_y, resp_z, resp_o);
1061 c->GetMotionMaster()->Initialize(); // prevent possible problems with default move generators
1062 CreatureRelocationNotify(c,resp_cell,resp_cell.cellPair());
1063 return true;
1065 else
1066 return false;
1069 bool Map::UnloadGrid(const uint32 &x, const uint32 &y, bool pForce)
1071 NGridType *grid = getNGrid(x, y);
1072 assert( grid != NULL);
1075 if(!pForce && ActiveObjectsNearGrid(x, y) )
1076 return false;
1078 DEBUG_LOG("Unloading grid[%u,%u] for map %u", x,y, i_id);
1079 ObjectGridUnloader unloader(*grid);
1081 // Finish creature moves, remove and delete all creatures with delayed remove before moving to respawn grids
1082 // Must know real mob position before move
1083 DoDelayedMovesAndRemoves();
1085 // move creatures to respawn grids if this is diff.grid or to remove list
1086 unloader.MoveToRespawnN();
1088 // Finish creature moves, remove and delete all creatures with delayed remove before unload
1089 DoDelayedMovesAndRemoves();
1091 unloader.UnloadN();
1092 delete getNGrid(x, y);
1093 setNGrid(NULL, x, y);
1096 int gx = (MAX_NUMBER_OF_GRIDS - 1) - x;
1097 int gy = (MAX_NUMBER_OF_GRIDS - 1) - y;
1099 // delete grid map, but don't delete if it is from parent map (and thus only reference)
1100 //+++if (GridMaps[gx][gy]) don't check for GridMaps[gx][gy], we might have to unload vmaps
1102 if (i_InstanceId == 0)
1104 if(GridMaps[gx][gy])
1106 GridMaps[gx][gy]->unloadData();
1107 delete GridMaps[gx][gy];
1109 VMAP::VMapFactory::createOrGetVMapManager()->unloadMap(GetId(), gx, gy);
1111 else
1112 ((MapInstanced*)m_parentMap)->RemoveGridMapReference(GridPair(gx, gy));
1114 GridMaps[gx][gy] = NULL;
1116 DEBUG_LOG("Unloading grid[%u,%u] for map %u finished", x,y, i_id);
1117 return true;
1120 void Map::UnloadAll(bool pForce)
1122 // clear all delayed moves, useless anyway do this moves before map unload.
1123 i_creaturesToMove.clear();
1125 for (GridRefManager<NGridType>::iterator i = GridRefManager<NGridType>::begin(); i != GridRefManager<NGridType>::end(); )
1127 NGridType &grid(*i->getSource());
1128 ++i;
1129 UnloadGrid(grid.getX(), grid.getY(), pForce); // deletes the grid and removes it from the GridRefManager
1133 MapDifficulty const* Map::GetMapDifficulty() const
1135 return GetMapDifficultyData(GetId(),GetDifficulty());
1138 uint32 Map::GetMaxPlayers() const
1140 if(MapDifficulty const* mapDiff = GetMapDifficulty())
1142 if(mapDiff->maxPlayers || IsRegularDifficulty()) // Normal case (expect that regular difficulty always have correct maxplayers)
1143 return mapDiff->maxPlayers;
1144 else // DBC have 0 maxplayers for heroic instances with expansion < 2
1145 { // The heroic entry exists, so we don't have to check anything, simply return normal max players
1146 MapDifficulty const* normalDiff = GetMapDifficultyData(i_id, REGULAR_DIFFICULTY);
1147 return normalDiff ? normalDiff->maxPlayers : 0;
1150 else // I'd rather assert(false);
1151 return 0;
1154 uint32 Map::GetMaxResetDelay() const
1156 MapDifficulty const* mapDiff = GetMapDifficulty();
1157 return mapDiff ? mapDiff->resetTime : 0;
1160 //*****************************
1161 // Grid function
1162 //*****************************
1163 GridMap::GridMap()
1165 m_flags = 0;
1166 // Area data
1167 m_gridArea = 0;
1168 m_area_map = NULL;
1169 // Height level data
1170 m_gridHeight = INVALID_HEIGHT;
1171 m_gridGetHeight = &GridMap::getHeightFromFlat;
1172 m_V9 = NULL;
1173 m_V8 = NULL;
1174 // Liquid data
1175 m_liquidType = 0;
1176 m_liquid_offX = 0;
1177 m_liquid_offY = 0;
1178 m_liquid_width = 0;
1179 m_liquid_height = 0;
1180 m_liquidLevel = INVALID_HEIGHT;
1181 m_liquid_type = NULL;
1182 m_liquid_map = NULL;
1185 GridMap::~GridMap()
1187 unloadData();
1190 bool GridMap::loadData(char *filename)
1192 // Unload old data if exist
1193 unloadData();
1195 map_fileheader header;
1196 // Not return error if file not found
1197 FILE *in = fopen(filename, "rb");
1198 if (!in)
1199 return true;
1200 fread(&header, sizeof(header),1,in);
1201 if (header.mapMagic == *((uint32 const*)(MAP_MAGIC)) &&
1202 header.versionMagic == *((uint32 const*)(MAP_VERSION_MAGIC)))
1204 // loadup area data
1205 if (header.areaMapOffset && !loadAreaData(in, header.areaMapOffset, header.areaMapSize))
1207 sLog.outError("Error loading map area data\n");
1208 fclose(in);
1209 return false;
1211 // loadup height data
1212 if (header.heightMapOffset && !loadHeightData(in, header.heightMapOffset, header.heightMapSize))
1214 sLog.outError("Error loading map height data\n");
1215 fclose(in);
1216 return false;
1218 // loadup liquid data
1219 if (header.liquidMapOffset && !loadLiquidData(in, header.liquidMapOffset, header.liquidMapSize))
1221 sLog.outError("Error loading map liquids data\n");
1222 fclose(in);
1223 return false;
1225 fclose(in);
1226 return true;
1228 sLog.outError("Map file '%s' is non-compatible version (outdated?). Please, create new using ad.exe program.", filename);
1229 fclose(in);
1230 return false;
1233 void GridMap::unloadData()
1235 if (m_area_map) delete[] m_area_map;
1236 if (m_V9) delete[] m_V9;
1237 if (m_V8) delete[] m_V8;
1238 if (m_liquid_type) delete[] m_liquid_type;
1239 if (m_liquid_map) delete[] m_liquid_map;
1240 m_area_map = NULL;
1241 m_V9 = NULL;
1242 m_V8 = NULL;
1243 m_liquid_type = NULL;
1244 m_liquid_map = NULL;
1245 m_gridGetHeight = &GridMap::getHeightFromFlat;
1248 bool GridMap::loadAreaData(FILE *in, uint32 offset, uint32 size)
1250 map_areaHeader header;
1251 fseek(in, offset, SEEK_SET);
1252 fread(&header, sizeof(header), 1, in);
1253 if (header.fourcc != *((uint32 const*)(MAP_AREA_MAGIC)))
1254 return false;
1256 m_gridArea = header.gridArea;
1257 if (!(header.flags & MAP_AREA_NO_AREA))
1259 m_area_map = new uint16 [16*16];
1260 fread(m_area_map, sizeof(uint16), 16*16, in);
1262 return true;
1265 bool GridMap::loadHeightData(FILE *in, uint32 offset, uint32 size)
1267 map_heightHeader header;
1268 fseek(in, offset, SEEK_SET);
1269 fread(&header, sizeof(header), 1, in);
1270 if (header.fourcc != *((uint32 const*)(MAP_HEIGHT_MAGIC)))
1271 return false;
1273 m_gridHeight = header.gridHeight;
1274 if (!(header.flags & MAP_HEIGHT_NO_HEIGHT))
1276 if ((header.flags & MAP_HEIGHT_AS_INT16))
1278 m_uint16_V9 = new uint16 [129*129];
1279 m_uint16_V8 = new uint16 [128*128];
1280 fread(m_uint16_V9, sizeof(uint16), 129*129, in);
1281 fread(m_uint16_V8, sizeof(uint16), 128*128, in);
1282 m_gridIntHeightMultiplier = (header.gridMaxHeight - header.gridHeight) / 65535;
1283 m_gridGetHeight = &GridMap::getHeightFromUint16;
1285 else if ((header.flags & MAP_HEIGHT_AS_INT8))
1287 m_uint8_V9 = new uint8 [129*129];
1288 m_uint8_V8 = new uint8 [128*128];
1289 fread(m_uint8_V9, sizeof(uint8), 129*129, in);
1290 fread(m_uint8_V8, sizeof(uint8), 128*128, in);
1291 m_gridIntHeightMultiplier = (header.gridMaxHeight - header.gridHeight) / 255;
1292 m_gridGetHeight = &GridMap::getHeightFromUint8;
1294 else
1296 m_V9 = new float [129*129];
1297 m_V8 = new float [128*128];
1298 fread(m_V9, sizeof(float), 129*129, in);
1299 fread(m_V8, sizeof(float), 128*128, in);
1300 m_gridGetHeight = &GridMap::getHeightFromFloat;
1303 else
1304 m_gridGetHeight = &GridMap::getHeightFromFlat;
1305 return true;
1308 bool GridMap::loadLiquidData(FILE *in, uint32 offset, uint32 size)
1310 map_liquidHeader header;
1311 fseek(in, offset, SEEK_SET);
1312 fread(&header, sizeof(header), 1, in);
1313 if (header.fourcc != *((uint32 const*)(MAP_LIQUID_MAGIC)))
1314 return false;
1316 m_liquidType = header.liquidType;
1317 m_liquid_offX = header.offsetX;
1318 m_liquid_offY = header.offsetY;
1319 m_liquid_width = header.width;
1320 m_liquid_height= header.height;
1321 m_liquidLevel = header.liquidLevel;
1323 if (!(header.flags & MAP_LIQUID_NO_TYPE))
1325 m_liquid_type = new uint8 [16*16];
1326 fread(m_liquid_type, sizeof(uint8), 16*16, in);
1328 if (!(header.flags & MAP_LIQUID_NO_HEIGHT))
1330 m_liquid_map = new float [m_liquid_width*m_liquid_height];
1331 fread(m_liquid_map, sizeof(float), m_liquid_width*m_liquid_height, in);
1333 return true;
1336 uint16 GridMap::getArea(float x, float y)
1338 if (!m_area_map)
1339 return m_gridArea;
1341 x = 16 * (32 - x/SIZE_OF_GRIDS);
1342 y = 16 * (32 - y/SIZE_OF_GRIDS);
1343 int lx = (int)x & 15;
1344 int ly = (int)y & 15;
1345 return m_area_map[lx*16 + ly];
1348 float GridMap::getHeightFromFlat(float /*x*/, float /*y*/) const
1350 return m_gridHeight;
1353 float GridMap::getHeightFromFloat(float x, float y) const
1355 if (!m_V8 || !m_V9)
1356 return m_gridHeight;
1358 x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
1359 y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
1361 int x_int = (int)x;
1362 int y_int = (int)y;
1363 x -= x_int;
1364 y -= y_int;
1365 x_int&=(MAP_RESOLUTION - 1);
1366 y_int&=(MAP_RESOLUTION - 1);
1368 // Height stored as: h5 - its v8 grid, h1-h4 - its v9 grid
1369 // +--------------> X
1370 // | h1-------h2 Coordinates is:
1371 // | | \ 1 / | h1 0,0
1372 // | | \ / | h2 0,1
1373 // | | 2 h5 3 | h3 1,0
1374 // | | / \ | h4 1,1
1375 // | | / 4 \ | h5 1/2,1/2
1376 // | h3-------h4
1377 // V Y
1378 // For find height need
1379 // 1 - detect triangle
1380 // 2 - solve linear equation from triangle points
1381 // Calculate coefficients for solve h = a*x + b*y + c
1383 float a,b,c;
1384 // Select triangle:
1385 if (x+y < 1)
1387 if (x > y)
1389 // 1 triangle (h1, h2, h5 points)
1390 float h1 = m_V9[(x_int )*129 + y_int];
1391 float h2 = m_V9[(x_int+1)*129 + y_int];
1392 float h5 = 2 * m_V8[x_int*128 + y_int];
1393 a = h2-h1;
1394 b = h5-h1-h2;
1395 c = h1;
1397 else
1399 // 2 triangle (h1, h3, h5 points)
1400 float h1 = m_V9[x_int*129 + y_int ];
1401 float h3 = m_V9[x_int*129 + y_int+1];
1402 float h5 = 2 * m_V8[x_int*128 + y_int];
1403 a = h5 - h1 - h3;
1404 b = h3 - h1;
1405 c = h1;
1408 else
1410 if (x > y)
1412 // 3 triangle (h2, h4, h5 points)
1413 float h2 = m_V9[(x_int+1)*129 + y_int ];
1414 float h4 = m_V9[(x_int+1)*129 + y_int+1];
1415 float h5 = 2 * m_V8[x_int*128 + y_int];
1416 a = h2 + h4 - h5;
1417 b = h4 - h2;
1418 c = h5 - h4;
1420 else
1422 // 4 triangle (h3, h4, h5 points)
1423 float h3 = m_V9[(x_int )*129 + y_int+1];
1424 float h4 = m_V9[(x_int+1)*129 + y_int+1];
1425 float h5 = 2 * m_V8[x_int*128 + y_int];
1426 a = h4 - h3;
1427 b = h3 + h4 - h5;
1428 c = h5 - h4;
1431 // Calculate height
1432 return a * x + b * y + c;
1435 float GridMap::getHeightFromUint8(float x, float y) const
1437 if (!m_uint8_V8 || !m_uint8_V9)
1438 return m_gridHeight;
1440 x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
1441 y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
1443 int x_int = (int)x;
1444 int y_int = (int)y;
1445 x -= x_int;
1446 y -= y_int;
1447 x_int&=(MAP_RESOLUTION - 1);
1448 y_int&=(MAP_RESOLUTION - 1);
1450 int32 a, b, c;
1451 uint8 *V9_h1_ptr = &m_uint8_V9[x_int*128 + x_int + y_int];
1452 if (x+y < 1)
1454 if (x > y)
1456 // 1 triangle (h1, h2, h5 points)
1457 int32 h1 = V9_h1_ptr[ 0];
1458 int32 h2 = V9_h1_ptr[129];
1459 int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int];
1460 a = h2-h1;
1461 b = h5-h1-h2;
1462 c = h1;
1464 else
1466 // 2 triangle (h1, h3, h5 points)
1467 int32 h1 = V9_h1_ptr[0];
1468 int32 h3 = V9_h1_ptr[1];
1469 int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int];
1470 a = h5 - h1 - h3;
1471 b = h3 - h1;
1472 c = h1;
1475 else
1477 if (x > y)
1479 // 3 triangle (h2, h4, h5 points)
1480 int32 h2 = V9_h1_ptr[129];
1481 int32 h4 = V9_h1_ptr[130];
1482 int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int];
1483 a = h2 + h4 - h5;
1484 b = h4 - h2;
1485 c = h5 - h4;
1487 else
1489 // 4 triangle (h3, h4, h5 points)
1490 int32 h3 = V9_h1_ptr[ 1];
1491 int32 h4 = V9_h1_ptr[130];
1492 int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int];
1493 a = h4 - h3;
1494 b = h3 + h4 - h5;
1495 c = h5 - h4;
1498 // Calculate height
1499 return (float)((a * x) + (b * y) + c)*m_gridIntHeightMultiplier + m_gridHeight;
1502 float GridMap::getHeightFromUint16(float x, float y) const
1504 if (!m_uint16_V8 || !m_uint16_V9)
1505 return m_gridHeight;
1507 x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
1508 y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
1510 int x_int = (int)x;
1511 int y_int = (int)y;
1512 x -= x_int;
1513 y -= y_int;
1514 x_int&=(MAP_RESOLUTION - 1);
1515 y_int&=(MAP_RESOLUTION - 1);
1517 int32 a, b, c;
1518 uint16 *V9_h1_ptr = &m_uint16_V9[x_int*128 + x_int + y_int];
1519 if (x+y < 1)
1521 if (x > y)
1523 // 1 triangle (h1, h2, h5 points)
1524 int32 h1 = V9_h1_ptr[ 0];
1525 int32 h2 = V9_h1_ptr[129];
1526 int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int];
1527 a = h2-h1;
1528 b = h5-h1-h2;
1529 c = h1;
1531 else
1533 // 2 triangle (h1, h3, h5 points)
1534 int32 h1 = V9_h1_ptr[0];
1535 int32 h3 = V9_h1_ptr[1];
1536 int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int];
1537 a = h5 - h1 - h3;
1538 b = h3 - h1;
1539 c = h1;
1542 else
1544 if (x > y)
1546 // 3 triangle (h2, h4, h5 points)
1547 int32 h2 = V9_h1_ptr[129];
1548 int32 h4 = V9_h1_ptr[130];
1549 int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int];
1550 a = h2 + h4 - h5;
1551 b = h4 - h2;
1552 c = h5 - h4;
1554 else
1556 // 4 triangle (h3, h4, h5 points)
1557 int32 h3 = V9_h1_ptr[ 1];
1558 int32 h4 = V9_h1_ptr[130];
1559 int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int];
1560 a = h4 - h3;
1561 b = h3 + h4 - h5;
1562 c = h5 - h4;
1565 // Calculate height
1566 return (float)((a * x) + (b * y) + c)*m_gridIntHeightMultiplier + m_gridHeight;
1569 float GridMap::getLiquidLevel(float x, float y)
1571 if (!m_liquid_map)
1572 return m_liquidLevel;
1574 x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
1575 y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
1577 int cx_int = ((int)x & (MAP_RESOLUTION-1)) - m_liquid_offY;
1578 int cy_int = ((int)y & (MAP_RESOLUTION-1)) - m_liquid_offX;
1580 if (cx_int < 0 || cx_int >=m_liquid_height)
1581 return INVALID_HEIGHT;
1582 if (cy_int < 0 || cy_int >=m_liquid_width )
1583 return INVALID_HEIGHT;
1585 return m_liquid_map[cx_int*m_liquid_width + cy_int];
1588 uint8 GridMap::getTerrainType(float x, float y)
1590 if (!m_liquid_type)
1591 return m_liquidType;
1593 x = 16 * (32 - x/SIZE_OF_GRIDS);
1594 y = 16 * (32 - y/SIZE_OF_GRIDS);
1595 int lx = (int)x & 15;
1596 int ly = (int)y & 15;
1597 return m_liquid_type[lx*16 + ly];
1600 // Get water state on map
1601 inline ZLiquidStatus GridMap::getLiquidStatus(float x, float y, float z, uint8 ReqLiquidType, LiquidData *data)
1603 // Check water type (if no water return)
1604 if (!m_liquid_type && !m_liquidType)
1605 return LIQUID_MAP_NO_WATER;
1607 // Get cell
1608 float cx = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
1609 float cy = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
1611 int x_int = (int)cx & (MAP_RESOLUTION-1);
1612 int y_int = (int)cy & (MAP_RESOLUTION-1);
1614 // Check water type in cell
1615 uint8 type = m_liquid_type ? m_liquid_type[(x_int>>3)*16 + (y_int>>3)] : m_liquidType;
1616 if (type == 0)
1617 return LIQUID_MAP_NO_WATER;
1619 // Check req liquid type mask
1620 if (ReqLiquidType && !(ReqLiquidType&type))
1621 return LIQUID_MAP_NO_WATER;
1623 // Check water level:
1624 // Check water height map
1625 int lx_int = x_int - m_liquid_offY;
1626 int ly_int = y_int - m_liquid_offX;
1627 if (lx_int < 0 || lx_int >=m_liquid_height)
1628 return LIQUID_MAP_NO_WATER;
1629 if (ly_int < 0 || ly_int >=m_liquid_width )
1630 return LIQUID_MAP_NO_WATER;
1632 // Get water level
1633 float liquid_level = m_liquid_map ? m_liquid_map[lx_int*m_liquid_width + ly_int] : m_liquidLevel;
1634 // Get ground level (sub 0.2 for fix some errors)
1635 float ground_level = getHeight(x, y);
1637 // Check water level and ground level
1638 if (liquid_level < ground_level || z < ground_level - 2)
1639 return LIQUID_MAP_NO_WATER;
1641 // All ok in water -> store data
1642 if (data)
1644 data->type = type;
1645 data->level = liquid_level;
1646 data->depth_level = ground_level;
1649 // For speed check as int values
1650 int delta = int((liquid_level - z) * 10);
1652 // Get position delta
1653 if (delta > 20) // Under water
1654 return LIQUID_MAP_UNDER_WATER;
1655 if (delta > 0 ) // In water
1656 return LIQUID_MAP_IN_WATER;
1657 if (delta > -1) // Walk on water
1658 return LIQUID_MAP_WATER_WALK;
1659 // Above water
1660 return LIQUID_MAP_ABOVE_WATER;
1663 inline GridMap *Map::GetGrid(float x, float y)
1665 // half opt method
1666 int gx=(int)(32-x/SIZE_OF_GRIDS); //grid x
1667 int gy=(int)(32-y/SIZE_OF_GRIDS); //grid y
1669 // ensure GridMap is loaded
1670 EnsureGridCreated(GridPair(63-gx,63-gy));
1672 return GridMaps[gx][gy];
1675 float Map::GetHeight(float x, float y, float z, bool pUseVmaps) const
1677 // find raw .map surface under Z coordinates
1678 float mapHeight;
1679 if(GridMap *gmap = const_cast<Map*>(this)->GetGrid(x, y))
1681 float _mapheight = gmap->getHeight(x,y);
1683 // look from a bit higher pos to find the floor, ignore under surface case
1684 if(z + 2.0f > _mapheight)
1685 mapHeight = _mapheight;
1686 else
1687 mapHeight = VMAP_INVALID_HEIGHT_VALUE;
1689 else
1690 mapHeight = VMAP_INVALID_HEIGHT_VALUE;
1692 float vmapHeight;
1693 if(pUseVmaps)
1695 VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager();
1696 if(vmgr->isHeightCalcEnabled())
1698 // look from a bit higher pos to find the floor
1699 vmapHeight = vmgr->getHeight(GetId(), x, y, z + 2.0f);
1701 else
1702 vmapHeight = VMAP_INVALID_HEIGHT_VALUE;
1704 else
1705 vmapHeight = VMAP_INVALID_HEIGHT_VALUE;
1707 // mapHeight set for any above raw ground Z or <= INVALID_HEIGHT
1708 // vmapheight set for any under Z value or <= INVALID_HEIGHT
1710 if( vmapHeight > INVALID_HEIGHT )
1712 if( mapHeight > INVALID_HEIGHT )
1714 // we have mapheight and vmapheight and must select more appropriate
1716 // we are already under the surface or vmap height above map heigt
1717 // or if the distance of the vmap height is less the land height distance
1718 if( z < mapHeight || vmapHeight > mapHeight || fabs(mapHeight-z) > fabs(vmapHeight-z) )
1719 return vmapHeight;
1720 else
1721 return mapHeight; // better use .map surface height
1724 else
1725 return vmapHeight; // we have only vmapHeight (if have)
1727 else
1729 if(!pUseVmaps)
1730 return mapHeight; // explicitly use map data (if have)
1731 else if(mapHeight > INVALID_HEIGHT && (z < mapHeight + 2 || z == MAX_HEIGHT))
1732 return mapHeight; // explicitly use map data if original z < mapHeight but map found (z+2 > mapHeight)
1733 else
1734 return VMAP_INVALID_HEIGHT_VALUE; // we not have any height
1738 uint16 Map::GetAreaFlag(float x, float y, float z) const
1740 uint16 areaflag;
1741 if(GridMap *gmap = const_cast<Map*>(this)->GetGrid(x, y))
1742 areaflag = gmap->getArea(x, y);
1743 // this used while not all *.map files generated (instances)
1744 else
1745 areaflag = GetAreaFlagByMapId(i_id);
1747 //FIXME: some hacks for areas above or underground for ground area
1748 // required for area specific spells/etc, until map/vmap data
1749 // not provided correct areaflag with this hacks
1750 switch(areaflag)
1752 // Acherus: The Ebon Hold (Plaguelands: The Scarlet Enclave)
1753 case 1984: // Plaguelands: The Scarlet Enclave
1754 case 2076: // Death's Breach (Plaguelands: The Scarlet Enclave)
1755 case 2745: // The Noxious Pass (Plaguelands: The Scarlet Enclave)
1756 if(z > 350.0f) areaflag = 2048; break;
1757 // Acherus: The Ebon Hold (Eastern Plaguelands)
1758 case 856: // The Noxious Glade (Eastern Plaguelands)
1759 case 2456: // Death's Breach (Eastern Plaguelands)
1760 if(z > 350.0f) areaflag = 1950; break;
1761 // Winterfin Caverns
1762 case 1652: // Coldarra
1763 case 1653: // The Westrift
1764 case 1661: // Winterfin Village
1765 if (x > 3823.0f && x < 4141.5f && y > 6247.0f && y < 64890.0f && z < 42.5f)
1766 areaflag = 1723;
1767 break;
1768 // Moonrest Gardens
1769 case 1787:
1770 if (x > 3315.3f && x < 3361.6f && y > 2469.4f && y < 2565.8f && z > 197.0f)
1771 areaflag = 1786; // Surge Needle (cords not entirely correct, will need round circle if this is really needed(see spell 47097 eff 77))
1772 break;
1773 // Dalaran
1774 case 2492: // Forlorn Woods (Crystalsong Forest)
1775 case 2371: // Valley of Echoes (Icecrown Glacier)
1776 if (x > 5568.0f && x < 6116.0f && y > 282.0f && y < 982.0f && z > 563.0f)
1778 // Krasus' Landing (Dalaran), fast check
1779 if (x > 5758.77f && x < 5869.03f && y < 510.46f)
1781 // Krasus' Landing (Dalaran), with open east side
1782 if (y < 449.33f || (x-5813.9f)*(x-5813.9f)+(y-449.33f)*(y-449.33f) < 1864.0f)
1784 areaflag = 2533; // Note: also 2633, possible one flight allowed and other not allowed case
1785 break;
1789 // Dalaran
1790 areaflag = 2153;
1792 break;
1793 // The Violet Citadel (Dalaran) or Dalaran
1794 case 2484: // The Twilight Rivulet (Crystalsong Forest)
1795 case 1593: // Crystalsong Forest
1796 // Dalaran
1797 if (x > 5568.0f && x < 6116.0f && y > 282.0f && y < 982.0f && z > 563.0f)
1799 // The Violet Citadel (Dalaran), fast check
1800 if (x > 5721.1f && x < 5884.66f && y > 764.4f && y < 948.0f)
1802 // The Violet Citadel (Dalaran)
1803 if ((x-5803.0f)*(x-5803.0f)+(y-846.18f)*(y-846.18f) < 6690.0f)
1805 areaflag = 2696;
1806 break;
1810 // Dalaran
1811 areaflag = 2153;
1813 break;
1814 // Vargoth's Retreat (Dalaran) or The Violet Citadel (Dalaran) or Dalaran
1815 case 2504: // Violet Stand (Crystalsong Forest)
1816 // Dalaran
1817 if (x > 5568.0f && x < 6116.0f && y > 282.0f && y < 982.0f && z > 563.0f)
1819 // The Violet Citadel (Dalaran), fast check
1820 if (x > 5721.1f && x < 5884.66f && y > 764.4f && y < 948.0f)
1822 // Vargoth's Retreat (Dalaran), nice slow circle with upper limit
1823 if (z < 898.0f && (x-5765.0f)*(x-5765.0f)+(y-862.4f)*(y-862.4f) < 262.0f)
1825 areaflag = 2748;
1826 break;
1829 // The Violet Citadel (Dalaran)
1830 if ((x-5803.0f)*(x-5803.0f)+(y-846.18f)*(y-846.18f) < 6690.0f)
1832 areaflag = 2696;
1833 break;
1837 // Dalaran
1838 areaflag = 2153;
1840 break;
1841 // Maw of Neltharion (cave)
1842 case 164: // Dragonblight
1843 case 1797: // Obsidian Dragonshrine (Dragonblight)
1844 case 1827: // Wintergrasp
1845 case 2591: // The Cauldron of Flames (Wintergrasp)
1846 if (x > 4364.0f && x < 4632.0f && y > 1545.0f && y < 1886.0f && z < 200.0f) areaflag = 1853; break;
1847 // Undercity (sewers enter and path)
1848 case 179: // Tirisfal Glades
1849 if (x > 1595.0f && x < 1699.0f && y > 535.0f && y < 643.5f && z < 30.5f) areaflag = 685; break;
1850 // Undercity (Royal Quarter)
1851 case 210: // Silverpine Forest
1852 case 316: // The Shining Strand (Silverpine Forest)
1853 case 438: // Lordamere Lake (Silverpine Forest)
1854 if (x > 1237.0f && x < 1401.0f && y > 284.0f && y < 440.0f && z < -40.0f) areaflag = 685; break;
1855 // Undercity (cave and ground zone, part of royal quarter)
1856 case 607: // Ruins of Lordaeron (Tirisfal Glades)
1857 // ground and near to ground (by city walls)
1858 if(z > 0.0f)
1860 if (x > 1510.0f && x < 1839.0f && y > 29.77f && y < 433.0f) areaflag = 685;
1862 // more wide underground, part of royal quarter
1863 else
1865 if (x > 1299.0f && x < 1839.0f && y > 10.0f && y < 440.0f) areaflag = 685;
1867 break;
1868 // The Makers' Perch (ground) and Makers' Overlook (ground and cave)
1869 case 1335: // Sholazar Basin
1870 // The Makers' Perch ground (fast box)
1871 if (x > 6100.0f && x < 6250.0f && y > 5650.0f && y < 5800.0f)
1873 // nice slow circle
1874 if ((x-6183.0f)*(x-6183.0f)+(y-5717.0f)*(y-5717.0f) < 2500.0f)
1875 areaflag = 2189;
1877 // Makers' Overlook (ground and cave)
1878 else if (x > 5634.48f && x < 5774.53f && y < 3475.0f && z > 300.0f)
1880 if (y > 3380.26f || (y > 3265.0f && z < 360.0f))
1881 areaflag = 2187;
1883 break;
1884 // The Makers' Perch (underground)
1885 case 2147: // The Stormwright's Shelf (Sholazar Basin)
1886 if (x > 6199.0f && x < 6283.0f && y > 5705.0f && y < 5817.0f && z < 38.0f) areaflag = 2189; break;
1887 // Makers' Overlook (deep cave)
1888 case 267: // Icecrown
1889 if (x > 5684.0f && x < 5798.0f && y > 3035.0f && y < 3367.0f && z < 358.0f) areaflag = 2187; break;
1890 // Wyrmrest Temple (Dragonblight)
1891 case 1814: // Path of the Titans (Dragonblight)
1892 case 1897: // The Dragon Wastes (Dragonblight)
1893 // fast box
1894 if (x > 3400.0f && x < 3700.0f && y > 130.0f && y < 420.0f)
1896 // nice slow circle
1897 if ((x-3546.87f)*(x-3546.87f)+(y-272.71f)*(y-272.71f) < 19600.0f) areaflag = 1791;
1899 break;
1902 return areaflag;
1905 uint8 Map::GetTerrainType(float x, float y ) const
1907 if(GridMap *gmap = const_cast<Map*>(this)->GetGrid(x, y))
1908 return gmap->getTerrainType(x, y);
1909 else
1910 return 0;
1913 ZLiquidStatus Map::getLiquidStatus(float x, float y, float z, uint8 ReqLiquidType, LiquidData *data) const
1915 if(GridMap* gmap = const_cast<Map*>(this)->GetGrid(x, y))
1916 return gmap->getLiquidStatus(x, y, z, ReqLiquidType, data);
1917 else
1918 return LIQUID_MAP_NO_WATER;
1921 float Map::GetWaterLevel(float x, float y ) const
1923 if(GridMap* gmap = const_cast<Map*>(this)->GetGrid(x, y))
1924 return gmap->getLiquidLevel(x, y);
1925 else
1926 return 0;
1929 uint32 Map::GetAreaIdByAreaFlag(uint16 areaflag,uint32 map_id)
1931 AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
1933 if (entry)
1934 return entry->ID;
1935 else
1936 return 0;
1939 uint32 Map::GetZoneIdByAreaFlag(uint16 areaflag,uint32 map_id)
1941 AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
1943 if( entry )
1944 return ( entry->zone != 0 ) ? entry->zone : entry->ID;
1945 else
1946 return 0;
1949 void Map::GetZoneAndAreaIdByAreaFlag(uint32& zoneid, uint32& areaid, uint16 areaflag,uint32 map_id)
1951 AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
1953 areaid = entry ? entry->ID : 0;
1954 zoneid = entry ? (( entry->zone != 0 ) ? entry->zone : entry->ID) : 0;
1957 bool Map::IsInWater(float x, float y, float pZ) const
1959 // Check surface in x, y point for liquid
1960 if (const_cast<Map*>(this)->GetGrid(x, y))
1962 LiquidData liquid_status;
1963 if (getLiquidStatus(x, y, pZ, MAP_ALL_LIQUIDS, &liquid_status))
1965 if (liquid_status.level - liquid_status.depth_level > 2)
1966 return true;
1969 return false;
1972 bool Map::IsUnderWater(float x, float y, float z) const
1974 if (const_cast<Map*>(this)->GetGrid(x, y))
1976 if (getLiquidStatus(x, y, z, MAP_LIQUID_TYPE_WATER|MAP_LIQUID_TYPE_OCEAN)&LIQUID_MAP_UNDER_WATER)
1977 return true;
1979 return false;
1982 bool Map::CheckGridIntegrity(Creature* c, bool moved) const
1984 Cell const& cur_cell = c->GetCurrentCell();
1986 CellPair xy_val = MaNGOS::ComputeCellPair(c->GetPositionX(), c->GetPositionY());
1987 Cell xy_cell(xy_val);
1988 if(xy_cell != cur_cell)
1990 sLog.outError("Creature (GUIDLow: %u) X: %f Y: %f (%s) in grid[%u,%u]cell[%u,%u] instead grid[%u,%u]cell[%u,%u]",
1991 c->GetGUIDLow(),
1992 c->GetPositionX(),c->GetPositionY(),(moved ? "final" : "original"),
1993 cur_cell.GridX(), cur_cell.GridY(), cur_cell.CellX(), cur_cell.CellY(),
1994 xy_cell.GridX(), xy_cell.GridY(), xy_cell.CellX(), xy_cell.CellY());
1995 return true; // not crash at error, just output error in debug mode
1998 return true;
2001 const char* Map::GetMapName() const
2003 return i_mapEntry ? i_mapEntry->name[sWorld.GetDefaultDbcLocale()] : "UNNAMEDMAP\x0";
2006 void Map::UpdateObjectVisibility( WorldObject* obj, Cell cell, CellPair cellpair)
2008 cell.data.Part.reserved = ALL_DISTRICT;
2009 cell.SetNoCreate();
2010 MaNGOS::VisibleChangesNotifier notifier(*obj);
2011 TypeContainerVisitor<MaNGOS::VisibleChangesNotifier, WorldTypeMapContainer > player_notifier(notifier);
2012 CellLock<GridReadGuard> cell_lock(cell, cellpair);
2013 cell_lock->Visit(cell_lock, player_notifier, *this, *obj, GetVisibilityDistance());
2016 void Map::UpdatePlayerVisibility( Player* player, Cell cell, CellPair cellpair )
2018 cell.data.Part.reserved = ALL_DISTRICT;
2020 MaNGOS::PlayerNotifier pl_notifier(*player);
2021 TypeContainerVisitor<MaNGOS::PlayerNotifier, WorldTypeMapContainer > player_notifier(pl_notifier);
2023 CellLock<ReadGuard> cell_lock(cell, cellpair);
2024 cell_lock->Visit(cell_lock, player_notifier, *this, *player, GetVisibilityDistance());
2027 void Map::UpdateObjectsVisibilityFor( Player* player, Cell cell, CellPair cellpair )
2029 MaNGOS::VisibleNotifier notifier(*player);
2031 cell.data.Part.reserved = ALL_DISTRICT;
2032 cell.SetNoCreate();
2033 TypeContainerVisitor<MaNGOS::VisibleNotifier, WorldTypeMapContainer > world_notifier(notifier);
2034 TypeContainerVisitor<MaNGOS::VisibleNotifier, GridTypeMapContainer > grid_notifier(notifier);
2035 CellLock<GridReadGuard> cell_lock(cell, cellpair);
2036 cell_lock->Visit(cell_lock, world_notifier, *this, *player, GetVisibilityDistance());
2037 cell_lock->Visit(cell_lock, grid_notifier, *this, *player, GetVisibilityDistance());
2039 // send data
2040 notifier.Notify();
2043 void Map::PlayerRelocationNotify( Player* player, Cell cell, CellPair cellpair )
2045 CellLock<ReadGuard> cell_lock(cell, cellpair);
2046 MaNGOS::PlayerRelocationNotifier relocationNotifier(*player);
2047 cell.data.Part.reserved = ALL_DISTRICT;
2049 TypeContainerVisitor<MaNGOS::PlayerRelocationNotifier, GridTypeMapContainer > p2grid_relocation(relocationNotifier);
2050 TypeContainerVisitor<MaNGOS::PlayerRelocationNotifier, WorldTypeMapContainer > p2world_relocation(relocationNotifier);
2052 cell_lock->Visit(cell_lock, p2grid_relocation, *this, *player, MAX_CREATURE_ATTACK_RADIUS);
2053 cell_lock->Visit(cell_lock, p2world_relocation, *this, *player, MAX_CREATURE_ATTACK_RADIUS);
2056 void Map::CreatureRelocationNotify(Creature *creature, Cell cell, CellPair cellpair)
2058 CellLock<ReadGuard> cell_lock(cell, cellpair);
2059 MaNGOS::CreatureRelocationNotifier relocationNotifier(*creature);
2060 cell.data.Part.reserved = ALL_DISTRICT;
2061 cell.SetNoCreate(); // not trigger load unloaded grids at notifier call
2063 TypeContainerVisitor<MaNGOS::CreatureRelocationNotifier, WorldTypeMapContainer > c2world_relocation(relocationNotifier);
2064 TypeContainerVisitor<MaNGOS::CreatureRelocationNotifier, GridTypeMapContainer > c2grid_relocation(relocationNotifier);
2066 cell_lock->Visit(cell_lock, c2world_relocation, *this, *creature, MAX_CREATURE_ATTACK_RADIUS);
2067 cell_lock->Visit(cell_lock, c2grid_relocation, *this, *creature, MAX_CREATURE_ATTACK_RADIUS);
2070 void Map::SendInitSelf( Player * player )
2072 sLog.outDetail("Creating player data for himself %u", player->GetGUIDLow());
2074 UpdateData data;
2076 // attach to player data current transport data
2077 if(Transport* transport = player->GetTransport())
2079 transport->BuildCreateUpdateBlockForPlayer(&data, player);
2082 // build data for self presence in world at own client (one time for map)
2083 player->BuildCreateUpdateBlockForPlayer(&data, player);
2085 // build other passengers at transport also (they always visible and marked as visible and will not send at visibility update at add to map
2086 if(Transport* transport = player->GetTransport())
2088 for(Transport::PlayerSet::const_iterator itr = transport->GetPassengers().begin();itr!=transport->GetPassengers().end();++itr)
2090 if(player!=(*itr) && player->HaveAtClient(*itr))
2092 (*itr)->BuildCreateUpdateBlockForPlayer(&data, player);
2097 WorldPacket packet;
2098 data.BuildPacket(&packet);
2099 player->GetSession()->SendPacket(&packet);
2102 void Map::SendInitTransports( Player * player )
2104 // Hack to send out transports
2105 MapManager::TransportMap& tmap = sMapMgr.m_TransportsByMap;
2107 // no transports at map
2108 if (tmap.find(player->GetMapId()) == tmap.end())
2109 return;
2111 UpdateData transData;
2113 MapManager::TransportSet& tset = tmap[player->GetMapId()];
2115 for (MapManager::TransportSet::const_iterator i = tset.begin(); i != tset.end(); ++i)
2117 // send data for current transport in other place
2118 if((*i) != player->GetTransport() && (*i)->GetMapId()==i_id)
2120 (*i)->BuildCreateUpdateBlockForPlayer(&transData, player);
2124 WorldPacket packet;
2125 transData.BuildPacket(&packet);
2126 player->GetSession()->SendPacket(&packet);
2129 void Map::SendRemoveTransports( Player * player )
2131 // Hack to send out transports
2132 MapManager::TransportMap& tmap = sMapMgr.m_TransportsByMap;
2134 // no transports at map
2135 if (tmap.find(player->GetMapId()) == tmap.end())
2136 return;
2138 UpdateData transData;
2140 MapManager::TransportSet& tset = tmap[player->GetMapId()];
2142 // except used transport
2143 for (MapManager::TransportSet::const_iterator i = tset.begin(); i != tset.end(); ++i)
2144 if((*i) != player->GetTransport() && (*i)->GetMapId()!=i_id)
2145 (*i)->BuildOutOfRangeUpdateBlock(&transData);
2147 WorldPacket packet;
2148 transData.BuildPacket(&packet);
2149 player->GetSession()->SendPacket(&packet);
2152 inline void Map::setNGrid(NGridType *grid, uint32 x, uint32 y)
2154 if(x >= MAX_NUMBER_OF_GRIDS || y >= MAX_NUMBER_OF_GRIDS)
2156 sLog.outError("map::setNGrid() Invalid grid coordinates found: %d, %d!",x,y);
2157 assert(false);
2159 i_grids[x][y] = grid;
2162 void Map::DoDelayedMovesAndRemoves()
2164 MoveAllCreaturesInMoveList();
2165 RemoveAllObjectsInRemoveList();
2168 void Map::AddObjectToRemoveList(WorldObject *obj)
2170 assert(obj->GetMapId()==GetId() && obj->GetInstanceId()==GetInstanceId());
2172 obj->CleanupsBeforeDelete(); // remove or simplify at least cross referenced links
2174 i_objectsToRemove.insert(obj);
2175 //sLog.outDebug("Object (GUID: %u TypeId: %u ) added to removing list.",obj->GetGUIDLow(),obj->GetTypeId());
2178 void Map::RemoveAllObjectsInRemoveList()
2180 if(i_objectsToRemove.empty())
2181 return;
2183 //sLog.outDebug("Object remover 1 check.");
2184 while(!i_objectsToRemove.empty())
2186 WorldObject* obj = *i_objectsToRemove.begin();
2187 i_objectsToRemove.erase(i_objectsToRemove.begin());
2189 switch(obj->GetTypeId())
2191 case TYPEID_CORPSE:
2193 // ??? WTF
2194 Corpse* corpse = GetCorpse(obj->GetGUID());
2195 if (!corpse)
2196 sLog.outError("Try delete corpse/bones %u that not in map", obj->GetGUIDLow());
2197 else
2198 Remove(corpse,true);
2199 break;
2201 case TYPEID_DYNAMICOBJECT:
2202 Remove((DynamicObject*)obj,true);
2203 break;
2204 case TYPEID_GAMEOBJECT:
2205 Remove((GameObject*)obj,true);
2206 break;
2207 case TYPEID_UNIT:
2208 Remove((Creature*)obj,true);
2209 break;
2210 default:
2211 sLog.outError("Non-grid object (TypeId: %u) in grid object removing list, ignored.",obj->GetTypeId());
2212 break;
2215 //sLog.outDebug("Object remover 2 check.");
2218 uint32 Map::GetPlayersCountExceptGMs() const
2220 uint32 count = 0;
2221 for(MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
2222 if(!itr->getSource()->isGameMaster())
2223 ++count;
2224 return count;
2227 void Map::SendToPlayers(WorldPacket const* data) const
2229 for(MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
2230 itr->getSource()->GetSession()->SendPacket(data);
2233 bool Map::ActiveObjectsNearGrid(uint32 x, uint32 y) const
2235 ASSERT(x < MAX_NUMBER_OF_GRIDS);
2236 ASSERT(y < MAX_NUMBER_OF_GRIDS);
2238 CellPair cell_min(x*MAX_NUMBER_OF_CELLS, y*MAX_NUMBER_OF_CELLS);
2239 CellPair cell_max(cell_min.x_coord + MAX_NUMBER_OF_CELLS, cell_min.y_coord+MAX_NUMBER_OF_CELLS);
2241 //we must find visible range in cells so we unload only non-visible cells...
2242 float viewDist = GetVisibilityDistance();
2243 int cell_range = (int)ceilf(viewDist / SIZE_OF_GRID_CELL) + 1;
2245 cell_min << cell_range;
2246 cell_min -= cell_range;
2247 cell_max >> cell_range;
2248 cell_max += cell_range;
2250 for(MapRefManager::const_iterator iter = m_mapRefManager.begin(); iter != m_mapRefManager.end(); ++iter)
2252 Player* plr = iter->getSource();
2254 CellPair p = MaNGOS::ComputeCellPair(plr->GetPositionX(), plr->GetPositionY());
2255 if( (cell_min.x_coord <= p.x_coord && p.x_coord <= cell_max.x_coord) &&
2256 (cell_min.y_coord <= p.y_coord && p.y_coord <= cell_max.y_coord) )
2257 return true;
2260 for(ActiveNonPlayers::const_iterator iter = m_activeNonPlayers.begin(); iter != m_activeNonPlayers.end(); ++iter)
2262 WorldObject* obj = *iter;
2264 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
2265 if( (cell_min.x_coord <= p.x_coord && p.x_coord <= cell_max.x_coord) &&
2266 (cell_min.y_coord <= p.y_coord && p.y_coord <= cell_max.y_coord) )
2267 return true;
2270 return false;
2273 void Map::AddToActive( Creature* c )
2275 AddToActiveHelper(c);
2277 // also not allow unloading spawn grid to prevent creating creature clone at load
2278 if(!c->isPet() && c->GetDBTableGUIDLow())
2280 float x,y,z;
2281 c->GetRespawnCoord(x,y,z);
2282 GridPair p = MaNGOS::ComputeGridPair(x, y);
2283 if(getNGrid(p.x_coord, p.y_coord))
2284 getNGrid(p.x_coord, p.y_coord)->incUnloadActiveLock();
2285 else
2287 GridPair p2 = MaNGOS::ComputeGridPair(c->GetPositionX(), c->GetPositionY());
2288 sLog.outError("Active creature (GUID: %u Entry: %u) added to grid[%u,%u] but spawn grid[%u,%u] not loaded.",
2289 c->GetGUIDLow(), c->GetEntry(), p.x_coord, p.y_coord, p2.x_coord, p2.y_coord);
2294 void Map::RemoveFromActive( Creature* c )
2296 RemoveFromActiveHelper(c);
2298 // also allow unloading spawn grid
2299 if(!c->isPet() && c->GetDBTableGUIDLow())
2301 float x,y,z;
2302 c->GetRespawnCoord(x,y,z);
2303 GridPair p = MaNGOS::ComputeGridPair(x, y);
2304 if(getNGrid(p.x_coord, p.y_coord))
2305 getNGrid(p.x_coord, p.y_coord)->decUnloadActiveLock();
2306 else
2308 GridPair p2 = MaNGOS::ComputeGridPair(c->GetPositionX(), c->GetPositionY());
2309 sLog.outError("Active creature (GUID: %u Entry: %u) removed from grid[%u,%u] but spawn grid[%u,%u] not loaded.",
2310 c->GetGUIDLow(), c->GetEntry(), p.x_coord, p.y_coord, p2.x_coord, p2.y_coord);
2315 template void Map::Add(Corpse *);
2316 template void Map::Add(Creature *);
2317 template void Map::Add(GameObject *);
2318 template void Map::Add(DynamicObject *);
2320 template void Map::Remove(Corpse *,bool);
2321 template void Map::Remove(Creature *,bool);
2322 template void Map::Remove(GameObject *, bool);
2323 template void Map::Remove(DynamicObject *, bool);
2325 /* ******* Dungeon Instance Maps ******* */
2327 InstanceMap::InstanceMap(uint32 id, time_t expiry, uint32 InstanceId, uint8 SpawnMode, Map* _parent)
2328 : Map(id, expiry, InstanceId, SpawnMode, _parent),
2329 m_resetAfterUnload(false), m_unloadWhenEmpty(false),
2330 i_data(NULL), i_script_id(0)
2332 //lets initialize visibility distance for dungeons
2333 InstanceMap::InitVisibilityDistance();
2335 // the timer is started by default, and stopped when the first player joins
2336 // this make sure it gets unloaded if for some reason no player joins
2337 m_unloadTimer = std::max(sWorld.getConfig(CONFIG_INSTANCE_UNLOAD_DELAY), (uint32)MIN_UNLOAD_DELAY);
2340 InstanceMap::~InstanceMap()
2342 if(i_data)
2344 delete i_data;
2345 i_data = NULL;
2349 void InstanceMap::InitVisibilityDistance()
2351 //init visibility distance for instances
2352 m_VisibleDistance = World::GetMaxVisibleDistanceInInstances();
2356 Do map specific checks to see if the player can enter
2358 bool InstanceMap::CanEnter(Player *player)
2360 if(player->GetMapRef().getTarget() == this)
2362 sLog.outError("InstanceMap::CanEnter - player %s(%u) already in map %d,%d,%d!", player->GetName(), player->GetGUIDLow(), GetId(), GetInstanceId(), GetSpawnMode());
2363 assert(false);
2364 return false;
2367 // cannot enter if the instance is full (player cap), GMs don't count
2368 uint32 maxPlayers = GetMaxPlayers();
2369 if (!player->isGameMaster() && GetPlayersCountExceptGMs() >= maxPlayers)
2371 sLog.outDetail("MAP: Instance '%u' of map '%s' cannot have more than '%u' players. Player '%s' rejected", GetInstanceId(), GetMapName(), maxPlayers, player->GetName());
2372 player->SendTransferAborted(GetId(), TRANSFER_ABORT_MAX_PLAYERS);
2373 return false;
2376 // cannot enter while players in the instance are in combat
2377 Group *pGroup = player->GetGroup();
2378 if(pGroup && pGroup->InCombatToInstance(GetInstanceId()) && player->isAlive() && player->GetMapId() != GetId())
2380 player->SendTransferAborted(GetId(), TRANSFER_ABORT_ZONE_IN_COMBAT);
2381 return false;
2384 return Map::CanEnter(player);
2388 Do map specific checks and add the player to the map if successful.
2390 bool InstanceMap::Add(Player *player)
2392 // TODO: Not sure about checking player level: already done in HandleAreaTriggerOpcode
2393 // GMs still can teleport player in instance.
2394 // Is it needed?
2397 Guard guard(*this);
2398 if(!CanEnter(player))
2399 return false;
2401 // Dungeon only code
2402 if(IsDungeon())
2404 // get or create an instance save for the map
2405 InstanceSave *mapSave = sInstanceSaveMgr.GetInstanceSave(GetInstanceId());
2406 if(!mapSave)
2408 sLog.outDetail("InstanceMap::Add: creating instance save for map %d spawnmode %d with instance id %d", GetId(), GetSpawnMode(), GetInstanceId());
2409 mapSave = sInstanceSaveMgr.AddInstanceSave(GetId(), GetInstanceId(), Difficulty(GetSpawnMode()), 0, true);
2412 // check for existing instance binds
2413 InstancePlayerBind *playerBind = player->GetBoundInstance(GetId(), Difficulty(GetSpawnMode()));
2414 if(playerBind && playerBind->perm)
2416 // cannot enter other instances if bound permanently
2417 if(playerBind->save != mapSave)
2419 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());
2420 assert(false);
2423 else
2425 Group *pGroup = player->GetGroup();
2426 if(pGroup)
2428 // solo saves should be reset when entering a group
2429 InstanceGroupBind *groupBind = pGroup->GetBoundInstance(this);
2430 if(playerBind)
2432 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());
2433 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());
2434 assert(false);
2436 // bind to the group or keep using the group save
2437 if(!groupBind)
2438 pGroup->BindToInstance(mapSave, false);
2439 else
2441 // cannot jump to a different instance without resetting it
2442 if(groupBind->save != mapSave)
2444 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());
2445 if(mapSave)
2446 sLog.outError("MapSave players: %d, group count: %d", mapSave->GetPlayerCount(), mapSave->GetGroupCount());
2447 else
2448 sLog.outError("MapSave NULL");
2449 if(groupBind->save)
2450 sLog.outError("GroupBind save players: %d, group count: %d", groupBind->save->GetPlayerCount(), groupBind->save->GetGroupCount());
2451 else
2452 sLog.outError("GroupBind save NULL");
2453 assert(false);
2455 // if the group/leader is permanently bound to the instance
2456 // players also become permanently bound when they enter
2457 if(groupBind->perm)
2459 WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
2460 data << uint32(0);
2461 player->GetSession()->SendPacket(&data);
2462 player->BindToInstance(mapSave, true);
2466 else
2468 // set up a solo bind or continue using it
2469 if(!playerBind)
2470 player->BindToInstance(mapSave, false);
2471 else
2472 // cannot jump to a different instance without resetting it
2473 assert(playerBind->save == mapSave);
2478 if(i_data) i_data->OnPlayerEnter(player);
2479 // for normal instances cancel the reset schedule when the
2480 // first player enters (no players yet)
2481 SetResetSchedule(false);
2483 sLog.outDetail("MAP: Player '%s' entered the instance '%u' of map '%s'", player->GetName(), GetInstanceId(), GetMapName());
2484 // initialize unload state
2485 m_unloadTimer = 0;
2486 m_resetAfterUnload = false;
2487 m_unloadWhenEmpty = false;
2490 // this will acquire the same mutex so it cannot be in the previous block
2491 Map::Add(player);
2492 return true;
2495 void InstanceMap::Update(const uint32& t_diff)
2497 Map::Update(t_diff);
2499 if(i_data)
2500 i_data->Update(t_diff);
2503 void InstanceMap::Remove(Player *player, bool remove)
2505 sLog.outDetail("MAP: Removing player '%s' from instance '%u' of map '%s' before relocating to other map", player->GetName(), GetInstanceId(), GetMapName());
2506 //if last player set unload timer
2507 if(!m_unloadTimer && m_mapRefManager.getSize() == 1)
2508 m_unloadTimer = m_unloadWhenEmpty ? MIN_UNLOAD_DELAY : std::max(sWorld.getConfig(CONFIG_INSTANCE_UNLOAD_DELAY), (uint32)MIN_UNLOAD_DELAY);
2509 Map::Remove(player, remove);
2510 // for normal instances schedule the reset after all players have left
2511 SetResetSchedule(true);
2514 void InstanceMap::CreateInstanceData(bool load)
2516 if(i_data != NULL)
2517 return;
2519 InstanceTemplate const* mInstance = ObjectMgr::GetInstanceTemplate(GetId());
2520 if (mInstance)
2522 i_script_id = mInstance->script_id;
2523 i_data = Script->CreateInstanceData(this);
2526 if(!i_data)
2527 return;
2529 if(load)
2531 // TODO: make a global storage for this
2532 QueryResult* result = CharacterDatabase.PQuery("SELECT data FROM instance WHERE map = '%u' AND id = '%u'", GetId(), i_InstanceId);
2533 if (result)
2535 Field* fields = result->Fetch();
2536 const char* data = fields[0].GetString();
2537 if(data)
2539 sLog.outDebug("Loading instance data for `%s` with id %u", sObjectMgr.GetScriptName(i_script_id), i_InstanceId);
2540 i_data->Load(data);
2542 delete result;
2545 else
2547 sLog.outDebug("New instance data, \"%s\" ,initialized!", sObjectMgr.GetScriptName(i_script_id));
2548 i_data->Initialize();
2553 Returns true if there are no players in the instance
2555 bool InstanceMap::Reset(uint8 method)
2557 // note: since the map may not be loaded when the instance needs to be reset
2558 // the instance must be deleted from the DB by InstanceSaveManager
2560 if(HavePlayers())
2562 if(method == INSTANCE_RESET_ALL)
2564 // notify the players to leave the instance so it can be reset
2565 for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
2566 itr->getSource()->SendResetFailedNotify(GetId());
2568 else
2570 if(method == INSTANCE_RESET_GLOBAL)
2572 // set the homebind timer for players inside (1 minute)
2573 for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
2574 itr->getSource()->m_InstanceValid = false;
2577 // the unload timer is not started
2578 // instead the map will unload immediately after the players have left
2579 m_unloadWhenEmpty = true;
2580 m_resetAfterUnload = true;
2583 else
2585 // unloaded at next update
2586 m_unloadTimer = MIN_UNLOAD_DELAY;
2587 m_resetAfterUnload = true;
2590 return m_mapRefManager.isEmpty();
2593 void InstanceMap::PermBindAllPlayers(Player *player)
2595 if(!IsDungeon())
2596 return;
2598 InstanceSave *save = sInstanceSaveMgr.GetInstanceSave(GetInstanceId());
2599 if(!save)
2601 sLog.outError("Cannot bind players, no instance save available for map!");
2602 return;
2605 Group *group = player->GetGroup();
2606 // group members outside the instance group don't get bound
2607 for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
2609 Player* plr = itr->getSource();
2610 // players inside an instance cannot be bound to other instances
2611 // some players may already be permanently bound, in this case nothing happens
2612 InstancePlayerBind *bind = plr->GetBoundInstance(save->GetMapId(), save->GetDifficulty());
2613 if(!bind || !bind->perm)
2615 plr->BindToInstance(save, true);
2616 WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
2617 data << uint32(0);
2618 plr->GetSession()->SendPacket(&data);
2621 // if the leader is not in the instance the group will not get a perm bind
2622 if(group && group->GetLeaderGUID() == plr->GetGUID())
2623 group->BindToInstance(save, true);
2627 void InstanceMap::UnloadAll(bool pForce)
2629 if(HavePlayers())
2631 sLog.outError("InstanceMap::UnloadAll: there are still players in the instance at unload, should not happen!");
2632 for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
2634 Player* plr = itr->getSource();
2635 plr->TeleportToHomebind();
2639 if(m_resetAfterUnload == true)
2640 sObjectMgr.DeleteRespawnTimeForInstance(GetInstanceId());
2642 Map::UnloadAll(pForce);
2645 void InstanceMap::SendResetWarnings(uint32 timeLeft) const
2647 for(MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
2648 itr->getSource()->SendInstanceResetWarning(GetId(), itr->getSource()->GetDifficulty(IsRaid()), timeLeft);
2651 void InstanceMap::SetResetSchedule(bool on)
2653 // only for normal instances
2654 // the reset time is only scheduled when there are no payers inside
2655 // it is assumed that the reset time will rarely (if ever) change while the reset is scheduled
2656 if(IsDungeon() && !HavePlayers() && !IsRaidOrHeroicDungeon())
2658 InstanceSave *save = sInstanceSaveMgr.GetInstanceSave(GetInstanceId());
2659 if(!save) sLog.outError("InstanceMap::SetResetSchedule: cannot turn schedule %s, no save available for instance %d of %d", on ? "on" : "off", GetInstanceId(), GetId());
2660 else sInstanceSaveMgr.ScheduleReset(on, save->GetResetTime(), InstanceSaveManager::InstResetEvent(0, GetId(), Difficulty(GetSpawnMode()), GetInstanceId()));
2664 /* ******* Battleground Instance Maps ******* */
2666 BattleGroundMap::BattleGroundMap(uint32 id, time_t expiry, uint32 InstanceId, Map* _parent, uint8 spawnMode)
2667 : Map(id, expiry, InstanceId, spawnMode, _parent)
2669 //lets initialize visibility distance for BG/Arenas
2670 BattleGroundMap::InitVisibilityDistance();
2673 BattleGroundMap::~BattleGroundMap()
2677 void BattleGroundMap::InitVisibilityDistance()
2679 //init visibility distance for BG/Arenas
2680 m_VisibleDistance = World::GetMaxVisibleDistanceInBGArenas();
2683 bool BattleGroundMap::CanEnter(Player * player)
2685 if(player->GetMapRef().getTarget() == this)
2687 sLog.outError("BGMap::CanEnter - player %u already in map!", player->GetGUIDLow());
2688 assert(false);
2689 return false;
2692 if(player->GetBattleGroundId() != GetInstanceId())
2693 return false;
2695 // player number limit is checked in bgmgr, no need to do it here
2697 return Map::CanEnter(player);
2700 bool BattleGroundMap::Add(Player * player)
2703 Guard guard(*this);
2704 if(!CanEnter(player))
2705 return false;
2706 // reset instance validity, battleground maps do not homebind
2707 player->m_InstanceValid = true;
2709 return Map::Add(player);
2712 void BattleGroundMap::Remove(Player *player, bool remove)
2714 sLog.outDetail("MAP: Removing player '%s' from bg '%u' of map '%s' before relocating to other map", player->GetName(), GetInstanceId(), GetMapName());
2715 Map::Remove(player, remove);
2718 void BattleGroundMap::SetUnload()
2720 m_unloadTimer = MIN_UNLOAD_DELAY;
2723 void BattleGroundMap::UnloadAll(bool pForce)
2725 while(HavePlayers())
2727 if(Player * plr = m_mapRefManager.getFirst()->getSource())
2729 plr->TeleportTo(plr->GetBattleGroundEntryPoint());
2730 // TeleportTo removes the player from this map (if the map exists) -> calls BattleGroundMap::Remove -> invalidates the iterator.
2731 // just in case, remove the player from the list explicitly here as well to prevent a possible infinite loop
2732 // note that this remove is not needed if the code works well in other places
2733 plr->GetMapRef().unlink();
2737 Map::UnloadAll(pForce);
2740 /// Put scripts in the execution queue
2741 void Map::ScriptsStart(ScriptMapMap const& scripts, uint32 id, Object* source, Object* target)
2743 ///- Find the script map
2744 ScriptMapMap::const_iterator s = scripts.find(id);
2745 if (s == scripts.end())
2746 return;
2748 // prepare static data
2749 uint64 sourceGUID = source->GetGUID();
2750 uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
2751 uint64 ownerGUID = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
2753 ///- Schedule script execution for all scripts in the script map
2754 ScriptMap const *s2 = &(s->second);
2755 bool immedScript = false;
2756 for (ScriptMap::const_iterator iter = s2->begin(); iter != s2->end(); ++iter)
2758 ScriptAction sa;
2759 sa.sourceGUID = sourceGUID;
2760 sa.targetGUID = targetGUID;
2761 sa.ownerGUID = ownerGUID;
2763 sa.script = &iter->second;
2764 m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(time_t(sWorld.GetGameTime() + iter->first), sa));
2765 if (iter->first == 0)
2766 immedScript = true;
2768 sWorld.IncreaseScheduledScriptsCount();
2770 ///- If one of the effects should be immediate, launch the script execution
2771 if (immedScript)
2772 ScriptsProcess();
2775 void Map::ScriptCommandStart(ScriptInfo const& script, uint32 delay, Object* source, Object* target)
2777 // NOTE: script record _must_ exist until command executed
2779 // prepare static data
2780 uint64 sourceGUID = source->GetGUID();
2781 uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
2782 uint64 ownerGUID = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
2784 ScriptAction sa;
2785 sa.sourceGUID = sourceGUID;
2786 sa.targetGUID = targetGUID;
2787 sa.ownerGUID = ownerGUID;
2789 sa.script = &script;
2790 m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(time_t(sWorld.GetGameTime() + delay), sa));
2792 sWorld.IncreaseScheduledScriptsCount();
2794 ///- If effects should be immediate, launch the script execution
2795 if(delay == 0)
2796 ScriptsProcess();
2799 /// Process queued scripts
2800 void Map::ScriptsProcess()
2802 if (m_scriptSchedule.empty())
2803 return;
2805 ///- Process overdue queued scripts
2806 std::multimap<time_t, ScriptAction>::iterator iter = m_scriptSchedule.begin();
2807 // ok as multimap is a *sorted* associative container
2808 while (!m_scriptSchedule.empty() && (iter->first <= sWorld.GetGameTime()))
2810 ScriptAction const& step = iter->second;
2812 Object* source = NULL;
2814 if(step.sourceGUID)
2816 switch(GUID_HIPART(step.sourceGUID))
2818 case HIGHGUID_ITEM:
2819 // case HIGHGUID_CONTAINER: ==HIGHGUID_ITEM
2821 Player* player = HashMapHolder<Player>::Find(step.ownerGUID);
2822 if(player)
2823 source = player->GetItemByGuid(step.sourceGUID);
2824 break;
2826 case HIGHGUID_UNIT:
2827 source = GetCreature(step.sourceGUID);
2828 break;
2829 case HIGHGUID_PET:
2830 source = GetPet(step.sourceGUID);
2831 break;
2832 case HIGHGUID_VEHICLE:
2833 source = GetVehicle(step.sourceGUID);
2834 break;
2835 case HIGHGUID_PLAYER:
2836 source = HashMapHolder<Player>::Find(step.sourceGUID);
2837 break;
2838 case HIGHGUID_GAMEOBJECT:
2839 source = GetGameObject(step.sourceGUID);
2840 break;
2841 case HIGHGUID_CORPSE:
2842 source = HashMapHolder<Corpse>::Find(step.sourceGUID);
2843 break;
2844 default:
2845 sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.sourceGUID));
2846 break;
2850 if(source && !source->IsInWorld()) source = NULL;
2852 Object* target = NULL;
2854 if(step.targetGUID)
2856 switch(GUID_HIPART(step.targetGUID))
2858 case HIGHGUID_UNIT:
2859 target = GetCreature(step.targetGUID);
2860 break;
2861 case HIGHGUID_PET:
2862 target = GetPet(step.targetGUID);
2863 break;
2864 case HIGHGUID_VEHICLE:
2865 target = GetVehicle(step.targetGUID);
2866 break;
2867 case HIGHGUID_PLAYER: // empty GUID case also
2868 target = HashMapHolder<Player>::Find(step.targetGUID);
2869 break;
2870 case HIGHGUID_GAMEOBJECT:
2871 target = GetGameObject(step.targetGUID);
2872 break;
2873 case HIGHGUID_CORPSE:
2874 target = HashMapHolder<Corpse>::Find(step.targetGUID);
2875 break;
2876 default:
2877 sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.targetGUID));
2878 break;
2882 if(target && !target->IsInWorld()) target = NULL;
2884 switch (step.script->command)
2886 case SCRIPT_COMMAND_TALK:
2888 if(!source)
2890 sLog.outError("SCRIPT_COMMAND_TALK call for NULL creature.");
2891 break;
2894 if(source->GetTypeId()!=TYPEID_UNIT)
2896 sLog.outError("SCRIPT_COMMAND_TALK call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
2897 break;
2900 uint64 unit_target = target ? target->GetGUID() : 0;
2902 //datalong 0=normal say, 1=whisper, 2=yell, 3=emote text
2903 switch(step.script->datalong)
2905 case 0: // Say
2906 ((Creature *)source)->Say(step.script->dataint, LANG_UNIVERSAL, unit_target);
2907 break;
2908 case 1: // Whisper
2909 if(!unit_target)
2911 sLog.outError("SCRIPT_COMMAND_TALK attempt to whisper (%u) NULL, skipping.",step.script->datalong);
2912 break;
2914 ((Creature *)source)->Whisper(step.script->dataint,unit_target);
2915 break;
2916 case 2: // Yell
2917 ((Creature *)source)->Yell(step.script->dataint, LANG_UNIVERSAL, unit_target);
2918 break;
2919 case 3: // Emote text
2920 ((Creature *)source)->TextEmote(step.script->dataint, unit_target);
2921 break;
2922 default:
2923 break; // must be already checked at load
2925 break;
2928 case SCRIPT_COMMAND_EMOTE:
2929 if(!source)
2931 sLog.outError("SCRIPT_COMMAND_EMOTE call for NULL creature.");
2932 break;
2935 if(source->GetTypeId()!=TYPEID_UNIT)
2937 sLog.outError("SCRIPT_COMMAND_EMOTE call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
2938 break;
2941 ((Creature *)source)->HandleEmoteCommand(step.script->datalong);
2942 break;
2943 case SCRIPT_COMMAND_FIELD_SET:
2944 if(!source)
2946 sLog.outError("SCRIPT_COMMAND_FIELD_SET call for NULL object.");
2947 break;
2949 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
2951 sLog.outError("SCRIPT_COMMAND_FIELD_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
2952 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
2953 break;
2956 source->SetUInt32Value(step.script->datalong, step.script->datalong2);
2957 break;
2958 case SCRIPT_COMMAND_MOVE_TO:
2959 if(!source)
2961 sLog.outError("SCRIPT_COMMAND_MOVE_TO call for NULL creature.");
2962 break;
2965 if(source->GetTypeId()!=TYPEID_UNIT)
2967 sLog.outError("SCRIPT_COMMAND_MOVE_TO call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
2968 break;
2970 ((Creature*)source)->SendMonsterMoveWithSpeed(step.script->x, step.script->y, step.script->z, step.script->datalong2 );
2971 ((Creature*)source)->GetMap()->CreatureRelocation(((Creature*)source), step.script->x, step.script->y, step.script->z, 0);
2972 break;
2973 case SCRIPT_COMMAND_FLAG_SET:
2974 if(!source)
2976 sLog.outError("SCRIPT_COMMAND_FLAG_SET call for NULL object.");
2977 break;
2979 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
2981 sLog.outError("SCRIPT_COMMAND_FLAG_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
2982 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
2983 break;
2986 source->SetFlag(step.script->datalong, step.script->datalong2);
2987 break;
2988 case SCRIPT_COMMAND_FLAG_REMOVE:
2989 if(!source)
2991 sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for NULL object.");
2992 break;
2994 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
2996 sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for wrong field %u (max count: %u) in object (TypeId: %u).",
2997 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
2998 break;
3001 source->RemoveFlag(step.script->datalong, step.script->datalong2);
3002 break;
3004 case SCRIPT_COMMAND_TELEPORT_TO:
3006 // accept player in any one from target/source arg
3007 if (!target && !source)
3009 sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for NULL object.");
3010 break;
3013 // must be only Player
3014 if((!target || target->GetTypeId() != TYPEID_PLAYER) && (!source || source->GetTypeId() != TYPEID_PLAYER))
3016 sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for non-player (TypeIdSource: %u)(TypeIdTarget: %u), skipping.", source ? source->GetTypeId() : 0, target ? target->GetTypeId() : 0);
3017 break;
3020 Player* pSource = target && target->GetTypeId() == TYPEID_PLAYER ? (Player*)target : (Player*)source;
3022 pSource->TeleportTo(step.script->datalong, step.script->x, step.script->y, step.script->z, step.script->o);
3023 break;
3026 case SCRIPT_COMMAND_KILL_CREDIT:
3028 // accept player in any one from target/source arg
3029 if (!target && !source)
3031 sLog.outError("SCRIPT_COMMAND_KILL_CREDIT call for NULL object.");
3032 break;
3035 // must be only Player
3036 if((!target || target->GetTypeId() != TYPEID_PLAYER) && (!source || source->GetTypeId() != TYPEID_PLAYER))
3038 sLog.outError("SCRIPT_COMMAND_KILL_CREDIT call for non-player (TypeIdSource: %u)(TypeIdTarget: %u), skipping.", source ? source->GetTypeId() : 0, target ? target->GetTypeId() : 0);
3039 break;
3042 Player* pSource = target && target->GetTypeId() == TYPEID_PLAYER ? (Player*)target : (Player*)source;
3044 if (step.script->datalong2)
3046 pSource->RewardPlayerAndGroupAtEvent(step.script->datalong, pSource);
3048 else
3050 pSource->KilledMonsterCredit(step.script->datalong, 0);
3053 break;
3056 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
3058 if(!step.script->datalong) // creature not specified
3060 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL creature.");
3061 break;
3064 if(!source)
3066 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL world object.");
3067 break;
3070 WorldObject* summoner = dynamic_cast<WorldObject*>(source);
3072 if(!summoner)
3074 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
3075 break;
3078 float x = step.script->x;
3079 float y = step.script->y;
3080 float z = step.script->z;
3081 float o = step.script->o;
3083 Creature* pCreature = summoner->SummonCreature(step.script->datalong, x, y, z, o,TEMPSUMMON_TIMED_OR_DEAD_DESPAWN,step.script->datalong2);
3084 if (!pCreature)
3086 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON failed for creature (entry: %u).",step.script->datalong);
3087 break;
3090 break;
3093 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
3095 if(!step.script->datalong) // gameobject not specified
3097 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL gameobject.");
3098 break;
3101 if(!source)
3103 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL world object.");
3104 break;
3107 WorldObject* summoner = dynamic_cast<WorldObject*>(source);
3109 if(!summoner)
3111 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
3112 break;
3115 GameObject *go = NULL;
3116 int32 time_to_despawn = step.script->datalong2<5 ? 5 : (int32)step.script->datalong2;
3118 CellPair p(MaNGOS::ComputeCellPair(summoner->GetPositionX(), summoner->GetPositionY()));
3119 Cell cell(p);
3120 cell.data.Part.reserved = ALL_DISTRICT;
3122 MaNGOS::GameObjectWithDbGUIDCheck go_check(*summoner,step.script->datalong);
3123 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(summoner, go,go_check);
3125 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
3126 CellLock<GridReadGuard> cell_lock(cell, p);
3127 cell_lock->Visit(cell_lock, object_checker, *summoner->GetMap());
3129 if ( !go )
3131 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT failed for gameobject(guid: %u).", step.script->datalong);
3132 break;
3135 if( go->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE ||
3136 go->GetGoType()==GAMEOBJECT_TYPE_DOOR ||
3137 go->GetGoType()==GAMEOBJECT_TYPE_BUTTON ||
3138 go->GetGoType()==GAMEOBJECT_TYPE_TRAP )
3140 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT can not be used with gameobject of type %u (guid: %u).", uint32(go->GetGoType()), step.script->datalong);
3141 break;
3144 if( go->isSpawned() )
3145 break; //gameobject already spawned
3147 go->SetLootState(GO_READY);
3148 go->SetRespawnTime(time_to_despawn); //despawn object in ? seconds
3150 go->GetMap()->Add(go);
3151 break;
3153 case SCRIPT_COMMAND_OPEN_DOOR:
3155 if(!step.script->datalong) // door not specified
3157 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL door.");
3158 break;
3161 if(!source)
3163 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL unit.");
3164 break;
3167 if(!source->isType(TYPEMASK_UNIT)) // must be any Unit (creature or player)
3169 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
3170 break;
3173 Unit* caster = (Unit*)source;
3175 GameObject *door = NULL;
3176 int32 time_to_close = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
3178 CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
3179 Cell cell(p);
3180 cell.data.Part.reserved = ALL_DISTRICT;
3182 MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
3183 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(caster,door,go_check);
3185 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
3186 CellLock<GridReadGuard> cell_lock(cell, p);
3187 cell_lock->Visit(cell_lock, object_checker, *caster->GetMap());
3189 if (!door)
3191 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for gameobject(guid: %u).", step.script->datalong);
3192 break;
3194 if (door->GetGoType() != GAMEOBJECT_TYPE_DOOR)
3196 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for non-door(GoType: %u).", door->GetGoType());
3197 break;
3200 if (door->GetGoState() != GO_STATE_READY)
3201 break; //door already open
3203 door->UseDoorOrButton(time_to_close);
3205 if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
3206 ((GameObject*)target)->UseDoorOrButton(time_to_close);
3207 break;
3209 case SCRIPT_COMMAND_CLOSE_DOOR:
3211 if(!step.script->datalong) // guid for door not specified
3213 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL door.");
3214 break;
3217 if(!source)
3219 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL unit.");
3220 break;
3223 if(!source->isType(TYPEMASK_UNIT)) // must be any Unit (creature or player)
3225 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
3226 break;
3229 Unit* caster = (Unit*)source;
3231 GameObject *door = NULL;
3232 int32 time_to_open = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
3234 CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
3235 Cell cell(p);
3236 cell.data.Part.reserved = ALL_DISTRICT;
3238 MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
3239 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(caster,door,go_check);
3241 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
3242 CellLock<GridReadGuard> cell_lock(cell, p);
3243 cell_lock->Visit(cell_lock, object_checker, *caster->GetMap());
3245 if ( !door )
3247 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for gameobject(guid: %u).", step.script->datalong);
3248 break;
3250 if ( door->GetGoType() != GAMEOBJECT_TYPE_DOOR )
3252 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for non-door(GoType: %u).", door->GetGoType());
3253 break;
3256 if( door->GetGoState() == GO_STATE_READY )
3257 break; //door already closed
3259 door->UseDoorOrButton(time_to_open);
3261 if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
3262 ((GameObject*)target)->UseDoorOrButton(time_to_open);
3264 break;
3266 case SCRIPT_COMMAND_QUEST_EXPLORED:
3268 if(!source)
3270 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL source.");
3271 break;
3274 if(!target)
3276 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL target.");
3277 break;
3280 // when script called for item spell casting then target == (unit or GO) and source is player
3281 WorldObject* worldObject;
3282 Player* player;
3284 if(target->GetTypeId()==TYPEID_PLAYER)
3286 if(source->GetTypeId()!=TYPEID_UNIT && source->GetTypeId()!=TYPEID_GAMEOBJECT)
3288 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",source->GetTypeId());
3289 break;
3292 worldObject = (WorldObject*)source;
3293 player = (Player*)target;
3295 else
3297 if(target->GetTypeId()!=TYPEID_UNIT && target->GetTypeId()!=TYPEID_GAMEOBJECT)
3299 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
3300 break;
3303 if(source->GetTypeId()!=TYPEID_PLAYER)
3305 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-player(TypeId: %u), skipping.",source->GetTypeId());
3306 break;
3309 worldObject = (WorldObject*)target;
3310 player = (Player*)source;
3313 // quest id and flags checked at script loading
3314 if( (worldObject->GetTypeId()!=TYPEID_UNIT || ((Unit*)worldObject)->isAlive()) &&
3315 (step.script->datalong2==0 || worldObject->IsWithinDistInMap(player,float(step.script->datalong2))) )
3316 player->AreaExploredOrEventHappens(step.script->datalong);
3317 else
3318 player->FailQuest(step.script->datalong);
3320 break;
3323 case SCRIPT_COMMAND_ACTIVATE_OBJECT:
3325 if(!source)
3327 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT must have source caster.");
3328 break;
3331 if(!source->isType(TYPEMASK_UNIT))
3333 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
3334 break;
3337 if(!target)
3339 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for NULL gameobject.");
3340 break;
3343 if(target->GetTypeId()!=TYPEID_GAMEOBJECT)
3345 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
3346 break;
3349 Unit* caster = (Unit*)source;
3351 GameObject *go = (GameObject*)target;
3353 go->Use(caster);
3354 break;
3357 case SCRIPT_COMMAND_REMOVE_AURA:
3359 Object* cmdTarget = step.script->datalong2 ? source : target;
3361 if(!cmdTarget)
3363 sLog.outError("SCRIPT_COMMAND_REMOVE_AURA call for NULL %s.",step.script->datalong2 ? "source" : "target");
3364 break;
3367 if(!cmdTarget->isType(TYPEMASK_UNIT))
3369 sLog.outError("SCRIPT_COMMAND_REMOVE_AURA %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 ? "source" : "target",cmdTarget->GetTypeId());
3370 break;
3373 ((Unit*)cmdTarget)->RemoveAurasDueToSpell(step.script->datalong);
3374 break;
3377 case SCRIPT_COMMAND_CAST_SPELL:
3379 if(!source)
3381 sLog.outError("SCRIPT_COMMAND_CAST_SPELL must have source caster.");
3382 break;
3385 Object* cmdTarget = step.script->datalong2 & 0x01 ? source : target;
3387 if(!cmdTarget)
3389 sLog.outError("SCRIPT_COMMAND_CAST_SPELL call for NULL %s.",step.script->datalong2 & 0x01 ? "source" : "target");
3390 break;
3393 if(!cmdTarget->isType(TYPEMASK_UNIT))
3395 sLog.outError("SCRIPT_COMMAND_CAST_SPELL %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 & 0x01 ? "source" : "target",cmdTarget->GetTypeId());
3396 break;
3399 Unit* spellTarget = (Unit*)cmdTarget;
3401 Object* cmdSource = step.script->datalong2 & 0x02 ? target : source;
3403 if(!cmdSource)
3405 sLog.outError("SCRIPT_COMMAND_CAST_SPELL call for NULL %s.",step.script->datalong2 & 0x02 ? "target" : "source");
3406 break;
3409 if(!cmdSource->isType(TYPEMASK_UNIT))
3411 sLog.outError("SCRIPT_COMMAND_CAST_SPELL %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 & 0x02 ? "target" : "source", cmdSource->GetTypeId());
3412 break;
3415 Unit* spellSource = (Unit*)cmdSource;
3417 //TODO: when GO cast implemented, code below must be updated accordingly to also allow GO spell cast
3418 spellSource->CastSpell(spellTarget,step.script->datalong,false);
3420 break;
3423 case SCRIPT_COMMAND_PLAY_SOUND:
3425 if(!source)
3427 sLog.outError("SCRIPT_COMMAND_PLAY_SOUND call for NULL creature.");
3428 break;
3431 WorldObject* pSource = dynamic_cast<WorldObject*>(source);
3432 if(!pSource)
3434 sLog.outError("SCRIPT_COMMAND_PLAY_SOUND call for non-world object (TypeId: %u), skipping.",source->GetTypeId());
3435 break;
3438 // bitmask: 0/1=anyone/target, 0/2=with distance dependent
3439 Player* pTarget = NULL;
3440 if(step.script->datalong2 & 1)
3442 if(!target)
3444 sLog.outError("SCRIPT_COMMAND_PLAY_SOUND in targeted mode call for NULL target.");
3445 break;
3448 if(target->GetTypeId()!=TYPEID_PLAYER)
3450 sLog.outError("SCRIPT_COMMAND_PLAY_SOUND in targeted mode call for non-player (TypeId: %u), skipping.",target->GetTypeId());
3451 break;
3454 pTarget = (Player*)target;
3457 // bitmask: 0/1=anyone/target, 0/2=with distance dependent
3458 if(step.script->datalong2 & 2)
3459 pSource->PlayDistanceSound(step.script->datalong,pTarget);
3460 else
3461 pSource->PlayDirectSound(step.script->datalong,pTarget);
3462 break;
3464 default:
3465 sLog.outError("Unknown script command %u called.",step.script->command);
3466 break;
3469 m_scriptSchedule.erase(iter);
3470 sWorld.DecreaseScheduledScriptCount();
3472 iter = m_scriptSchedule.begin();
3474 return;
3477 Creature* Map::GetCreature(uint64 guid)
3479 return m_objectsStore.find<Creature>(guid, (Creature*)NULL);
3482 Vehicle* Map::GetVehicle(uint64 guid)
3484 return m_objectsStore.find<Vehicle>(guid, (Vehicle*)NULL);
3487 Pet* Map::GetPet(uint64 guid)
3489 return m_objectsStore.find<Pet>(guid, (Pet*)NULL);
3492 Corpse* Map::GetCorpse(uint64 guid)
3494 Corpse * ret = ObjectAccessor::GetCorpseInMap(guid,GetId());
3495 if (!ret)
3496 return NULL;
3497 if (ret->GetInstanceId() != GetInstanceId())
3498 return NULL;
3499 return ret;
3502 Creature* Map::GetCreatureOrPetOrVehicle(uint64 guid)
3504 if (IS_PLAYER_GUID(guid))
3505 return NULL;
3507 if (IS_PET_GUID(guid))
3508 return GetPet(guid);
3510 if (IS_VEHICLE_GUID(guid))
3511 return GetVehicle(guid);
3513 return GetCreature(guid);
3516 GameObject* Map::GetGameObject(uint64 guid)
3518 return m_objectsStore.find<GameObject>(guid, (GameObject*)NULL);
3521 DynamicObject* Map::GetDynamicObject(uint64 guid)
3523 return m_objectsStore.find<DynamicObject>(guid, (DynamicObject*)NULL);
3526 WorldObject* Map::GetWorldObject(uint64 guid)
3528 switch(GUID_HIPART(guid))
3530 case HIGHGUID_PLAYER: return ObjectAccessor::FindPlayer(guid);
3531 case HIGHGUID_GAMEOBJECT: return GetGameObject(guid);
3532 case HIGHGUID_UNIT: return GetCreature(guid);
3533 case HIGHGUID_PET: return GetPet(guid);
3534 case HIGHGUID_VEHICLE: return GetVehicle(guid);
3535 case HIGHGUID_DYNAMICOBJECT:return GetDynamicObject(guid);
3536 case HIGHGUID_CORPSE: return GetCorpse(guid);
3537 case HIGHGUID_MO_TRANSPORT:
3538 case HIGHGUID_TRANSPORT:
3539 default: break;
3542 return NULL;
3545 void Map::SendObjectUpdates()
3547 UpdateDataMapType update_players;
3549 while(!i_objectsToClientUpdate.empty())
3551 Object* obj = *i_objectsToClientUpdate.begin();
3552 i_objectsToClientUpdate.erase(i_objectsToClientUpdate.begin());
3553 obj->BuildUpdateData(update_players);
3556 WorldPacket packet; // here we allocate a std::vector with a size of 0x10000
3557 for(UpdateDataMapType::iterator iter = update_players.begin(); iter != update_players.end(); ++iter)
3559 iter->second.BuildPacket(&packet);
3560 iter->first->GetSession()->SendPacket(&packet);
3561 packet.clear(); // clean the string
3565 uint32 Map::GenerateLocalLowGuid(HighGuid guidhigh)
3567 // TODO: for map local guid counters possible force reload map instead shutdown server at guid counter overflow
3568 switch(guidhigh)
3570 case HIGHGUID_DYNAMICOBJECT:
3571 if (m_hiDynObjectGuid >= 0xFFFFFFFE)
3573 sLog.outError("DynamicObject guid overflow!! Can't continue, shutting down server. ");
3574 World::StopNow(ERROR_EXIT_CODE);
3576 return m_hiDynObjectGuid++;
3577 case HIGHGUID_PET:
3578 if(m_hiPetGuid>=0x00FFFFFE)
3580 sLog.outError("Pet guid overflow!! Can't continue, shutting down server. ");
3581 World::StopNow(ERROR_EXIT_CODE);
3583 return m_hiPetGuid++;
3584 case HIGHGUID_VEHICLE:
3585 if(m_hiVehicleGuid>=0x00FFFFFF)
3587 sLog.outError("Vehicle guid overflow!! Can't continue, shutting down server. ");
3588 World::StopNow(ERROR_EXIT_CODE);
3590 return m_hiVehicleGuid++;
3591 default:
3592 ASSERT(0);
3595 ASSERT(0);
3596 return 0;