First Commit

For Azeroth!
This commit is contained in:
Yehonal
2016-06-26 10:39:44 +02:00
commit e8e94a0a66
3777 changed files with 1419268 additions and 0 deletions

3189
src/server/game/Maps/Map.cpp Normal file

File diff suppressed because it is too large Load Diff

783
src/server/game/Maps/Map.h Normal file
View File

@@ -0,0 +1,783 @@
/*
* Copyright (C)
* Copyright (C)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef TRINITY_MAP_H
#define TRINITY_MAP_H
// Pathfinding
#include "DetourAlloc.h"
#include "DetourNavMesh.h"
#include "DetourNavMeshQuery.h"
#include "Define.h"
#include <ace/RW_Thread_Mutex.h>
#include <ace/Thread_Mutex.h>
#include "DBCStructure.h"
#include "GridDefines.h"
#include "Cell.h"
#include "Timer.h"
#include "SharedDefines.h"
#include "GridRefManager.h"
#include "MapRefManager.h"
#include "DynamicTree.h"
#include "GameObjectModel.h"
#include "Log.h"
#include <bitset>
#include <list>
class Unit;
class WorldPacket;
class InstanceScript;
class Group;
class InstanceSave;
class Object;
class WorldObject;
class TempSummon;
class Player;
class CreatureGroup;
struct ScriptInfo;
struct ScriptAction;
struct Position;
class Battleground;
class MapInstanced;
class InstanceMap;
class BattlegroundMap;
class Transport;
class StaticTransport;
class MotionTransport;
namespace Trinity { struct ObjectUpdater; }
struct ScriptAction
{
uint64 sourceGUID;
uint64 targetGUID;
uint64 ownerGUID; // owner of source if source is item
ScriptInfo const* script; // pointer to static script data
};
// ******************************************
// Map file format defines
// ******************************************
struct map_fileheader
{
uint32 mapMagic;
uint32 versionMagic;
uint32 buildMagic;
uint32 areaMapOffset;
uint32 areaMapSize;
uint32 heightMapOffset;
uint32 heightMapSize;
uint32 liquidMapOffset;
uint32 liquidMapSize;
};
#define MAP_AREA_NO_AREA 0x0001
struct map_areaHeader
{
uint32 fourcc;
uint16 flags;
uint16 gridArea;
};
#define MAP_HEIGHT_NO_HEIGHT 0x0001
#define MAP_HEIGHT_AS_INT16 0x0002
#define MAP_HEIGHT_AS_INT8 0x0004
struct map_heightHeader
{
uint32 fourcc;
uint32 flags;
float gridHeight;
float gridMaxHeight;
};
#define MAP_LIQUID_NO_TYPE 0x0001
#define MAP_LIQUID_NO_HEIGHT 0x0002
struct map_liquidHeader
{
uint32 fourcc;
uint16 flags;
uint16 liquidType;
uint8 offsetX;
uint8 offsetY;
uint8 width;
uint8 height;
float liquidLevel;
};
enum ZLiquidStatus
{
LIQUID_MAP_NO_WATER = 0x00000000,
LIQUID_MAP_ABOVE_WATER = 0x00000001,
LIQUID_MAP_WATER_WALK = 0x00000002,
LIQUID_MAP_IN_WATER = 0x00000004,
LIQUID_MAP_UNDER_WATER = 0x00000008
};
#define MAP_LIQUID_TYPE_NO_WATER 0x00
#define MAP_LIQUID_TYPE_WATER 0x01
#define MAP_LIQUID_TYPE_OCEAN 0x02
#define MAP_LIQUID_TYPE_MAGMA 0x04
#define MAP_LIQUID_TYPE_SLIME 0x08
#define MAP_ALL_LIQUIDS (MAP_LIQUID_TYPE_WATER | MAP_LIQUID_TYPE_OCEAN | MAP_LIQUID_TYPE_MAGMA | MAP_LIQUID_TYPE_SLIME)
#define MAP_LIQUID_TYPE_DARK_WATER 0x10
#define MAP_LIQUID_TYPE_WMO_WATER 0x20
struct LiquidData
{
uint32 type_flags;
uint32 entry;
float level;
float depth_level;
};
class GridMap
{
uint32 _flags;
union{
float* m_V9;
uint16* m_uint16_V9;
uint8* m_uint8_V9;
};
union{
float* m_V8;
uint16* m_uint16_V8;
uint8* m_uint8_V8;
};
// Height level data
float _gridHeight;
float _gridIntHeightMultiplier;
// Area data
uint16* _areaMap;
// Liquid data
float _liquidLevel;
uint16* _liquidEntry;
uint8* _liquidFlags;
float* _liquidMap;
uint16 _gridArea;
uint16 _liquidType;
uint8 _liquidOffX;
uint8 _liquidOffY;
uint8 _liquidWidth;
uint8 _liquidHeight;
bool loadAreaData(FILE* in, uint32 offset, uint32 size);
bool loadHeightData(FILE* in, uint32 offset, uint32 size);
bool loadLiquidData(FILE* in, uint32 offset, uint32 size);
// Get height functions and pointers
typedef float (GridMap::*GetHeightPtr) (float x, float y) const;
GetHeightPtr _gridGetHeight;
float getHeightFromFloat(float x, float y) const;
float getHeightFromUint16(float x, float y) const;
float getHeightFromUint8(float x, float y) const;
float getHeightFromFlat(float x, float y) const;
public:
GridMap();
~GridMap();
bool loadData(char* filaname);
void unloadData();
uint16 getArea(float x, float y) const;
inline float getHeight(float x, float y) const {return (this->*_gridGetHeight)(x, y);}
float getLiquidLevel(float x, float y) const;
uint8 getTerrainType(float x, float y) const;
ZLiquidStatus getLiquidStatus(float x, float y, float z, uint8 ReqLiquidType, LiquidData* data = 0);
};
// GCC have alternative #pragma pack(N) syntax and old gcc version not support pack(push, N), also any gcc version not support it at some platform
#if defined(__GNUC__)
#pragma pack(1)
#else
#pragma pack(push, 1)
#endif
struct InstanceTemplate
{
uint32 Parent;
uint32 ScriptId;
bool AllowMount;
};
enum LevelRequirementVsMode
{
LEVELREQUIREMENT_HEROIC = 70
};
struct ZoneDynamicInfo
{
ZoneDynamicInfo() : MusicId(0), WeatherId(0), WeatherGrade(0.0f),
OverrideLightId(0), LightFadeInTime(0) { }
uint32 MusicId;
uint32 WeatherId;
float WeatherGrade;
uint32 OverrideLightId;
uint32 LightFadeInTime;
};
#if defined(__GNUC__)
#pragma pack()
#else
#pragma pack(pop)
#endif
#define MAX_HEIGHT 100000.0f // can be use for find ground height at surface
#define INVALID_HEIGHT -100000.0f // for check, must be equal to VMAP_INVALID_HEIGHT, real value for unknown height is VMAP_INVALID_HEIGHT_VALUE
#define MAX_FALL_DISTANCE 250000.0f // "unlimited fall" to find VMap ground if it is available, just larger than MAX_HEIGHT - INVALID_HEIGHT
#define DEFAULT_HEIGHT_SEARCH 70.0f // default search distance to find height at nearby locations
#define MIN_UNLOAD_DELAY 1 // immediate unload
typedef std::map<uint32/*leaderDBGUID*/, CreatureGroup*> CreatureGroupHolderType;
typedef UNORDERED_MAP<uint32 /*zoneId*/, ZoneDynamicInfo> ZoneDynamicInfoMap;
typedef std::set<MotionTransport*> TransportsContainer;
enum EncounterCreditType
{
ENCOUNTER_CREDIT_KILL_CREATURE = 0,
ENCOUNTER_CREDIT_CAST_SPELL = 1,
};
class Map : public GridRefManager<NGridType>
{
friend class MapReference;
public:
Map(uint32 id, uint32 InstanceId, uint8 SpawnMode, Map* _parent = NULL);
virtual ~Map();
MapEntry const* GetEntry() const { return i_mapEntry; }
// currently unused for normal maps
bool CanUnload(uint32 diff)
{
if (!m_unloadTimer)
return false;
if (m_unloadTimer <= diff)
return true;
m_unloadTimer -= diff;
return false;
}
virtual bool AddPlayerToMap(Player*);
virtual void RemovePlayerFromMap(Player*, bool);
virtual void AfterPlayerUnlinkFromMap();
template<class T> bool AddToMap(T *, bool checkTransport = false);
template<class T> void RemoveFromMap(T *, bool);
void VisitNearbyCellsOf(WorldObject* obj, TypeContainerVisitor<Trinity::ObjectUpdater, GridTypeMapContainer> &gridVisitor, TypeContainerVisitor<Trinity::ObjectUpdater, WorldTypeMapContainer> &worldVisitor);
virtual void Update(const uint32, const uint32, bool thread = true);
float GetVisibilityRange() const { return m_VisibleDistance; }
void SetVisibilityRange(float range) { m_VisibleDistance = range; }
//function for setting up visibility distance for maps on per-type/per-Id basis
virtual void InitVisibilityDistance();
void PlayerRelocation(Player*, float x, float y, float z, float o);
void CreatureRelocation(Creature* creature, float x, float y, float z, float o);
void GameObjectRelocation(GameObject* go, float x, float y, float z, float o);
void DynamicObjectRelocation(DynamicObject* go, float x, float y, float z, float o);
template<class T, class CONTAINER> void Visit(const Cell& cell, TypeContainerVisitor<T, CONTAINER> &visitor);
bool IsRemovalGrid(float x, float y) const
{
GridCoord p = Trinity::ComputeGridCoord(x, y);
return !getNGrid(p.x_coord, p.y_coord);
}
bool IsGridLoaded(float x, float y) const
{
return IsGridLoaded(Trinity::ComputeGridCoord(x, y));
}
void LoadGrid(float x, float y);
bool UnloadGrid(NGridType& ngrid);
virtual void UnloadAll();
uint32 GetId(void) const { return i_mapEntry->MapID; }
static bool ExistMap(uint32 mapid, int gx, int gy);
static bool ExistVMap(uint32 mapid, int gx, int gy);
Map const* GetParent() const { return m_parentMap; }
// pussywizard: movemaps, mmaps
ACE_RW_Thread_Mutex& GetMMapLock() const { return *(const_cast<ACE_RW_Thread_Mutex*>(&MMapLock)); }
// pussywizard:
UNORDERED_SET<Object*> i_objectsToUpdate;
void BuildAndSendUpdateForObjects(); // definition in ObjectAccessor.cpp, below ObjectAccessor::Update, because it does the same for a map
UNORDERED_SET<Unit*> i_objectsForDelayedVisibility;
void HandleDelayedVisibility();
// some calls like isInWater should not use vmaps due to processor power
// can return INVALID_HEIGHT if under z+2 z coord not found height
float GetHeight(float x, float y, float z, bool checkVMap = true, float maxSearchDist = DEFAULT_HEIGHT_SEARCH) const;
Transport* GetTransportForPos(uint32 phase, float x, float y, float z, WorldObject* worldobject = NULL);
ZLiquidStatus getLiquidStatus(float x, float y, float z, uint8 ReqLiquidType, LiquidData* data = 0) const;
uint16 GetAreaFlag(float x, float y, float z, bool *isOutdoors=0) const;
bool GetAreaInfo(float x, float y, float z, uint32 &mogpflags, int32 &adtId, int32 &rootId, int32 &groupId) const;
bool IsOutdoors(float x, float y, float z) const;
uint8 GetTerrainType(float x, float y) const;
float GetWaterLevel(float x, float y) const;
bool IsInWater(float x, float y, float z, LiquidData* data = 0) const;
bool IsUnderWater(float x, float y, float z) const;
static uint32 GetAreaIdByAreaFlag(uint16 areaflag, uint32 map_id);
static uint32 GetZoneIdByAreaFlag(uint16 areaflag, uint32 map_id);
static void GetZoneAndAreaIdByAreaFlag(uint32& zoneid, uint32& areaid, uint16 areaflag, uint32 map_id);
uint32 GetAreaId(float x, float y, float z) const
{
return GetAreaIdByAreaFlag(GetAreaFlag(x, y, z), GetId());
}
uint32 GetZoneId(float x, float y, float z) const
{
return GetZoneIdByAreaFlag(GetAreaFlag(x, y, z), GetId());
}
void GetZoneAndAreaId(uint32& zoneid, uint32& areaid, float x, float y, float z) const
{
GetZoneAndAreaIdByAreaFlag(zoneid, areaid, GetAreaFlag(x, y, z), GetId());
}
void MoveAllCreaturesInMoveList();
void MoveAllGameObjectsInMoveList();
void MoveAllDynamicObjectsInMoveList();
void RemoveAllObjectsInRemoveList();
virtual void RemoveAllPlayers();
uint32 GetInstanceId() const { return i_InstanceId; }
uint8 GetSpawnMode() const { return (i_spawnMode); }
virtual bool CanEnter(Player* /*player*/, bool loginCheck = false) { return true; }
const char* GetMapName() const;
// have meaning only for instanced map (that have set real difficulty)
Difficulty GetDifficulty() const { return Difficulty(GetSpawnMode()); }
bool IsRegularDifficulty() const { return GetDifficulty() == REGULAR_DIFFICULTY; }
MapDifficulty const* GetMapDifficulty() const;
bool Instanceable() const { return i_mapEntry && i_mapEntry->Instanceable(); }
bool IsDungeon() const { return i_mapEntry && i_mapEntry->IsDungeon(); }
bool IsNonRaidDungeon() const { return i_mapEntry && i_mapEntry->IsNonRaidDungeon(); }
bool IsRaid() const { return i_mapEntry && i_mapEntry->IsRaid(); }
bool IsRaidOrHeroicDungeon() const { return IsRaid() || i_spawnMode > DUNGEON_DIFFICULTY_NORMAL; }
bool IsHeroic() const { return IsRaid() ? i_spawnMode >= RAID_DIFFICULTY_10MAN_HEROIC : i_spawnMode >= DUNGEON_DIFFICULTY_HEROIC; }
bool Is25ManRaid() const { return IsRaid() && i_spawnMode & RAID_DIFFICULTY_MASK_25MAN; } // since 25man difficulties are 1 and 3, we can check them like that
bool IsBattleground() const { return i_mapEntry && i_mapEntry->IsBattleground(); }
bool IsBattleArena() const { return i_mapEntry && i_mapEntry->IsBattleArena(); }
bool IsBattlegroundOrArena() const { return i_mapEntry && i_mapEntry->IsBattlegroundOrArena(); }
bool GetEntrancePos(int32 &mapid, float &x, float &y)
{
if (!i_mapEntry)
return false;
return i_mapEntry->GetEntrancePos(mapid, x, y);
}
void AddObjectToRemoveList(WorldObject* obj);
void AddObjectToSwitchList(WorldObject* obj, bool on);
virtual void DelayedUpdate(const uint32 diff);
//void UpdateObjectVisibility(WorldObject* obj, Cell cell, CellCoord cellpair);
//void UpdateObjectsVisibilityFor(Player* player, Cell cell, CellCoord cellpair);
void resetMarkedCells() { marked_cells.reset(); }
bool isCellMarked(uint32 pCellId) { return marked_cells.test(pCellId); }
void markCell(uint32 pCellId) { marked_cells.set(pCellId); }
bool HavePlayers() const { return !m_mapRefManager.isEmpty(); }
uint32 GetPlayersCountExceptGMs() const;
void AddWorldObject(WorldObject* obj) { i_worldObjects.insert(obj); }
void RemoveWorldObject(WorldObject* obj) { i_worldObjects.erase(obj); }
void SendToPlayers(WorldPacket const* data) const;
typedef MapRefManager PlayerList;
PlayerList const& GetPlayers() const { return m_mapRefManager; }
//per-map script storage
void ScriptsStart(std::map<uint32, std::multimap<uint32, ScriptInfo> > const& scripts, uint32 id, Object* source, Object* target);
void ScriptCommandStart(ScriptInfo const& script, uint32 delay, Object* source, Object* target);
// must called with AddToWorld
template<class T>
void AddToActive(T* obj);
// must called with RemoveFromWorld
template<class T>
void RemoveFromActive(T* obj);
template<class T> void SwitchGridContainers(T* obj, bool on);
template<class NOTIFIER> void VisitAll(const float &x, const float &y, float radius, NOTIFIER &notifier);
template<class NOTIFIER> void VisitFirstFound(const float &x, const float &y, float radius, NOTIFIER &notifier);
template<class NOTIFIER> void VisitWorld(const float &x, const float &y, float radius, NOTIFIER &notifier);
template<class NOTIFIER> void VisitGrid(const float &x, const float &y, float radius, NOTIFIER &notifier);
CreatureGroupHolderType CreatureGroupHolder;
void UpdateIteratorBack(Player* player);
TempSummon* SummonCreature(uint32 entry, Position const& pos, SummonPropertiesEntry const* properties = NULL, uint32 duration = 0, Unit* summoner = NULL, uint32 spellId = 0, uint32 vehId = 0);
GameObject* SummonGameObject(uint32 entry, float x, float y, float z, float ang, float rotation0, float rotation1, float rotation2, float rotation3, uint32 respawnTime, bool checkTransport = true);
void SummonCreatureGroup(uint8 group, std::list<TempSummon*>* list = NULL);
Player* GetPlayer(uint64 guid);
Creature* GetCreature(uint64 guid);
GameObject* GetGameObject(uint64 guid);
Transport* GetTransport(uint64 guid);
DynamicObject* GetDynamicObject(uint64 guid);
Pet* GetPet(uint64 guid);
Corpse* GetCorpse(uint64 guid);
MapInstanced* ToMapInstanced(){ if (Instanceable()) return reinterpret_cast<MapInstanced*>(this); else return NULL; }
const MapInstanced* ToMapInstanced() const { if (Instanceable()) return (const MapInstanced*)((MapInstanced*)this); else return NULL; }
InstanceMap* ToInstanceMap(){ if (IsDungeon()) return reinterpret_cast<InstanceMap*>(this); else return NULL; }
const InstanceMap* ToInstanceMap() const { if (IsDungeon()) return (const InstanceMap*)((InstanceMap*)this); else return NULL; }
BattlegroundMap* ToBattlegroundMap() { if (IsBattlegroundOrArena()) return reinterpret_cast<BattlegroundMap*>(this); else return NULL; }
const BattlegroundMap* ToBattlegroundMap() const { if (IsBattlegroundOrArena()) return reinterpret_cast<BattlegroundMap const*>(this); return NULL; }
float GetWaterOrGroundLevel(float x, float y, float z, float* ground = NULL, bool swim = false, float maxSearchDist = 50.0f) const;
float GetHeight(uint32 phasemask, float x, float y, float z, bool vmap = true, float maxSearchDist = DEFAULT_HEIGHT_SEARCH) const;
bool isInLineOfSight(float x1, float y1, float z1, float x2, float y2, float z2, uint32 phasemask) const;
void Balance() { _dynamicTree.balance(); }
void RemoveGameObjectModel(const GameObjectModel& model) { _dynamicTree.remove(model); }
void InsertGameObjectModel(const GameObjectModel& model) { _dynamicTree.insert(model); }
bool ContainsGameObjectModel(const GameObjectModel& model) const { return _dynamicTree.contains(model);}
DynamicMapTree const& GetDynamicMapTree() const { return _dynamicTree; }
bool getObjectHitPos(uint32 phasemask, float x1, float y1, float z1, float x2, float y2, float z2, float& rx, float &ry, float& rz, float modifyDist);
/*
RESPAWN TIMES
*/
time_t GetLinkedRespawnTime(uint64 guid) const;
time_t GetCreatureRespawnTime(uint32 dbGuid) const
{
UNORDERED_MAP<uint32 /*dbGUID*/, time_t>::const_iterator itr = _creatureRespawnTimes.find(dbGuid);
if (itr != _creatureRespawnTimes.end())
return itr->second;
return time_t(0);
}
time_t GetGORespawnTime(uint32 dbGuid) const
{
UNORDERED_MAP<uint32 /*dbGUID*/, time_t>::const_iterator itr = _goRespawnTimes.find(dbGuid);
if (itr != _goRespawnTimes.end())
return itr->second;
return time_t(0);
}
void SaveCreatureRespawnTime(uint32 dbGuid, time_t& respawnTime);
void RemoveCreatureRespawnTime(uint32 dbGuid);
void SaveGORespawnTime(uint32 dbGuid, time_t& respawnTime);
void RemoveGORespawnTime(uint32 dbGuid);
void LoadRespawnTimes();
void DeleteRespawnTimes();
time_t GetInstanceResetPeriod() const { return _instanceResetPeriod; }
static void DeleteRespawnTimesInDB(uint16 mapId, uint32 instanceId);
void SendInitTransports(Player* player);
void SendRemoveTransports(Player* player);
void SendZoneDynamicInfo(Player* player);
void SendInitSelf(Player* player);
void SetZoneMusic(uint32 zoneId, uint32 musicId);
void SetZoneWeather(uint32 zoneId, uint32 weatherId, float weatherGrade);
void SetZoneOverrideLight(uint32 zoneId, uint32 lightId, uint32 fadeInTime);
// Checks encounter state at kill/spellcast, originally in InstanceScript however not every map has instance script :(
void UpdateEncounterState(EncounterCreditType type, uint32 creditEntry, Unit* source);
void LogEncounterFinished(EncounterCreditType type, uint32 creditEntry);
GridMap* GetGrid(float x, float y);
void EnsureGridCreated(const GridCoord &);
bool AllTransportsEmpty() const; // pussywizard
void AllTransportsRemovePassengers(); // pussywizard
TransportsContainer const& GetAllTransports() const { return _transports; }
private:
void LoadMapAndVMap(int gx, int gy);
void LoadVMap(int gx, int gy);
void LoadMap(int gx, int gy, bool reload = false);
// Load MMap Data
void LoadMMap(int gx, int gy);
template<class T> void InitializeObject(T* obj);
void AddCreatureToMoveList(Creature* c);
void RemoveCreatureFromMoveList(Creature* c);
void AddGameObjectToMoveList(GameObject* go);
void RemoveGameObjectFromMoveList(GameObject* go);
void AddDynamicObjectToMoveList(DynamicObject* go);
void RemoveDynamicObjectFromMoveList(DynamicObject* go);
std::vector<Creature*> _creaturesToMove;
std::vector<GameObject*> _gameObjectsToMove;
std::vector<DynamicObject*> _dynamicObjectsToMove;
bool IsGridLoaded(const GridCoord &) const;
void EnsureGridCreated_i(const GridCoord &);
void buildNGridLinkage(NGridType* pNGridType) { pNGridType->link(this); }
NGridType* getNGrid(uint32 x, uint32 y) const
{
ASSERT(x < MAX_NUMBER_OF_GRIDS && y < MAX_NUMBER_OF_GRIDS);
return i_grids[x][y];
}
bool EnsureGridLoaded(Cell const&);
bool isGridObjectDataLoaded(uint32 x, uint32 y) const { return getNGrid(x, y)->isGridObjectDataLoaded(); }
void setGridObjectDataLoaded(bool pLoaded, uint32 x, uint32 y) { getNGrid(x, y)->setGridObjectDataLoaded(pLoaded); }
void setNGrid(NGridType* grid, uint32 x, uint32 y);
void ScriptsProcess();
void UpdateActiveCells(const float &x, const float &y, const uint32 t_diff);
protected:
ACE_Thread_Mutex Lock;
ACE_Thread_Mutex GridLock;
ACE_RW_Thread_Mutex MMapLock;
MapEntry const* i_mapEntry;
uint8 i_spawnMode;
uint32 i_InstanceId;
uint32 m_unloadTimer;
float m_VisibleDistance;
DynamicMapTree _dynamicTree;
time_t _instanceResetPeriod; // pussywizard
MapRefManager m_mapRefManager;
MapRefManager::iterator m_mapRefIter;
typedef std::set<WorldObject*> ActiveNonPlayers;
ActiveNonPlayers m_activeNonPlayers;
ActiveNonPlayers::iterator m_activeNonPlayersIter;
// Objects that must update even in inactive grids without activating them
TransportsContainer _transports;
TransportsContainer::iterator _transportsUpdateIter;
private:
Player* _GetScriptPlayerSourceOrTarget(Object* source, Object* target, const ScriptInfo* scriptInfo) const;
Creature* _GetScriptCreatureSourceOrTarget(Object* source, Object* target, const ScriptInfo* scriptInfo, bool bReverse = false) const;
Unit* _GetScriptUnit(Object* obj, bool isSource, const ScriptInfo* scriptInfo) const;
Player* _GetScriptPlayer(Object* obj, bool isSource, const ScriptInfo* scriptInfo) const;
Creature* _GetScriptCreature(Object* obj, bool isSource, const ScriptInfo* scriptInfo) const;
WorldObject* _GetScriptWorldObject(Object* obj, bool isSource, const ScriptInfo* scriptInfo) const;
void _ScriptProcessDoor(Object* source, Object* target, const ScriptInfo* scriptInfo) const;
GameObject* _FindGameObject(WorldObject* pWorldObject, uint32 guid) const;
//used for fast base_map (e.g. MapInstanced class object) search for
//InstanceMaps and BattlegroundMaps...
Map* m_parentMap;
NGridType* i_grids[MAX_NUMBER_OF_GRIDS][MAX_NUMBER_OF_GRIDS];
GridMap* GridMaps[MAX_NUMBER_OF_GRIDS][MAX_NUMBER_OF_GRIDS];
std::bitset<TOTAL_NUMBER_OF_CELLS_PER_MAP*TOTAL_NUMBER_OF_CELLS_PER_MAP> marked_cells;
bool i_scriptLock;
UNORDERED_SET<WorldObject*> i_objectsToRemove;
std::map<WorldObject*, bool> i_objectsToSwitch;
UNORDERED_SET<WorldObject*> i_worldObjects;
typedef std::multimap<time_t, ScriptAction> ScriptScheduleMap;
ScriptScheduleMap m_scriptSchedule;
// Type specific code for add/remove to/from grid
template<class T>
void AddToGrid(T* object, Cell const& cell);
template<class T>
void DeleteFromWorld(T*);
void AddToActiveHelper(WorldObject* obj)
{
m_activeNonPlayers.insert(obj);
}
void RemoveFromActiveHelper(WorldObject* obj)
{
// Map::Update for active object in proccess
if (m_activeNonPlayersIter != m_activeNonPlayers.end())
{
ActiveNonPlayers::iterator itr = m_activeNonPlayers.find(obj);
if (itr == m_activeNonPlayers.end())
return;
if (itr == m_activeNonPlayersIter)
++m_activeNonPlayersIter;
m_activeNonPlayers.erase(itr);
}
else
m_activeNonPlayers.erase(obj);
}
UNORDERED_MAP<uint32 /*dbGUID*/, time_t> _creatureRespawnTimes;
UNORDERED_MAP<uint32 /*dbGUID*/, time_t> _goRespawnTimes;
ZoneDynamicInfoMap _zoneDynamicInfo;
uint32 _defaultLight;
};
enum InstanceResetMethod
{
INSTANCE_RESET_ALL, // reset all option under portrait, resets only normal 5-mans
INSTANCE_RESET_CHANGE_DIFFICULTY, // on changing difficulty
INSTANCE_RESET_GLOBAL, // global id reset
INSTANCE_RESET_GROUP_JOIN, // on joining group
INSTANCE_RESET_GROUP_LEAVE // on leaving group
};
class InstanceMap : public Map
{
public:
InstanceMap(uint32 id, uint32 InstanceId, uint8 SpawnMode, Map* _parent);
~InstanceMap();
bool AddPlayerToMap(Player*);
void RemovePlayerFromMap(Player*, bool);
void AfterPlayerUnlinkFromMap();
void Update(const uint32, const uint32, bool thread = true);
void CreateInstanceScript(bool load, std::string data, uint32 completedEncounterMask);
bool Reset(uint8 method, std::list<uint32>* globalSkipList = NULL);
uint32 GetScriptId() { return i_script_id; }
InstanceScript* GetInstanceScript() { return instance_script; }
void PermBindAllPlayers();
void UnloadAll();
bool CanEnter(Player* player, bool loginCheck = false);
void SendResetWarnings(uint32 timeLeft) const;
uint32 GetMaxPlayers() const;
uint32 GetMaxResetDelay() const;
virtual void InitVisibilityDistance();
private:
bool m_resetAfterUnload;
bool m_unloadWhenEmpty;
InstanceScript* instance_script;
uint32 i_script_id;
};
class BattlegroundMap : public Map
{
public:
BattlegroundMap(uint32 id, uint32 InstanceId, Map* _parent, uint8 spawnMode);
~BattlegroundMap();
bool AddPlayerToMap(Player*);
void RemovePlayerFromMap(Player*, bool);
bool CanEnter(Player* player, bool loginCheck = false);
void SetUnload();
//void UnloadAll(bool pForce);
void RemoveAllPlayers();
virtual void InitVisibilityDistance();
Battleground* GetBG() { return m_bg; }
void SetBG(Battleground* bg) { m_bg = bg; }
private:
Battleground* m_bg;
};
template<class T, class CONTAINER>
inline void Map::Visit(Cell const& cell, TypeContainerVisitor<T, CONTAINER>& visitor)
{
const uint32 x = cell.GridX();
const uint32 y = cell.GridY();
const uint32 cell_x = cell.CellX();
const uint32 cell_y = cell.CellY();
if (!cell.NoCreate() || IsGridLoaded(GridCoord(x, y)))
{
EnsureGridLoaded(cell);
getNGrid(x, y)->VisitGrid(cell_x, cell_y, visitor);
}
}
template<class NOTIFIER>
inline void Map::VisitAll(float const& x, float const& y, float radius, NOTIFIER& notifier)
{
CellCoord p(Trinity::ComputeCellCoord(x, y));
Cell cell(p);
cell.SetNoCreate();
TypeContainerVisitor<NOTIFIER, WorldTypeMapContainer> world_object_notifier(notifier);
cell.Visit(p, world_object_notifier, *this, radius, x, y);
TypeContainerVisitor<NOTIFIER, GridTypeMapContainer > grid_object_notifier(notifier);
cell.Visit(p, grid_object_notifier, *this, radius, x, y);
}
// should be used with Searcher notifiers, tries to search world if nothing found in grid
template<class NOTIFIER>
inline void Map::VisitFirstFound(const float &x, const float &y, float radius, NOTIFIER &notifier)
{
CellCoord p(Trinity::ComputeCellCoord(x, y));
Cell cell(p);
cell.SetNoCreate();
TypeContainerVisitor<NOTIFIER, WorldTypeMapContainer> world_object_notifier(notifier);
cell.Visit(p, world_object_notifier, *this, radius, x, y);
if (!notifier.i_object)
{
TypeContainerVisitor<NOTIFIER, GridTypeMapContainer > grid_object_notifier(notifier);
cell.Visit(p, grid_object_notifier, *this, radius, x, y);
}
}
template<class NOTIFIER>
inline void Map::VisitWorld(const float &x, const float &y, float radius, NOTIFIER &notifier)
{
CellCoord p(Trinity::ComputeCellCoord(x, y));
Cell cell(p);
cell.SetNoCreate();
TypeContainerVisitor<NOTIFIER, WorldTypeMapContainer> world_object_notifier(notifier);
cell.Visit(p, world_object_notifier, *this, radius, x, y);
}
template<class NOTIFIER>
inline void Map::VisitGrid(const float &x, const float &y, float radius, NOTIFIER &notifier)
{
CellCoord p(Trinity::ComputeCellCoord(x, y));
Cell cell(p);
cell.SetNoCreate();
TypeContainerVisitor<NOTIFIER, GridTypeMapContainer > grid_object_notifier(notifier);
cell.Visit(p, grid_object_notifier, *this, radius, x, y);
}
#endif

