[9411] More SpellEffectIndex using in apropriate cases
[getmangos.git] / src / game / Map.cpp
blob3e077c75c4fc4979e50bda3297eeeee77c210e12
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 GridState* si_GridStates[MAX_GRID_STATE];
45 static char const* MAP_MAGIC = "MAPS";
46 static char const* MAP_VERSION_MAGIC = "v1.1";
47 static char const* MAP_AREA_MAGIC = "AREA";
48 static char const* MAP_HEIGHT_MAGIC = "MHGT";
49 static char const* MAP_LIQUID_MAGIC = "MLIQ";
51 struct ScriptAction
53 uint64 sourceGUID;
54 uint64 targetGUID;
55 uint64 ownerGUID; // owner of source if source is item
56 ScriptInfo const* script; // pointer to static script data
59 Map::~Map()
61 ObjectAccessor::DelinkMap(this);
62 UnloadAll(true);
64 if(!m_scriptSchedule.empty())
65 sWorld.DecreaseScheduledScriptCount(m_scriptSchedule.size());
68 bool Map::ExistMap(uint32 mapid,int gx,int gy)
70 int len = sWorld.GetDataPath().length()+strlen("maps/%03u%02u%02u.map")+1;
71 char* tmp = new char[len];
72 snprintf(tmp, len, (char *)(sWorld.GetDataPath()+"maps/%03u%02u%02u.map").c_str(),mapid,gx,gy);
74 FILE *pf=fopen(tmp,"rb");
76 if(!pf)
78 sLog.outError("Check existing of map file '%s': not exist!",tmp);
79 delete[] tmp;
80 return false;
83 map_fileheader header;
84 fread(&header, sizeof(header), 1, pf);
85 if (header.mapMagic != *((uint32 const*)(MAP_MAGIC)) ||
86 header.versionMagic != *((uint32 const*)(MAP_VERSION_MAGIC)) ||
87 !IsAcceptableClientBuild(header.buildMagic))
89 sLog.outError("Map file '%s' is non-compatible version (outdated?). Please, create new using ad.exe program.",tmp);
90 delete [] tmp;
91 fclose(pf); //close file before return
92 return false;
95 delete [] tmp;
96 fclose(pf);
97 return true;
100 bool Map::ExistVMap(uint32 mapid,int gx,int gy)
102 if(VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager())
104 if(vmgr->isMapLoadingEnabled())
106 // x and y are swapped !! => fixed now
107 bool exists = vmgr->existsMap((sWorld.GetDataPath()+ "vmaps").c_str(), mapid, gx,gy);
108 if(!exists)
110 std::string name = vmgr->getDirFileName(mapid,gx,gy);
111 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());
112 return false;
117 return true;
120 void Map::LoadVMap(int gx,int gy)
122 // x and y are swapped !!
123 int vmapLoadResult = VMAP::VMapFactory::createOrGetVMapManager()->loadMap((sWorld.GetDataPath()+ "vmaps").c_str(), GetId(), gx,gy);
124 switch(vmapLoadResult)
126 case VMAP::VMAP_LOAD_RESULT_OK:
127 sLog.outDetail("VMAP loaded name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", GetMapName(), GetId(), gx,gy,gx,gy);
128 break;
129 case VMAP::VMAP_LOAD_RESULT_ERROR:
130 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);
131 break;
132 case VMAP::VMAP_LOAD_RESULT_IGNORED:
133 DEBUG_LOG("Ignored VMAP name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", GetMapName(), GetId(), gx,gy,gx,gy);
134 break;
138 void Map::LoadMap(int gx,int gy, bool reload)
140 if( i_InstanceId != 0 )
142 if(GridMaps[gx][gy])
143 return;
145 // load grid map for base map
146 if (!m_parentMap->GridMaps[gx][gy])
147 m_parentMap->EnsureGridCreated(GridPair(63-gx,63-gy));
149 ((MapInstanced*)(m_parentMap))->AddGridMapReference(GridPair(gx,gy));
150 GridMaps[gx][gy] = m_parentMap->GridMaps[gx][gy];
151 return;
154 if(GridMaps[gx][gy] && !reload)
155 return;
157 //map already load, delete it before reloading (Is it necessary? Do we really need the ability the reload maps during runtime?)
158 if(GridMaps[gx][gy])
160 sLog.outDetail("Unloading already loaded map %u before reloading.",i_id);
161 delete (GridMaps[gx][gy]);
162 GridMaps[gx][gy]=NULL;
165 // map file name
166 char *tmp=NULL;
167 int len = sWorld.GetDataPath().length()+strlen("maps/%03u%02u%02u.map")+1;
168 tmp = new char[len];
169 snprintf(tmp, len, (char *)(sWorld.GetDataPath()+"maps/%03u%02u%02u.map").c_str(),i_id,gx,gy);
170 sLog.outDetail("Loading map %s",tmp);
171 // loading data
172 GridMaps[gx][gy] = new GridMap();
173 if (!GridMaps[gx][gy]->loadData(tmp))
175 sLog.outError("Error load map file: \n %s\n", tmp);
177 delete [] tmp;
180 void Map::LoadMapAndVMap(int gx,int gy)
182 LoadMap(gx,gy);
183 if(i_InstanceId == 0)
184 LoadVMap(gx, gy); // Only load the data for the base map
187 void Map::InitStateMachine()
189 si_GridStates[GRID_STATE_INVALID] = new InvalidState;
190 si_GridStates[GRID_STATE_ACTIVE] = new ActiveState;
191 si_GridStates[GRID_STATE_IDLE] = new IdleState;
192 si_GridStates[GRID_STATE_REMOVAL] = new RemovalState;
195 void Map::DeleteStateMachine()
197 delete si_GridStates[GRID_STATE_INVALID];
198 delete si_GridStates[GRID_STATE_ACTIVE];
199 delete si_GridStates[GRID_STATE_IDLE];
200 delete si_GridStates[GRID_STATE_REMOVAL];
203 Map::Map(uint32 id, time_t expiry, uint32 InstanceId, uint8 SpawnMode, Map* _parent)
204 : i_mapEntry (sMapStore.LookupEntry(id)), i_spawnMode(SpawnMode),
205 i_id(id), i_InstanceId(InstanceId), m_unloadTimer(0),
206 m_VisibleDistance(DEFAULT_VISIBILITY_DISTANCE),
207 m_activeNonPlayersIter(m_activeNonPlayers.end()),
208 i_gridExpiry(expiry), m_parentMap(_parent ? _parent : this),
209 m_hiDynObjectGuid(1), m_hiPetGuid(1), m_hiVehicleGuid(1)
211 for(unsigned int idx=0; idx < MAX_NUMBER_OF_GRIDS; ++idx)
213 for(unsigned int j=0; j < MAX_NUMBER_OF_GRIDS; ++j)
215 //z code
216 GridMaps[idx][j] =NULL;
217 setNGrid(NULL, idx, j);
220 ObjectAccessor::LinkMap(this);
222 //lets initialize visibility distance for map
223 Map::InitVisibilityDistance();
226 void Map::InitVisibilityDistance()
228 //init visibility for continents
229 m_VisibleDistance = World::GetMaxVisibleDistanceOnContinents();
232 // Template specialization of utility methods
233 template<class T>
234 void Map::AddToGrid(T* obj, NGridType *grid, Cell const& cell)
236 (*grid)(cell.CellX(), cell.CellY()).template AddGridObject<T>(obj);
239 template<>
240 void Map::AddToGrid(Player* obj, NGridType *grid, Cell const& cell)
242 (*grid)(cell.CellX(), cell.CellY()).AddWorldObject(obj);
245 template<>
246 void Map::AddToGrid(Corpse *obj, NGridType *grid, Cell const& cell)
248 // add to world object registry in grid
249 if(obj->GetType()!=CORPSE_BONES)
251 (*grid)(cell.CellX(), cell.CellY()).AddWorldObject(obj);
253 // add to grid object store
254 else
256 (*grid)(cell.CellX(), cell.CellY()).AddGridObject(obj);
260 template<>
261 void Map::AddToGrid(Creature* obj, NGridType *grid, Cell const& cell)
263 // add to world object registry in grid
264 if(obj->isPet() || obj->isVehicle())
266 (*grid)(cell.CellX(), cell.CellY()).AddWorldObject<Creature>(obj);
267 obj->SetCurrentCell(cell);
269 // add to grid object store
270 else
272 (*grid)(cell.CellX(), cell.CellY()).AddGridObject<Creature>(obj);
273 obj->SetCurrentCell(cell);
277 template<class T>
278 void Map::RemoveFromGrid(T* obj, NGridType *grid, Cell const& cell)
280 (*grid)(cell.CellX(), cell.CellY()).template RemoveGridObject<T>(obj);
283 template<>
284 void Map::RemoveFromGrid(Player* obj, NGridType *grid, Cell const& cell)
286 (*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject(obj);
289 template<>
290 void Map::RemoveFromGrid(Corpse *obj, NGridType *grid, Cell const& cell)
292 // remove from world object registry in grid
293 if(obj->GetType()!=CORPSE_BONES)
295 (*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject(obj);
297 // remove from grid object store
298 else
300 (*grid)(cell.CellX(), cell.CellY()).RemoveGridObject(obj);
304 template<>
305 void Map::RemoveFromGrid(Creature* obj, NGridType *grid, Cell const& cell)
307 // remove from world object registry in grid
308 if(obj->isPet() || obj->isVehicle())
310 (*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject<Creature>(obj);
312 // remove from grid object store
313 else
315 (*grid)(cell.CellX(), cell.CellY()).RemoveGridObject<Creature>(obj);
319 template<class T>
320 void Map::DeleteFromWorld(T* obj)
322 // Note: In case resurrectable corpse and pet its removed from global lists in own destructor
323 delete obj;
326 template<>
327 void Map::DeleteFromWorld(Player* pl)
329 sObjectAccessor.RemoveObject(pl);
330 delete pl;
333 template<class T>
334 void Map::AddNotifier(T* , Cell const& , CellPair const& )
338 template<>
339 void Map::AddNotifier(Player* obj, Cell const& cell, CellPair const& cellpair)
341 PlayerRelocationNotify(obj,cell,cellpair);
344 template<>
345 void Map::AddNotifier(Creature* obj, Cell const&, CellPair const&)
347 obj->SetNeedNotify();
350 void
351 Map::EnsureGridCreated(const GridPair &p)
353 if(!getNGrid(p.x_coord, p.y_coord))
355 Guard guard(*this);
356 if(!getNGrid(p.x_coord, p.y_coord))
358 setNGrid(new NGridType(p.x_coord*MAX_NUMBER_OF_GRIDS + p.y_coord, p.x_coord, p.y_coord, i_gridExpiry, sWorld.getConfig(CONFIG_BOOL_GRID_UNLOAD)),
359 p.x_coord, p.y_coord);
361 // build a linkage between this map and NGridType
362 buildNGridLinkage(getNGrid(p.x_coord, p.y_coord));
364 getNGrid(p.x_coord, p.y_coord)->SetGridState(GRID_STATE_IDLE);
366 //z coord
367 int gx = (MAX_NUMBER_OF_GRIDS - 1) - p.x_coord;
368 int gy = (MAX_NUMBER_OF_GRIDS - 1) - p.y_coord;
370 if(!GridMaps[gx][gy])
371 LoadMapAndVMap(gx,gy);
376 void
377 Map::EnsureGridLoadedAtEnter(const Cell &cell, Player *player)
379 NGridType *grid;
381 if(EnsureGridLoaded(cell))
383 grid = getNGrid(cell.GridX(), cell.GridY());
385 if (player)
387 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);
389 else
391 DEBUG_LOG("Active object nearby triggers of loading grid [%u,%u] on map %u", cell.GridX(), cell.GridY(), i_id);
394 ResetGridExpiry(*getNGrid(cell.GridX(), cell.GridY()), 0.1f);
395 grid->SetGridState(GRID_STATE_ACTIVE);
397 else
398 grid = getNGrid(cell.GridX(), cell.GridY());
400 if (player)
401 AddToGrid(player,grid,cell);
404 bool Map::EnsureGridLoaded(const Cell &cell)
406 EnsureGridCreated(GridPair(cell.GridX(), cell.GridY()));
407 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
409 assert(grid != NULL);
410 if( !isGridObjectDataLoaded(cell.GridX(), cell.GridY()) )
412 ObjectGridLoader loader(*grid, this, cell);
413 loader.LoadN();
415 // Add resurrectable corpses to world object list in grid
416 sObjectAccessor.AddCorpsesToGrid(GridPair(cell.GridX(),cell.GridY()),(*grid)(cell.CellX(), cell.CellY()), this);
418 setGridObjectDataLoaded(true,cell.GridX(), cell.GridY());
419 return true;
422 return false;
425 void Map::LoadGrid(const Cell& cell, bool no_unload)
427 EnsureGridLoaded(cell);
429 if(no_unload)
430 getNGrid(cell.GridX(), cell.GridY())->setUnloadExplicitLock(true);
433 bool Map::Add(Player *player)
435 player->GetMapRef().link(this, player);
436 player->SetMap(this);
438 // update player state for other player and visa-versa
439 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
440 Cell cell(p);
441 EnsureGridLoadedAtEnter(cell, player);
442 player->AddToWorld();
444 SendInitSelf(player);
445 SendInitTransports(player);
447 UpdatePlayerVisibility(player,cell,p);
448 UpdateObjectsVisibilityFor(player,cell,p);
450 AddNotifier(player,cell,p);
451 return true;
454 template<class T>
455 void
456 Map::Add(T *obj)
458 assert(obj);
460 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
461 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
463 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);
464 return;
467 obj->SetMap(this);
469 Cell cell(p);
470 if(obj->isActiveObject())
471 EnsureGridLoadedAtEnter(cell);
472 else
473 EnsureGridCreated(GridPair(cell.GridX(), cell.GridY()));
475 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
476 assert( grid != NULL );
478 AddToGrid(obj,grid,cell);
479 obj->AddToWorld();
481 if(obj->isActiveObject())
482 AddToActive(obj);
484 DEBUG_LOG("Object %u enters grid[%u,%u]", GUID_LOPART(obj->GetGUID()), cell.GridX(), cell.GridY());
486 UpdateObjectVisibility(obj,cell,p);
488 AddNotifier(obj,cell,p);
491 void Map::MessageBroadcast(Player *player, WorldPacket *msg, bool to_self)
493 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
495 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
497 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);
498 return;
501 Cell cell(p);
502 cell.data.Part.reserved = ALL_DISTRICT;
503 cell.SetNoCreate();
505 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
506 return;
508 MaNGOS::MessageDeliverer post_man(*player, msg, to_self);
509 TypeContainerVisitor<MaNGOS::MessageDeliverer, WorldTypeMapContainer > message(post_man);
510 cell.Visit(p, message, *this, *player, GetVisibilityDistance());
513 void Map::MessageBroadcast(WorldObject *obj, WorldPacket *msg)
515 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
517 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
519 sLog.outError("Map::MessageBroadcast: 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);
520 return;
523 Cell cell(p);
524 cell.data.Part.reserved = ALL_DISTRICT;
525 cell.SetNoCreate();
527 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
528 return;
530 //TODO: currently on continents when Visibility.Distance.InFlight > Visibility.Distance.Continents
531 //we have alot of blinking mobs because monster move packet send is broken...
532 MaNGOS::ObjectMessageDeliverer post_man(*obj,msg);
533 TypeContainerVisitor<MaNGOS::ObjectMessageDeliverer, WorldTypeMapContainer > message(post_man);
534 cell.Visit(p, message, *this, *obj, GetVisibilityDistance());
537 void Map::MessageDistBroadcast(Player *player, WorldPacket *msg, float dist, bool to_self, bool own_team_only)
539 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
541 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
543 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);
544 return;
547 Cell cell(p);
548 cell.data.Part.reserved = ALL_DISTRICT;
549 cell.SetNoCreate();
551 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
552 return;
554 MaNGOS::MessageDistDeliverer post_man(*player, msg, dist, to_self, own_team_only);
555 TypeContainerVisitor<MaNGOS::MessageDistDeliverer , WorldTypeMapContainer > message(post_man);
556 cell.Visit(p, message, *this, *player, dist);
559 void Map::MessageDistBroadcast(WorldObject *obj, WorldPacket *msg, float dist)
561 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
563 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
565 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);
566 return;
569 Cell cell(p);
570 cell.data.Part.reserved = ALL_DISTRICT;
571 cell.SetNoCreate();
573 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
574 return;
576 MaNGOS::ObjectMessageDistDeliverer post_man(*obj, msg, dist);
577 TypeContainerVisitor<MaNGOS::ObjectMessageDistDeliverer, WorldTypeMapContainer > message(post_man);
578 cell.Visit(p, message, *this, *obj, dist);
581 bool Map::loaded(const GridPair &p) const
583 return ( getNGrid(p.x_coord, p.y_coord) && isGridObjectDataLoaded(p.x_coord, p.y_coord) );
586 void Map::Update(const uint32 &t_diff)
588 /// update players at tick
589 for(m_mapRefIter = m_mapRefManager.begin(); m_mapRefIter != m_mapRefManager.end(); ++m_mapRefIter)
591 Player* plr = m_mapRefIter->getSource();
592 if(plr && plr->IsInWorld())
593 plr->Update(t_diff);
596 /// update active cells around players and active objects
597 resetMarkedCells();
599 MaNGOS::ObjectUpdater updater(t_diff);
600 // for creature
601 TypeContainerVisitor<MaNGOS::ObjectUpdater, GridTypeMapContainer > grid_object_update(updater);
602 // for pets
603 TypeContainerVisitor<MaNGOS::ObjectUpdater, WorldTypeMapContainer > world_object_update(updater);
605 // the player iterator is stored in the map object
606 // to make sure calls to Map::Remove don't invalidate it
607 for(m_mapRefIter = m_mapRefManager.begin(); m_mapRefIter != m_mapRefManager.end(); ++m_mapRefIter)
609 Player* plr = m_mapRefIter->getSource();
611 if(!plr->IsInWorld())
612 continue;
614 CellPair standing_cell(MaNGOS::ComputeCellPair(plr->GetPositionX(), plr->GetPositionY()));
616 // Check for correctness of standing_cell, it also avoids problems with update_cell
617 if (standing_cell.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || standing_cell.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
618 continue;
620 // the overloaded operators handle range checking
621 // so ther's no need for range checking inside the loop
622 CellPair begin_cell(standing_cell), end_cell(standing_cell);
623 //lets update mobs/objects in ALL visible cells around player!
624 CellArea area = Cell::CalculateCellArea(*plr, GetVisibilityDistance());
625 area.ResizeBorders(begin_cell, end_cell);
627 for(uint32 x = begin_cell.x_coord; x <= end_cell.x_coord; ++x)
629 for(uint32 y = begin_cell.y_coord; y <= end_cell.y_coord; ++y)
631 // marked cells are those that have been visited
632 // don't visit the same cell twice
633 uint32 cell_id = (y * TOTAL_NUMBER_OF_CELLS_PER_MAP) + x;
634 if(!isCellMarked(cell_id))
636 markCell(cell_id);
637 CellPair pair(x,y);
638 Cell cell(pair);
639 cell.data.Part.reserved = CENTER_DISTRICT;
640 cell.SetNoCreate();
641 cell.Visit(pair, grid_object_update, *this);
642 cell.Visit(pair, world_object_update, *this);
648 // non-player active objects
649 if(!m_activeNonPlayers.empty())
651 for(m_activeNonPlayersIter = m_activeNonPlayers.begin(); m_activeNonPlayersIter != m_activeNonPlayers.end(); )
653 // skip not in world
654 WorldObject* obj = *m_activeNonPlayersIter;
656 // step before processing, in this case if Map::Remove remove next object we correctly
657 // step to next-next, and if we step to end() then newly added objects can wait next update.
658 ++m_activeNonPlayersIter;
660 if(!obj->IsInWorld())
661 continue;
663 CellPair standing_cell(MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY()));
665 // Check for correctness of standing_cell, it also avoids problems with update_cell
666 if (standing_cell.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || standing_cell.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
667 continue;
669 // the overloaded operators handle range checking
670 // so ther's no need for range checking inside the loop
671 CellPair begin_cell(standing_cell), end_cell(standing_cell);
672 begin_cell << 1; begin_cell -= 1; // upper left
673 end_cell >> 1; end_cell += 1; // lower right
675 for(uint32 x = begin_cell.x_coord; x <= end_cell.x_coord; ++x)
677 for(uint32 y = begin_cell.y_coord; y <= end_cell.y_coord; ++y)
679 // marked cells are those that have been visited
680 // don't visit the same cell twice
681 uint32 cell_id = (y * TOTAL_NUMBER_OF_CELLS_PER_MAP) + x;
682 if(!isCellMarked(cell_id))
684 markCell(cell_id);
685 CellPair pair(x,y);
686 Cell cell(pair);
687 cell.data.Part.reserved = CENTER_DISTRICT;
688 cell.SetNoCreate();
689 cell.Visit(pair, grid_object_update, *this);
690 cell.Visit(pair, world_object_update, *this);
697 // Send world objects and item update field changes
698 SendObjectUpdates();
700 // 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 !
701 // This isn't really bother us, since as soon as we have instanced BG-s, the whole map unloads as the BG gets ended
702 if (!IsBattleGroundOrArena())
704 for (GridRefManager<NGridType>::iterator i = GridRefManager<NGridType>::begin(); i != GridRefManager<NGridType>::end(); )
706 NGridType *grid = i->getSource();
707 GridInfo *info = i->getSource()->getGridInfoRef();
708 ++i; // The update might delete the map and we need the next map before the iterator gets invalid
709 assert(grid->GetGridState() >= 0 && grid->GetGridState() < MAX_GRID_STATE);
710 si_GridStates[grid->GetGridState()]->Update(*this, *grid, *info, grid->getX(), grid->getY(), t_diff);
714 ///- Process necessary scripts
715 if (!m_scriptSchedule.empty())
716 ScriptsProcess();
719 void Map::Remove(Player *player, bool remove)
721 if(remove)
722 player->CleanupsBeforeDelete();
723 else
724 player->RemoveFromWorld();
726 // this may be called during Map::Update
727 // after decrement+unlink, ++m_mapRefIter will continue correctly
728 // when the first element of the list is being removed
729 // nocheck_prev will return the padding element of the RefManager
730 // instead of NULL in the case of prev
731 if(m_mapRefIter == player->GetMapRef())
732 m_mapRefIter = m_mapRefIter->nocheck_prev();
733 player->GetMapRef().unlink();
734 CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
735 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
737 // invalid coordinates
738 player->ResetMap();
740 if( remove )
741 DeleteFromWorld(player);
743 return;
746 Cell cell(p);
748 if( !getNGrid(cell.data.Part.grid_x, cell.data.Part.grid_y) )
750 sLog.outError("Map::Remove() i_grids was NULL x:%d, y:%d",cell.data.Part.grid_x,cell.data.Part.grid_y);
751 return;
754 DEBUG_LOG("Remove player %s from grid[%u,%u]", player->GetName(), cell.GridX(), cell.GridY());
755 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
756 assert(grid != NULL);
758 RemoveFromGrid(player,grid,cell);
760 SendRemoveTransports(player);
761 UpdateObjectsVisibilityFor(player,cell,p);
763 player->ResetMap();
764 if( remove )
765 DeleteFromWorld(player);
768 bool Map::RemoveBones(uint64 guid, float x, float y)
770 if (IsRemovalGrid(x, y))
772 Corpse* corpse = ObjectAccessor::GetCorpseInMap(guid,GetId());
773 if (!corpse)
774 return false;
776 CellPair p = MaNGOS::ComputeCellPair(x,y);
777 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
779 sLog.outError("Map::RemoveBones: invalid coordinates supplied X:%f Y:%f grid cell [%u:%u]", x, y, p.x_coord, p.y_coord);
780 return false;
783 CellPair q = MaNGOS::ComputeCellPair(corpse->GetPositionX(),corpse->GetPositionY());
784 if(q.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || q.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
786 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);
787 return false;
790 int32 dx = int32(p.x_coord) - int32(q.x_coord);
791 int32 dy = int32(p.y_coord) - int32(q.y_coord);
793 if (dx <= -2 || dx >= 2 || dy <= -2 || dy >= 2)
794 return false;
796 if(corpse && corpse->GetTypeId() == TYPEID_CORPSE && corpse->GetType() == CORPSE_BONES)
797 corpse->DeleteBonesFromWorld();
798 else
799 return false;
801 return true;
804 template<class T>
805 void
806 Map::Remove(T *obj, bool remove)
808 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
809 if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
811 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);
812 return;
815 Cell cell(p);
816 if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
817 return;
819 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);
820 NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
821 assert( grid != NULL );
823 if(obj->isActiveObject())
824 RemoveFromActive(obj);
826 if(remove)
827 obj->CleanupsBeforeDelete();
828 else
829 obj->RemoveFromWorld();
831 RemoveFromGrid(obj,grid,cell);
833 UpdateObjectVisibility(obj,cell,p);
835 obj->ResetMap();
836 if( remove )
838 // if option set then object already saved at this moment
839 if(!sWorld.getConfig(CONFIG_BOOL_SAVE_RESPAWN_TIME_IMMEDIATLY))
840 obj->SaveRespawnTime();
841 DeleteFromWorld(obj);
845 void
846 Map::PlayerRelocation(Player *player, float x, float y, float z, float orientation)
848 assert(player);
850 CellPair old_val = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
851 CellPair new_val = MaNGOS::ComputeCellPair(x, y);
853 Cell old_cell(old_val);
854 Cell new_cell(new_val);
855 new_cell |= old_cell;
856 bool same_cell = (new_cell == old_cell);
858 player->Relocate(x, y, z, orientation);
860 if( old_cell.DiffGrid(new_cell) || old_cell.DiffCell(new_cell) )
862 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());
864 // update player position for group at taxi flight
865 if(player->GetGroup() && player->isInFlight())
866 player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
868 NGridType* oldGrid = getNGrid(old_cell.GridX(), old_cell.GridY());
869 RemoveFromGrid(player, oldGrid,old_cell);
870 if( !old_cell.DiffGrid(new_cell) )
871 AddToGrid(player, oldGrid,new_cell);
872 else
873 EnsureGridLoadedAtEnter(new_cell, player);
876 // if move then update what player see and who seen
877 UpdatePlayerVisibility(player,new_cell,new_val);
878 UpdateObjectsVisibilityFor(player,new_cell,new_val);
879 PlayerRelocationNotify(player,new_cell,new_val);
880 NGridType* newGrid = getNGrid(new_cell.GridX(), new_cell.GridY());
881 if( !same_cell && newGrid->GetGridState()!= GRID_STATE_ACTIVE )
883 ResetGridExpiry(*newGrid, 0.1f);
884 newGrid->SetGridState(GRID_STATE_ACTIVE);
888 void
889 Map::CreatureRelocation(Creature *creature, float x, float y, float z, float ang)
891 assert(CheckGridIntegrity(creature,false));
893 Cell old_cell = creature->GetCurrentCell();
895 CellPair new_val = MaNGOS::ComputeCellPair(x, y);
896 Cell new_cell(new_val);
898 // delay creature move for grid/cell to grid/cell moves
899 if (old_cell.DiffCell(new_cell) || old_cell.DiffGrid(new_cell))
901 #ifdef MANGOS_DEBUG
902 if ((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES) == 0)
903 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());
904 #endif
906 // do move or do move to respawn or remove creature if previous all fail
907 if(CreatureCellRelocation(creature,new_cell))
909 // update pos
910 creature->Relocate(x, y, z, ang);
912 // in diffcell/diffgrid case notifiers called in Creature::Update
913 creature->SetNeedNotify();
915 else
917 // if creature can't be move in new cell/grid (not loaded) move it to repawn cell/grid
918 // creature coordinates will be updated and notifiers send
919 if(!CreatureRespawnRelocation(creature))
921 // ... or unload (if respawn grid also not loaded)
922 #ifdef MANGOS_DEBUG
923 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
924 sLog.outDebug("Creature (GUID: %u Entry: %u ) can't be move to unloaded respawn grid.",creature->GetGUIDLow(),creature->GetEntry());
925 #endif
926 creature->SetNeedNotify();
930 else
932 creature->Relocate(x, y, z, ang);
933 creature->SetNeedNotify();
936 assert(CheckGridIntegrity(creature,true));
939 bool Map::CreatureCellRelocation(Creature *c, Cell new_cell)
941 Cell const& old_cell = c->GetCurrentCell();
942 if(!old_cell.DiffGrid(new_cell) ) // in same grid
944 // if in same cell then none do
945 if(old_cell.DiffCell(new_cell))
947 #ifdef MANGOS_DEBUG
948 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
949 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());
950 #endif
952 if( !old_cell.DiffGrid(new_cell) )
954 RemoveFromGrid(c,getNGrid(old_cell.GridX(), old_cell.GridY()),old_cell);
955 AddToGrid(c,getNGrid(new_cell.GridX(), new_cell.GridY()),new_cell);
956 c->SetCurrentCell(new_cell);
959 else
961 #ifdef MANGOS_DEBUG
962 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
963 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());
964 #endif
967 return true;
970 // in diff. grids but active creature
971 if(c->isActiveObject())
973 EnsureGridLoadedAtEnter(new_cell);
975 #ifdef MANGOS_DEBUG
976 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
977 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());
978 #endif
980 RemoveFromGrid(c,getNGrid(old_cell.GridX(), old_cell.GridY()),old_cell);
981 AddToGrid(c,getNGrid(new_cell.GridX(), new_cell.GridY()),new_cell);
983 return true;
986 // in diff. loaded grid normal creature
987 if(loaded(GridPair(new_cell.GridX(), new_cell.GridY())))
989 #ifdef MANGOS_DEBUG
990 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
991 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());
992 #endif
994 RemoveFromGrid(c,getNGrid(old_cell.GridX(), old_cell.GridY()),old_cell);
996 EnsureGridCreated(GridPair(new_cell.GridX(), new_cell.GridY()));
997 AddToGrid(c,getNGrid(new_cell.GridX(), new_cell.GridY()),new_cell);
1000 return true;
1003 // fail to move: normal creature attempt move to unloaded grid
1004 #ifdef MANGOS_DEBUG
1005 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
1006 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());
1007 #endif
1008 return false;
1011 bool Map::CreatureRespawnRelocation(Creature *c)
1013 float resp_x, resp_y, resp_z, resp_o;
1014 c->GetRespawnCoord(resp_x, resp_y, resp_z, &resp_o);
1016 CellPair resp_val = MaNGOS::ComputeCellPair(resp_x, resp_y);
1017 Cell resp_cell(resp_val);
1019 c->CombatStop();
1020 c->GetMotionMaster()->Clear();
1022 #ifdef MANGOS_DEBUG
1023 if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
1024 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());
1025 #endif
1027 // teleport it to respawn point (like normal respawn if player see)
1028 if(CreatureCellRelocation(c,resp_cell))
1030 c->Relocate(resp_x, resp_y, resp_z, resp_o);
1031 c->GetMotionMaster()->Initialize(); // prevent possible problems with default move generators
1032 c->SetNeedNotify();
1033 return true;
1035 else
1036 return false;
1039 bool Map::UnloadGrid(const uint32 &x, const uint32 &y, bool pForce)
1041 NGridType *grid = getNGrid(x, y);
1042 assert( grid != NULL);
1045 if(!pForce && ActiveObjectsNearGrid(x, y) )
1046 return false;
1048 DEBUG_LOG("Unloading grid[%u,%u] for map %u", x,y, i_id);
1049 ObjectGridUnloader unloader(*grid);
1051 // Finish remove and delete all creatures with delayed remove before moving to respawn grids
1052 // Must know real mob position before move
1053 RemoveAllObjectsInRemoveList();
1055 // move creatures to respawn grids if this is diff.grid or to remove list
1056 unloader.MoveToRespawnN();
1058 // Finish remove and delete all creatures with delayed remove before unload
1059 RemoveAllObjectsInRemoveList();
1061 unloader.UnloadN();
1062 delete getNGrid(x, y);
1063 setNGrid(NULL, x, y);
1066 int gx = (MAX_NUMBER_OF_GRIDS - 1) - x;
1067 int gy = (MAX_NUMBER_OF_GRIDS - 1) - y;
1069 // delete grid map, but don't delete if it is from parent map (and thus only reference)
1070 //+++if (GridMaps[gx][gy]) don't check for GridMaps[gx][gy], we might have to unload vmaps
1072 if (i_InstanceId == 0)
1074 if(GridMaps[gx][gy])
1076 GridMaps[gx][gy]->unloadData();
1077 delete GridMaps[gx][gy];
1079 VMAP::VMapFactory::createOrGetVMapManager()->unloadMap(GetId(), gx, gy);
1081 else
1082 ((MapInstanced*)m_parentMap)->RemoveGridMapReference(GridPair(gx, gy));
1084 GridMaps[gx][gy] = NULL;
1086 DEBUG_LOG("Unloading grid[%u,%u] for map %u finished", x,y, i_id);
1087 return true;
1090 void Map::UnloadAll(bool pForce)
1092 for (GridRefManager<NGridType>::iterator i = GridRefManager<NGridType>::begin(); i != GridRefManager<NGridType>::end(); )
1094 NGridType &grid(*i->getSource());
1095 ++i;
1096 UnloadGrid(grid.getX(), grid.getY(), pForce); // deletes the grid and removes it from the GridRefManager
1100 MapDifficulty const* Map::GetMapDifficulty() const
1102 return GetMapDifficultyData(GetId(),GetDifficulty());
1105 uint32 Map::GetMaxPlayers() const
1107 if(MapDifficulty const* mapDiff = GetMapDifficulty())
1109 if(mapDiff->maxPlayers || IsRegularDifficulty()) // Normal case (expect that regular difficulty always have correct maxplayers)
1110 return mapDiff->maxPlayers;
1111 else // DBC have 0 maxplayers for heroic instances with expansion < 2
1112 { // The heroic entry exists, so we don't have to check anything, simply return normal max players
1113 MapDifficulty const* normalDiff = GetMapDifficultyData(i_id, REGULAR_DIFFICULTY);
1114 return normalDiff ? normalDiff->maxPlayers : 0;
1117 else // I'd rather assert(false);
1118 return 0;
1121 uint32 Map::GetMaxResetDelay() const
1123 MapDifficulty const* mapDiff = GetMapDifficulty();
1124 return mapDiff ? mapDiff->resetTime : 0;
1127 //*****************************
1128 // Grid function
1129 //*****************************
1130 GridMap::GridMap()
1132 m_flags = 0;
1133 // Area data
1134 m_gridArea = 0;
1135 m_area_map = NULL;
1136 // Height level data
1137 m_gridHeight = INVALID_HEIGHT;
1138 m_gridGetHeight = &GridMap::getHeightFromFlat;
1139 m_V9 = NULL;
1140 m_V8 = NULL;
1141 // Liquid data
1142 m_liquidType = 0;
1143 m_liquid_offX = 0;
1144 m_liquid_offY = 0;
1145 m_liquid_width = 0;
1146 m_liquid_height = 0;
1147 m_liquidLevel = INVALID_HEIGHT;
1148 m_liquid_type = NULL;
1149 m_liquid_map = NULL;
1152 GridMap::~GridMap()
1154 unloadData();
1157 bool GridMap::loadData(char *filename)
1159 // Unload old data if exist
1160 unloadData();
1162 map_fileheader header;
1163 // Not return error if file not found
1164 FILE *in = fopen(filename, "rb");
1165 if (!in)
1166 return true;
1167 fread(&header, sizeof(header),1,in);
1168 if (header.mapMagic == *((uint32 const*)(MAP_MAGIC)) &&
1169 header.versionMagic == *((uint32 const*)(MAP_VERSION_MAGIC)) ||
1170 !IsAcceptableClientBuild(header.buildMagic))
1172 // loadup area data
1173 if (header.areaMapOffset && !loadAreaData(in, header.areaMapOffset, header.areaMapSize))
1175 sLog.outError("Error loading map area data\n");
1176 fclose(in);
1177 return false;
1179 // loadup height data
1180 if (header.heightMapOffset && !loadHeightData(in, header.heightMapOffset, header.heightMapSize))
1182 sLog.outError("Error loading map height data\n");
1183 fclose(in);
1184 return false;
1186 // loadup liquid data
1187 if (header.liquidMapOffset && !loadLiquidData(in, header.liquidMapOffset, header.liquidMapSize))
1189 sLog.outError("Error loading map liquids data\n");
1190 fclose(in);
1191 return false;
1193 fclose(in);
1194 return true;
1196 sLog.outError("Map file '%s' is non-compatible version (outdated?). Please, create new using ad.exe program.", filename);
1197 fclose(in);
1198 return false;
1201 void GridMap::unloadData()
1203 if (m_area_map) delete[] m_area_map;
1204 if (m_V9) delete[] m_V9;
1205 if (m_V8) delete[] m_V8;
1206 if (m_liquid_type) delete[] m_liquid_type;
1207 if (m_liquid_map) delete[] m_liquid_map;
1208 m_area_map = NULL;
1209 m_V9 = NULL;
1210 m_V8 = NULL;
1211 m_liquid_type = NULL;
1212 m_liquid_map = NULL;
1213 m_gridGetHeight = &GridMap::getHeightFromFlat;
1216 bool GridMap::loadAreaData(FILE *in, uint32 offset, uint32 /*size*/)
1218 map_areaHeader header;
1219 fseek(in, offset, SEEK_SET);
1220 fread(&header, sizeof(header), 1, in);
1221 if (header.fourcc != *((uint32 const*)(MAP_AREA_MAGIC)))
1222 return false;
1224 m_gridArea = header.gridArea;
1225 if (!(header.flags & MAP_AREA_NO_AREA))
1227 m_area_map = new uint16 [16*16];
1228 fread(m_area_map, sizeof(uint16), 16*16, in);
1230 return true;
1233 bool GridMap::loadHeightData(FILE *in, uint32 offset, uint32 /*size*/)
1235 map_heightHeader header;
1236 fseek(in, offset, SEEK_SET);
1237 fread(&header, sizeof(header), 1, in);
1238 if (header.fourcc != *((uint32 const*)(MAP_HEIGHT_MAGIC)))
1239 return false;
1241 m_gridHeight = header.gridHeight;
1242 if (!(header.flags & MAP_HEIGHT_NO_HEIGHT))
1244 if ((header.flags & MAP_HEIGHT_AS_INT16))
1246 m_uint16_V9 = new uint16 [129*129];
1247 m_uint16_V8 = new uint16 [128*128];
1248 fread(m_uint16_V9, sizeof(uint16), 129*129, in);
1249 fread(m_uint16_V8, sizeof(uint16), 128*128, in);
1250 m_gridIntHeightMultiplier = (header.gridMaxHeight - header.gridHeight) / 65535;
1251 m_gridGetHeight = &GridMap::getHeightFromUint16;
1253 else if ((header.flags & MAP_HEIGHT_AS_INT8))
1255 m_uint8_V9 = new uint8 [129*129];
1256 m_uint8_V8 = new uint8 [128*128];
1257 fread(m_uint8_V9, sizeof(uint8), 129*129, in);
1258 fread(m_uint8_V8, sizeof(uint8), 128*128, in);
1259 m_gridIntHeightMultiplier = (header.gridMaxHeight - header.gridHeight) / 255;
1260 m_gridGetHeight = &GridMap::getHeightFromUint8;
1262 else
1264 m_V9 = new float [129*129];
1265 m_V8 = new float [128*128];
1266 fread(m_V9, sizeof(float), 129*129, in);
1267 fread(m_V8, sizeof(float), 128*128, in);
1268 m_gridGetHeight = &GridMap::getHeightFromFloat;
1271 else
1272 m_gridGetHeight = &GridMap::getHeightFromFlat;
1273 return true;
1276 bool GridMap::loadLiquidData(FILE *in, uint32 offset, uint32 /*size*/)
1278 map_liquidHeader header;
1279 fseek(in, offset, SEEK_SET);
1280 fread(&header, sizeof(header), 1, in);
1281 if (header.fourcc != *((uint32 const*)(MAP_LIQUID_MAGIC)))
1282 return false;
1284 m_liquidType = header.liquidType;
1285 m_liquid_offX = header.offsetX;
1286 m_liquid_offY = header.offsetY;
1287 m_liquid_width = header.width;
1288 m_liquid_height= header.height;
1289 m_liquidLevel = header.liquidLevel;
1291 if (!(header.flags & MAP_LIQUID_NO_TYPE))
1293 m_liquid_type = new uint8 [16*16];
1294 fread(m_liquid_type, sizeof(uint8), 16*16, in);
1296 if (!(header.flags & MAP_LIQUID_NO_HEIGHT))
1298 m_liquid_map = new float [m_liquid_width*m_liquid_height];
1299 fread(m_liquid_map, sizeof(float), m_liquid_width*m_liquid_height, in);
1301 return true;
1304 uint16 GridMap::getArea(float x, float y)
1306 if (!m_area_map)
1307 return m_gridArea;
1309 x = 16 * (32 - x/SIZE_OF_GRIDS);
1310 y = 16 * (32 - y/SIZE_OF_GRIDS);
1311 int lx = (int)x & 15;
1312 int ly = (int)y & 15;
1313 return m_area_map[lx*16 + ly];
1316 float GridMap::getHeightFromFlat(float /*x*/, float /*y*/) const
1318 return m_gridHeight;
1321 float GridMap::getHeightFromFloat(float x, float y) const
1323 if (!m_V8 || !m_V9)
1324 return m_gridHeight;
1326 x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
1327 y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
1329 int x_int = (int)x;
1330 int y_int = (int)y;
1331 x -= x_int;
1332 y -= y_int;
1333 x_int&=(MAP_RESOLUTION - 1);
1334 y_int&=(MAP_RESOLUTION - 1);
1336 // Height stored as: h5 - its v8 grid, h1-h4 - its v9 grid
1337 // +--------------> X
1338 // | h1-------h2 Coordinates is:
1339 // | | \ 1 / | h1 0,0
1340 // | | \ / | h2 0,1
1341 // | | 2 h5 3 | h3 1,0
1342 // | | / \ | h4 1,1
1343 // | | / 4 \ | h5 1/2,1/2
1344 // | h3-------h4
1345 // V Y
1346 // For find height need
1347 // 1 - detect triangle
1348 // 2 - solve linear equation from triangle points
1349 // Calculate coefficients for solve h = a*x + b*y + c
1351 float a,b,c;
1352 // Select triangle:
1353 if (x+y < 1)
1355 if (x > y)
1357 // 1 triangle (h1, h2, h5 points)
1358 float h1 = m_V9[(x_int )*129 + y_int];
1359 float h2 = m_V9[(x_int+1)*129 + y_int];
1360 float h5 = 2 * m_V8[x_int*128 + y_int];
1361 a = h2-h1;
1362 b = h5-h1-h2;
1363 c = h1;
1365 else
1367 // 2 triangle (h1, h3, h5 points)
1368 float h1 = m_V9[x_int*129 + y_int ];
1369 float h3 = m_V9[x_int*129 + y_int+1];
1370 float h5 = 2 * m_V8[x_int*128 + y_int];
1371 a = h5 - h1 - h3;
1372 b = h3 - h1;
1373 c = h1;
1376 else
1378 if (x > y)
1380 // 3 triangle (h2, h4, h5 points)
1381 float h2 = m_V9[(x_int+1)*129 + y_int ];
1382 float h4 = m_V9[(x_int+1)*129 + y_int+1];
1383 float h5 = 2 * m_V8[x_int*128 + y_int];
1384 a = h2 + h4 - h5;
1385 b = h4 - h2;
1386 c = h5 - h4;
1388 else
1390 // 4 triangle (h3, h4, h5 points)
1391 float h3 = m_V9[(x_int )*129 + y_int+1];
1392 float h4 = m_V9[(x_int+1)*129 + y_int+1];
1393 float h5 = 2 * m_V8[x_int*128 + y_int];
1394 a = h4 - h3;
1395 b = h3 + h4 - h5;
1396 c = h5 - h4;
1399 // Calculate height
1400 return a * x + b * y + c;
1403 float GridMap::getHeightFromUint8(float x, float y) const
1405 if (!m_uint8_V8 || !m_uint8_V9)
1406 return m_gridHeight;
1408 x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
1409 y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
1411 int x_int = (int)x;
1412 int y_int = (int)y;
1413 x -= x_int;
1414 y -= y_int;
1415 x_int&=(MAP_RESOLUTION - 1);
1416 y_int&=(MAP_RESOLUTION - 1);
1418 int32 a, b, c;
1419 uint8 *V9_h1_ptr = &m_uint8_V9[x_int*128 + x_int + y_int];
1420 if (x+y < 1)
1422 if (x > y)
1424 // 1 triangle (h1, h2, h5 points)
1425 int32 h1 = V9_h1_ptr[ 0];
1426 int32 h2 = V9_h1_ptr[129];
1427 int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int];
1428 a = h2-h1;
1429 b = h5-h1-h2;
1430 c = h1;
1432 else
1434 // 2 triangle (h1, h3, h5 points)
1435 int32 h1 = V9_h1_ptr[0];
1436 int32 h3 = V9_h1_ptr[1];
1437 int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int];
1438 a = h5 - h1 - h3;
1439 b = h3 - h1;
1440 c = h1;
1443 else
1445 if (x > y)
1447 // 3 triangle (h2, h4, h5 points)
1448 int32 h2 = V9_h1_ptr[129];
1449 int32 h4 = V9_h1_ptr[130];
1450 int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int];
1451 a = h2 + h4 - h5;
1452 b = h4 - h2;
1453 c = h5 - h4;
1455 else
1457 // 4 triangle (h3, h4, h5 points)
1458 int32 h3 = V9_h1_ptr[ 1];
1459 int32 h4 = V9_h1_ptr[130];
1460 int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int];
1461 a = h4 - h3;
1462 b = h3 + h4 - h5;
1463 c = h5 - h4;
1466 // Calculate height
1467 return (float)((a * x) + (b * y) + c)*m_gridIntHeightMultiplier + m_gridHeight;
1470 float GridMap::getHeightFromUint16(float x, float y) const
1472 if (!m_uint16_V8 || !m_uint16_V9)
1473 return m_gridHeight;
1475 x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
1476 y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
1478 int x_int = (int)x;
1479 int y_int = (int)y;
1480 x -= x_int;
1481 y -= y_int;
1482 x_int&=(MAP_RESOLUTION - 1);
1483 y_int&=(MAP_RESOLUTION - 1);
1485 int32 a, b, c;
1486 uint16 *V9_h1_ptr = &m_uint16_V9[x_int*128 + x_int + y_int];
1487 if (x+y < 1)
1489 if (x > y)
1491 // 1 triangle (h1, h2, h5 points)
1492 int32 h1 = V9_h1_ptr[ 0];
1493 int32 h2 = V9_h1_ptr[129];
1494 int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int];
1495 a = h2-h1;
1496 b = h5-h1-h2;
1497 c = h1;
1499 else
1501 // 2 triangle (h1, h3, h5 points)
1502 int32 h1 = V9_h1_ptr[0];
1503 int32 h3 = V9_h1_ptr[1];
1504 int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int];
1505 a = h5 - h1 - h3;
1506 b = h3 - h1;
1507 c = h1;
1510 else
1512 if (x > y)
1514 // 3 triangle (h2, h4, h5 points)
1515 int32 h2 = V9_h1_ptr[129];
1516 int32 h4 = V9_h1_ptr[130];
1517 int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int];
1518 a = h2 + h4 - h5;
1519 b = h4 - h2;
1520 c = h5 - h4;
1522 else
1524 // 4 triangle (h3, h4, h5 points)
1525 int32 h3 = V9_h1_ptr[ 1];
1526 int32 h4 = V9_h1_ptr[130];
1527 int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int];
1528 a = h4 - h3;
1529 b = h3 + h4 - h5;
1530 c = h5 - h4;
1533 // Calculate height
1534 return (float)((a * x) + (b * y) + c)*m_gridIntHeightMultiplier + m_gridHeight;
1537 float GridMap::getLiquidLevel(float x, float y)
1539 if (!m_liquid_map)
1540 return m_liquidLevel;
1542 x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
1543 y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
1545 int cx_int = ((int)x & (MAP_RESOLUTION-1)) - m_liquid_offY;
1546 int cy_int = ((int)y & (MAP_RESOLUTION-1)) - m_liquid_offX;
1548 if (cx_int < 0 || cx_int >=m_liquid_height)
1549 return INVALID_HEIGHT;
1550 if (cy_int < 0 || cy_int >=m_liquid_width )
1551 return INVALID_HEIGHT;
1553 return m_liquid_map[cx_int*m_liquid_width + cy_int];
1556 uint8 GridMap::getTerrainType(float x, float y)
1558 if (!m_liquid_type)
1559 return (uint8)m_liquidType;
1561 x = 16 * (32 - x/SIZE_OF_GRIDS);
1562 y = 16 * (32 - y/SIZE_OF_GRIDS);
1563 int lx = (int)x & 15;
1564 int ly = (int)y & 15;
1565 return m_liquid_type[lx*16 + ly];
1568 // Get water state on map
1569 inline ZLiquidStatus GridMap::getLiquidStatus(float x, float y, float z, uint8 ReqLiquidType, LiquidData *data)
1571 // Check water type (if no water return)
1572 if (!m_liquid_type && !m_liquidType)
1573 return LIQUID_MAP_NO_WATER;
1575 // Get cell
1576 float cx = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
1577 float cy = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
1579 int x_int = (int)cx & (MAP_RESOLUTION-1);
1580 int y_int = (int)cy & (MAP_RESOLUTION-1);
1582 // Check water type in cell
1583 uint8 type = m_liquid_type ? m_liquid_type[(x_int>>3)*16 + (y_int>>3)] : m_liquidType;
1584 if (type == 0)
1585 return LIQUID_MAP_NO_WATER;
1587 // Check req liquid type mask
1588 if (ReqLiquidType && !(ReqLiquidType&type))
1589 return LIQUID_MAP_NO_WATER;
1591 // Check water level:
1592 // Check water height map
1593 int lx_int = x_int - m_liquid_offY;
1594 int ly_int = y_int - m_liquid_offX;
1595 if (lx_int < 0 || lx_int >=m_liquid_height)
1596 return LIQUID_MAP_NO_WATER;
1597 if (ly_int < 0 || ly_int >=m_liquid_width )
1598 return LIQUID_MAP_NO_WATER;
1600 // Get water level
1601 float liquid_level = m_liquid_map ? m_liquid_map[lx_int*m_liquid_width + ly_int] : m_liquidLevel;
1602 // Get ground level (sub 0.2 for fix some errors)
1603 float ground_level = getHeight(x, y);
1605 // Check water level and ground level
1606 if (liquid_level < ground_level || z < ground_level - 2)
1607 return LIQUID_MAP_NO_WATER;
1609 // All ok in water -> store data
1610 if (data)
1612 data->type = type;
1613 data->level = liquid_level;
1614 data->depth_level = ground_level;
1617 // For speed check as int values
1618 int delta = int((liquid_level - z) * 10);
1620 // Get position delta
1621 if (delta > 20) // Under water
1622 return LIQUID_MAP_UNDER_WATER;
1623 if (delta > 0 ) // In water
1624 return LIQUID_MAP_IN_WATER;
1625 if (delta > -1) // Walk on water
1626 return LIQUID_MAP_WATER_WALK;
1627 // Above water
1628 return LIQUID_MAP_ABOVE_WATER;
1631 inline GridMap *Map::GetGrid(float x, float y)
1633 // half opt method
1634 int gx=(int)(32-x/SIZE_OF_GRIDS); //grid x
1635 int gy=(int)(32-y/SIZE_OF_GRIDS); //grid y
1637 // ensure GridMap is loaded
1638 EnsureGridCreated(GridPair(63-gx,63-gy));
1640 return GridMaps[gx][gy];
1643 float Map::GetHeight(float x, float y, float z, bool pUseVmaps) const
1645 // find raw .map surface under Z coordinates
1646 float mapHeight;
1647 if(GridMap *gmap = const_cast<Map*>(this)->GetGrid(x, y))
1649 float _mapheight = gmap->getHeight(x,y);
1651 // look from a bit higher pos to find the floor, ignore under surface case
1652 if(z + 2.0f > _mapheight)
1653 mapHeight = _mapheight;
1654 else
1655 mapHeight = VMAP_INVALID_HEIGHT_VALUE;
1657 else
1658 mapHeight = VMAP_INVALID_HEIGHT_VALUE;
1660 float vmapHeight;
1661 if(pUseVmaps)
1663 VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager();
1664 if(vmgr->isHeightCalcEnabled())
1666 // look from a bit higher pos to find the floor
1667 vmapHeight = vmgr->getHeight(GetId(), x, y, z + 2.0f);
1669 else
1670 vmapHeight = VMAP_INVALID_HEIGHT_VALUE;
1672 else
1673 vmapHeight = VMAP_INVALID_HEIGHT_VALUE;
1675 // mapHeight set for any above raw ground Z or <= INVALID_HEIGHT
1676 // vmapheight set for any under Z value or <= INVALID_HEIGHT
1678 if( vmapHeight > INVALID_HEIGHT )
1680 if( mapHeight > INVALID_HEIGHT )
1682 // we have mapheight and vmapheight and must select more appropriate
1684 // we are already under the surface or vmap height above map heigt
1685 // or if the distance of the vmap height is less the land height distance
1686 if( z < mapHeight || vmapHeight > mapHeight || fabs(mapHeight-z) > fabs(vmapHeight-z) )
1687 return vmapHeight;
1688 else
1689 return mapHeight; // better use .map surface height
1692 else
1693 return vmapHeight; // we have only vmapHeight (if have)
1695 else
1697 if(!pUseVmaps)
1698 return mapHeight; // explicitly use map data (if have)
1699 else if(mapHeight > INVALID_HEIGHT && (z < mapHeight + 2 || z == MAX_HEIGHT))
1700 return mapHeight; // explicitly use map data if original z < mapHeight but map found (z+2 > mapHeight)
1701 else
1702 return VMAP_INVALID_HEIGHT_VALUE; // we not have any height
1706 uint16 Map::GetAreaFlag(float x, float y, float z) const
1708 uint16 areaflag;
1709 if(GridMap *gmap = const_cast<Map*>(this)->GetGrid(x, y))
1710 areaflag = gmap->getArea(x, y);
1711 // this used while not all *.map files generated (instances)
1712 else
1713 areaflag = GetAreaFlagByMapId(i_id);
1715 //FIXME: some hacks for areas above or underground for ground area
1716 // required for area specific spells/etc, until map/vmap data
1717 // not provided correct areaflag with this hacks
1718 switch(areaflag)
1720 // Acherus: The Ebon Hold (Plaguelands: The Scarlet Enclave)
1721 case 1984: // Plaguelands: The Scarlet Enclave
1722 case 2076: // Death's Breach (Plaguelands: The Scarlet Enclave)
1723 case 2745: // The Noxious Pass (Plaguelands: The Scarlet Enclave)
1724 if(z > 350.0f) areaflag = 2048; break;
1725 // Acherus: The Ebon Hold (Eastern Plaguelands)
1726 case 856: // The Noxious Glade (Eastern Plaguelands)
1727 case 2456: // Death's Breach (Eastern Plaguelands)
1728 if(z > 350.0f) areaflag = 1950; break;
1729 // Winterfin Caverns
1730 case 1652: // Coldarra
1731 case 1653: // The Westrift
1732 case 1661: // Winterfin Village
1733 if (x > 3823.0f && x < 4141.5f && y > 6247.0f && y < 64890.0f && z < 42.5f)
1734 areaflag = 1723;
1735 break;
1736 // Moonrest Gardens
1737 case 1787:
1738 if (x > 3315.3f && x < 3361.6f && y > 2469.4f && y < 2565.8f && z > 197.0f)
1739 areaflag = 1786; // Surge Needle (cords not entirely correct, will need round circle if this is really needed(see spell 47097 eff 77))
1740 break;
1741 // Dalaran
1742 case 2492: // Forlorn Woods (Crystalsong Forest)
1743 case 2371: // Valley of Echoes (Icecrown Glacier)
1744 if (x > 5568.0f && x < 6116.0f && y > 282.0f && y < 982.0f && z > 563.0f)
1746 // Krasus' Landing (Dalaran), fast check
1747 if (x > 5758.77f && x < 5869.03f && y < 510.46f)
1749 // Krasus' Landing (Dalaran), with open east side
1750 if (y < 449.33f || (x-5813.9f)*(x-5813.9f)+(y-449.33f)*(y-449.33f) < 1864.0f)
1752 areaflag = 2531; // Note: also 2633, possible one flight allowed and other not allowed case
1753 break;
1757 // Dalaran
1758 areaflag = 2153;
1760 break;
1761 // The Violet Citadel (Dalaran) or Dalaran
1762 case 2484: // The Twilight Rivulet (Crystalsong Forest)
1763 case 1593: // Crystalsong Forest
1764 // Dalaran
1765 if (x > 5568.0f && x < 6116.0f && y > 282.0f && y < 982.0f && z > 563.0f)
1767 // The Violet Citadel (Dalaran), fast check
1768 if (x > 5721.1f && x < 5884.66f && y > 764.4f && y < 948.0f)
1770 // The Violet Citadel (Dalaran)
1771 if ((x-5803.0f)*(x-5803.0f)+(y-846.18f)*(y-846.18f) < 6690.0f)
1773 areaflag = 2696;
1774 break;
1778 // Dalaran
1779 areaflag = 2153;
1781 break;
1782 // Vargoth's Retreat (Dalaran) or The Violet Citadel (Dalaran) or Dalaran
1783 case 2504: // Violet Stand (Crystalsong Forest)
1784 // Dalaran
1785 if (x > 5568.0f && x < 6116.0f && y > 282.0f && y < 982.0f && z > 563.0f)
1787 // The Violet Citadel (Dalaran), fast check
1788 if (x > 5721.1f && x < 5884.66f && y > 764.4f && y < 948.0f)
1790 // Vargoth's Retreat (Dalaran), nice slow circle with upper limit
1791 if (z < 898.0f && (x-5765.0f)*(x-5765.0f)+(y-862.4f)*(y-862.4f) < 262.0f)
1793 areaflag = 2748;
1794 break;
1797 // The Violet Citadel (Dalaran)
1798 if ((x-5803.0f)*(x-5803.0f)+(y-846.18f)*(y-846.18f) < 6690.0f)
1800 areaflag = 2696;
1801 break;
1805 // Dalaran
1806 areaflag = 2153;
1808 break;
1809 // Maw of Neltharion (cave)
1810 case 164: // Dragonblight
1811 case 1797: // Obsidian Dragonshrine (Dragonblight)
1812 case 1827: // Wintergrasp
1813 case 2591: // The Cauldron of Flames (Wintergrasp)
1814 if (x > 4364.0f && x < 4632.0f && y > 1545.0f && y < 1886.0f && z < 200.0f) areaflag = 1853; break;
1815 // Undercity (sewers enter and path)
1816 case 179: // Tirisfal Glades
1817 if (x > 1595.0f && x < 1699.0f && y > 535.0f && y < 643.5f && z < 30.5f) areaflag = 685; break;
1818 // Undercity (Royal Quarter)
1819 case 210: // Silverpine Forest
1820 case 316: // The Shining Strand (Silverpine Forest)
1821 case 438: // Lordamere Lake (Silverpine Forest)
1822 if (x > 1237.0f && x < 1401.0f && y > 284.0f && y < 440.0f && z < -40.0f) areaflag = 685; break;
1823 // Undercity (cave and ground zone, part of royal quarter)
1824 case 607: // Ruins of Lordaeron (Tirisfal Glades)
1825 // ground and near to ground (by city walls)
1826 if(z > 0.0f)
1828 if (x > 1510.0f && x < 1839.0f && y > 29.77f && y < 433.0f) areaflag = 685;
1830 // more wide underground, part of royal quarter
1831 else
1833 if (x > 1299.0f && x < 1839.0f && y > 10.0f && y < 440.0f) areaflag = 685;
1835 break;
1836 // The Makers' Perch (ground) and Makers' Overlook (ground and cave)
1837 case 1335: // Sholazar Basin
1838 // The Makers' Perch ground (fast box)
1839 if (x > 6100.0f && x < 6250.0f && y > 5650.0f && y < 5800.0f)
1841 // nice slow circle
1842 if ((x-6183.0f)*(x-6183.0f)+(y-5717.0f)*(y-5717.0f) < 2500.0f)
1843 areaflag = 2189;
1845 // Makers' Overlook (ground and cave)
1846 else if (x > 5634.48f && x < 5774.53f && y < 3475.0f && z > 300.0f)
1848 if (y > 3380.26f || (y > 3265.0f && z < 360.0f))
1849 areaflag = 2187;
1851 break;
1852 // The Makers' Perch (underground)
1853 case 2147: // The Stormwright's Shelf (Sholazar Basin)
1854 if (x > 6199.0f && x < 6283.0f && y > 5705.0f && y < 5817.0f && z < 38.0f) areaflag = 2189; break;
1855 // Makers' Overlook (deep cave)
1856 case 267: // Icecrown
1857 if (x > 5684.0f && x < 5798.0f && y > 3035.0f && y < 3367.0f && z < 358.0f) areaflag = 2187; break;
1858 // Wyrmrest Temple (Dragonblight)
1859 case 1814: // Path of the Titans (Dragonblight)
1860 case 1897: // The Dragon Wastes (Dragonblight)
1861 // fast box
1862 if (x > 3400.0f && x < 3700.0f && y > 130.0f && y < 420.0f)
1864 // nice slow circle
1865 if ((x-3546.87f)*(x-3546.87f)+(y-272.71f)*(y-272.71f) < 19600.0f) areaflag = 1791;
1867 break;
1868 // The Forlorn Mine (The Storm Peaks)
1869 case 166: // The Storm Peaks
1870 case 2207: // Brunnhildar Village (The Storm Peaks)
1871 case 2209: // Sifreldar Village (The Storm Peaks)
1872 case 2227: // The Foot Steppes (The Storm Peaks)
1873 // fast big box
1874 if (x > 6812.0f && x < 7049.5f && y > -1474.5f && y < -1162.5f && z < 866.15f)
1876 // east, avoid ground east-south corner wrong detection
1877 if (x > 6925.0f && y > -1474.5f && y < -1290.0f)
1878 areaflag = 2213;
1879 // east middle, wide part
1880 else if (x > 6812.0f && y > -1400.0f && y < -1290.0f)
1881 areaflag = 2213;
1882 // west middle, avoid ground west-south corner wrong detection
1883 else if (x > 6833.0f && y > -1474.5f && y < -1233.0f)
1884 areaflag = 2213;
1885 // west, avoid ground west-south corner wrong detection
1886 else if (x > 6885.0f && y > -1474.5f && y < -1162.5f)
1887 areaflag = 2213;
1889 break;
1890 default:
1891 break;
1894 return areaflag;
1897 uint8 Map::GetTerrainType(float x, float y ) const
1899 if(GridMap *gmap = const_cast<Map*>(this)->GetGrid(x, y))
1900 return gmap->getTerrainType(x, y);
1901 else
1902 return 0;
1905 ZLiquidStatus Map::getLiquidStatus(float x, float y, float z, uint8 ReqLiquidType, LiquidData *data) const
1907 if(GridMap* gmap = const_cast<Map*>(this)->GetGrid(x, y))
1908 return gmap->getLiquidStatus(x, y, z, ReqLiquidType, data);
1909 else
1910 return LIQUID_MAP_NO_WATER;
1913 float Map::GetWaterLevel(float x, float y ) const
1915 if(GridMap* gmap = const_cast<Map*>(this)->GetGrid(x, y))
1916 return gmap->getLiquidLevel(x, y);
1917 else
1918 return 0;
1921 uint32 Map::GetAreaIdByAreaFlag(uint16 areaflag,uint32 map_id)
1923 AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
1925 if (entry)
1926 return entry->ID;
1927 else
1928 return 0;
1931 uint32 Map::GetZoneIdByAreaFlag(uint16 areaflag,uint32 map_id)
1933 AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
1935 if( entry )
1936 return ( entry->zone != 0 ) ? entry->zone : entry->ID;
1937 else
1938 return 0;
1941 void Map::GetZoneAndAreaIdByAreaFlag(uint32& zoneid, uint32& areaid, uint16 areaflag,uint32 map_id)
1943 AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
1945 areaid = entry ? entry->ID : 0;
1946 zoneid = entry ? (( entry->zone != 0 ) ? entry->zone : entry->ID) : 0;
1949 bool Map::IsInWater(float x, float y, float pZ) const
1951 // Check surface in x, y point for liquid
1952 if (const_cast<Map*>(this)->GetGrid(x, y))
1954 LiquidData liquid_status;
1955 if (getLiquidStatus(x, y, pZ, MAP_ALL_LIQUIDS, &liquid_status))
1957 if (liquid_status.level - liquid_status.depth_level > 2)
1958 return true;
1961 return false;
1964 bool Map::IsUnderWater(float x, float y, float z) const
1966 if (const_cast<Map*>(this)->GetGrid(x, y))
1968 if (getLiquidStatus(x, y, z, MAP_LIQUID_TYPE_WATER|MAP_LIQUID_TYPE_OCEAN)&LIQUID_MAP_UNDER_WATER)
1969 return true;
1971 return false;
1974 bool Map::CheckGridIntegrity(Creature* c, bool moved) const
1976 Cell const& cur_cell = c->GetCurrentCell();
1978 CellPair xy_val = MaNGOS::ComputeCellPair(c->GetPositionX(), c->GetPositionY());
1979 Cell xy_cell(xy_val);
1980 if(xy_cell != cur_cell)
1982 sLog.outError("Creature (GUIDLow: %u) X: %f Y: %f (%s) in grid[%u,%u]cell[%u,%u] instead grid[%u,%u]cell[%u,%u]",
1983 c->GetGUIDLow(),
1984 c->GetPositionX(),c->GetPositionY(),(moved ? "final" : "original"),
1985 cur_cell.GridX(), cur_cell.GridY(), cur_cell.CellX(), cur_cell.CellY(),
1986 xy_cell.GridX(), xy_cell.GridY(), xy_cell.CellX(), xy_cell.CellY());
1987 return true; // not crash at error, just output error in debug mode
1990 return true;
1993 const char* Map::GetMapName() const
1995 return i_mapEntry ? i_mapEntry->name[sWorld.GetDefaultDbcLocale()] : "UNNAMEDMAP\x0";
1998 void Map::UpdateObjectVisibility( WorldObject* obj, Cell cell, CellPair cellpair)
2000 cell.data.Part.reserved = ALL_DISTRICT;
2001 cell.SetNoCreate();
2002 MaNGOS::VisibleChangesNotifier notifier(*obj);
2003 TypeContainerVisitor<MaNGOS::VisibleChangesNotifier, WorldTypeMapContainer > player_notifier(notifier);
2004 cell.Visit(cellpair, player_notifier, *this, *obj, GetVisibilityDistance());
2007 void Map::UpdatePlayerVisibility( Player* player, Cell cell, CellPair cellpair )
2009 cell.data.Part.reserved = ALL_DISTRICT;
2011 MaNGOS::PlayerNotifier pl_notifier(*player);
2012 TypeContainerVisitor<MaNGOS::PlayerNotifier, WorldTypeMapContainer > player_notifier(pl_notifier);
2014 cell.Visit(cellpair, player_notifier, *this, *player, GetVisibilityDistance());
2017 void Map::UpdateObjectsVisibilityFor( Player* player, Cell cell, CellPair cellpair )
2019 MaNGOS::VisibleNotifier notifier(*player);
2021 cell.data.Part.reserved = ALL_DISTRICT;
2022 cell.SetNoCreate();
2023 TypeContainerVisitor<MaNGOS::VisibleNotifier, WorldTypeMapContainer > world_notifier(notifier);
2024 TypeContainerVisitor<MaNGOS::VisibleNotifier, GridTypeMapContainer > grid_notifier(notifier);
2025 cell.Visit(cellpair, world_notifier, *this, *player, GetVisibilityDistance());
2026 cell.Visit(cellpair, grid_notifier, *this, *player, GetVisibilityDistance());
2028 // send data
2029 notifier.Notify();
2032 void Map::PlayerRelocationNotify( Player* player, Cell cell, CellPair cellpair )
2034 MaNGOS::PlayerRelocationNotifier relocationNotifier(*player);
2035 cell.data.Part.reserved = ALL_DISTRICT;
2037 TypeContainerVisitor<MaNGOS::PlayerRelocationNotifier, GridTypeMapContainer > p2grid_relocation(relocationNotifier);
2038 TypeContainerVisitor<MaNGOS::PlayerRelocationNotifier, WorldTypeMapContainer > p2world_relocation(relocationNotifier);
2040 float radius = MAX_CREATURE_ATTACK_RADIUS * sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_AGGRO);
2042 cell.Visit(cellpair, p2grid_relocation, *this, *player, radius);
2043 cell.Visit(cellpair, p2world_relocation, *this, *player, radius);
2046 void Map::SendInitSelf( Player * player )
2048 sLog.outDetail("Creating player data for himself %u", player->GetGUIDLow());
2050 UpdateData data;
2052 // attach to player data current transport data
2053 if(Transport* transport = player->GetTransport())
2055 transport->BuildCreateUpdateBlockForPlayer(&data, player);
2058 // build data for self presence in world at own client (one time for map)
2059 player->BuildCreateUpdateBlockForPlayer(&data, player);
2061 // build other passengers at transport also (they always visible and marked as visible and will not send at visibility update at add to map
2062 if(Transport* transport = player->GetTransport())
2064 for(Transport::PlayerSet::const_iterator itr = transport->GetPassengers().begin();itr!=transport->GetPassengers().end();++itr)
2066 if(player!=(*itr) && player->HaveAtClient(*itr))
2068 (*itr)->BuildCreateUpdateBlockForPlayer(&data, player);
2073 WorldPacket packet;
2074 data.BuildPacket(&packet);
2075 player->GetSession()->SendPacket(&packet);
2078 void Map::SendInitTransports( Player * player )
2080 // Hack to send out transports
2081 MapManager::TransportMap& tmap = sMapMgr.m_TransportsByMap;
2083 // no transports at map
2084 if (tmap.find(player->GetMapId()) == tmap.end())
2085 return;
2087 UpdateData transData;
2089 MapManager::TransportSet& tset = tmap[player->GetMapId()];
2091 for (MapManager::TransportSet::const_iterator i = tset.begin(); i != tset.end(); ++i)
2093 // send data for current transport in other place
2094 if((*i) != player->GetTransport() && (*i)->GetMapId()==i_id)
2096 (*i)->BuildCreateUpdateBlockForPlayer(&transData, player);
2100 WorldPacket packet;
2101 transData.BuildPacket(&packet);
2102 player->GetSession()->SendPacket(&packet);
2105 void Map::SendRemoveTransports( Player * player )
2107 // Hack to send out transports
2108 MapManager::TransportMap& tmap = sMapMgr.m_TransportsByMap;
2110 // no transports at map
2111 if (tmap.find(player->GetMapId()) == tmap.end())
2112 return;
2114 UpdateData transData;
2116 MapManager::TransportSet& tset = tmap[player->GetMapId()];
2118 // except used transport
2119 for (MapManager::TransportSet::const_iterator i = tset.begin(); i != tset.end(); ++i)
2120 if((*i) != player->GetTransport() && (*i)->GetMapId()!=i_id)
2121 (*i)->BuildOutOfRangeUpdateBlock(&transData);
2123 WorldPacket packet;
2124 transData.BuildPacket(&packet);
2125 player->GetSession()->SendPacket(&packet);
2128 inline void Map::setNGrid(NGridType *grid, uint32 x, uint32 y)
2130 if(x >= MAX_NUMBER_OF_GRIDS || y >= MAX_NUMBER_OF_GRIDS)
2132 sLog.outError("map::setNGrid() Invalid grid coordinates found: %d, %d!",x,y);
2133 assert(false);
2135 i_grids[x][y] = grid;
2138 void Map::AddObjectToRemoveList(WorldObject *obj)
2140 assert(obj->GetMapId()==GetId() && obj->GetInstanceId()==GetInstanceId());
2142 obj->CleanupsBeforeDelete(); // remove or simplify at least cross referenced links
2144 i_objectsToRemove.insert(obj);
2145 //sLog.outDebug("Object (GUID: %u TypeId: %u ) added to removing list.",obj->GetGUIDLow(),obj->GetTypeId());
2148 void Map::RemoveAllObjectsInRemoveList()
2150 if(i_objectsToRemove.empty())
2151 return;
2153 //sLog.outDebug("Object remover 1 check.");
2154 while(!i_objectsToRemove.empty())
2156 WorldObject* obj = *i_objectsToRemove.begin();
2157 i_objectsToRemove.erase(i_objectsToRemove.begin());
2159 switch(obj->GetTypeId())
2161 case TYPEID_CORPSE:
2163 // ??? WTF
2164 Corpse* corpse = GetCorpse(obj->GetGUID());
2165 if (!corpse)
2166 sLog.outError("Try delete corpse/bones %u that not in map", obj->GetGUIDLow());
2167 else
2168 Remove(corpse,true);
2169 break;
2171 case TYPEID_DYNAMICOBJECT:
2172 Remove((DynamicObject*)obj,true);
2173 break;
2174 case TYPEID_GAMEOBJECT:
2175 Remove((GameObject*)obj,true);
2176 break;
2177 case TYPEID_UNIT:
2178 Remove((Creature*)obj,true);
2179 break;
2180 default:
2181 sLog.outError("Non-grid object (TypeId: %u) in grid object removing list, ignored.",obj->GetTypeId());
2182 break;
2185 //sLog.outDebug("Object remover 2 check.");
2188 uint32 Map::GetPlayersCountExceptGMs() const
2190 uint32 count = 0;
2191 for(MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
2192 if(!itr->getSource()->isGameMaster())
2193 ++count;
2194 return count;
2197 void Map::SendToPlayers(WorldPacket const* data) const
2199 for(MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
2200 itr->getSource()->GetSession()->SendPacket(data);
2203 bool Map::ActiveObjectsNearGrid(uint32 x, uint32 y) const
2205 ASSERT(x < MAX_NUMBER_OF_GRIDS);
2206 ASSERT(y < MAX_NUMBER_OF_GRIDS);
2208 CellPair cell_min(x*MAX_NUMBER_OF_CELLS, y*MAX_NUMBER_OF_CELLS);
2209 CellPair cell_max(cell_min.x_coord + MAX_NUMBER_OF_CELLS, cell_min.y_coord+MAX_NUMBER_OF_CELLS);
2211 //we must find visible range in cells so we unload only non-visible cells...
2212 float viewDist = GetVisibilityDistance();
2213 int cell_range = (int)ceilf(viewDist / SIZE_OF_GRID_CELL) + 1;
2215 cell_min << cell_range;
2216 cell_min -= cell_range;
2217 cell_max >> cell_range;
2218 cell_max += cell_range;
2220 for(MapRefManager::const_iterator iter = m_mapRefManager.begin(); iter != m_mapRefManager.end(); ++iter)
2222 Player* plr = iter->getSource();
2224 CellPair p = MaNGOS::ComputeCellPair(plr->GetPositionX(), plr->GetPositionY());
2225 if( (cell_min.x_coord <= p.x_coord && p.x_coord <= cell_max.x_coord) &&
2226 (cell_min.y_coord <= p.y_coord && p.y_coord <= cell_max.y_coord) )
2227 return true;
2230 for(ActiveNonPlayers::const_iterator iter = m_activeNonPlayers.begin(); iter != m_activeNonPlayers.end(); ++iter)
2232 WorldObject* obj = *iter;
2234 CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
2235 if( (cell_min.x_coord <= p.x_coord && p.x_coord <= cell_max.x_coord) &&
2236 (cell_min.y_coord <= p.y_coord && p.y_coord <= cell_max.y_coord) )
2237 return true;
2240 return false;
2243 void Map::AddToActive( Creature* c )
2245 AddToActiveHelper(c);
2247 // also not allow unloading spawn grid to prevent creating creature clone at load
2248 if(!c->isPet() && c->GetDBTableGUIDLow())
2250 float x,y,z;
2251 c->GetRespawnCoord(x,y,z);
2252 GridPair p = MaNGOS::ComputeGridPair(x, y);
2253 if(getNGrid(p.x_coord, p.y_coord))
2254 getNGrid(p.x_coord, p.y_coord)->incUnloadActiveLock();
2255 else
2257 GridPair p2 = MaNGOS::ComputeGridPair(c->GetPositionX(), c->GetPositionY());
2258 sLog.outError("Active creature (GUID: %u Entry: %u) added to grid[%u,%u] but spawn grid[%u,%u] not loaded.",
2259 c->GetGUIDLow(), c->GetEntry(), p.x_coord, p.y_coord, p2.x_coord, p2.y_coord);
2264 void Map::RemoveFromActive( Creature* c )
2266 RemoveFromActiveHelper(c);
2268 // also allow unloading spawn grid
2269 if(!c->isPet() && c->GetDBTableGUIDLow())
2271 float x,y,z;
2272 c->GetRespawnCoord(x,y,z);
2273 GridPair p = MaNGOS::ComputeGridPair(x, y);
2274 if(getNGrid(p.x_coord, p.y_coord))
2275 getNGrid(p.x_coord, p.y_coord)->decUnloadActiveLock();
2276 else
2278 GridPair p2 = MaNGOS::ComputeGridPair(c->GetPositionX(), c->GetPositionY());
2279 sLog.outError("Active creature (GUID: %u Entry: %u) removed from grid[%u,%u] but spawn grid[%u,%u] not loaded.",
2280 c->GetGUIDLow(), c->GetEntry(), p.x_coord, p.y_coord, p2.x_coord, p2.y_coord);
2285 template void Map::Add(Corpse *);
2286 template void Map::Add(Creature *);
2287 template void Map::Add(GameObject *);
2288 template void Map::Add(DynamicObject *);
2290 template void Map::Remove(Corpse *,bool);
2291 template void Map::Remove(Creature *,bool);
2292 template void Map::Remove(GameObject *, bool);
2293 template void Map::Remove(DynamicObject *, bool);
2295 /* ******* Dungeon Instance Maps ******* */
2297 InstanceMap::InstanceMap(uint32 id, time_t expiry, uint32 InstanceId, uint8 SpawnMode, Map* _parent)
2298 : Map(id, expiry, InstanceId, SpawnMode, _parent),
2299 m_resetAfterUnload(false), m_unloadWhenEmpty(false),
2300 i_data(NULL), i_script_id(0)
2302 //lets initialize visibility distance for dungeons
2303 InstanceMap::InitVisibilityDistance();
2305 // the timer is started by default, and stopped when the first player joins
2306 // this make sure it gets unloaded if for some reason no player joins
2307 m_unloadTimer = std::max(sWorld.getConfig(CONFIG_UINT32_INSTANCE_UNLOAD_DELAY), (uint32)MIN_UNLOAD_DELAY);
2310 InstanceMap::~InstanceMap()
2312 if(i_data)
2314 delete i_data;
2315 i_data = NULL;
2319 void InstanceMap::InitVisibilityDistance()
2321 //init visibility distance for instances
2322 m_VisibleDistance = World::GetMaxVisibleDistanceInInstances();
2326 Do map specific checks to see if the player can enter
2328 bool InstanceMap::CanEnter(Player *player)
2330 if(player->GetMapRef().getTarget() == this)
2332 sLog.outError("InstanceMap::CanEnter - player %s(%u) already in map %d,%d,%d!", player->GetName(), player->GetGUIDLow(), GetId(), GetInstanceId(), GetSpawnMode());
2333 assert(false);
2334 return false;
2337 // cannot enter if the instance is full (player cap), GMs don't count
2338 uint32 maxPlayers = GetMaxPlayers();
2339 if (!player->isGameMaster() && GetPlayersCountExceptGMs() >= maxPlayers)
2341 sLog.outDetail("MAP: Instance '%u' of map '%s' cannot have more than '%u' players. Player '%s' rejected", GetInstanceId(), GetMapName(), maxPlayers, player->GetName());
2342 player->SendTransferAborted(GetId(), TRANSFER_ABORT_MAX_PLAYERS);
2343 return false;
2346 // cannot enter while players in the instance are in combat
2347 Group *pGroup = player->GetGroup();
2348 if(pGroup && pGroup->InCombatToInstance(GetInstanceId()) && player->isAlive() && player->GetMapId() != GetId())
2350 player->SendTransferAborted(GetId(), TRANSFER_ABORT_ZONE_IN_COMBAT);
2351 return false;
2354 return Map::CanEnter(player);
2358 Do map specific checks and add the player to the map if successful.
2360 bool InstanceMap::Add(Player *player)
2362 // TODO: Not sure about checking player level: already done in HandleAreaTriggerOpcode
2363 // GMs still can teleport player in instance.
2364 // Is it needed?
2367 Guard guard(*this);
2368 if(!CanEnter(player))
2369 return false;
2371 // Dungeon only code
2372 if(IsDungeon())
2374 // get or create an instance save for the map
2375 InstanceSave *mapSave = sInstanceSaveMgr.GetInstanceSave(GetInstanceId());
2376 if(!mapSave)
2378 sLog.outDetail("InstanceMap::Add: creating instance save for map %d spawnmode %d with instance id %d", GetId(), GetSpawnMode(), GetInstanceId());
2379 mapSave = sInstanceSaveMgr.AddInstanceSave(GetId(), GetInstanceId(), Difficulty(GetSpawnMode()), 0, true);
2382 // check for existing instance binds
2383 InstancePlayerBind *playerBind = player->GetBoundInstance(GetId(), Difficulty(GetSpawnMode()));
2384 if(playerBind && playerBind->perm)
2386 // cannot enter other instances if bound permanently
2387 if(playerBind->save != mapSave)
2389 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());
2390 assert(false);
2393 else
2395 Group *pGroup = player->GetGroup();
2396 if(pGroup)
2398 // solo saves should be reset when entering a group
2399 InstanceGroupBind *groupBind = pGroup->GetBoundInstance(this);
2400 if(playerBind)
2402 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());
2403 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());
2404 assert(false);
2406 // bind to the group or keep using the group save
2407 if(!groupBind)
2408 pGroup->BindToInstance(mapSave, false);
2409 else
2411 // cannot jump to a different instance without resetting it
2412 if(groupBind->save != mapSave)
2414 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());
2415 if(mapSave)
2416 sLog.outError("MapSave players: %d, group count: %d", mapSave->GetPlayerCount(), mapSave->GetGroupCount());
2417 else
2418 sLog.outError("MapSave NULL");
2419 if(groupBind->save)
2420 sLog.outError("GroupBind save players: %d, group count: %d", groupBind->save->GetPlayerCount(), groupBind->save->GetGroupCount());
2421 else
2422 sLog.outError("GroupBind save NULL");
2423 assert(false);
2425 // if the group/leader is permanently bound to the instance
2426 // players also become permanently bound when they enter
2427 if(groupBind->perm)
2429 WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
2430 data << uint32(0);
2431 player->GetSession()->SendPacket(&data);
2432 player->BindToInstance(mapSave, true);
2436 else
2438 // set up a solo bind or continue using it
2439 if(!playerBind)
2440 player->BindToInstance(mapSave, false);
2441 else
2442 // cannot jump to a different instance without resetting it
2443 assert(playerBind->save == mapSave);
2448 // for normal instances cancel the reset schedule when the
2449 // first player enters (no players yet)
2450 SetResetSchedule(false);
2452 sLog.outDetail("MAP: Player '%s' is entering instance '%u' of map '%s'", player->GetName(), GetInstanceId(), GetMapName());
2453 // initialize unload state
2454 m_unloadTimer = 0;
2455 m_resetAfterUnload = false;
2456 m_unloadWhenEmpty = false;
2459 // this will acquire the same mutex so it cannot be in the previous block
2460 Map::Add(player);
2462 if (i_data)
2463 i_data->OnPlayerEnter(player);
2465 return true;
2468 void InstanceMap::Update(const uint32& t_diff)
2470 Map::Update(t_diff);
2472 if(i_data)
2473 i_data->Update(t_diff);
2476 void InstanceMap::Remove(Player *player, bool remove)
2478 sLog.outDetail("MAP: Removing player '%s' from instance '%u' of map '%s' before relocating to other map", player->GetName(), GetInstanceId(), GetMapName());
2479 //if last player set unload timer
2480 if(!m_unloadTimer && m_mapRefManager.getSize() == 1)
2481 m_unloadTimer = m_unloadWhenEmpty ? MIN_UNLOAD_DELAY : std::max(sWorld.getConfig(CONFIG_UINT32_INSTANCE_UNLOAD_DELAY), (uint32)MIN_UNLOAD_DELAY);
2482 Map::Remove(player, remove);
2483 // for normal instances schedule the reset after all players have left
2484 SetResetSchedule(true);
2487 void InstanceMap::CreateInstanceData(bool load)
2489 if(i_data != NULL)
2490 return;
2492 InstanceTemplate const* mInstance = ObjectMgr::GetInstanceTemplate(GetId());
2493 if (mInstance)
2495 i_script_id = mInstance->script_id;
2496 i_data = Script->CreateInstanceData(this);
2499 if(!i_data)
2500 return;
2502 if(load)
2504 // TODO: make a global storage for this
2505 QueryResult* result = CharacterDatabase.PQuery("SELECT data FROM instance WHERE map = '%u' AND id = '%u'", GetId(), i_InstanceId);
2506 if (result)
2508 Field* fields = result->Fetch();
2509 const char* data = fields[0].GetString();
2510 if(data)
2512 sLog.outDebug("Loading instance data for `%s` with id %u", sObjectMgr.GetScriptName(i_script_id), i_InstanceId);
2513 i_data->Load(data);
2515 delete result;
2518 else
2520 sLog.outDebug("New instance data, \"%s\" ,initialized!", sObjectMgr.GetScriptName(i_script_id));
2521 i_data->Initialize();
2526 Returns true if there are no players in the instance
2528 bool InstanceMap::Reset(uint8 method)
2530 // note: since the map may not be loaded when the instance needs to be reset
2531 // the instance must be deleted from the DB by InstanceSaveManager
2533 if(HavePlayers())
2535 if(method == INSTANCE_RESET_ALL)
2537 // notify the players to leave the instance so it can be reset
2538 for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
2539 itr->getSource()->SendResetFailedNotify(GetId());
2541 else
2543 if(method == INSTANCE_RESET_GLOBAL)
2545 // set the homebind timer for players inside (1 minute)
2546 for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
2547 itr->getSource()->m_InstanceValid = false;
2550 // the unload timer is not started
2551 // instead the map will unload immediately after the players have left
2552 m_unloadWhenEmpty = true;
2553 m_resetAfterUnload = true;
2556 else
2558 // unloaded at next update
2559 m_unloadTimer = MIN_UNLOAD_DELAY;
2560 m_resetAfterUnload = true;
2563 return m_mapRefManager.isEmpty();
2566 void InstanceMap::PermBindAllPlayers(Player *player)
2568 if(!IsDungeon())
2569 return;
2571 InstanceSave *save = sInstanceSaveMgr.GetInstanceSave(GetInstanceId());
2572 if(!save)
2574 sLog.outError("Cannot bind players, no instance save available for map!");
2575 return;
2578 Group *group = player->GetGroup();
2579 // group members outside the instance group don't get bound
2580 for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
2582 Player* plr = itr->getSource();
2583 // players inside an instance cannot be bound to other instances
2584 // some players may already be permanently bound, in this case nothing happens
2585 InstancePlayerBind *bind = plr->GetBoundInstance(save->GetMapId(), save->GetDifficulty());
2586 if(!bind || !bind->perm)
2588 plr->BindToInstance(save, true);
2589 WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
2590 data << uint32(0);
2591 plr->GetSession()->SendPacket(&data);
2594 // if the leader is not in the instance the group will not get a perm bind
2595 if(group && group->GetLeaderGUID() == plr->GetGUID())
2596 group->BindToInstance(save, true);
2600 void InstanceMap::UnloadAll(bool pForce)
2602 if(HavePlayers())
2604 sLog.outError("InstanceMap::UnloadAll: there are still players in the instance at unload, should not happen!");
2605 for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
2607 Player* plr = itr->getSource();
2608 plr->TeleportToHomebind();
2612 if(m_resetAfterUnload == true)
2613 sObjectMgr.DeleteRespawnTimeForInstance(GetInstanceId());
2615 Map::UnloadAll(pForce);
2618 void InstanceMap::SendResetWarnings(uint32 timeLeft) const
2620 for(MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
2621 itr->getSource()->SendInstanceResetWarning(GetId(), itr->getSource()->GetDifficulty(IsRaid()), timeLeft);
2624 void InstanceMap::SetResetSchedule(bool on)
2626 // only for normal instances
2627 // the reset time is only scheduled when there are no payers inside
2628 // it is assumed that the reset time will rarely (if ever) change while the reset is scheduled
2629 if(IsDungeon() && !HavePlayers() && !IsRaidOrHeroicDungeon())
2631 InstanceSave *save = sInstanceSaveMgr.GetInstanceSave(GetInstanceId());
2632 if(!save) sLog.outError("InstanceMap::SetResetSchedule: cannot turn schedule %s, no save available for instance %d of %d", on ? "on" : "off", GetInstanceId(), GetId());
2633 else sInstanceSaveMgr.ScheduleReset(on, save->GetResetTime(), InstanceSaveManager::InstResetEvent(0, GetId(), Difficulty(GetSpawnMode()), GetInstanceId()));
2637 /* ******* Battleground Instance Maps ******* */
2639 BattleGroundMap::BattleGroundMap(uint32 id, time_t expiry, uint32 InstanceId, Map* _parent, uint8 spawnMode)
2640 : Map(id, expiry, InstanceId, spawnMode, _parent)
2642 //lets initialize visibility distance for BG/Arenas
2643 BattleGroundMap::InitVisibilityDistance();
2646 BattleGroundMap::~BattleGroundMap()
2650 void BattleGroundMap::InitVisibilityDistance()
2652 //init visibility distance for BG/Arenas
2653 m_VisibleDistance = World::GetMaxVisibleDistanceInBGArenas();
2656 bool BattleGroundMap::CanEnter(Player * player)
2658 if(player->GetMapRef().getTarget() == this)
2660 sLog.outError("BGMap::CanEnter - player %u already in map!", player->GetGUIDLow());
2661 assert(false);
2662 return false;
2665 if(player->GetBattleGroundId() != GetInstanceId())
2666 return false;
2668 // player number limit is checked in bgmgr, no need to do it here
2670 return Map::CanEnter(player);
2673 bool BattleGroundMap::Add(Player * player)
2676 Guard guard(*this);
2677 if(!CanEnter(player))
2678 return false;
2679 // reset instance validity, battleground maps do not homebind
2680 player->m_InstanceValid = true;
2682 return Map::Add(player);
2685 void BattleGroundMap::Remove(Player *player, bool remove)
2687 sLog.outDetail("MAP: Removing player '%s' from bg '%u' of map '%s' before relocating to other map", player->GetName(), GetInstanceId(), GetMapName());
2688 Map::Remove(player, remove);
2691 void BattleGroundMap::SetUnload()
2693 m_unloadTimer = MIN_UNLOAD_DELAY;
2696 void BattleGroundMap::UnloadAll(bool pForce)
2698 while(HavePlayers())
2700 if(Player * plr = m_mapRefManager.getFirst()->getSource())
2702 plr->TeleportTo(plr->GetBattleGroundEntryPoint());
2703 // TeleportTo removes the player from this map (if the map exists) -> calls BattleGroundMap::Remove -> invalidates the iterator.
2704 // just in case, remove the player from the list explicitly here as well to prevent a possible infinite loop
2705 // note that this remove is not needed if the code works well in other places
2706 plr->GetMapRef().unlink();
2710 Map::UnloadAll(pForce);
2713 /// Put scripts in the execution queue
2714 void Map::ScriptsStart(ScriptMapMap const& scripts, uint32 id, Object* source, Object* target)
2716 ///- Find the script map
2717 ScriptMapMap::const_iterator s = scripts.find(id);
2718 if (s == scripts.end())
2719 return;
2721 // prepare static data
2722 uint64 sourceGUID = source->GetGUID();
2723 uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
2724 uint64 ownerGUID = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
2726 ///- Schedule script execution for all scripts in the script map
2727 ScriptMap const *s2 = &(s->second);
2728 bool immedScript = false;
2729 for (ScriptMap::const_iterator iter = s2->begin(); iter != s2->end(); ++iter)
2731 ScriptAction sa;
2732 sa.sourceGUID = sourceGUID;
2733 sa.targetGUID = targetGUID;
2734 sa.ownerGUID = ownerGUID;
2736 sa.script = &iter->second;
2737 m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(time_t(sWorld.GetGameTime() + iter->first), sa));
2738 if (iter->first == 0)
2739 immedScript = true;
2741 sWorld.IncreaseScheduledScriptsCount();
2743 ///- If one of the effects should be immediate, launch the script execution
2744 if (immedScript)
2745 ScriptsProcess();
2748 void Map::ScriptCommandStart(ScriptInfo const& script, uint32 delay, Object* source, Object* target)
2750 // NOTE: script record _must_ exist until command executed
2752 // prepare static data
2753 uint64 sourceGUID = source->GetGUID();
2754 uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
2755 uint64 ownerGUID = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
2757 ScriptAction sa;
2758 sa.sourceGUID = sourceGUID;
2759 sa.targetGUID = targetGUID;
2760 sa.ownerGUID = ownerGUID;
2762 sa.script = &script;
2763 m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(time_t(sWorld.GetGameTime() + delay), sa));
2765 sWorld.IncreaseScheduledScriptsCount();
2767 ///- If effects should be immediate, launch the script execution
2768 if(delay == 0)
2769 ScriptsProcess();
2772 /// Process queued scripts
2773 void Map::ScriptsProcess()
2775 if (m_scriptSchedule.empty())
2776 return;
2778 ///- Process overdue queued scripts
2779 std::multimap<time_t, ScriptAction>::iterator iter = m_scriptSchedule.begin();
2780 // ok as multimap is a *sorted* associative container
2781 while (!m_scriptSchedule.empty() && (iter->first <= sWorld.GetGameTime()))
2783 ScriptAction const& step = iter->second;
2785 Object* source = NULL;
2787 if(step.sourceGUID)
2789 switch(GUID_HIPART(step.sourceGUID))
2791 case HIGHGUID_ITEM:
2792 // case HIGHGUID_CONTAINER: ==HIGHGUID_ITEM
2794 Player* player = HashMapHolder<Player>::Find(step.ownerGUID);
2795 if(player)
2796 source = player->GetItemByGuid(step.sourceGUID);
2797 break;
2799 case HIGHGUID_UNIT:
2800 source = GetCreature(step.sourceGUID);
2801 break;
2802 case HIGHGUID_PET:
2803 source = GetPet(step.sourceGUID);
2804 break;
2805 case HIGHGUID_VEHICLE:
2806 source = GetVehicle(step.sourceGUID);
2807 break;
2808 case HIGHGUID_PLAYER:
2809 source = HashMapHolder<Player>::Find(step.sourceGUID);
2810 break;
2811 case HIGHGUID_GAMEOBJECT:
2812 source = GetGameObject(step.sourceGUID);
2813 break;
2814 case HIGHGUID_CORPSE:
2815 source = HashMapHolder<Corpse>::Find(step.sourceGUID);
2816 break;
2817 default:
2818 sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.sourceGUID));
2819 break;
2823 if(source && !source->IsInWorld()) source = NULL;
2825 Object* target = NULL;
2827 if(step.targetGUID)
2829 switch(GUID_HIPART(step.targetGUID))
2831 case HIGHGUID_UNIT:
2832 target = GetCreature(step.targetGUID);
2833 break;
2834 case HIGHGUID_PET:
2835 target = GetPet(step.targetGUID);
2836 break;
2837 case HIGHGUID_VEHICLE:
2838 target = GetVehicle(step.targetGUID);
2839 break;
2840 case HIGHGUID_PLAYER: // empty GUID case also
2841 target = HashMapHolder<Player>::Find(step.targetGUID);
2842 break;
2843 case HIGHGUID_GAMEOBJECT:
2844 target = GetGameObject(step.targetGUID);
2845 break;
2846 case HIGHGUID_CORPSE:
2847 target = HashMapHolder<Corpse>::Find(step.targetGUID);
2848 break;
2849 default:
2850 sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.targetGUID));
2851 break;
2855 if(target && !target->IsInWorld()) target = NULL;
2857 switch (step.script->command)
2859 case SCRIPT_COMMAND_TALK:
2861 if(!source)
2863 sLog.outError("SCRIPT_COMMAND_TALK call for NULL creature.");
2864 break;
2867 if(source->GetTypeId()!=TYPEID_UNIT)
2869 sLog.outError("SCRIPT_COMMAND_TALK call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
2870 break;
2873 uint64 unit_target = target ? target->GetGUID() : 0;
2875 //datalong 0=normal say, 1=whisper, 2=yell, 3=emote text
2876 switch(step.script->datalong)
2878 case 0: // Say
2879 ((Creature *)source)->Say(step.script->dataint, LANG_UNIVERSAL, unit_target);
2880 break;
2881 case 1: // Whisper
2882 if(!unit_target)
2884 sLog.outError("SCRIPT_COMMAND_TALK attempt to whisper (%u) NULL, skipping.",step.script->datalong);
2885 break;
2887 ((Creature *)source)->Whisper(step.script->dataint,unit_target);
2888 break;
2889 case 2: // Yell
2890 ((Creature *)source)->Yell(step.script->dataint, LANG_UNIVERSAL, unit_target);
2891 break;
2892 case 3: // Emote text
2893 ((Creature *)source)->TextEmote(step.script->dataint, unit_target);
2894 break;
2895 default:
2896 break; // must be already checked at load
2898 break;
2901 case SCRIPT_COMMAND_EMOTE:
2902 if(!source)
2904 sLog.outError("SCRIPT_COMMAND_EMOTE call for NULL creature.");
2905 break;
2908 if(source->GetTypeId()!=TYPEID_UNIT)
2910 sLog.outError("SCRIPT_COMMAND_EMOTE call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
2911 break;
2914 ((Creature *)source)->HandleEmoteCommand(step.script->datalong);
2915 break;
2916 case SCRIPT_COMMAND_FIELD_SET:
2917 if(!source)
2919 sLog.outError("SCRIPT_COMMAND_FIELD_SET call for NULL object.");
2920 break;
2922 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
2924 sLog.outError("SCRIPT_COMMAND_FIELD_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
2925 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
2926 break;
2929 source->SetUInt32Value(step.script->datalong, step.script->datalong2);
2930 break;
2931 case SCRIPT_COMMAND_MOVE_TO:
2932 if(!source)
2934 sLog.outError("SCRIPT_COMMAND_MOVE_TO call for NULL creature.");
2935 break;
2938 if(source->GetTypeId()!=TYPEID_UNIT)
2940 sLog.outError("SCRIPT_COMMAND_MOVE_TO call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
2941 break;
2943 ((Unit*)source)->MonsterMoveWithSpeed(step.script->x, step.script->y, step.script->z, step.script->datalong2 );
2944 break;
2945 case SCRIPT_COMMAND_FLAG_SET:
2946 if(!source)
2948 sLog.outError("SCRIPT_COMMAND_FLAG_SET call for NULL object.");
2949 break;
2951 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
2953 sLog.outError("SCRIPT_COMMAND_FLAG_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
2954 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
2955 break;
2958 source->SetFlag(step.script->datalong, step.script->datalong2);
2959 break;
2960 case SCRIPT_COMMAND_FLAG_REMOVE:
2961 if(!source)
2963 sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for NULL object.");
2964 break;
2966 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
2968 sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for wrong field %u (max count: %u) in object (TypeId: %u).",
2969 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
2970 break;
2973 source->RemoveFlag(step.script->datalong, step.script->datalong2);
2974 break;
2976 case SCRIPT_COMMAND_TELEPORT_TO:
2978 // accept player in any one from target/source arg
2979 if (!target && !source)
2981 sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for NULL object.");
2982 break;
2985 // must be only Player
2986 if((!target || target->GetTypeId() != TYPEID_PLAYER) && (!source || source->GetTypeId() != TYPEID_PLAYER))
2988 sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for non-player (TypeIdSource: %u)(TypeIdTarget: %u), skipping.", source ? source->GetTypeId() : 0, target ? target->GetTypeId() : 0);
2989 break;
2992 Player* pSource = target && target->GetTypeId() == TYPEID_PLAYER ? (Player*)target : (Player*)source;
2994 pSource->TeleportTo(step.script->datalong, step.script->x, step.script->y, step.script->z, step.script->o);
2995 break;
2998 case SCRIPT_COMMAND_KILL_CREDIT:
3000 // accept player in any one from target/source arg
3001 if (!target && !source)
3003 sLog.outError("SCRIPT_COMMAND_KILL_CREDIT call for NULL object.");
3004 break;
3007 // must be only Player
3008 if((!target || target->GetTypeId() != TYPEID_PLAYER) && (!source || source->GetTypeId() != TYPEID_PLAYER))
3010 sLog.outError("SCRIPT_COMMAND_KILL_CREDIT call for non-player (TypeIdSource: %u)(TypeIdTarget: %u), skipping.", source ? source->GetTypeId() : 0, target ? target->GetTypeId() : 0);
3011 break;
3014 Player* pSource = target && target->GetTypeId() == TYPEID_PLAYER ? (Player*)target : (Player*)source;
3016 if (step.script->datalong2)
3018 pSource->RewardPlayerAndGroupAtEvent(step.script->datalong, pSource);
3020 else
3022 pSource->KilledMonsterCredit(step.script->datalong, 0);
3025 break;
3028 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
3030 if(!step.script->datalong) // creature not specified
3032 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL creature.");
3033 break;
3036 if(!source)
3038 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL world object.");
3039 break;
3042 WorldObject* summoner = dynamic_cast<WorldObject*>(source);
3044 if(!summoner)
3046 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
3047 break;
3050 float x = step.script->x;
3051 float y = step.script->y;
3052 float z = step.script->z;
3053 float o = step.script->o;
3055 Creature* pCreature = summoner->SummonCreature(step.script->datalong, x, y, z, o,TEMPSUMMON_TIMED_OR_DEAD_DESPAWN,step.script->datalong2);
3056 if (!pCreature)
3058 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON failed for creature (entry: %u).",step.script->datalong);
3059 break;
3062 break;
3065 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
3067 if(!step.script->datalong) // gameobject not specified
3069 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL gameobject.");
3070 break;
3073 if(!source)
3075 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL world object.");
3076 break;
3079 WorldObject* summoner = dynamic_cast<WorldObject*>(source);
3081 if(!summoner)
3083 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
3084 break;
3087 GameObject *go = NULL;
3088 int32 time_to_despawn = step.script->datalong2<5 ? 5 : (int32)step.script->datalong2;
3090 CellPair p(MaNGOS::ComputeCellPair(summoner->GetPositionX(), summoner->GetPositionY()));
3091 Cell cell(p);
3092 cell.data.Part.reserved = ALL_DISTRICT;
3094 MaNGOS::GameObjectWithDbGUIDCheck go_check(*summoner,step.script->datalong);
3095 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(summoner, go,go_check);
3097 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
3098 cell.Visit(p, object_checker, *summoner->GetMap());
3100 if ( !go )
3102 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT failed for gameobject(guid: %u).", step.script->datalong);
3103 break;
3106 if( go->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE ||
3107 go->GetGoType()==GAMEOBJECT_TYPE_DOOR ||
3108 go->GetGoType()==GAMEOBJECT_TYPE_BUTTON ||
3109 go->GetGoType()==GAMEOBJECT_TYPE_TRAP )
3111 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT can not be used with gameobject of type %u (guid: %u).", uint32(go->GetGoType()), step.script->datalong);
3112 break;
3115 if( go->isSpawned() )
3116 break; //gameobject already spawned
3118 go->SetLootState(GO_READY);
3119 go->SetRespawnTime(time_to_despawn); //despawn object in ? seconds
3121 go->GetMap()->Add(go);
3122 break;
3124 case SCRIPT_COMMAND_OPEN_DOOR:
3126 if(!step.script->datalong) // door not specified
3128 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL door.");
3129 break;
3132 if(!source)
3134 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL unit.");
3135 break;
3138 if(!source->isType(TYPEMASK_UNIT)) // must be any Unit (creature or player)
3140 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
3141 break;
3144 Unit* caster = (Unit*)source;
3146 GameObject *door = NULL;
3147 int32 time_to_close = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
3149 CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
3150 Cell cell(p);
3151 cell.data.Part.reserved = ALL_DISTRICT;
3153 MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
3154 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(caster,door,go_check);
3156 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
3157 cell.Visit(p, object_checker, *caster->GetMap());
3159 if (!door)
3161 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for gameobject(guid: %u).", step.script->datalong);
3162 break;
3164 if (door->GetGoType() != GAMEOBJECT_TYPE_DOOR)
3166 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for non-door(GoType: %u).", door->GetGoType());
3167 break;
3170 if (door->GetGoState() != GO_STATE_READY)
3171 break; //door already open
3173 door->UseDoorOrButton(time_to_close);
3175 if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
3176 ((GameObject*)target)->UseDoorOrButton(time_to_close);
3177 break;
3179 case SCRIPT_COMMAND_CLOSE_DOOR:
3181 if(!step.script->datalong) // guid for door not specified
3183 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL door.");
3184 break;
3187 if(!source)
3189 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL unit.");
3190 break;
3193 if(!source->isType(TYPEMASK_UNIT)) // must be any Unit (creature or player)
3195 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
3196 break;
3199 Unit* caster = (Unit*)source;
3201 GameObject *door = NULL;
3202 int32 time_to_open = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
3204 CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
3205 Cell cell(p);
3206 cell.data.Part.reserved = ALL_DISTRICT;
3208 MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
3209 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(caster,door,go_check);
3211 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
3212 cell.Visit(p, object_checker, *caster->GetMap());
3214 if ( !door )
3216 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for gameobject(guid: %u).", step.script->datalong);
3217 break;
3219 if ( door->GetGoType() != GAMEOBJECT_TYPE_DOOR )
3221 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for non-door(GoType: %u).", door->GetGoType());
3222 break;
3225 if( door->GetGoState() == GO_STATE_READY )
3226 break; //door already closed
3228 door->UseDoorOrButton(time_to_open);
3230 if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
3231 ((GameObject*)target)->UseDoorOrButton(time_to_open);
3233 break;
3235 case SCRIPT_COMMAND_QUEST_EXPLORED:
3237 if(!source)
3239 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL source.");
3240 break;
3243 if(!target)
3245 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL target.");
3246 break;
3249 // when script called for item spell casting then target == (unit or GO) and source is player
3250 WorldObject* worldObject;
3251 Player* player;
3253 if(target->GetTypeId()==TYPEID_PLAYER)
3255 if(source->GetTypeId()!=TYPEID_UNIT && source->GetTypeId()!=TYPEID_GAMEOBJECT)
3257 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",source->GetTypeId());
3258 break;
3261 worldObject = (WorldObject*)source;
3262 player = (Player*)target;
3264 else
3266 if(target->GetTypeId()!=TYPEID_UNIT && target->GetTypeId()!=TYPEID_GAMEOBJECT)
3268 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
3269 break;
3272 if(source->GetTypeId()!=TYPEID_PLAYER)
3274 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-player(TypeId: %u), skipping.",source->GetTypeId());
3275 break;
3278 worldObject = (WorldObject*)target;
3279 player = (Player*)source;
3282 // quest id and flags checked at script loading
3283 if( (worldObject->GetTypeId()!=TYPEID_UNIT || ((Unit*)worldObject)->isAlive()) &&
3284 (step.script->datalong2==0 || worldObject->IsWithinDistInMap(player,float(step.script->datalong2))) )
3285 player->AreaExploredOrEventHappens(step.script->datalong);
3286 else
3287 player->FailQuest(step.script->datalong);
3289 break;
3292 case SCRIPT_COMMAND_ACTIVATE_OBJECT:
3294 if(!source)
3296 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT must have source caster.");
3297 break;
3300 if(!source->isType(TYPEMASK_UNIT))
3302 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
3303 break;
3306 if(!target)
3308 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for NULL gameobject.");
3309 break;
3312 if(target->GetTypeId()!=TYPEID_GAMEOBJECT)
3314 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
3315 break;
3318 Unit* caster = (Unit*)source;
3320 GameObject *go = (GameObject*)target;
3322 go->Use(caster);
3323 break;
3326 case SCRIPT_COMMAND_REMOVE_AURA:
3328 Object* cmdTarget = step.script->datalong2 ? source : target;
3330 if(!cmdTarget)
3332 sLog.outError("SCRIPT_COMMAND_REMOVE_AURA call for NULL %s.",step.script->datalong2 ? "source" : "target");
3333 break;
3336 if(!cmdTarget->isType(TYPEMASK_UNIT))
3338 sLog.outError("SCRIPT_COMMAND_REMOVE_AURA %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 ? "source" : "target",cmdTarget->GetTypeId());
3339 break;
3342 ((Unit*)cmdTarget)->RemoveAurasDueToSpell(step.script->datalong);
3343 break;
3346 case SCRIPT_COMMAND_CAST_SPELL:
3348 if(!source)
3350 sLog.outError("SCRIPT_COMMAND_CAST_SPELL must have source caster.");
3351 break;
3354 Object* cmdTarget = step.script->datalong2 & 0x01 ? source : target;
3356 if(!cmdTarget)
3358 sLog.outError("SCRIPT_COMMAND_CAST_SPELL call for NULL %s.",step.script->datalong2 & 0x01 ? "source" : "target");
3359 break;
3362 if(!cmdTarget->isType(TYPEMASK_UNIT))
3364 sLog.outError("SCRIPT_COMMAND_CAST_SPELL %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 & 0x01 ? "source" : "target",cmdTarget->GetTypeId());
3365 break;
3368 Unit* spellTarget = (Unit*)cmdTarget;
3370 Object* cmdSource = step.script->datalong2 & 0x02 ? target : source;
3372 if(!cmdSource)
3374 sLog.outError("SCRIPT_COMMAND_CAST_SPELL call for NULL %s.",step.script->datalong2 & 0x02 ? "target" : "source");
3375 break;
3378 if(!cmdSource->isType(TYPEMASK_UNIT))
3380 sLog.outError("SCRIPT_COMMAND_CAST_SPELL %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 & 0x02 ? "target" : "source", cmdSource->GetTypeId());
3381 break;
3384 Unit* spellSource = (Unit*)cmdSource;
3386 //TODO: when GO cast implemented, code below must be updated accordingly to also allow GO spell cast
3387 spellSource->CastSpell(spellTarget,step.script->datalong,false);
3389 break;
3392 case SCRIPT_COMMAND_PLAY_SOUND:
3394 if(!source)
3396 sLog.outError("SCRIPT_COMMAND_PLAY_SOUND call for NULL creature.");
3397 break;
3400 WorldObject* pSource = dynamic_cast<WorldObject*>(source);
3401 if(!pSource)
3403 sLog.outError("SCRIPT_COMMAND_PLAY_SOUND call for non-world object (TypeId: %u), skipping.",source->GetTypeId());
3404 break;
3407 // bitmask: 0/1=anyone/target, 0/2=with distance dependent
3408 Player* pTarget = NULL;
3409 if(step.script->datalong2 & 1)
3411 if(!target)
3413 sLog.outError("SCRIPT_COMMAND_PLAY_SOUND in targeted mode call for NULL target.");
3414 break;
3417 if(target->GetTypeId()!=TYPEID_PLAYER)
3419 sLog.outError("SCRIPT_COMMAND_PLAY_SOUND in targeted mode call for non-player (TypeId: %u), skipping.",target->GetTypeId());
3420 break;
3423 pTarget = (Player*)target;
3426 // bitmask: 0/1=anyone/target, 0/2=with distance dependent
3427 if(step.script->datalong2 & 2)
3428 pSource->PlayDistanceSound(step.script->datalong,pTarget);
3429 else
3430 pSource->PlayDirectSound(step.script->datalong,pTarget);
3431 break;
3433 default:
3434 sLog.outError("Unknown script command %u called.",step.script->command);
3435 break;
3438 m_scriptSchedule.erase(iter);
3439 sWorld.DecreaseScheduledScriptCount();
3441 iter = m_scriptSchedule.begin();
3443 return;
3446 Creature* Map::GetCreature(uint64 guid)
3448 return m_objectsStore.find<Creature>(guid, (Creature*)NULL);
3451 Vehicle* Map::GetVehicle(uint64 guid)
3453 return m_objectsStore.find<Vehicle>(guid, (Vehicle*)NULL);
3456 Pet* Map::GetPet(uint64 guid)
3458 return m_objectsStore.find<Pet>(guid, (Pet*)NULL);
3461 Corpse* Map::GetCorpse(uint64 guid)
3463 Corpse * ret = ObjectAccessor::GetCorpseInMap(guid,GetId());
3464 if (!ret)
3465 return NULL;
3466 if (ret->GetInstanceId() != GetInstanceId())
3467 return NULL;
3468 return ret;
3471 Creature* Map::GetCreatureOrPetOrVehicle(uint64 guid)
3473 if (IS_PLAYER_GUID(guid))
3474 return NULL;
3476 if (IS_PET_GUID(guid))
3477 return GetPet(guid);
3479 if (IS_VEHICLE_GUID(guid))
3480 return GetVehicle(guid);
3482 return GetCreature(guid);
3485 GameObject* Map::GetGameObject(uint64 guid)
3487 return m_objectsStore.find<GameObject>(guid, (GameObject*)NULL);
3490 DynamicObject* Map::GetDynamicObject(uint64 guid)
3492 return m_objectsStore.find<DynamicObject>(guid, (DynamicObject*)NULL);
3495 WorldObject* Map::GetWorldObject(uint64 guid)
3497 switch(GUID_HIPART(guid))
3499 case HIGHGUID_PLAYER: return ObjectAccessor::FindPlayer(guid);
3500 case HIGHGUID_GAMEOBJECT: return GetGameObject(guid);
3501 case HIGHGUID_UNIT: return GetCreature(guid);
3502 case HIGHGUID_PET: return GetPet(guid);
3503 case HIGHGUID_VEHICLE: return GetVehicle(guid);
3504 case HIGHGUID_DYNAMICOBJECT:return GetDynamicObject(guid);
3505 case HIGHGUID_CORPSE: return GetCorpse(guid);
3506 case HIGHGUID_MO_TRANSPORT:
3507 case HIGHGUID_TRANSPORT:
3508 default: break;
3511 return NULL;
3514 void Map::SendObjectUpdates()
3516 UpdateDataMapType update_players;
3518 while(!i_objectsToClientUpdate.empty())
3520 Object* obj = *i_objectsToClientUpdate.begin();
3521 i_objectsToClientUpdate.erase(i_objectsToClientUpdate.begin());
3522 obj->BuildUpdateData(update_players);
3525 WorldPacket packet; // here we allocate a std::vector with a size of 0x10000
3526 for(UpdateDataMapType::iterator iter = update_players.begin(); iter != update_players.end(); ++iter)
3528 iter->second.BuildPacket(&packet);
3529 iter->first->GetSession()->SendPacket(&packet);
3530 packet.clear(); // clean the string
3534 uint32 Map::GenerateLocalLowGuid(HighGuid guidhigh)
3536 // TODO: for map local guid counters possible force reload map instead shutdown server at guid counter overflow
3537 switch(guidhigh)
3539 case HIGHGUID_DYNAMICOBJECT:
3540 if (m_hiDynObjectGuid >= 0xFFFFFFFE)
3542 sLog.outError("DynamicObject guid overflow!! Can't continue, shutting down server. ");
3543 World::StopNow(ERROR_EXIT_CODE);
3545 return m_hiDynObjectGuid++;
3546 case HIGHGUID_PET:
3547 if(m_hiPetGuid>=0x00FFFFFE)
3549 sLog.outError("Pet guid overflow!! Can't continue, shutting down server. ");
3550 World::StopNow(ERROR_EXIT_CODE);
3552 return m_hiPetGuid++;
3553 case HIGHGUID_VEHICLE:
3554 if(m_hiVehicleGuid>=0x00FFFFFF)
3556 sLog.outError("Vehicle guid overflow!! Can't continue, shutting down server. ");
3557 World::StopNow(ERROR_EXIT_CODE);
3559 return m_hiVehicleGuid++;
3560 default:
3561 ASSERT(0);
3564 ASSERT(0);
3565 return 0;