root/trunk/src/game/Map.h @ 257

Revision 257, 13.9 kB (checked in by yumileroy, 17 years ago)

*Merge from Mangos. Add MapReference?. Author: hunuza.
*Also re-commit the patches reverted in 255.

Original author: megamage
Date: 2008-11-18 19:40:06-06:00

Line 
1/*
2 * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
3 *
4 * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19 */
20
21#ifndef TRINITY_MAP_H
22#define TRINITY_MAP_H
23
24#include "Platform/Define.h"
25#include "Policies/ThreadingModel.h"
26#include "zthread/Lockable.h"
27#include "zthread/Mutex.h"
28#include "zthread/FairReadWriteLock.h"
29#include "Database/DBCStructure.h"
30#include "GridDefines.h"
31#include "Cell.h"
32#include "Object.h"
33#include "Timer.h"
34#include "SharedDefines.h"
35#include "GameSystem/GridRefManager.h"
36#include "MapRefManager.h"
37
38#include <bitset>
39#include <list>
40
41class Unit;
42class WorldPacket;
43class InstanceData;
44class Group;
45class InstanceSave;
46
47namespace ZThread
48{
49    class Lockable;
50    class ReadWriteLock;
51}
52
53typedef ZThread::FairReadWriteLock GridRWLock;
54
55template<class MUTEX, class LOCK_TYPE>
56struct RGuard
57{
58    RGuard(MUTEX &l) : i_lock(l.getReadLock()) {}
59    Trinity::GeneralLock<LOCK_TYPE> i_lock;
60};
61
62template<class MUTEX, class LOCK_TYPE>
63struct WGuard
64{
65    WGuard(MUTEX &l) : i_lock(l.getWriteLock()) {}
66    Trinity::GeneralLock<LOCK_TYPE> i_lock;
67};
68
69typedef RGuard<GridRWLock, ZThread::Lockable> GridReadGuard;
70typedef WGuard<GridRWLock, ZThread::Lockable> GridWriteGuard;
71typedef Trinity::SingleThreaded<GridRWLock>::Lock NullGuard;
72
73typedef struct
74{
75    uint16 area_flag[16][16];
76    uint8 terrain_type[16][16];
77    float liquid_level[128][128];
78    float Z[MAP_RESOLUTION][MAP_RESOLUTION];
79}GridMap;
80
81struct CreatureMover
82{
83    CreatureMover() : x(0), y(0), z(0), ang(0) {}
84    CreatureMover(float _x, float _y, float _z, float _ang) : x(_x), y(_y), z(_z), ang(_ang) {}
85
86    float x, y, z, ang;
87};
88
89// 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
90#if defined( __GNUC__ )
91#pragma pack(1)
92#else
93#pragma pack(push,1)
94#endif
95
96struct InstanceTemplate
97{
98    uint32 map;
99    uint32 parent;
100    uint32 levelMin;
101    uint32 levelMax;
102    uint32 maxPlayers;
103    uint32 reset_delay;
104    float startLocX;
105    float startLocY;
106    float startLocZ;
107    float startLocO;
108    char const* script;
109};
110
111enum LevelRequirementVsMode
112{
113    LEVELREQUIREMENT_HEROIC = 70
114};
115
116#if defined( __GNUC__ )
117#pragma pack()
118#else
119#pragma pack(pop)
120#endif
121
122typedef UNORDERED_MAP<Creature*, CreatureMover> CreatureMoveList;
123
124#define MAX_HEIGHT            100000.0f                     // can be use for find ground height at surface
125#define INVALID_HEIGHT       -100000.0f                     // for check, must be equal to VMAP_INVALID_HEIGHT, real value for unknown height is VMAP_INVALID_HEIGHT_VALUE
126#define MIN_UNLOAD_DELAY      1                             // immediate unload
127
128class TRINITY_DLL_SPEC Map : public GridRefManager<NGridType>, public Trinity::ObjectLevelLockable<Map, ZThread::Mutex>
129{
130    friend class MapReference;
131    public:
132        Map(uint32 id, time_t, uint32 InstanceId, uint8 SpawnMode);
133        virtual ~Map();
134
135        // currently unused for normal maps
136        virtual bool CanUnload(const uint32& diff);
137
138        virtual bool Add(Player *);
139        virtual void Remove(Player *, bool);
140        template<class T> void Add(T *);
141        template<class T> void Remove(T *, bool);
142
143        virtual void Update(const uint32&);
144
145        void MessageBroadcast(Player *, WorldPacket *, bool to_self, bool to_possessor);
146        void MessageBroadcast(WorldObject *, WorldPacket *, bool to_possessor);
147        void MessageDistBroadcast(Player *, WorldPacket *, float dist, bool to_self, bool to_possessor, bool own_team_only = false);
148        void MessageDistBroadcast(WorldObject *, WorldPacket *, float dist, bool to_possessor);
149
150        void PlayerRelocation(Player *, float x, float y, float z, float angl);
151        void CreatureRelocation(Creature *creature, float x, float y, float, float);
152
153        template<class LOCK_TYPE, class T, class CONTAINER> void Visit(const CellLock<LOCK_TYPE> &cell, TypeContainerVisitor<T, CONTAINER> &visitor);
154
155        inline bool IsRemovalGrid(float x, float y) const
156        {
157            GridPair p = Trinity::ComputeGridPair(x, y);
158            return( !getNGrid(p.x_coord, p.y_coord) || getNGrid(p.x_coord, p.y_coord)->GetGridState() == GRID_STATE_REMOVAL );
159        }
160
161        bool GetUnloadFlag(const GridPair &p) const { return getNGrid(p.x_coord, p.y_coord)->getUnloadFlag(); }
162        void SetUnloadFlag(const GridPair &p, bool unload) { getNGrid(p.x_coord, p.y_coord)->setUnloadFlag(unload); }
163        void LoadGrid(const Cell& cell, bool no_unload = false);
164        bool UnloadGrid(const uint32 &x, const uint32 &y, bool pForce);
165        virtual void UnloadAll(bool pForce);
166
167        void ResetGridExpiry(NGridType &grid, float factor = 1) const
168        {
169            grid.ResetTimeTracker((time_t)((float)i_gridExpiry*factor));
170        }
171
172        time_t GetGridExpiry(void) const { return i_gridExpiry; }
173        uint32 GetId(void) const { return i_id; }
174
175        static bool ExistMap(uint32 mapid, int x, int y);
176        static bool ExistVMap(uint32 mapid, int x, int y);
177        void LoadMapAndVMap(uint32 mapid, uint32 instanceid, int x, int y);
178
179        static void InitStateMachine();
180        static void DeleteStateMachine();
181
182        // some calls like isInWater should not use vmaps due to processor power
183        // can return INVALID_HEIGHT if under z+2 z coord not found height
184        float GetHeight(float x, float y, float z, bool pCheckVMap=true) const;
185        bool IsInWater(float x, float y, float z) const;    // does not use z pos. This is for future use
186
187        uint16 GetAreaFlag(float x, float y ) const;
188        uint8 GetTerrainType(float x, float y ) const;
189        float GetWaterLevel(float x, float y ) const;
190        bool IsUnderWater(float x, float y, float z) const;
191
192        static uint32 GetAreaId(uint16 areaflag,uint32 map_id);
193        static uint32 GetZoneId(uint16 areaflag,uint32 map_id);
194
195        uint32 GetAreaId(float x, float y) const
196        {
197            return GetAreaId(GetAreaFlag(x,y),i_id);
198        }
199
200        uint32 GetZoneId(float x, float y) const
201        {
202            return GetZoneId(GetAreaFlag(x,y),i_id);
203        }
204
205        virtual void MoveAllCreaturesInMoveList();
206        virtual void RemoveAllObjectsInRemoveList();
207
208        bool CreatureRespawnRelocation(Creature *c);        // used only in MoveAllCreaturesInMoveList and ObjectGridUnloader
209
210        // assert print helper
211        bool CheckGridIntegrity(Creature* c, bool moved) const;
212
213        uint32 GetInstanceId() { return i_InstanceId; }
214        uint8 GetSpawnMode() { return (i_spawnMode); }
215        virtual bool CanEnter(Player* /*player*/) { return true; }
216        const char* GetMapName() const;
217
218        bool Instanceable() const { return i_mapEntry && i_mapEntry->Instanceable(); }
219        // NOTE: this duplicate of Instanceable(), but Instanceable() can be changed when BG also will be instanceable
220        bool IsDungeon() const { return i_mapEntry && i_mapEntry->IsDungeon(); }
221        bool IsRaid() const { return i_mapEntry && i_mapEntry->IsRaid(); }
222        bool IsHeroic() const { return i_spawnMode == DIFFICULTY_HEROIC; }
223        bool IsBattleGround() const { return i_mapEntry && i_mapEntry->IsBattleGround(); }
224        bool IsBattleArena() const { return i_mapEntry && i_mapEntry->IsBattleArena(); }
225        bool IsBattleGroundOrArena() const { return i_mapEntry && i_mapEntry->IsBattleGroundOrArena(); }
226
227        void AddObjectToRemoveList(WorldObject *obj);
228        void DoDelayedMovesAndRemoves();
229
230        virtual bool RemoveBones(uint64 guid, float x, float y);
231
232        void UpdateObjectVisibility(WorldObject* obj, Cell cell, CellPair cellpair);
233        void UpdatePlayerVisibility(Player* player, Cell cell, CellPair cellpair);
234        void UpdateObjectsVisibilityFor(Player* player, Cell cell, CellPair cellpair);
235
236        void resetMarkedCells() { marked_cells.reset(); }
237        bool isCellMarked(uint32 pCellId) { return marked_cells.test(pCellId); }
238        void markCell(uint32 pCellId) { marked_cells.set(pCellId); }
239        Creature* GetCreatureInMap(uint64 guid);
240        GameObject* GetGameObjectInMap(uint64 guid);
241
242        bool HavePlayers() const { return !m_mapRefManager.isEmpty(); }
243        uint32 GetPlayersCountExceptGMs() const;
244        bool PlayersNearGrid(uint32 x,uint32 y) const;
245
246        void SendToPlayers(WorldPacket const* data) const;
247
248        typedef MapRefManager PlayerList;
249        PlayerList const& GetPlayers() const { return m_mapRefManager; }
250        template<class T> void SwitchGridContainers(T* obj, bool active);
251    private:
252        void LoadVMap(int pX, int pY);
253        void LoadMap(uint32 mapid, uint32 instanceid, int x,int y);
254
255        void SetTimer(uint32 t) { i_gridExpiry = t < MIN_GRID_DELAY ? MIN_GRID_DELAY : t; }
256        //uint64 CalculateGridMask(const uint32 &y) const;
257
258        void SendInitSelf( Player * player );
259
260        void SendInitTransports( Player * player );
261        void SendRemoveTransports( Player * player );
262
263        void PlayerRelocationNotify(Player* player, Cell cell, CellPair cellpair);
264        void CreatureRelocationNotify(Creature *creature, Cell newcell, CellPair newval);
265
266        bool CreatureCellRelocation(Creature *creature, Cell new_cell);
267
268        void AddCreatureToMoveList(Creature *c, float x, float y, float z, float ang);
269        CreatureMoveList i_creaturesToMove;
270
271        bool loaded(const GridPair &) const;
272        void EnsureGridLoadedForPlayer(const Cell&, Player*, bool add_player);
273        void  EnsureGridCreated(const GridPair &);
274
275        void buildNGridLinkage(NGridType* pNGridType) { pNGridType->link(this); }
276
277        template<class T> void AddType(T *obj);
278        template<class T> void RemoveType(T *obj, bool);
279
280        NGridType* getNGrid(uint32 x, uint32 y) const
281        {
282            return i_grids[x][y];
283        }
284
285        bool isGridObjectDataLoaded(uint32 x, uint32 y) const { return getNGrid(x,y)->isGridObjectDataLoaded(); }
286        void setGridObjectDataLoaded(bool pLoaded, uint32 x, uint32 y) { getNGrid(x,y)->setGridObjectDataLoaded(pLoaded); }
287
288        inline void setNGrid(NGridType* grid, uint32 x, uint32 y);
289
290    protected:
291        typedef Trinity::ObjectLevelLockable<Map, ZThread::Mutex>::Lock Guard;
292
293        MapEntry const* i_mapEntry;
294        uint8 i_spawnMode;
295        uint32 i_id;
296        uint32 i_InstanceId;
297        uint32 m_unloadTimer;
298
299        MapRefManager m_mapRefManager;
300    private:
301        typedef GridReadGuard ReadGuard;
302        typedef GridWriteGuard WriteGuard;
303
304        NGridType* i_grids[MAX_NUMBER_OF_GRIDS][MAX_NUMBER_OF_GRIDS];
305        GridMap *GridMaps[MAX_NUMBER_OF_GRIDS][MAX_NUMBER_OF_GRIDS];
306        std::bitset<TOTAL_NUMBER_OF_CELLS_PER_MAP*TOTAL_NUMBER_OF_CELLS_PER_MAP> marked_cells;
307
308        time_t i_gridExpiry;
309
310        std::set<WorldObject *> i_objectsToRemove;
311
312        // Type specific code for add/remove to/from grid
313        template<class T>
314            void AddToGrid(T*, NGridType *, Cell const&);
315
316        template<class T>
317            void AddNotifier(T*, Cell const&, CellPair const&);
318
319        template<class T>
320            void RemoveFromGrid(T*, NGridType *, Cell const&);
321
322        template<class T>
323            void DeleteFromWorld(T*);
324};
325
326enum InstanceResetMethod
327{
328    INSTANCE_RESET_ALL,
329    INSTANCE_RESET_CHANGE_DIFFICULTY,
330    INSTANCE_RESET_GLOBAL,
331    INSTANCE_RESET_GROUP_DISBAND,
332    INSTANCE_RESET_GROUP_JOIN,
333    INSTANCE_RESET_RESPAWN_DELAY
334};
335
336class TRINITY_DLL_SPEC InstanceMap : public Map
337{
338    public:
339        InstanceMap(uint32 id, time_t, uint32 InstanceId, uint8 SpawnMode);
340        ~InstanceMap();
341        bool Add(Player *);
342        void Remove(Player *, bool);
343        void Update(const uint32&);
344        void CreateInstanceData(bool load);
345        bool Reset(uint8 method);
346        std::string GetScript() { return i_script; }
347        InstanceData* GetInstanceData() { return i_data; }
348        void PermBindAllPlayers(Player *player);
349        time_t GetResetTime();
350        void UnloadAll(bool pForce);
351        bool CanEnter(Player* player);
352        void SendResetWarnings(uint32 timeLeft) const;
353        void SetResetSchedule(bool on);
354    private:
355        bool m_resetAfterUnload;
356        bool m_unloadWhenEmpty;
357        InstanceData* i_data;
358        std::string i_script;
359        // only online players that are inside the instance currently
360        // TODO ? - use the grid instead to access the players
361        PlayerList i_Players;
362};
363
364class TRINITY_DLL_SPEC BattleGroundMap : public Map
365{
366    public:
367        BattleGroundMap(uint32 id, time_t, uint32 InstanceId);
368        ~BattleGroundMap();
369
370        bool Add(Player *);
371        void Remove(Player *, bool);
372        bool CanEnter(Player* player);
373        void SetUnload();
374        void UnloadAll(bool pForce);
375};
376
377/*inline
378uint64
379Map::CalculateGridMask(const uint32 &y) const
380{
381    uint64 mask = 1;
382    mask <<= y;
383    return mask;
384}
385*/
386
387template<class LOCK_TYPE, class T, class CONTAINER>
388inline void
389Map::Visit(const CellLock<LOCK_TYPE> &cell, TypeContainerVisitor<T, CONTAINER> &visitor)
390{
391    const uint32 x = cell->GridX();
392    const uint32 y = cell->GridY();
393    const uint32 cell_x = cell->CellX();
394    const uint32 cell_y = cell->CellY();
395
396    if( !cell->NoCreate() || loaded(GridPair(x,y)) )
397    {
398        EnsureGridLoadedForPlayer(cell, NULL, false);
399        //LOCK_TYPE guard(i_info[x][y]->i_lock);
400        getNGrid(x, y)->Visit(cell_x, cell_y, visitor);
401    }
402}
403#endif
Note: See TracBrowser for help on using the browser.