View File

@@ -0,0 +1,276 @@
/*
* Copyright (C)
* Copyright (C)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "MapInstanced.h"
#include "ObjectMgr.h"
#include "MapManager.h"
#include "Battleground.h"
#include "VMapFactory.h"
#include "MMapFactory.h"
#include "InstanceSaveMgr.h"
#include "World.h"
#include "Group.h"
#include "Player.h"
MapInstanced::MapInstanced(uint32 id) : Map(id, 0, DUNGEON_DIFFICULTY_NORMAL)
{
// initialize instanced maps list
m_InstancedMaps.clear();
}
void MapInstanced::InitVisibilityDistance()
{
if (m_InstancedMaps.empty())
return;
//initialize visibility distances for all instance copies
for (InstancedMaps::iterator i = m_InstancedMaps.begin(); i != m_InstancedMaps.end(); ++i)
{
(*i).second->InitVisibilityDistance();
}
}
void MapInstanced::Update(const uint32 t, const uint32 s_diff, bool /*thread*/)
{
// take care of loaded GridMaps (when unused, unload it!)
Map::Update(t, s_diff, false);
// update the instanced maps
InstancedMaps::iterator i = m_InstancedMaps.begin();
while (i != m_InstancedMaps.end())
{
if (i->second->CanUnload(t))
{
if (!DestroyInstance(i)) // iterator incremented
{
//m_unloadTimer
}
}
else
{
// update only here, because it may schedule some bad things before delete
if (sMapMgr->GetMapUpdater()->activated())
sMapMgr->GetMapUpdater()->schedule_update(*i->second, t, s_diff);
else
i->second->Update(t, s_diff);
++i;
}
}
}
void MapInstanced::DelayedUpdate(const uint32 diff)
{
for (InstancedMaps::iterator i = m_InstancedMaps.begin(); i != m_InstancedMaps.end(); ++i)
i->second->DelayedUpdate(diff);
Map::DelayedUpdate(diff); // this may be removed
}
/*
void MapInstanced::RelocationNotify()
{
for (InstancedMaps::iterator i = m_InstancedMaps.begin(); i != m_InstancedMaps.end(); ++i)
i->second->RelocationNotify();
}
*/
void MapInstanced::UnloadAll()
{
// Unload instanced maps
for (InstancedMaps::iterator i = m_InstancedMaps.begin(); i != m_InstancedMaps.end(); ++i)
i->second->UnloadAll();
// Delete the maps only after everything is unloaded to prevent crashes
for (InstancedMaps::iterator i = m_InstancedMaps.begin(); i != m_InstancedMaps.end(); ++i)
delete i->second;
m_InstancedMaps.clear();
// Unload own grids (just dummy(placeholder) grids, neccesary to unload GridMaps!)
Map::UnloadAll();
}
/*
- return the right instance for the object, based on its InstanceId
- create the instance if it's not created already
- the player is not actually added to the instance (only in InstanceMap::Add)
*/
Map* MapInstanced::CreateInstanceForPlayer(const uint32 mapId, Player* player)
{
if (GetId() != mapId || !player)
return NULL;
Map* map = NULL;
if (IsBattlegroundOrArena())
{
// instantiate or find existing bg map for player
// the instance id is set in battlegroundid
uint32 newInstanceId = player->GetBattlegroundId();
if (!newInstanceId)
return NULL;
map = sMapMgr->FindMap(mapId, newInstanceId);
if (!map)
{
Battleground* bg = player->GetBattleground(true);
if (bg && bg->GetStatus() < STATUS_WAIT_LEAVE)
map = CreateBattleground(newInstanceId, bg);
else
{
player->TeleportToEntryPoint();
return NULL;
}
}
}
else
{
Difficulty realdiff = player->GetDifficulty(IsRaid());
uint32 destInstId = sInstanceSaveMgr->PlayerGetDestinationInstanceId(player, GetId(), realdiff);
if (destInstId)
{
InstanceSave* pSave = sInstanceSaveMgr->GetInstanceSave(destInstId);
ASSERT(pSave); // pussywizard: must exist
map = FindInstanceMap(destInstId);
if (!map)
map = CreateInstance(destInstId, pSave, realdiff);
else if ((mapId == 631 || mapId == 724) && !map->HavePlayers() && map->GetDifficulty() != realdiff)
{
if (player->isBeingLoaded()) // pussywizard: crashfix (assert(passengers.empty) fail in ~transport), could be added to a transport during loading from db
return NULL;
if (!map->AllTransportsEmpty())
map->AllTransportsRemovePassengers(); // pussywizard: gameobjects / summons (assert(passengers.empty) fail in ~transport)
for (InstancedMaps::iterator i = m_InstancedMaps.begin(); i != m_InstancedMaps.end(); ++i)
if (i->first == destInstId)
{
DestroyInstance(i);
map = CreateInstance(destInstId, pSave, realdiff);
break;
}
}
}
else
{
uint32 newInstanceId = sMapMgr->GenerateInstanceId();
ASSERT(!FindInstanceMap(newInstanceId)); // pussywizard: instance with new id can't exist
Difficulty diff = player->GetGroup() ? player->GetGroup()->GetDifficulty(IsRaid()) : player->GetDifficulty(IsRaid());
map = CreateInstance(newInstanceId, NULL, diff);
}
}
return map;
}
InstanceMap* MapInstanced::CreateInstance(uint32 InstanceId, InstanceSave* save, Difficulty difficulty)
{
// load/create a map
TRINITY_GUARD(ACE_Thread_Mutex, Lock);
// make sure we have a valid map id
const MapEntry* entry = sMapStore.LookupEntry(GetId());
if (!entry)
{
sLog->outError("CreateInstance: no entry for map %d", GetId());
ASSERT(false);
}
const InstanceTemplate* iTemplate = sObjectMgr->GetInstanceTemplate(GetId());
if (!iTemplate)
{
sLog->outError("CreateInstance: no instance template for map %d", GetId());
ASSERT(false);
}
// some instances only have one difficulty
GetDownscaledMapDifficultyData(GetId(), difficulty);
;//sLog->outDebug(LOG_FILTER_MAPS, "MapInstanced::CreateInstance: %s map instance %d for %d created with difficulty %s", save?"":"new ", InstanceId, GetId(), difficulty?"heroic":"normal");
InstanceMap* map = new InstanceMap(GetId(), InstanceId, difficulty, this);
ASSERT(map->IsDungeon());
map->LoadRespawnTimes();
if (save)
map->CreateInstanceScript(true, save->GetInstanceData(), save->GetCompletedEncounterMask());
else
map->CreateInstanceScript(false, "", 0);
if (!save) // this is for sure a dungeon (assert above), no need to check here
sInstanceSaveMgr->AddInstanceSave(GetId(), InstanceId, difficulty);
m_InstancedMaps[InstanceId] = map;
return map;
}
BattlegroundMap* MapInstanced::CreateBattleground(uint32 InstanceId, Battleground* bg)
{
// load/create a map
TRINITY_GUARD(ACE_Thread_Mutex, Lock);
;//sLog->outDebug(LOG_FILTER_MAPS, "MapInstanced::CreateBattleground: map bg %d for %d created.", InstanceId, GetId());
PvPDifficultyEntry const* bracketEntry = GetBattlegroundBracketByLevel(bg->GetMapId(), bg->GetMinLevel());
uint8 spawnMode;
if (bracketEntry)
spawnMode = bracketEntry->difficulty;
else
spawnMode = REGULAR_DIFFICULTY;
BattlegroundMap* map = new BattlegroundMap(GetId(), InstanceId, this, spawnMode);
ASSERT(map->IsBattlegroundOrArena());
map->SetBG(bg);
bg->SetBgMap(map);
m_InstancedMaps[InstanceId] = map;
return map;
}
// increments the iterator after erase
bool MapInstanced::DestroyInstance(InstancedMaps::iterator &itr)
{
itr->second->RemoveAllPlayers();
if (itr->second->HavePlayers())
{
++itr;
return false;
}
itr->second->UnloadAll();
// Free up the instance id and allow it to be reused for bgs and arenas (other instances are handled in the InstanceSaveMgr)
//if (itr->second->IsBattlegroundOrArena())
// sMapMgr->FreeInstanceId(itr->second->GetInstanceId());
// erase map
delete itr->second;
m_InstancedMaps.erase(itr++);
return true;
}
bool MapInstanced::CanEnter(Player* /*player*/, bool /*loginCheck*/)
{
//ASSERT(false);
return true;
}

