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