View File

@@ -0,0 +1,59 @@
/*
* Copyright (C)
* Copyright (C)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef TRINITY_MAP_INSTANCED_H
#define TRINITY_MAP_INSTANCED_H
#include "Map.h"
#include "InstanceSaveMgr.h"
#include "DBCEnums.h"
class MapInstanced : public Map
{
friend class MapManager;
public:
typedef UNORDERED_MAP< uint32, Map*> InstancedMaps;
MapInstanced(uint32 id);
~MapInstanced() {}
// functions overwrite Map versions
void Update(const uint32, const uint32, bool thread = true);
void DelayedUpdate(const uint32 diff);
//void RelocationNotify();
void UnloadAll();
bool CanEnter(Player* player, bool loginCheck = false);
Map* CreateInstanceForPlayer(const uint32 mapId, Player* player);
Map* FindInstanceMap(uint32 instanceId) const
{
InstancedMaps::const_iterator i = m_InstancedMaps.find(instanceId);
return(i == m_InstancedMaps.end() ? NULL : i->second);
}
bool DestroyInstance(InstancedMaps::iterator &itr);
InstancedMaps &GetInstancedMaps() { return m_InstancedMaps; }
virtual void InitVisibilityDistance();
private:
InstanceMap* CreateInstance(uint32 InstanceId, InstanceSave* save, Difficulty difficulty);
BattlegroundMap* CreateBattleground(uint32 InstanceId, Battleground* bg);
InstancedMaps m_InstancedMaps;
};
#endif

View File

@@ -0,0 +1,414 @@
/*
* Copyright (C)
* Copyright (C)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "MapManager.h"
#include "InstanceSaveMgr.h"
#include "DatabaseEnv.h"
#include "Log.h"
#include "ObjectAccessor.h"
#include "Transport.h"
#include "GridDefines.h"
#include "MapInstanced.h"
#include "InstanceScript.h"
#include "Config.h"
#include "World.h"
#include "CellImpl.h"
#include "Corpse.h"
#include "ObjectMgr.h"
#include "Language.h"
#include "WorldPacket.h"
#include "Group.h"
#include "Player.h"
#include "WorldSession.h"
#include "Opcodes.h"
#include "LFGMgr.h"
#include "Chat.h"
#include "AvgDiffTracker.h"
MapManager::MapManager()
{
i_timer[3].SetInterval(sWorld->getIntConfig(CONFIG_INTERVAL_MAPUPDATE));
mapUpdateStep = 0;
_nextInstanceId = 0;
}
MapManager::~MapManager()
{
}
void MapManager::Initialize()
{
int num_threads(sWorld->getIntConfig(CONFIG_NUMTHREADS));
// Start mtmaps if needed.
if (num_threads > 0 && m_updater.activate(num_threads) == -1)
abort();
}
void MapManager::InitializeVisibilityDistanceInfo()
{
for (MapMapType::iterator iter=i_maps.begin(); iter != i_maps.end(); ++iter)
(*iter).second->InitVisibilityDistance();
}
Map* MapManager::CreateBaseMap(uint32 id)
{
Map* map = FindBaseMap(id);
if (map == NULL)
{
TRINITY_GUARD(ACE_Thread_Mutex, Lock);
map = FindBaseMap(id);
if (map == NULL) // pussywizard: check again after acquiring mutex
{
MapEntry const* entry = sMapStore.LookupEntry(id);
ASSERT(entry);
if (entry->Instanceable())
map = new MapInstanced(id);
else
{
map = new Map(id, 0, REGULAR_DIFFICULTY);
map->LoadRespawnTimes();
}
i_maps[id] = map;
}
}
ASSERT(map);
return map;
}
Map* MapManager::FindBaseNonInstanceMap(uint32 mapId) const
{
Map* map = FindBaseMap(mapId);
if (map && map->Instanceable())
return NULL;
return map;
}
Map* MapManager::CreateMap(uint32 id, Player* player)
{
Map* m = CreateBaseMap(id);
if (m && m->Instanceable())
m = ((MapInstanced*)m)->CreateInstanceForPlayer(id, player);
return m;
}
Map* MapManager::FindMap(uint32 mapid, uint32 instanceId) const
{
Map* map = FindBaseMap(mapid);
if (!map)
return NULL;
if (!map->Instanceable())
return instanceId == 0 ? map : NULL;
return ((MapInstanced*)map)->FindInstanceMap(instanceId);
}
bool MapManager::CanPlayerEnter(uint32 mapid, Player* player, bool loginCheck)
{
MapEntry const* entry = sMapStore.LookupEntry(mapid);
if (!entry)
return false;
if (!entry->IsDungeon())
return true;
InstanceTemplate const* instance = sObjectMgr->GetInstanceTemplate(mapid);
if (!instance)
return false;
Difficulty targetDifficulty, requestedDifficulty;
targetDifficulty = requestedDifficulty = player->GetDifficulty(entry->IsRaid());
// Get the highest available difficulty if current setting is higher than the instance allows
MapDifficulty const* mapDiff = GetDownscaledMapDifficultyData(entry->MapID, targetDifficulty);
if (!mapDiff)
{
player->SendTransferAborted(mapid, TRANSFER_ABORT_DIFFICULTY, requestedDifficulty);
return false;
}
//Bypass checks for GMs
if (player->IsGameMaster())
return true;
char const* mapName = entry->name[player->GetSession()->GetSessionDbcLocale()];
Group* group = player->GetGroup();
if (entry->IsRaid())
{
// can only enter in a raid group
if ((!group || !group->isRaidGroup()) && !sWorld->getBoolConfig(CONFIG_INSTANCE_IGNORE_RAID))
{
// probably there must be special opcode, because client has this string constant in GlobalStrings.lua
// TODO: this is not a good place to send the message
player->GetSession()->SendAreaTriggerMessage(player->GetSession()->GetTrinityString(LANG_INSTANCE_RAID_GROUP_ONLY), mapName);
;//sLog->outDebug(LOG_FILTER_MAPS, "MAP: Player '%s' must be in a raid group to enter instance '%s'", player->GetName().c_str(), mapName);
return false;
}
}
// xinef: dont allow LFG Group to enter other instance that is selected
if (group)
if (group->isLFGGroup())
if (!sLFGMgr->inLfgDungeonMap(group->GetGUID(), mapid, targetDifficulty))
{
player->SendTransferAborted(mapid, TRANSFER_ABORT_MAP_NOT_ALLOWED);
return false;
}
if (!player->IsAlive())
{
if (Corpse* corpse = player->GetCorpse())
{
// let enter in ghost mode in instance that connected to inner instance with corpse
uint32 corpseMap = corpse->GetMapId();
do
{
if (corpseMap == mapid)
break;
InstanceTemplate const* corpseInstance = sObjectMgr->GetInstanceTemplate(corpseMap);
corpseMap = corpseInstance ? corpseInstance->Parent : 0;
} while (corpseMap);
if (!corpseMap)
{
WorldPacket data(SMSG_CORPSE_NOT_IN_INSTANCE, 0);
player->GetSession()->SendPacket(&data);
;//sLog->outDebug(LOG_FILTER_MAPS, "MAP: Player '%s' does not have a corpse in instance '%s' and cannot enter.", player->GetName().c_str(), mapName);
return false;
}
;//sLog->outDebug(LOG_FILTER_MAPS, "MAP: Player '%s' has corpse in instance '%s' and can enter.", player->GetName().c_str(), mapName);
player->ResurrectPlayer(0.5f, false);
player->SpawnCorpseBones();
}
else
;//sLog->outDebug(LOG_FILTER_MAPS, "Map::CanPlayerEnter - player '%s' is dead but does not have a corpse!", player->GetName().c_str());
}
// if map exists - check for being full, etc.
if (!loginCheck) // for login this is done by the calling function
{
uint32 destInstId = sInstanceSaveMgr->PlayerGetDestinationInstanceId(player, mapid, targetDifficulty);
if (destInstId)
if (Map* boundMap = sMapMgr->FindMap(mapid, destInstId))
if (!boundMap->CanEnter(player, loginCheck))
return false;
}
// players are only allowed to enter 5 instances per hour
if (entry->IsDungeon() && (!group || !group->isLFGGroup() || !group->IsLfgRandomInstance()))
{
uint32 instaceIdToCheck = 0;
if (InstanceSave* save = sInstanceSaveMgr->PlayerGetInstanceSave(player->GetGUIDLow(), mapid, player->GetDifficulty(entry->IsRaid())))
instaceIdToCheck = save->GetInstanceId();
// instaceIdToCheck can be 0 if save not found - means no bind so the instance is new
if (!player->CheckInstanceCount(instaceIdToCheck) && !player->isDead())
{
player->SendTransferAborted(mapid, TRANSFER_ABORT_TOO_MANY_INSTANCES);
return false;
}
}
//Other requirements
return player->Satisfy(sObjectMgr->GetAccessRequirement(mapid, targetDifficulty), mapid, true);
}
void MapManager::Update(uint32 diff)
{
for (uint8 i=0; i<4; ++i)
i_timer[i].Update(diff);
// pussywizard: lfg compatibles update, schedule before maps so it is processed from the very beginning
//if (mapUpdateStep == 0)
{
if (m_updater.activated())
m_updater.schedule_lfg_update(diff);
else
{
uint32 startTime = getMSTime();
sLFGMgr->Update(diff, 1);
uint32 totalTime = getMSTimeDiff(startTime, getMSTime());
lfgDiffTracker.Update(10000+totalTime); // +10k to mark it was NOT multithreaded
}
}
MapMapType::iterator iter = i_maps.begin();
for (; iter != i_maps.end(); ++iter)
{
bool full = mapUpdateStep<3 && ((mapUpdateStep==0 && !iter->second->IsBattlegroundOrArena() && !iter->second->IsDungeon()) || (mapUpdateStep==1 && iter->second->IsBattlegroundOrArena()) || (mapUpdateStep==2 && iter->second->IsDungeon()));
if (m_updater.activated())
m_updater.schedule_update(*iter->second, uint32(full ? i_timer[mapUpdateStep].GetCurrent() : 0), diff);
else
iter->second->Update(uint32(full ? i_timer[mapUpdateStep].GetCurrent() : 0), diff);
}
if (m_updater.activated())
m_updater.wait();
sObjectAccessor->ProcessDelayedCorpseActions();
if (mapUpdateStep<3)
{
for (iter = i_maps.begin(); iter != i_maps.end(); ++iter)
{
bool full = ((mapUpdateStep==0 && !iter->second->IsBattlegroundOrArena() && !iter->second->IsDungeon()) || (mapUpdateStep==1 && iter->second->IsBattlegroundOrArena()) || (mapUpdateStep==2 && iter->second->IsDungeon()));
if (full)
iter->second->DelayedUpdate(uint32(i_timer[mapUpdateStep].GetCurrent()));
}
i_timer[mapUpdateStep].SetCurrent(0);
++mapUpdateStep;
}
sObjectAccessor->Update(0);
if (mapUpdateStep == 3 && i_timer[3].Passed())
{
mapUpdateStep = 0;
i_timer[3].SetCurrent(0);
}
}
void MapManager::DoDelayedMovesAndRemoves()
{
}
bool MapManager::ExistMapAndVMap(uint32 mapid, float x, float y)
{
GridCoord p = Trinity::ComputeGridCoord(x, y);
int gx=63-p.x_coord;
int gy=63-p.y_coord;
return Map::ExistMap(mapid, gx, gy) && Map::ExistVMap(mapid, gx, gy);
}
bool MapManager::IsValidMAP(uint32 mapid, bool startUp)
{
MapEntry const* mEntry = sMapStore.LookupEntry(mapid);
if (startUp)
return mEntry ? true : false;
else
return mEntry && (!mEntry->IsDungeon() || sObjectMgr->GetInstanceTemplate(mapid));
// TODO: add check for battleground template
}
void MapManager::UnloadAll()
{
for (MapMapType::iterator iter = i_maps.begin(); iter != i_maps.end();)
{
iter->second->UnloadAll();
delete iter->second;
i_maps.erase(iter++);
}
if (m_updater.activated())
m_updater.deactivate();
}
void MapManager::GetNumInstances(uint32& dungeons, uint32& battlegrounds, uint32& arenas)
{
for (MapMapType::iterator itr = i_maps.begin(); itr != i_maps.end(); ++itr)
{
Map* map = itr->second;
if (!map->Instanceable())
continue;
MapInstanced::InstancedMaps &maps = ((MapInstanced*)map)->GetInstancedMaps();
for (MapInstanced::InstancedMaps::iterator mitr = maps.begin(); mitr != maps.end(); ++mitr)
{
if (mitr->second->IsDungeon()) dungeons++;
else if (mitr->second->IsBattleground()) battlegrounds++;
else if (mitr->second->IsBattleArena()) arenas++;
}
}
}
void MapManager::GetNumPlayersInInstances(uint32& dungeons, uint32& battlegrounds, uint32& arenas, uint32& spectators)
{
for (MapMapType::iterator itr = i_maps.begin(); itr != i_maps.end(); ++itr)
{
Map* map = itr->second;
if (!map->Instanceable())
continue;
MapInstanced::InstancedMaps &maps = ((MapInstanced*)map)->GetInstancedMaps();
for (MapInstanced::InstancedMaps::iterator mitr = maps.begin(); mitr != maps.end(); ++mitr)
{
if (mitr->second->IsDungeon()) dungeons += ((InstanceMap*)mitr->second)->GetPlayers().getSize();
else if (mitr->second->IsBattleground()) battlegrounds += ((InstanceMap*)mitr->second)->GetPlayers().getSize();
else if (mitr->second->IsBattleArena())
{
uint32 spect = 0;
if (BattlegroundMap* bgmap = mitr->second->ToBattlegroundMap())
if (Battleground* bg = bgmap->GetBG())
spect = bg->GetSpectators().size();
arenas += ((InstanceMap*)mitr->second)->GetPlayers().getSize() - spect;
spectators += spect;
}
}
}
}
void MapManager::InitInstanceIds()
{
_nextInstanceId = 1;
QueryResult result = CharacterDatabase.Query("SELECT MAX(id) FROM instance");
if (result)
{
uint32 maxId = (*result)[0].GetUInt32();
_instanceIds.resize(maxId+1);
}
}
void MapManager::RegisterInstanceId(uint32 instanceId)
{
// Allocation was done in InitInstanceIds()
_instanceIds[instanceId] = true;
// Instances are pulled in ascending order from db and _nextInstanceId is initialized with 1,
// so if the instance id is used, increment
if (_nextInstanceId == instanceId)
++_nextInstanceId;
}
uint32 MapManager::GenerateInstanceId()
{
uint32 newInstanceId = _nextInstanceId;
// find the lowest available id starting from the current _nextInstanceId
while (_nextInstanceId < 0xFFFFFFFF && ++_nextInstanceId < _instanceIds.size() && _instanceIds[_nextInstanceId]);
if (_nextInstanceId == 0xFFFFFFFF)
{
sLog->outError("Instance ID overflow!! Can't continue, shutting down server. ");
World::StopNow(ERROR_EXIT_CODE);
}
return newInstanceId;
}

View File

@@ -0,0 +1,158 @@
/*
* Copyright (C)
* Copyright (C)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef TRINITY_MAPMANAGER_H
#define TRINITY_MAPMANAGER_H
#include "Define.h"
#include <ace/Singleton.h>
#include <ace/Thread_Mutex.h>
#include "Common.h"
#include "Map.h"
#include "Object.h"
#include "MapUpdater.h"
class Transport;
class StaticTransport;
class MotionTransport;
struct TransportCreatureProto;
class MapManager
{
friend class ACE_Singleton<MapManager, ACE_Thread_Mutex>;
public:
Map* CreateBaseMap(uint32 mapId);
Map* FindBaseNonInstanceMap(uint32 mapId) const;
Map* CreateMap(uint32 mapId, Player* player);
Map* FindMap(uint32 mapId, uint32 instanceId) const;
Map* FindBaseMap(uint32 mapId) const // pussywizard: need this public for movemaps (mmaps)
{
MapMapType::const_iterator iter = i_maps.find(mapId);
return (iter == i_maps.end() ? NULL : iter->second);
}
uint16 GetAreaFlag(uint32 mapid, float x, float y, float z) const
{
Map const* m = const_cast<MapManager*>(this)->CreateBaseMap(mapid);
return m->GetAreaFlag(x, y, z);
}
uint32 GetAreaId(uint32 mapid, float x, float y, float z) const
{
return Map::GetAreaIdByAreaFlag(GetAreaFlag(mapid, x, y, z), mapid);
}
uint32 GetZoneId(uint32 mapid, float x, float y, float z) const
{
return Map::GetZoneIdByAreaFlag(GetAreaFlag(mapid, x, y, z), mapid);
}
void GetZoneAndAreaId(uint32& zoneid, uint32& areaid, uint32 mapid, float x, float y, float z)
{
Map::GetZoneAndAreaIdByAreaFlag(zoneid, areaid, GetAreaFlag(mapid, x, y, z), mapid);
}
void Initialize(void);
void Update(uint32);
void SetMapUpdateInterval(uint32 t)
{
if (t < MIN_MAP_UPDATE_DELAY)
t = MIN_MAP_UPDATE_DELAY;
i_timer[3].SetInterval(t);
i_timer[3].Reset();
}
//void LoadGrid(int mapid, int instId, float x, float y, const WorldObject* obj, bool no_unload = false);
void UnloadAll();
static bool ExistMapAndVMap(uint32 mapid, float x, float y);
static bool IsValidMAP(uint32 mapid, bool startUp);
static bool IsValidMapCoord(uint32 mapid, float x, float y)
{
return IsValidMAP(mapid, false) && Trinity::IsValidMapCoord(x, y);
}
static bool IsValidMapCoord(uint32 mapid, float x, float y, float z)
{
return IsValidMAP(mapid, false) && Trinity::IsValidMapCoord(x, y, z);
}
static bool IsValidMapCoord(uint32 mapid, float x, float y, float z, float o)
{
return IsValidMAP(mapid, false) && Trinity::IsValidMapCoord(x, y, z, o);
}
static bool IsValidMapCoord(WorldLocation const& loc)
{
return IsValidMapCoord(loc.GetMapId(), loc.GetPositionX(), loc.GetPositionY(), loc.GetPositionZ(), loc.GetOrientation());
}
// modulos a radian orientation to the range of 0..2PI
static float NormalizeOrientation(float o)
{
// fmod only supports positive numbers. Thus we have
// to emulate negative numbers
if (o < 0)
{
float mod = o *-1;
mod = fmod(mod, 2.0f * static_cast<float>(M_PI));
mod = -mod + 2.0f * static_cast<float>(M_PI);
return mod;
}
return fmod(o, 2.0f * static_cast<float>(M_PI));
}
void DoDelayedMovesAndRemoves();
bool CanPlayerEnter(uint32 mapid, Player* player, bool loginCheck = false);
void InitializeVisibilityDistanceInfo();
/* statistics */
void GetNumInstances(uint32& dungeons, uint32& battlegrounds, uint32& arenas);
void GetNumPlayersInInstances(uint32& dungeons, uint32& battlegrounds, uint32& arenas, uint32& spectators);
// Instance ID management
void InitInstanceIds();
void RegisterInstanceId(uint32 instanceId);
uint32 GenerateInstanceId();
MapUpdater * GetMapUpdater() { return &m_updater; }
private:
typedef UNORDERED_MAP<uint32, Map*> MapMapType;
typedef std::vector<bool> InstanceIds;
MapManager();
~MapManager();
MapManager(const MapManager &);
MapManager& operator=(const MapManager &);
ACE_Thread_Mutex Lock;
MapMapType i_maps;
IntervalTimer i_timer[4]; // continents, bgs/arenas, instances, total from the beginning
uint8 mapUpdateStep;
InstanceIds _instanceIds;
uint32 _nextInstanceId;
MapUpdater m_updater;
};
#define sMapMgr ACE_Singleton<MapManager, ACE_Thread_Mutex>::instance()
#endif

View File

@@ -0,0 +1,45 @@
/*
* Copyright (C)
* Copyright (C)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _MAPREFMANAGER
#define _MAPREFMANAGER
#include "RefManager.h"
class MapReference;
class MapRefManager : public RefManager<Map, Player>
{
public:
typedef LinkedListHead::Iterator< MapReference > iterator;
typedef LinkedListHead::Iterator< MapReference const > const_iterator;
MapReference* getFirst() { return (MapReference*)RefManager<Map, Player>::getFirst(); }
MapReference const* getFirst() const { return (MapReference const*)RefManager<Map, Player>::getFirst(); }
MapReference* getLast() { return (MapReference*)RefManager<Map, Player>::getLast(); }
MapReference const* getLast() const { return (MapReference const*)RefManager<Map, Player>::getLast(); }
iterator begin() { return iterator(getFirst()); }
iterator end() { return iterator(NULL); }
iterator rbegin() { return iterator(getLast()); }
iterator rend() { return iterator(NULL); }
const_iterator begin() const { return const_iterator(getFirst()); }
const_iterator end() const { return const_iterator(NULL); }
};
#endif

View File

@@ -0,0 +1,53 @@
/*
* Copyright (C)
* Copyright (C)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _MAPREFERENCE_H
#define _MAPREFERENCE_H
#include "Reference.h"
#include "Map.h"
class MapReference : public Reference<Map, Player>
{
protected:
void targetObjectBuildLink()
{
// called from link()
getTarget()->m_mapRefManager.insertFirst(this);
getTarget()->m_mapRefManager.incSize();
}
void targetObjectDestroyLink()
{
// called from unlink()
if (isValid()) getTarget()->m_mapRefManager.decSize();
}
void sourceObjectDestroyLink()
{
// called from invalidate()
getTarget()->m_mapRefManager.decSize();
}
public:
MapReference() : Reference<Map, Player>() {}
~MapReference() { unlink(); }
MapReference* next() { return (MapReference*)Reference<Map, Player>::next(); }
MapReference const* next() const { return (MapReference const*)Reference<Map, Player>::next(); }
MapReference* nockeck_prev() { return (MapReference*)Reference<Map, Player>::nocheck_prev(); }
MapReference const* nocheck_prev() const { return (MapReference const*)Reference<Map, Player>::nocheck_prev(); }
};
#endif

View File

@@ -0,0 +1,170 @@
#include "MapUpdater.h"
#include "DelayExecutor.h"
#include "Map.h"
#include "DatabaseEnv.h"
#include "LFGMgr.h"
#include "AvgDiffTracker.h"
#include <ace/Guard_T.h>
#include <ace/Method_Request.h>
class WDBThreadStartReq1 : public ACE_Method_Request
{
public:
WDBThreadStartReq1()
{
}
virtual int call()
{
return 0;
}
};
class WDBThreadEndReq1 : public ACE_Method_Request
{
public:
WDBThreadEndReq1()
{
}
virtual int call()
{
return 0;
}
};
class MapUpdateRequest : public ACE_Method_Request
{
private:
Map& m_map;
MapUpdater& m_updater;
ACE_UINT32 m_diff;
ACE_UINT32 s_diff;
public:
MapUpdateRequest(Map& m, MapUpdater& u, ACE_UINT32 d, ACE_UINT32 sd)
: m_map(m), m_updater(u), m_diff(d), s_diff(sd)
{
}
virtual int call()
{
m_map.Update (m_diff, s_diff);
m_updater.update_finished();
return 0;
}
};
class LFGUpdateRequest : public ACE_Method_Request
{
private:
MapUpdater& m_updater;
ACE_UINT32 m_diff;
public:
LFGUpdateRequest(MapUpdater& u, ACE_UINT32 d) : m_updater(u), m_diff(d) {}
virtual int call()
{
uint32 startTime = getMSTime();
sLFGMgr->Update(m_diff, 1);
uint32 totalTime = getMSTimeDiff(startTime, getMSTime());
lfgDiffTracker.Update(totalTime);
m_updater.update_finished();
return 0;
}
};
MapUpdater::MapUpdater():
m_executor(), m_mutex(), m_condition(m_mutex), pending_requests(0)
{
}
MapUpdater::~MapUpdater()
{
deactivate();
}
int MapUpdater::activate(size_t num_threads)
{
return m_executor.start((int)num_threads, new WDBThreadStartReq1, new WDBThreadEndReq1);
}
int MapUpdater::deactivate()
{
wait();
return m_executor.deactivate();
}
int MapUpdater::wait()
{
TRINITY_GUARD(ACE_Thread_Mutex, m_mutex);
while (pending_requests > 0)
m_condition.wait();
return 0;
}
int MapUpdater::schedule_update(Map& map, ACE_UINT32 diff, ACE_UINT32 s_diff)
{
TRINITY_GUARD(ACE_Thread_Mutex, m_mutex);
++pending_requests;
if (m_executor.execute(new MapUpdateRequest(map, *this, diff, s_diff)) == -1)
{
ACE_DEBUG((LM_ERROR, ACE_TEXT("(%t) \n"), ACE_TEXT("Failed to schedule Map Update")));
--pending_requests;
return -1;
}
return 0;
}
int MapUpdater::schedule_lfg_update(ACE_UINT32 diff)
{
TRINITY_GUARD(ACE_Thread_Mutex, m_mutex);
++pending_requests;
if (m_executor.execute(new LFGUpdateRequest(*this, diff)) == -1)
{
ACE_DEBUG((LM_ERROR, ACE_TEXT("(%t) \n"), ACE_TEXT("Failed to schedule LFG Update")));
--pending_requests;
return -1;
}
return 0;
}
bool MapUpdater::activated()
{
return m_executor.activated();
}
void MapUpdater::update_finished()
{
TRINITY_GUARD(ACE_Thread_Mutex, m_mutex);
if (pending_requests == 0)
{
ACE_ERROR((LM_ERROR, ACE_TEXT("(%t)\n"), ACE_TEXT("MapUpdater::update_finished BUG, report to devs")));
sLog->outMisc("WOOT! pending_requests == 0 before decrement!");
m_condition.broadcast();
return;
}
--pending_requests;
m_condition.broadcast();
}

View File

@@ -0,0 +1,43 @@
#ifndef _MAP_UPDATER_H_INCLUDED
#define _MAP_UPDATER_H_INCLUDED
#include <ace/Thread_Mutex.h>
#include <ace/Condition_Thread_Mutex.h>
#include "DelayExecutor.h"
#include "World.h"
class Map;
class MapUpdater
{
public:
MapUpdater();
virtual ~MapUpdater();
friend class MapUpdateRequest;
friend class LFGUpdateRequest;
int schedule_update(Map& map, ACE_UINT32 diff, ACE_UINT32 s_diff);
int schedule_lfg_update(ACE_UINT32 diff);
int wait();
int activate(size_t num_threads);
int deactivate();
bool activated();
private:
DelayExecutor m_executor;
ACE_Thread_Mutex m_mutex;
ACE_Condition_Thread_Mutex m_condition;
size_t pending_requests;
void update_finished();
};
#endif //_MAP_UPDATER_H_INCLUDED

View File

@@ -0,0 +1,530 @@
/*
* Copyright (C)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "TransportMgr.h"
#include "Transport.h"
#include "InstanceScript.h"
#include "MoveSpline.h"
#include "MapManager.h"
TransportTemplate::~TransportTemplate()
{
// Collect shared pointers into a set to avoid deleting the same memory more than once
std::set<TransportSpline*> splines;
for (size_t i = 0; i < keyFrames.size(); ++i)
splines.insert(keyFrames[i].Spline);
for (std::set<TransportSpline*>::iterator itr = splines.begin(); itr != splines.end(); ++itr)
delete *itr;
}
TransportMgr::TransportMgr() { }
TransportMgr::~TransportMgr() { }
void TransportMgr::Unload()
{
_transportTemplates.clear();
}
void TransportMgr::LoadTransportTemplates()
{
uint32 oldMSTime = getMSTime();
QueryResult result = WorldDatabase.Query("SELECT entry FROM gameobject_template WHERE type = 15 ORDER BY entry ASC");
if (!result)
{
sLog->outString(">> Loaded 0 transport templates. DB table `gameobject_template` has no transports!");
return;
}
uint32 count = 0;
do
{
Field* fields = result->Fetch();
uint32 entry = fields[0].GetUInt32();
GameObjectTemplate const* goInfo = sObjectMgr->GetGameObjectTemplate(entry);
if (goInfo == NULL)
{
sLog->outError("Transport %u has no associated GameObjectTemplate from `gameobject_template` , skipped.", entry);
continue;
}
if (goInfo->moTransport.taxiPathId >= sTaxiPathNodesByPath.size())
{
sLog->outError("Transport %u (name: %s) has an invalid path specified in `gameobject_template`.`data0` (%u) field, skipped.", entry, goInfo->name.c_str(), goInfo->moTransport.taxiPathId);
continue;
}
// paths are generated per template, saves us from generating it again in case of instanced transports
TransportTemplate& transport = _transportTemplates[entry];
transport.entry = entry;
GeneratePath(goInfo, &transport);
// transports in instance are only on one map
if (transport.inInstance)
_instanceTransports[*transport.mapsUsed.begin()].insert(entry);
++count;
} while (result->NextRow());
sLog->outString(">> Loaded %u transport templates in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
}
class SplineRawInitializer
{
public:
SplineRawInitializer(Movement::PointsArray& points) : _points(points) { }
void operator()(uint8& mode, bool& cyclic, Movement::PointsArray& points, int& lo, int& hi) const
{
mode = Movement::SplineBase::ModeCatmullrom;
cyclic = false;
points.assign(_points.begin(), _points.end());
lo = 1;
hi = points.size() - 2;
}
Movement::PointsArray& _points;
};
void TransportMgr::GeneratePath(GameObjectTemplate const* goInfo, TransportTemplate* transport)
{
uint32 pathId = goInfo->moTransport.taxiPathId;
TaxiPathNodeList const& path = sTaxiPathNodesByPath[pathId];
std::vector<KeyFrame>& keyFrames = transport->keyFrames;
Movement::PointsArray splinePath, allPoints;
bool mapChange = false;
for (size_t i = 0; i < path.size(); ++i)
allPoints.push_back(G3D::Vector3(path[i]->x, path[i]->y, path[i]->z));
// Add extra points to allow derivative calculations for all path nodes
allPoints.insert(allPoints.begin(), allPoints.front().lerp(allPoints[1], -0.2f));
allPoints.push_back(allPoints.back().lerp(allPoints[allPoints.size() - 2], -0.2f));
allPoints.push_back(allPoints.back().lerp(allPoints[allPoints.size() - 2], -1.0f));
SplineRawInitializer initer(allPoints);
TransportSpline orientationSpline;
orientationSpline.init_spline_custom(initer);
orientationSpline.initLengths();
for (size_t i = 0; i < path.size(); ++i)
{
if (!mapChange)
{
TaxiPathNodeEntry const* node_i = path[i];
if (i != path.size() - 1 && (node_i->actionFlag & 1 || node_i->mapid != path[i + 1]->mapid))
{
keyFrames.back().Teleport = true;
mapChange = true;
}
else
{
KeyFrame k(node_i);
G3D::Vector3 h;
orientationSpline.evaluate_derivative(i + 1, 0.0f, h);
k.InitialOrientation = Position::NormalizeOrientation(atan2(h.y, h.x) + M_PI);
keyFrames.push_back(k);
splinePath.push_back(G3D::Vector3(node_i->x, node_i->y, node_i->z));
transport->mapsUsed.insert(k.Node->mapid);
}
}
else
mapChange = false;
}
if (splinePath.size() >= 2)
{
// Remove special catmull-rom spline points
//if (!keyFrames.front().IsStopFrame() && !keyFrames.front().Node->arrivalEventID && !keyFrames.front().Node->departureEventID)
{
splinePath.erase(splinePath.begin());
keyFrames.erase(keyFrames.begin());
}
//if (!keyFrames.back().IsStopFrame() && !keyFrames.back().Node->arrivalEventID && !keyFrames.back().Node->departureEventID)
{
splinePath.pop_back();
keyFrames.pop_back();
}
}
ASSERT(!keyFrames.empty());
if (transport->mapsUsed.size() > 1)
{
for (std::set<uint32>::const_iterator itr = transport->mapsUsed.begin(); itr != transport->mapsUsed.end(); ++itr)
ASSERT(!sMapStore.LookupEntry(*itr)->Instanceable());
transport->inInstance = false;
}
else
transport->inInstance = sMapStore.LookupEntry(*transport->mapsUsed.begin())->Instanceable();
// last to first is always "teleport", even for closed paths
keyFrames.back().Teleport = true;
const float speed = float(goInfo->moTransport.moveSpeed);
const float accel = float(goInfo->moTransport.accelRate);
const float accel_dist = 0.5f * speed * speed / accel;
transport->accelTime = speed / accel;
transport->accelDist = accel_dist;
int32 firstStop = -1;
int32 lastStop = -1;
// first cell is arrived at by teleportation :S
keyFrames[0].DistFromPrev = 0;
keyFrames[0].Index = 1;
if (keyFrames[0].IsStopFrame())
{
firstStop = 0;
lastStop = 0;
}
// find the rest of the distances between key points
// Every path segment has its own spline
size_t start = 0;
for (size_t i = 1; i < keyFrames.size(); ++i)
{
if (keyFrames[i - 1].Teleport || i + 1 == keyFrames.size())
{
size_t extra = !keyFrames[i - 1].Teleport ? 1 : 0;
TransportSpline* spline = new TransportSpline();
spline->init_spline(&splinePath[start], i - start + extra, Movement::SplineBase::ModeCatmullrom);
spline->initLengths();
for (size_t j = start; j < i + extra; ++j)
{
keyFrames[j].Index = j - start + 1;
keyFrames[j].DistFromPrev = spline->length(j - start, j + 1 - start);
if (j > 0)
keyFrames[j - 1].NextDistFromPrev = keyFrames[j].DistFromPrev;
keyFrames[j].Spline = spline;
}
if (keyFrames[i - 1].Teleport)
{
keyFrames[i].Index = i - start + 1;
keyFrames[i].DistFromPrev = 0.0f;
keyFrames[i - 1].NextDistFromPrev = 0.0f;
keyFrames[i].Spline = spline;
}
start = i;
}
if (keyFrames[i].IsStopFrame())
{
// remember first stop frame
if (firstStop == -1)
firstStop = i;
lastStop = i;
}
}
keyFrames.back().NextDistFromPrev = keyFrames.front().DistFromPrev;
if (firstStop == -1 || lastStop == -1)
firstStop = lastStop = 0;
// at stopping keyframes, we define distSinceStop == 0,
// and distUntilStop is to the next stopping keyframe.
// this is required to properly handle cases of two stopping frames in a row (yes they do exist)
float tmpDist = 0.0f;
for (size_t i = 0; i < keyFrames.size(); ++i)
{
int32 j = (i + lastStop) % keyFrames.size();
if (keyFrames[j].IsStopFrame() || j == lastStop)
tmpDist = 0.0f;
else
tmpDist += keyFrames[j].DistFromPrev;
keyFrames[j].DistSinceStop = tmpDist;
}
tmpDist = 0.0f;
for (int32 i = int32(keyFrames.size()) - 1; i >= 0; i--)
{
int32 j = (i + firstStop) % keyFrames.size();
tmpDist += keyFrames[(j + 1) % keyFrames.size()].DistFromPrev;
keyFrames[j].DistUntilStop = tmpDist;
if (keyFrames[j].IsStopFrame() || j == firstStop)
tmpDist = 0.0f;
}
for (size_t i = 0; i < keyFrames.size(); ++i)
{
float total_dist = keyFrames[i].DistSinceStop + keyFrames[i].DistUntilStop;
if (total_dist < 2 * accel_dist) // won't reach full speed
{
if (keyFrames[i].DistSinceStop < keyFrames[i].DistUntilStop) // is still accelerating
{
// calculate accel+brake time for this short segment
float segment_time = 2.0f * sqrt((keyFrames[i].DistUntilStop + keyFrames[i].DistSinceStop) / accel);
// substract acceleration time
keyFrames[i].TimeTo = segment_time - sqrt(2 * keyFrames[i].DistSinceStop / accel);
}
else // slowing down
keyFrames[i].TimeTo = sqrt(2 * keyFrames[i].DistUntilStop / accel);
}
else if (keyFrames[i].DistSinceStop < accel_dist) // still accelerating (but will reach full speed)
{
// calculate accel + cruise + brake time for this long segment
float segment_time = (keyFrames[i].DistUntilStop + keyFrames[i].DistSinceStop) / speed + (speed / accel);
// substract acceleration time
keyFrames[i].TimeTo = segment_time - sqrt(2 * keyFrames[i].DistSinceStop / accel);
}
else if (keyFrames[i].DistUntilStop < accel_dist) // already slowing down (but reached full speed)
keyFrames[i].TimeTo = sqrt(2 * keyFrames[i].DistUntilStop / accel);
else // at full speed
keyFrames[i].TimeTo = (keyFrames[i].DistUntilStop / speed) + (0.5f * speed / accel);
}
// calculate tFrom times from tTo times
float segmentTime = 0.0f;
for (size_t i = 0; i < keyFrames.size(); ++i)
{
int32 j = (i + lastStop) % keyFrames.size();
if (keyFrames[j].IsStopFrame() || j == lastStop)
segmentTime = keyFrames[j].TimeTo;
keyFrames[j].TimeFrom = segmentTime - keyFrames[j].TimeTo;
}
// calculate path times
keyFrames[0].ArriveTime = 0;
float curPathTime = 0.0f;
if (keyFrames[0].IsStopFrame())
{
curPathTime = float(keyFrames[0].Node->delay);
keyFrames[0].DepartureTime = uint32(curPathTime * IN_MILLISECONDS);
}
for (size_t i = 1; i < keyFrames.size(); ++i)
{
curPathTime += keyFrames[i - 1].TimeTo;
if (keyFrames[i].IsStopFrame())
{
keyFrames[i].ArriveTime = uint32(curPathTime * IN_MILLISECONDS);
keyFrames[i - 1].NextArriveTime = keyFrames[i].ArriveTime;
curPathTime += float(keyFrames[i].Node->delay);
keyFrames[i].DepartureTime = uint32(curPathTime * IN_MILLISECONDS);
}
else
{
curPathTime -= keyFrames[i].TimeTo;
keyFrames[i].ArriveTime = uint32(curPathTime * IN_MILLISECONDS);
keyFrames[i - 1].NextArriveTime = keyFrames[i].ArriveTime;
keyFrames[i].DepartureTime = keyFrames[i].ArriveTime;
}
}
keyFrames.back().NextArriveTime = keyFrames.back().DepartureTime;
transport->pathTime = keyFrames.back().DepartureTime;
}
void TransportMgr::AddPathNodeToTransport(uint32 transportEntry, uint32 timeSeg, TransportAnimationEntry const* node)
{
TransportAnimation& animNode = _transportAnimations[transportEntry];
if (animNode.TotalTime < timeSeg)
animNode.TotalTime = timeSeg;
animNode.Path[timeSeg] = node;
}
MotionTransport* TransportMgr::CreateTransport(uint32 entry, uint32 guid /*= 0*/, Map* map /*= NULL*/)
{
// instance case, execute GetGameObjectEntry hook
if (map)
{
// SetZoneScript() is called after adding to map, so fetch the script using map
if (map->IsDungeon())
if (InstanceScript* instance = static_cast<InstanceMap*>(map)->GetInstanceScript())
entry = instance->GetGameObjectEntry(0, entry);
if (!entry)
return NULL;
}
TransportTemplate const* tInfo = GetTransportTemplate(entry);
if (!tInfo)
{
sLog->outError("Transport %u will not be loaded, `transport_template` missing", entry);
return NULL;
}
// create transport...
MotionTransport* trans = new MotionTransport();
// ...at first waypoint
TaxiPathNodeEntry const* startNode = tInfo->keyFrames.begin()->Node;
uint32 mapId = startNode->mapid;
float x = startNode->x;
float y = startNode->y;
float z = startNode->z;
float o = tInfo->keyFrames.begin()->InitialOrientation;
// initialize the gameobject base
uint32 guidLow = guid ? guid : sObjectMgr->GenerateLowGuid(HIGHGUID_MO_TRANSPORT);
if (!trans->CreateMoTrans(guidLow, entry, mapId, x, y, z, o, 255))
{
delete trans;
return NULL;
}
if (MapEntry const* mapEntry = sMapStore.LookupEntry(mapId))
{
if (mapEntry->Instanceable() != tInfo->inInstance)
{
sLog->outError("Transport %u (name: %s) attempted creation in instance map (id: %u) but it is not an instanced transport!", entry, trans->GetName().c_str(), mapId);
delete trans;
return NULL;
}
}
// use preset map for instances (need to know which instance)
trans->SetMap(map ? map : sMapMgr->CreateMap(mapId, NULL));
if (map && map->IsDungeon())
trans->m_zoneScript = map->ToInstanceMap()->GetInstanceScript();
// xinef: transports are active so passengers can be relocated (grids must be loaded)
trans->setActive(true);
trans->GetMap()->AddToMap<MotionTransport>(trans);
return trans;
}
void TransportMgr::SpawnContinentTransports()
{
if (_transportTemplates.empty())
return;
uint32 oldMSTime = getMSTime();
QueryResult result = WorldDatabase.Query("SELECT guid, entry FROM transports");
uint32 count = 0;
if (result)
{
do
{
Field* fields = result->Fetch();
uint32 guid = fields[0].GetUInt32();
uint32 entry = fields[1].GetUInt32();
if (TransportTemplate const* tInfo = GetTransportTemplate(entry))
if (!tInfo->inInstance)
if (CreateTransport(entry, guid))
++count;
} while (result->NextRow());
}
sLog->outString(">> Spawned %u continent motion transports in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
// pussywizard: preload grids for continent static transports
oldMSTime = getMSTime();
result = WorldDatabase.Query("SELECT map, position_x, position_y FROM gameobject g JOIN gameobject_template t ON g.id = t.entry WHERE t.type = 11");
count = 0;
if (result)
{
do
{
Field* fields = result->Fetch();
uint32 mapId = fields[0].GetUInt32();
float x = fields[1].GetFloat();
float y = fields[2].GetFloat();
MapEntry const* mapEntry = sMapStore.LookupEntry(mapId);
if (mapEntry && !mapEntry->Instanceable())
if (Map* map = sMapMgr->CreateBaseMap(mapId))
{
map->LoadGrid(x, y);
++count;
}
} while (result->NextRow());
}
sLog->outString(">> Preloaded grids for %u continent static transports in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
}
void TransportMgr::CreateInstanceTransports(Map* map)
{
TransportInstanceMap::const_iterator mapTransports = _instanceTransports.find(map->GetId());
// no transports here
if (mapTransports == _instanceTransports.end() || mapTransports->second.empty())
return;
// create transports
for (std::set<uint32>::const_iterator itr = mapTransports->second.begin(); itr != mapTransports->second.end(); ++itr)
CreateTransport(*itr, 0, map);
}
bool TransportAnimation::GetAnimNode(uint32 time, TransportAnimationEntry const* &curr, TransportAnimationEntry const* &next, float &percPos) const
{
if (Path.empty())
return false;
for (TransportPathContainer::const_reverse_iterator itr = Path.rbegin(); itr != Path.rend(); ++itr)
if (time >= itr->first)
{
curr = itr->second;
ASSERT(itr != Path.rbegin());
--itr;
next = itr->second;
percPos = float(time - curr->TimeSeg) / float(next->TimeSeg - curr->TimeSeg);
return true;
}
return false;
}
void TransportAnimation::GetAnimRotation(uint32 time, G3D::Quat &curr, G3D::Quat &next, float &percRot) const
{
if (Rotations.empty())
{
curr = G3D::Quat(0.0f, 0.0f, 0.0f, 1.0f);
next = G3D::Quat(0.0f, 0.0f, 0.0f, 1.0f);
percRot = 0.0f;
return;
}
for (TransportPathRotationContainer::const_reverse_iterator itr = Rotations.rbegin(); itr != Rotations.rend(); ++itr)
if (time >= itr->first)
{
uint32 currSeg = itr->second->TimeSeg, nextSeg;
curr = G3D::Quat(itr->second->X, itr->second->Y, itr->second->Z, itr->second->W);
if (itr != Rotations.rbegin())
{
--itr;
next = G3D::Quat(itr->second->X, itr->second->Y, itr->second->Z, itr->second->W);
nextSeg = itr->second->TimeSeg;
}
else
{
next = G3D::Quat(Rotations.begin()->second->X, Rotations.begin()->second->Y, Rotations.begin()->second->Z, Rotations.begin()->second->W);
nextSeg = this->TotalTime;
}
percRot = float(time - currSeg) / float(nextSeg - currSeg);
return;
}
curr = G3D::Quat(0.0f, 0.0f, 0.0f, 1.0f);
next = G3D::Quat(0.0f, 0.0f, 0.0f, 1.0f);
percRot = 0.0f;
}

View File

@@ -0,0 +1,164 @@
/*
* Copyright (C)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef TRANSPORTMGR_H
#define TRANSPORTMGR_H
#include <ace/Singleton.h>
#include <G3D/Quat.h>
#include "Spline.h"
#include "DBCStores.h"
struct KeyFrame;
struct GameObjectTemplate;
struct TransportTemplate;
class Transport;
class StaticTransport;
class MotionTransport;
class Map;
typedef Movement::Spline<double> TransportSpline;
typedef std::vector<KeyFrame> KeyFrameVec;
typedef UNORDERED_MAP<uint32, TransportTemplate> TransportTemplates;
typedef std::set<MotionTransport*> TransportSet;
typedef UNORDERED_MAP<uint32, TransportSet> TransportMap;
typedef UNORDERED_MAP<uint32, std::set<uint32> > TransportInstanceMap;
struct KeyFrame
{
explicit KeyFrame(TaxiPathNodeEntry const* node) : Index(0), Node(node), InitialOrientation(0.0f),
DistSinceStop(-1.0f), DistUntilStop(-1.0f), DistFromPrev(-1.0f), TimeFrom(0.0f), TimeTo(0.0f),
Teleport(false), ArriveTime(0), DepartureTime(0), Spline(NULL), NextDistFromPrev(0.0f), NextArriveTime(0)
{
}
uint32 Index;
TaxiPathNodeEntry const* Node;
float InitialOrientation;
float DistSinceStop;
float DistUntilStop;
float DistFromPrev;
float TimeFrom;
float TimeTo;
bool Teleport;
uint32 ArriveTime;
uint32 DepartureTime;
TransportSpline* Spline;
// Data needed for next frame
float NextDistFromPrev;
uint32 NextArriveTime;
bool IsTeleportFrame() const { return Teleport; }
bool IsStopFrame() const { return Node->actionFlag == 2; }
};
struct TransportTemplate
{
TransportTemplate() : inInstance(false), pathTime(0), accelTime(0.0f), accelDist(0.0f), entry(0) { }
~TransportTemplate();
std::set<uint32> mapsUsed;
bool inInstance;
uint32 pathTime;
KeyFrameVec keyFrames;
float accelTime;
float accelDist;
uint32 entry;
};
typedef std::map<uint32, TransportAnimationEntry const*> TransportPathContainer;
typedef std::map<uint32, TransportRotationEntry const*> TransportPathRotationContainer;
struct TransportAnimation
{
TransportAnimation() : TotalTime(0) { }
TransportPathContainer Path;
TransportPathRotationContainer Rotations;
uint32 TotalTime;
bool GetAnimNode(uint32 time, TransportAnimationEntry const* &curr, TransportAnimationEntry const* &next, float &percPos) const;
void GetAnimRotation(uint32 time, G3D::Quat &curr, G3D::Quat &next, float &percRot) const;
};
typedef std::map<uint32, TransportAnimation> TransportAnimationContainer;
class TransportMgr
{
friend class ACE_Singleton<TransportMgr, ACE_Thread_Mutex>;
friend void LoadDBCStores(std::string const&);
public:
void Unload();
void LoadTransportTemplates();
// Creates a transport using given GameObject template entry
MotionTransport* CreateTransport(uint32 entry, uint32 guid = 0, Map* map = NULL);
// Spawns all continent transports, used at core startup
void SpawnContinentTransports();
// creates all transports for instance
void CreateInstanceTransports(Map* map);
TransportTemplate const* GetTransportTemplate(uint32 entry) const
{
TransportTemplates::const_iterator itr = _transportTemplates.find(entry);
if (itr != _transportTemplates.end())
return &itr->second;
return NULL;
}
TransportAnimation const* GetTransportAnimInfo(uint32 entry) const
{
TransportAnimationContainer::const_iterator itr = _transportAnimations.find(entry);
if (itr != _transportAnimations.end())
return &itr->second;
return NULL;
}
private:
TransportMgr();
~TransportMgr();
TransportMgr(TransportMgr const&);
TransportMgr& operator=(TransportMgr const&);
// Generates and precaches a path for transport to avoid generation each time transport instance is created
void GeneratePath(GameObjectTemplate const* goInfo, TransportTemplate* transport);
void AddPathNodeToTransport(uint32 transportEntry, uint32 timeSeg, TransportAnimationEntry const* node);
void AddPathRotationToTransport(uint32 transportEntry, uint32 timeSeg, TransportRotationEntry const* node)
{
_transportAnimations[transportEntry].Rotations[timeSeg] = node;
}
// Container storing transport templates
TransportTemplates _transportTemplates;
// Container storing transport entries to create for instanced maps
TransportInstanceMap _instanceTransports;
TransportAnimationContainer _transportAnimations;
};
#define sTransportMgr ACE_Singleton<TransportMgr, ACE_Thread_Mutex>::instance()
#endif // TRANSPORTMGR_H

View File

@@ -0,0 +1,54 @@
/*
* Copyright (C)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef ZONE_SCRIPT_H_
#define ZONE_SCRIPT_H_
#include "Common.h"
#include "Creature.h"
class GameObject;
class ZoneScript
{
public:
ZoneScript() {}
virtual ~ZoneScript() {}
virtual uint32 GetCreatureEntry(uint32 /*guidlow*/, CreatureData const* data) { return data->id; }
virtual uint32 GetGameObjectEntry(uint32 /*guidlow*/, uint32 entry) { return entry; }
virtual void OnCreatureCreate(Creature *) { }
virtual void OnCreatureRemove(Creature *) { }
virtual void OnGameObjectCreate(GameObject *) { }
virtual void OnGameObjectRemove(GameObject *) { }
virtual void OnUnitDeath(Unit*) { }
//All-purpose data storage 64 bit
virtual uint64 GetData64(uint32 /*DataId*/) const { return 0; }
virtual void SetData64(uint32 /*DataId*/, uint64 /*Value*/) {}
//All-purpose data storage 32 bit
virtual uint32 GetData(uint32 /*DataId*/) const { return 0; }
virtual void SetData(uint32 /*DataId*/, uint32 /*Value*/) {}
virtual void ProcessEvent(WorldObject* /*obj*/, uint32 /*eventId*/) {}
};
#endif