root/trunk/src/game/Map.cpp @ 157

Revision 149, 63.4 kB (checked in by yumileroy, 17 years ago)

[svn] *Implement new player conditions CONDITION_NO_AURA, CONDITION_ACTIVE_EVENT
* Default behaviour of pets for creatures changed to REACT_DEFENSIVE
* Disallowed sending wrapped items as COD
* Prevent loading and saving single target auras for pet in same way as already implemented for player
* Correctly limit use some flask types to zones.
* Fixed extracting common.MPQ under *nix
* Many small xleanups and fixes.
** mangos merge rev.

TEST REV so be careful of creepy crawly bugs!

Original author: KingPin?
Date: 2008-11-02 16:53:46-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#include "MapManager.h"
22#include "Player.h"
23#include "GridNotifiers.h"
24#include "WorldSession.h"
25#include "Log.h"
26#include "GridStates.h"
27#include "CellImpl.h"
28#include "InstanceData.h"
29#include "Map.h"
30#include "GridNotifiersImpl.h"
31#include "Config/ConfigEnv.h"
32#include "Transports.h"
33#include "ObjectAccessor.h"
34#include "ObjectMgr.h"
35#include "World.h"
36#include "ScriptCalls.h"
37#include "Group.h"
38
39#include "MapInstanced.h"
40#include "InstanceSaveMgr.h"
41#include "VMapFactory.h"
42
43#define DEFAULT_GRID_EXPIRY     300
44#define MAX_GRID_LOAD_TIME      50
45
46// magic *.map header
47const char MAP_MAGIC[] = "MAP_2.00";
48
49GridState* si_GridStates[MAX_GRID_STATE];
50
51Map::~Map()
52{
53    UnloadAll(true);
54}
55
56bool Map::ExistMap(uint32 mapid,int x,int y)
57{
58    int len = sWorld.GetDataPath().length()+strlen("maps/%03u%02u%02u.map")+1;
59    char* tmp = new char[len];
60    snprintf(tmp, len, (char *)(sWorld.GetDataPath()+"maps/%03u%02u%02u.map").c_str(),mapid,x,y);
61
62    FILE *pf=fopen(tmp,"rb");
63
64    if(!pf)
65    {
66        sLog.outError("Check existing of map file '%s': not exist!",tmp);
67        delete[] tmp;
68        return false;
69    }
70
71    char magic[8];
72    fread(magic,1,8,pf);
73    if(strncmp(MAP_MAGIC,magic,8))
74    {
75        sLog.outError("Map file '%s' is non-compatible version (outdated?). Please, create new using ad.exe program.",tmp);
76        delete [] tmp;
77        fclose(pf);                                         //close file before return
78        return false;
79    }
80
81    delete [] tmp;
82    fclose(pf);
83
84    return true;
85}
86
87bool Map::ExistVMap(uint32 mapid,int x,int y)
88{
89    if(VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager())
90    {
91        if(vmgr->isMapLoadingEnabled())
92        {
93                                                            // x and y are swaped !! => fixed now
94            bool exists = vmgr->existsMap((sWorld.GetDataPath()+ "vmaps").c_str(),  mapid, x,y);
95            if(!exists)
96            {
97                std::string name = vmgr->getDirFileName(mapid,x,y);
98                sLog.outError("VMap file '%s' is missing or point to wrong version vmap file, redo vmaps with latest vmap_assembler.exe program", (sWorld.GetDataPath()+"vmaps/"+name).c_str());
99                return false;
100            }
101        }
102    }
103
104    return true;
105}
106
107void Map::LoadVMap(int x,int y)
108{
109                                                            // x and y are swaped !!
110    int vmapLoadResult = VMAP::VMapFactory::createOrGetVMapManager()->loadMap((sWorld.GetDataPath()+ "vmaps").c_str(),  GetId(), x,y);
111    switch(vmapLoadResult)
112    {
113        case VMAP::VMAP_LOAD_RESULT_OK:
114            sLog.outDetail("VMAP loaded name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", GetMapName(), GetId(), x,y, x,y);
115            break;
116        case VMAP::VMAP_LOAD_RESULT_ERROR:
117            sLog.outDetail("Could not load VMAP name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", GetMapName(), GetId(), x,y, x,y);
118            break;
119        case VMAP::VMAP_LOAD_RESULT_IGNORED:
120            DEBUG_LOG("Ignored VMAP name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", GetMapName(), GetId(), x,y, x,y);
121            break;
122    }
123}
124
125void Map::LoadMap(uint32 mapid, uint32 instanceid, int x,int y)
126{
127    if( instanceid != 0 )
128    {
129        if(GridMaps[x][y])
130            return;
131
132        Map* baseMap = const_cast<Map*>(MapManager::Instance().GetBaseMap(mapid));
133
134        // load gridmap for base map
135        if (!baseMap->GridMaps[x][y])
136            baseMap->EnsureGridCreated(GridPair(63-x,63-y));
137
138//+++        if (!baseMap->GridMaps[x][y])  don't check for GridMaps[gx][gy], we need the management for vmaps
139//            return;
140
141        ((MapInstanced*)(baseMap))->AddGridMapReference(GridPair(x,y));
142        baseMap->SetUnloadFlag(GridPair(63-x,63-y), false);
143        GridMaps[x][y] = baseMap->GridMaps[x][y];
144        return;
145    }
146
147    //map already load, delete it before reloading (Is it neccessary? Do we really need the abilty the reload maps during runtime?)
148    if(GridMaps[x][y])
149    {
150        sLog.outDetail("Unloading already loaded map %u before reloading.",mapid);
151        delete (GridMaps[x][y]);
152        GridMaps[x][y]=NULL;
153    }
154
155    // map file name
156    char *tmp=NULL;
157    // Pihhan: dataPath length + "maps/" + 3+2+2+ ".map" length may be > 32 !
158    int len = sWorld.GetDataPath().length()+strlen("maps/%03u%02u%02u.map")+1;
159    tmp = new char[len];
160    snprintf(tmp, len, (char *)(sWorld.GetDataPath()+"maps/%03u%02u%02u.map").c_str(),mapid,x,y);
161    sLog.outDetail("Loading map %s",tmp);
162    // loading data
163    FILE *pf=fopen(tmp,"rb");
164    if(!pf)
165    {
166        delete [] tmp;
167        return;
168    }
169
170    char magic[8];
171    fread(magic,1,8,pf);
172    if(strncmp(MAP_MAGIC,magic,8))
173    {
174        sLog.outError("Map file '%s' is non-compatible version (outdated?). Please, create new using ad.exe program.",tmp);
175        delete [] tmp;
176        fclose(pf);                                         //close file before return
177        return;
178    }
179    delete []  tmp;
180
181    GridMap * buf= new GridMap;
182    fread(buf,1,sizeof(GridMap),pf);
183    fclose(pf);
184
185    GridMaps[x][y] = buf;
186}
187
188void Map::LoadMapAndVMap(uint32 mapid, uint32 instanceid, int x,int y)
189{
190    LoadMap(mapid,instanceid,x,y);
191    if(instanceid == 0)
192        LoadVMap(x, y);                                     // Only load the data for the base map
193}
194
195void Map::InitStateMachine()
196{
197    si_GridStates[GRID_STATE_INVALID] = new InvalidState;
198    si_GridStates[GRID_STATE_ACTIVE] = new ActiveState;
199    si_GridStates[GRID_STATE_IDLE] = new IdleState;
200    si_GridStates[GRID_STATE_REMOVAL] = new RemovalState;
201}
202
203void Map::DeleteStateMachine()
204{
205    delete si_GridStates[GRID_STATE_INVALID];
206    delete si_GridStates[GRID_STATE_ACTIVE];
207    delete si_GridStates[GRID_STATE_IDLE];
208    delete si_GridStates[GRID_STATE_REMOVAL];
209}
210
211Map::Map(uint32 id, time_t expiry, uint32 InstanceId, uint8 SpawnMode)
212  : i_id(id), i_gridExpiry(expiry), i_mapEntry (sMapStore.LookupEntry(id)),
213 i_InstanceId(InstanceId), i_spawnMode(SpawnMode), m_unloadTimer(0)
214{
215    for(unsigned int idx=0; idx < MAX_NUMBER_OF_GRIDS; ++idx)
216    {
217        for(unsigned int j=0; j < MAX_NUMBER_OF_GRIDS; ++j)
218        {
219            //z code
220            GridMaps[idx][j] =NULL;
221            setNGrid(NULL, idx, j);
222        }
223    }
224}
225
226// Template specialization of utility methods
227template<class T>
228void Map::AddToGrid(T* obj, NGridType *grid, Cell const& cell)
229{
230    (*grid)(cell.CellX(), cell.CellY()).template AddGridObject<T>(obj, obj->GetGUID());
231}
232
233template<>
234void Map::AddToGrid(Player* obj, NGridType *grid, Cell const& cell)
235{
236    (*grid)(cell.CellX(), cell.CellY()).AddWorldObject(obj, obj->GetGUID());
237}
238
239template<>
240void Map::AddToGrid(Corpse *obj, NGridType *grid, Cell const& cell)
241{
242    // add to world object registry in grid
243    if(obj->GetType()!=CORPSE_BONES)
244    {
245        (*grid)(cell.CellX(), cell.CellY()).AddWorldObject(obj, obj->GetGUID());
246    }
247    // add to grid object store
248    else
249    {
250        (*grid)(cell.CellX(), cell.CellY()).AddGridObject(obj, obj->GetGUID());
251    }
252}
253
254template<>
255void Map::AddToGrid(Creature* obj, NGridType *grid, Cell const& cell)
256{
257    // add to world object registry in grid
258    if(obj->isPet())
259    {
260        (*grid)(cell.CellX(), cell.CellY()).AddWorldObject<Creature>(obj, obj->GetGUID());
261        obj->SetCurrentCell(cell);
262    }
263    // add to grid object store
264    else
265    {
266        (*grid)(cell.CellX(), cell.CellY()).AddGridObject<Creature>(obj, obj->GetGUID());
267        obj->SetCurrentCell(cell);
268    }
269}
270
271template<class T>
272void Map::RemoveFromGrid(T* obj, NGridType *grid, Cell const& cell)
273{
274    (*grid)(cell.CellX(), cell.CellY()).template RemoveGridObject<T>(obj, obj->GetGUID());
275}
276
277template<>
278void Map::RemoveFromGrid(Player* obj, NGridType *grid, Cell const& cell)
279{
280    (*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject(obj, obj->GetGUID());
281}
282
283template<>
284void Map::RemoveFromGrid(Corpse *obj, NGridType *grid, Cell const& cell)
285{
286    // remove from world object registry in grid
287    if(obj->GetType()!=CORPSE_BONES)
288    {
289        (*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject(obj, obj->GetGUID());
290    }
291    // remove from grid object store
292    else
293    {
294        (*grid)(cell.CellX(), cell.CellY()).RemoveGridObject(obj, obj->GetGUID());
295    }
296}
297
298template<>
299void Map::RemoveFromGrid(Creature* obj, NGridType *grid, Cell const& cell)
300{
301    // remove from world object registry in grid
302    if(obj->isPet())
303    {
304        (*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject<Creature>(obj, obj->GetGUID());
305    }
306    // remove from grid object store
307    else
308    {
309        (*grid)(cell.CellX(), cell.CellY()).RemoveGridObject<Creature>(obj, obj->GetGUID());
310    }
311}
312
313template<class T>
314void Map::DeleteFromWorld(T* obj)
315{
316    // Note: In case resurrectable corpse and pet its removed from gloabal lists in own destructors
317    delete obj;
318}
319
320template<class T>
321void Map::AddNotifier(T* , Cell const& , CellPair const& )
322{
323}
324
325template<>
326void Map::AddNotifier(Player* obj, Cell const& cell, CellPair const& cellpair)
327{
328    PlayerRelocationNotify(obj,cell,cellpair);
329}
330
331template<>
332void Map::AddNotifier(Creature* obj, Cell const& cell, CellPair const& cellpair)
333{
334    CreatureRelocationNotify(obj,cell,cellpair);
335}
336
337void
338Map::EnsureGridCreated(const GridPair &p)
339{
340    if(!getNGrid(p.x_coord, p.y_coord))
341    {
342        Guard guard(*this);
343        if(!getNGrid(p.x_coord, p.y_coord))
344        {
345            setNGrid(new NGridType(p.x_coord*MAX_NUMBER_OF_GRIDS + p.y_coord, p.x_coord, p.y_coord, i_gridExpiry, sWorld.getConfig(CONFIG_GRID_UNLOAD)),
346                p.x_coord, p.y_coord);
347
348            // build a linkage between this map and NGridType
349            buildNGridLinkage(getNGrid(p.x_coord, p.y_coord));
350
351            getNGrid(p.x_coord, p.y_coord)->SetGridState(GRID_STATE_IDLE);
352
353            //z coord
354            int gx=63-p.x_coord;
355            int gy=63-p.y_coord;
356
357            if(!GridMaps[gx][gy])
358                Map::LoadMapAndVMap(i_id,i_InstanceId,gx,gy);
359        }
360    }
361}
362
363void
364Map::EnsureGridLoadedForPlayer(const Cell &cell, Player *player, bool add_player)
365{
366    EnsureGridCreated(GridPair(cell.GridX(), cell.GridY()));
367    NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
368
369    assert(grid != NULL);
370    if( !isGridObjectDataLoaded(cell.GridX(), cell.GridY()) )
371    {
372        if( player != NULL )
373        {
374            player->SendDelayResponse(MAX_GRID_LOAD_TIME);
375            DEBUG_LOG("Player %s enter cell[%u,%u] triggers of loading grid[%u,%u] on map %u", player->GetName(), cell.CellX(), cell.CellY(), cell.GridX(), cell.GridY(), i_id);
376        }
377        else
378        {
379            DEBUG_LOG("Player nearby triggers of loading grid [%u,%u] on map %u", cell.GridX(), cell.GridY(), i_id);
380        }
381
382        ObjectGridLoader loader(*grid, this, cell);
383        loader.LoadN();
384        setGridObjectDataLoaded(true, cell.GridX(), cell.GridY());
385
386        // Add resurrectable corpses to world object list in grid
387        ObjectAccessor::Instance().AddCorpsesToGrid(GridPair(cell.GridX(),cell.GridY()),(*grid)(cell.CellX(), cell.CellY()), this);
388
389        ResetGridExpiry(*getNGrid(cell.GridX(), cell.GridY()), 0.1f);
390        grid->SetGridState(GRID_STATE_ACTIVE);
391
392        if( add_player && player != NULL )
393            (*grid)(cell.CellX(), cell.CellY()).AddWorldObject(player, player->GetGUID());
394    }
395    else if( player && add_player )
396        AddToGrid(player,grid,cell);
397}
398
399void
400Map::LoadGrid(const Cell& cell, bool no_unload)
401{
402    EnsureGridCreated(GridPair(cell.GridX(), cell.GridY()));
403    NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
404
405    assert(grid != NULL);
406    if( !isGridObjectDataLoaded(cell.GridX(), cell.GridY()) )
407    {
408        ObjectGridLoader loader(*grid, this, cell);
409        loader.LoadN();
410
411        // Add resurrectable corpses to world object list in grid
412        ObjectAccessor::Instance().AddCorpsesToGrid(GridPair(cell.GridX(),cell.GridY()),(*grid)(cell.CellX(), cell.CellY()), this);
413
414        setGridObjectDataLoaded(true,cell.GridX(), cell.GridY());
415        if(no_unload)
416            getNGrid(cell.GridX(), cell.GridY())->setUnloadFlag(false);
417    }
418    LoadVMap(63-cell.GridX(),63-cell.GridY());
419}
420
421bool Map::Add(Player *player)
422{
423    player->SetInstanceId(this->GetInstanceId());
424
425    // update player state for other player and visa-versa
426    CellPair p = Trinity::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
427    Cell cell(p);
428    EnsureGridLoadedForPlayer(cell, player, true);
429    player->AddToWorld();
430
431    SendInitSelf(player);
432    SendInitTransports(player);
433
434    UpdatePlayerVisibility(player,cell,p);
435    UpdateObjectsVisibilityFor(player,cell,p);
436
437    AddNotifier(player,cell,p);
438    return true;
439}
440
441template<class T>
442void
443Map::Add(T *obj)
444{
445    CellPair p = Trinity::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
446
447    assert(obj);
448
449    if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
450    {
451        sLog.outError("Map::Add: Object " I64FMTD " have invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUID(), obj->GetPositionX(), obj->GetPositionY(), p.x_coord, p.y_coord);
452        return;
453    }
454
455    Cell cell(p);
456    EnsureGridCreated(GridPair(cell.GridX(), cell.GridY()));
457    NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
458    assert( grid != NULL );
459
460    AddToGrid(obj,grid,cell);
461    obj->AddToWorld();
462
463    DEBUG_LOG("Object %u enters grid[%u,%u]", GUID_LOPART(obj->GetGUID()), cell.GridX(), cell.GridY());
464
465    UpdateObjectVisibility(obj,cell,p);
466
467    AddNotifier(obj,cell,p);
468}
469
470void Map::MessageBroadcast(Player *player, WorldPacket *msg, bool to_self)
471{
472    CellPair p = Trinity::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
473
474    if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
475    {
476        sLog.outError("Map::MessageBroadcast: Player (GUID: %u) have invalid coordinates X:%f Y:%f grid cell [%u:%u]", player->GetGUIDLow(), player->GetPositionX(), player->GetPositionY(), p.x_coord, p.y_coord);
477        return;
478    }
479
480    Cell cell(p);
481    cell.data.Part.reserved = ALL_DISTRICT;
482
483    if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
484        return;
485
486    Trinity::MessageDeliverer post_man(*player, msg, to_self);
487    TypeContainerVisitor<Trinity::MessageDeliverer, WorldTypeMapContainer > message(post_man);
488    CellLock<ReadGuard> cell_lock(cell, p);
489    cell_lock->Visit(cell_lock, message, *this);
490}
491
492void Map::MessageBroadcast(WorldObject *obj, WorldPacket *msg)
493{
494    CellPair p = Trinity::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
495
496    if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
497    {
498        sLog.outError("Map::MessageBroadcast: Object " I64FMTD " have invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUID(), obj->GetPositionX(), obj->GetPositionY(), p.x_coord, p.y_coord);
499        return;
500    }
501
502    Cell cell(p);
503    cell.data.Part.reserved = ALL_DISTRICT;
504    cell.SetNoCreate();
505
506    if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
507        return;
508
509    Trinity::ObjectMessageDeliverer post_man(msg);
510    TypeContainerVisitor<Trinity::ObjectMessageDeliverer, WorldTypeMapContainer > message(post_man);
511    CellLock<ReadGuard> cell_lock(cell, p);
512    cell_lock->Visit(cell_lock, message, *this);
513}
514
515void Map::MessageDistBroadcast(Player *player, WorldPacket *msg, float dist, bool to_self, bool own_team_only)
516{
517    CellPair p = Trinity::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
518
519    if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
520    {
521        sLog.outError("Map::MessageBroadcast: Player (GUID: %u) have invalid coordinates X:%f Y:%f grid cell [%u:%u]", player->GetGUIDLow(), player->GetPositionX(), player->GetPositionY(), p.x_coord, p.y_coord);
522        return;
523    }
524
525    Cell cell(p);
526    cell.data.Part.reserved = ALL_DISTRICT;
527
528    if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
529        return;
530
531    Trinity::MessageDistDeliverer post_man(*player, msg, dist, to_self, own_team_only);
532    TypeContainerVisitor<Trinity::MessageDistDeliverer , WorldTypeMapContainer > message(post_man);
533    CellLock<ReadGuard> cell_lock(cell, p);
534    cell_lock->Visit(cell_lock, message, *this);
535}
536
537void Map::MessageDistBroadcast(WorldObject *obj, WorldPacket *msg, float dist)
538{
539    CellPair p = Trinity::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
540
541    if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
542    {
543        sLog.outError("Map::MessageBroadcast: Object " I64FMTD " have invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUID(), obj->GetPositionX(), obj->GetPositionY(), p.x_coord, p.y_coord);
544        return;
545    }
546
547    Cell cell(p);
548    cell.data.Part.reserved = ALL_DISTRICT;
549    cell.SetNoCreate();
550
551    if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
552        return;
553
554    Trinity::ObjectMessageDistDeliverer post_man(*obj, msg,dist);
555    TypeContainerVisitor<Trinity::ObjectMessageDistDeliverer, WorldTypeMapContainer > message(post_man);
556    CellLock<ReadGuard> cell_lock(cell, p);
557    cell_lock->Visit(cell_lock, message, *this);
558}
559
560bool Map::loaded(const GridPair &p) const
561{
562    return ( getNGrid(p.x_coord, p.y_coord) && isGridObjectDataLoaded(p.x_coord, p.y_coord) );
563}
564
565void Map::Update(const uint32 &t_diff)
566{
567    // Don't unload grids if it's battleground, since we may have manually added GOs,creatures, those doesn't load from DB at grid re-load !
568    // This isn't really bother us, since as soon as we have instanced BG-s, the whole map unloads as the BG gets ended
569    if (IsBattleGroundOrArena())
570        return;
571
572    for (GridRefManager<NGridType>::iterator i = GridRefManager<NGridType>::begin(); i != GridRefManager<NGridType>::end(); )
573    {
574        NGridType *grid = i->getSource();
575        GridInfo *info = i->getSource()->getGridInfoRef();
576        ++i;                                                // The update might delete the map and we need the next map before the iterator gets invalid
577        assert(grid->GetGridState() >= 0 && grid->GetGridState() < MAX_GRID_STATE);
578        si_GridStates[grid->GetGridState()]->Update(*this, *grid, *info, grid->getX(), grid->getY(), t_diff);
579    }
580}
581
582void Map::Remove(Player *player, bool remove)
583{
584    CellPair p = Trinity::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
585    if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
586    {
587        // invalid coordinates
588        player->RemoveFromWorld();
589
590        if( remove )
591            DeleteFromWorld(player);
592
593        return;
594    }
595
596    Cell cell(p);
597
598    if( !getNGrid(cell.data.Part.grid_x, cell.data.Part.grid_y) )
599    {
600        sLog.outError("Map::Remove() i_grids was NULL x:%d, y:%d",cell.data.Part.grid_x,cell.data.Part.grid_y);
601        return;
602    }
603
604    DEBUG_LOG("Remove player %s from grid[%u,%u]", player->GetName(), cell.GridX(), cell.GridY());
605    NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
606    assert(grid != NULL);
607
608    player->RemoveFromWorld();
609    RemoveFromGrid(player,grid,cell);
610
611    SendRemoveTransports(player);
612
613    UpdateObjectsVisibilityFor(player,cell,p);
614
615    if( remove )
616        DeleteFromWorld(player);
617}
618
619bool Map::RemoveBones(uint64 guid, float x, float y)
620{
621    if (IsRemovalGrid(x, y))
622    {
623        Corpse * corpse = ObjectAccessor::Instance().GetObjectInWorld(GetId(), x, y, guid, (Corpse*)NULL);
624        if(corpse && corpse->GetTypeId() == TYPEID_CORPSE && corpse->GetType() == CORPSE_BONES)
625            corpse->DeleteBonesFromWorld();
626        else
627            return false;
628    }
629    return true;
630}
631
632template<class T>
633void
634Map::Remove(T *obj, bool remove)
635{
636    CellPair p = Trinity::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
637    if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP )
638    {
639        sLog.outError("Map::Remove: Object " I64FMTD " have invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUID(), obj->GetPositionX(), obj->GetPositionY(), p.x_coord, p.y_coord);
640        return;
641    }
642
643    Cell cell(p);
644    if( !loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)) )
645        return;
646
647    DEBUG_LOG("Remove object " I64FMTD " from grid[%u,%u]", obj->GetGUID(), cell.data.Part.grid_x, cell.data.Part.grid_y);
648    NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
649    assert( grid != NULL );
650
651    obj->RemoveFromWorld();
652    RemoveFromGrid(obj,grid,cell);
653
654    UpdateObjectVisibility(obj,cell,p);
655
656    if( remove )
657    {
658        // if option set then object already saved at this moment
659        if(!sWorld.getConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY))
660            obj->SaveRespawnTime();
661        DeleteFromWorld(obj);
662    }
663}
664
665void
666Map::PlayerRelocation(Player *player, float x, float y, float z, float orientation)
667{
668    assert(player);
669
670    CellPair old_val = Trinity::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
671    CellPair new_val = Trinity::ComputeCellPair(x, y);
672
673    Cell old_cell(old_val);
674    Cell new_cell(new_val);
675    new_cell |= old_cell;
676    bool same_cell = (new_cell == old_cell);
677
678    player->Relocate(x, y, z, orientation);
679
680    if( old_cell.DiffGrid(new_cell) || old_cell.DiffCell(new_cell) )
681    {
682        DEBUG_LOG("Player %s relocation grid[%u,%u]cell[%u,%u]->grid[%u,%u]cell[%u,%u]", player->GetName(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY(), new_cell.GridX(), new_cell.GridY(), new_cell.CellX(), new_cell.CellY());
683
684        // update player position for group at taxi flight
685        if(player->GetGroup() && player->isInFlight())
686            player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
687
688        NGridType* oldGrid = getNGrid(old_cell.GridX(), old_cell.GridY());
689        RemoveFromGrid(player, oldGrid,old_cell);
690        if( !old_cell.DiffGrid(new_cell) )
691            AddToGrid(player, oldGrid,new_cell);
692
693        if( old_cell.DiffGrid(new_cell) )
694            EnsureGridLoadedForPlayer(new_cell, player, true);
695    }
696
697    // if move then update what player see and who seen
698    UpdatePlayerVisibility(player,new_cell,new_val);
699    UpdateObjectsVisibilityFor(player,new_cell,new_val);
700    PlayerRelocationNotify(player,new_cell,new_val);
701    NGridType* newGrid = getNGrid(new_cell.GridX(), new_cell.GridY());
702    if( !same_cell && newGrid->GetGridState()!= GRID_STATE_ACTIVE )
703    {
704        ResetGridExpiry(*newGrid, 0.1f);
705        newGrid->SetGridState(GRID_STATE_ACTIVE);
706    }
707}
708
709void
710Map::CreatureRelocation(Creature *creature, float x, float y, float z, float ang)
711{
712    assert(CheckGridIntegrity(creature,false));
713
714    Cell old_cell = creature->GetCurrentCell();
715
716    CellPair new_val = Trinity::ComputeCellPair(x, y);
717    Cell new_cell(new_val);
718
719    // delay creature move for grid/cell to grid/cell moves
720    if( old_cell.DiffCell(new_cell) || old_cell.DiffGrid(new_cell) )
721    {
722        #ifdef TRINITY_DEBUG
723        if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
724            sLog.outDebug("Creature (GUID: %u Entry: %u) added to moving list from grid[%u,%u]cell[%u,%u] to grid[%u,%u]cell[%u,%u].", creature->GetGUIDLow(), creature->GetEntry(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY(), new_cell.GridX(), new_cell.GridY(), new_cell.CellX(), new_cell.CellY());
725        #endif
726        AddCreatureToMoveList(creature,x,y,z,ang);
727        // in diffcell/diffgrid case notifiers called at finishing move creature in Map::MoveAllCreaturesInMoveList
728    }
729    else
730    {
731        creature->Relocate(x, y, z, ang);
732        CreatureRelocationNotify(creature,new_cell,new_val);
733    }
734    assert(CheckGridIntegrity(creature,true));
735}
736
737void Map::AddCreatureToMoveList(Creature *c, float x, float y, float z, float ang)
738{
739    if(!c)
740        return;
741
742    i_creaturesToMove[c] = CreatureMover(x,y,z,ang);
743}
744
745void Map::MoveAllCreaturesInMoveList()
746{
747    while(!i_creaturesToMove.empty())
748    {
749        // get data and remove element;
750        CreatureMoveList::iterator iter = i_creaturesToMove.begin();
751        Creature* c = iter->first;
752        CreatureMover cm = iter->second;
753        i_creaturesToMove.erase(iter);
754
755        // calculate cells
756        CellPair new_val = Trinity::ComputeCellPair(cm.x, cm.y);
757        Cell new_cell(new_val);
758
759        // do move or do move to respawn or remove creature if previous all fail
760        if(CreatureCellRelocation(c,new_cell))
761        {
762            // update pos
763            c->Relocate(cm.x, cm.y, cm.z, cm.ang);
764            CreatureRelocationNotify(c,new_cell,new_cell.cellPair());
765        }
766        else
767        {
768            // if creature can't be move in new cell/grid (not loaded) move it to repawn cell/grid
769            // creature coordinates will be updated and notifiers send
770            if(!CreatureRespawnRelocation(c))
771            {
772                // ... or unload (if respawn grid also not loaded)
773                #ifdef TRINITY_DEBUG
774                if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
775                    sLog.outDebug("Creature (GUID: %u Entry: %u ) can't be move to unloaded respawn grid.",c->GetGUIDLow(),c->GetEntry());
776                #endif
777                c->CleanupsBeforeDelete();
778                AddObjectToRemoveList(c);
779            }
780        }
781    }
782}
783
784bool Map::CreatureCellRelocation(Creature *c, Cell new_cell)
785{
786    Cell const& old_cell = c->GetCurrentCell();
787    if(!old_cell.DiffGrid(new_cell) )                       // in same grid
788    {
789        // if in same cell then none do
790        if(old_cell.DiffCell(new_cell))
791        {
792            #ifdef TRINITY_DEBUG
793            if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
794                sLog.outDebug("Creature (GUID: %u Entry: %u) moved in grid[%u,%u] from cell[%u,%u] to cell[%u,%u].", c->GetGUIDLow(), c->GetEntry(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY(), new_cell.CellX(), new_cell.CellY());
795            #endif
796
797            if( !old_cell.DiffGrid(new_cell) )
798            {
799                RemoveFromGrid(c,getNGrid(old_cell.GridX(), old_cell.GridY()),old_cell);
800                AddToGrid(c,getNGrid(new_cell.GridX(), new_cell.GridY()),new_cell);
801                c->SetCurrentCell(new_cell);
802            }
803        }
804        else
805        {
806            #ifdef TRINITY_DEBUG
807            if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
808                sLog.outDebug("Creature (GUID: %u Entry: %u) move in same grid[%u,%u]cell[%u,%u].", c->GetGUIDLow(), c->GetEntry(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY());
809            #endif
810        }
811    }
812    else                                                    // in diff. grids
813    if(loaded(GridPair(new_cell.GridX(), new_cell.GridY())))
814    {
815        #ifdef TRINITY_DEBUG
816        if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
817            sLog.outDebug("Creature (GUID: %u Entry: %u) moved from grid[%u,%u]cell[%u,%u] to grid[%u,%u]cell[%u,%u].", c->GetGUIDLow(), c->GetEntry(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY(), new_cell.GridX(), new_cell.GridY(), new_cell.CellX(), new_cell.CellY());
818        #endif
819
820        RemoveFromGrid(c,getNGrid(old_cell.GridX(), old_cell.GridY()),old_cell);
821        {
822            EnsureGridCreated(GridPair(new_cell.GridX(), new_cell.GridY()));
823            AddToGrid(c,getNGrid(new_cell.GridX(), new_cell.GridY()),new_cell);
824        }
825    }
826    else
827    {
828        #ifdef TRINITY_DEBUG
829        if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
830            sLog.outDebug("Creature (GUID: %u Entry: %u) attempt move from grid[%u,%u]cell[%u,%u] to unloaded grid[%u,%u]cell[%u,%u].", c->GetGUIDLow(), c->GetEntry(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY(), new_cell.GridX(), new_cell.GridY(), new_cell.CellX(), new_cell.CellY());
831        #endif
832        return false;
833    }
834
835    return true;
836}
837
838bool Map::CreatureRespawnRelocation(Creature *c)
839{
840    float resp_x, resp_y, resp_z, resp_o;
841    c->GetRespawnCoord(resp_x, resp_y, resp_z, &resp_o);
842
843    CellPair resp_val = Trinity::ComputeCellPair(resp_x, resp_y);
844    Cell resp_cell(resp_val);
845
846    c->CombatStop();
847    c->GetMotionMaster()->Clear();
848
849    #ifdef TRINITY_DEBUG
850    if((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES)==0)
851        sLog.outDebug("Creature (GUID: %u Entry: %u) will moved from grid[%u,%u]cell[%u,%u] to respawn grid[%u,%u]cell[%u,%u].", c->GetGUIDLow(), c->GetEntry(), c->GetCurrentCell().GridX(), c->GetCurrentCell().GridY(), c->GetCurrentCell().CellX(), c->GetCurrentCell().CellY(), resp_cell.GridX(), resp_cell.GridY(), resp_cell.CellX(), resp_cell.CellY());
852    #endif
853
854    // teleport it to respawn point (like normal respawn if player see)
855    if(CreatureCellRelocation(c,resp_cell))
856    {
857        c->Relocate(resp_x, resp_y, resp_z, resp_o);
858        c->GetMotionMaster()->Initialize();                 // prevent possible problems with default move generators
859        CreatureRelocationNotify(c,resp_cell,resp_cell.cellPair());
860        return true;
861    }
862    else
863        return false;
864}
865
866bool Map::UnloadGrid(const uint32 &x, const uint32 &y, bool pForce)
867{
868    NGridType *grid = getNGrid(x, y);
869    assert( grid != NULL);
870
871    {
872        if(!pForce && ObjectAccessor::Instance().ActiveObjectsNearGrid(x, y, i_id, i_InstanceId) )
873            return false;
874
875        DEBUG_LOG("Unloading grid[%u,%u] for map %u", x,y, i_id);
876        ObjectGridUnloader unloader(*grid);
877
878        // Finish creature moves, remove and delete all creatures with delayed remove before moving to respawn grids
879        // Must know real mob position before move
880        DoDelayedMovesAndRemoves();
881
882        // move creatures to respawn grids if this is diff.grid or to remove list
883        unloader.MoveToRespawnN();
884
885        // Finish creature moves, remove and delete all creatures with delayed remove before unload
886        DoDelayedMovesAndRemoves();
887
888        unloader.UnloadN();
889        delete getNGrid(x, y);
890        setNGrid(NULL, x, y);
891    }
892    int gx=63-x;
893    int gy=63-y;
894
895    // delete grid map, but don't delete if it is from parent map (and thus only reference)
896    //+++if (GridMaps[gx][gy]) don't check for GridMaps[gx][gy], we might have to unload vmaps
897    {
898        if (i_InstanceId == 0)
899        {
900            if(GridMaps[gx][gy]) delete (GridMaps[gx][gy]);
901            // x and y are swaped
902            VMAP::VMapFactory::createOrGetVMapManager()->unloadMap(GetId(), gy, gx);
903        }
904        else
905            ((MapInstanced*)(MapManager::Instance().GetBaseMap(i_id)))->RemoveGridMapReference(GridPair(gx, gy));
906        GridMaps[gx][gy] = NULL;
907    }
908    DEBUG_LOG("Unloading grid[%u,%u] for map %u finished", x,y, i_id);
909    return true;
910}
911
912void Map::UnloadAll(bool pForce)
913{
914    // clear all delayed moves, useless anyway do this moves before map unload.
915    i_creaturesToMove.clear();
916
917    for (GridRefManager<NGridType>::iterator i = GridRefManager<NGridType>::begin(); i != GridRefManager<NGridType>::end(); )
918    {
919        NGridType &grid(*i->getSource());
920        ++i;
921        UnloadGrid(grid.getX(), grid.getY(), pForce);       // deletes the grid and removes it from the GridRefManager
922    }
923}
924
925float Map::GetHeight(float x, float y, float z, bool pUseVmaps) const
926{
927    GridPair p = Trinity::ComputeGridPair(x, y);
928
929    // half opt method
930    int gx=(int)(32-x/SIZE_OF_GRIDS);                       //grid x
931    int gy=(int)(32-y/SIZE_OF_GRIDS);                       //grid y
932
933    float lx=MAP_RESOLUTION*(32 -x/SIZE_OF_GRIDS - gx);
934    float ly=MAP_RESOLUTION*(32 -y/SIZE_OF_GRIDS - gy);
935
936    // ensure GridMap is loaded
937    const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
938
939    // find raw .map surface under Z coordinates
940    float mapHeight;
941    if(GridMap* gmap = GridMaps[gx][gy])
942    {
943        int lx_int = (int)lx;
944        int ly_int = (int)ly;
945
946        float zi[4];
947        // Probe 4 nearest points (except border cases)
948        zi[0] = gmap->Z[lx_int][ly_int];
949        zi[1] = lx < MAP_RESOLUTION-1 ? gmap->Z[lx_int+1][ly_int] : zi[0];
950        zi[2] = ly < MAP_RESOLUTION-1 ? gmap->Z[lx_int][ly_int+1] : zi[0];
951        zi[3] = lx < MAP_RESOLUTION-1 && ly < MAP_RESOLUTION-1 ? gmap->Z[lx_int+1][ly_int+1] : zi[0];
952        // Recalculate them like if their x,y positions were in the range 0,1
953        float b[4];
954        b[0] = zi[0];
955        b[1] = zi[1]-zi[0];
956        b[2] = zi[2]-zi[0];
957        b[3] = zi[0]-zi[1]-zi[2]+zi[3];
958        // Normalize the dx and dy to be in range 0..1
959        float fact_x = lx - lx_int;
960        float fact_y = ly - ly_int;
961        // Use the simplified bilinear equation, as described in [url="http://en.wikipedia.org/wiki/Bilinear_interpolation"]http://en.wikipedia.org/wiki/Bilinear_interpolation[/url]
962        float _mapheight = b[0] + (b[1]*fact_x) + (b[2]*fact_y) + (b[3]*fact_x*fact_y);
963
964        // look from a bit higher pos to find the floor, ignore under surface case
965        if(z + 2.0f > _mapheight)
966            mapHeight = _mapheight;
967        else
968            mapHeight = VMAP_INVALID_HEIGHT_VALUE;
969    }
970    else
971        mapHeight = VMAP_INVALID_HEIGHT_VALUE;
972
973    float vmapHeight;
974    if(pUseVmaps)
975    {
976        VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager();
977        if(vmgr->isHeightCalcEnabled())
978        {
979            // look from a bit higher pos to find the floor
980            vmapHeight = vmgr->getHeight(GetId(), x, y, z + 2.0f);
981        }
982        else
983            vmapHeight = VMAP_INVALID_HEIGHT_VALUE;
984    }
985    else
986        vmapHeight = VMAP_INVALID_HEIGHT_VALUE;
987
988    // mapHeight set for any above raw ground Z or <= INVALID_HEIGHT
989    // vmapheight set for any under Z value or <= INVALID_HEIGHT
990
991    if( vmapHeight > INVALID_HEIGHT )
992    {
993        if( mapHeight > INVALID_HEIGHT )
994        {
995            // we have mapheight and vmapheight and must select more appropriate
996
997            // we are already under the surface or vmap height above map heigt
998            // or if the distance of the vmap height is less the land height distance
999            if( z < mapHeight || vmapHeight > mapHeight || fabs(mapHeight-z) > fabs(vmapHeight-z) )
1000                return vmapHeight;
1001            else
1002                return mapHeight;                           // better use .map surface height
1003
1004        }
1005        else
1006            return vmapHeight;                              // we have only vmapHeight (if have)
1007    }
1008    else
1009    {
1010        if(!pUseVmaps)
1011            return mapHeight;                               // explicitly use map data (if have)
1012        else if(mapHeight > INVALID_HEIGHT && (z < mapHeight + 2 || z == MAX_HEIGHT))
1013            return mapHeight;                               // explicitly use map data if original z < mapHeight but map found (z+2 > mapHeight)
1014        else
1015            return VMAP_INVALID_HEIGHT_VALUE;               // we not have any height
1016    }
1017}
1018
1019uint16 Map::GetAreaFlag(float x, float y ) const
1020{
1021    //local x,y coords
1022    float lx,ly;
1023    int gx,gy;
1024    GridPair p = Trinity::ComputeGridPair(x, y);
1025
1026    // half opt method
1027    gx=(int)(32-x/SIZE_OF_GRIDS) ;                          //grid x
1028    gy=(int)(32-y/SIZE_OF_GRIDS);                           //grid y
1029
1030    lx=16*(32 -x/SIZE_OF_GRIDS - gx);
1031    ly=16*(32 -y/SIZE_OF_GRIDS - gy);
1032    //DEBUG_LOG("my %d %d si %d %d",gx,gy,p.x_coord,p.y_coord);
1033
1034    // ensure GridMap is loaded
1035    const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
1036
1037    if(GridMaps[gx][gy])
1038        return GridMaps[gx][gy]->area_flag[(int)(lx)][(int)(ly)];
1039    // this used while not all *.map files generated (instances)
1040    else
1041        return GetAreaFlagByMapId(i_id);
1042}
1043
1044uint8 Map::GetTerrainType(float x, float y ) const
1045{
1046    //local x,y coords
1047    float lx,ly;
1048    int gx,gy;
1049
1050    // half opt method
1051    gx=(int)(32-x/SIZE_OF_GRIDS) ;                          //grid x
1052    gy=(int)(32-y/SIZE_OF_GRIDS);                           //grid y
1053
1054    lx=16*(32 -x/SIZE_OF_GRIDS - gx);
1055    ly=16*(32 -y/SIZE_OF_GRIDS - gy);
1056
1057    // ensure GridMap is loaded
1058    const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
1059
1060    if(GridMaps[gx][gy])
1061        return GridMaps[gx][gy]->terrain_type[(int)(lx)][(int)(ly)];
1062    else
1063        return 0;
1064
1065}
1066
1067float Map::GetWaterLevel(float x, float y ) const
1068{
1069    //local x,y coords
1070    float lx,ly;
1071    int gx,gy;
1072
1073    // half opt method
1074    gx=(int)(32-x/SIZE_OF_GRIDS) ;                          //grid x
1075    gy=(int)(32-y/SIZE_OF_GRIDS);                           //grid y
1076
1077    lx=128*(32 -x/SIZE_OF_GRIDS - gx);
1078    ly=128*(32 -y/SIZE_OF_GRIDS - gy);
1079
1080    // ensure GridMap is loaded
1081    const_cast<Map*>(this)->EnsureGridCreated(GridPair(63-gx,63-gy));
1082
1083    if(GridMaps[gx][gy])
1084        return GridMaps[gx][gy]->liquid_level[(int)(lx)][(int)(ly)];
1085    else
1086        return 0;
1087}
1088
1089uint32 Map::GetAreaId(uint16 areaflag,uint32 map_id)
1090{
1091    AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
1092
1093    if (entry)
1094        return entry->ID;
1095    else
1096        return 0;
1097}
1098
1099uint32 Map::GetZoneId(uint16 areaflag,uint32 map_id)
1100{
1101    AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
1102
1103    if( entry )
1104        return ( entry->zone != 0 ) ? entry->zone : entry->ID;
1105    else
1106        return 0;
1107}
1108
1109bool Map::IsInWater(float x, float y, float pZ) const
1110{
1111    // This method is called too often to use vamps for that (4. parameter = false).
1112    // The pZ pos is taken anyway for future use
1113    float z = GetHeight(x,y,pZ,false);                      // use .map base surface height
1114
1115    // underground or instance without vmap
1116    if(z <= INVALID_HEIGHT)
1117        return false;
1118
1119    float water_z = GetWaterLevel(x,y);
1120    uint8 flag = GetTerrainType(x,y);
1121    return (z < (water_z-2)) && (flag & 0x01);
1122}
1123
1124bool Map::IsUnderWater(float x, float y, float z) const
1125{
1126    float water_z = GetWaterLevel(x,y);
1127    uint8 flag = GetTerrainType(x,y);
1128    return (z < (water_z-2)) && (flag & 0x01);
1129}
1130
1131bool Map::CheckGridIntegrity(Creature* c, bool moved) const
1132{
1133    Cell const& cur_cell = c->GetCurrentCell();
1134
1135    CellPair xy_val = Trinity::ComputeCellPair(c->GetPositionX(), c->GetPositionY());
1136    Cell xy_cell(xy_val);
1137    if(xy_cell != cur_cell)
1138    {
1139        sLog.outError("ERROR: %s (GUID: %u) X: %f Y: %f (%s) in grid[%u,%u]cell[%u,%u] instead grid[%u,%u]cell[%u,%u]",
1140            (c->GetTypeId()==TYPEID_PLAYER ? "Player" : "Creature"),c->GetGUIDLow(),
1141            c->GetPositionX(),c->GetPositionY(),(moved ? "final" : "original"),
1142            cur_cell.GridX(), cur_cell.GridY(), cur_cell.CellX(), cur_cell.CellY(),
1143            xy_cell.GridX(),  xy_cell.GridY(),  xy_cell.CellX(),  xy_cell.CellY());
1144        return true;                                        // not crash at error, just output error in debug mode
1145    }
1146
1147    return true;
1148}
1149
1150const char* Map::GetMapName() const
1151{
1152    return i_mapEntry ? i_mapEntry->name[sWorld.GetDefaultDbcLocale()] : "UNNAMEDMAP\x0";
1153}
1154
1155void Map::UpdateObjectVisibility( WorldObject* obj, Cell cell, CellPair cellpair)
1156{
1157    cell.data.Part.reserved = ALL_DISTRICT;
1158    cell.SetNoCreate();
1159    Trinity::VisibleChangesNotifier notifier(*obj);
1160    TypeContainerVisitor<Trinity::VisibleChangesNotifier, WorldTypeMapContainer > player_notifier(notifier);
1161    CellLock<GridReadGuard> cell_lock(cell, cellpair);
1162    cell_lock->Visit(cell_lock, player_notifier, *this);
1163}
1164
1165void Map::UpdatePlayerVisibility( Player* player, Cell cell, CellPair cellpair )
1166{
1167    cell.data.Part.reserved = ALL_DISTRICT;
1168
1169    Trinity::PlayerNotifier pl_notifier(*player);
1170    TypeContainerVisitor<Trinity::PlayerNotifier, WorldTypeMapContainer > player_notifier(pl_notifier);
1171
1172    CellLock<ReadGuard> cell_lock(cell, cellpair);
1173    cell_lock->Visit(cell_lock, player_notifier, *this);
1174}
1175
1176void Map::UpdateObjectsVisibilityFor( Player* player, Cell cell, CellPair cellpair )
1177{
1178    Trinity::VisibleNotifier notifier(*player);
1179
1180    cell.data.Part.reserved = ALL_DISTRICT;
1181    cell.SetNoCreate();
1182    TypeContainerVisitor<Trinity::VisibleNotifier, WorldTypeMapContainer > world_notifier(notifier);
1183    TypeContainerVisitor<Trinity::VisibleNotifier, GridTypeMapContainer  > grid_notifier(notifier);
1184    CellLock<GridReadGuard> cell_lock(cell, cellpair);
1185    cell_lock->Visit(cell_lock, world_notifier, *this);
1186    cell_lock->Visit(cell_lock, grid_notifier,  *this);
1187
1188    // send data
1189    notifier.Notify();
1190}
1191
1192void Map::PlayerRelocationNotify( Player* player, Cell cell, CellPair cellpair )
1193{
1194    CellLock<ReadGuard> cell_lock(cell, cellpair);
1195    Trinity::PlayerRelocationNotifier relocationNotifier(*player);
1196    cell.data.Part.reserved = ALL_DISTRICT;
1197
1198    TypeContainerVisitor<Trinity::PlayerRelocationNotifier, GridTypeMapContainer >  p2grid_relocation(relocationNotifier);
1199    TypeContainerVisitor<Trinity::PlayerRelocationNotifier, WorldTypeMapContainer > p2world_relocation(relocationNotifier);
1200
1201    cell_lock->Visit(cell_lock, p2grid_relocation, *this);
1202    cell_lock->Visit(cell_lock, p2world_relocation, *this);
1203}
1204
1205void Map::CreatureRelocationNotify(Creature *creature, Cell cell, CellPair cellpair)
1206{
1207    CellLock<ReadGuard> cell_lock(cell, cellpair);
1208    Trinity::CreatureRelocationNotifier relocationNotifier(*creature);
1209    cell.data.Part.reserved = ALL_DISTRICT;
1210    cell.SetNoCreate();                                     // not trigger load unloaded grids at notifier call
1211
1212    TypeContainerVisitor<Trinity::CreatureRelocationNotifier, WorldTypeMapContainer > c2world_relocation(relocationNotifier);
1213    TypeContainerVisitor<Trinity::CreatureRelocationNotifier, GridTypeMapContainer >  c2grid_relocation(relocationNotifier);
1214
1215    cell_lock->Visit(cell_lock, c2world_relocation, *this);
1216    cell_lock->Visit(cell_lock, c2grid_relocation, *this);
1217}
1218
1219void Map::SendInitSelf( Player * player )
1220{
1221    sLog.outDetail("Creating player data for himself %u", player->GetGUIDLow());
1222
1223    UpdateData data;
1224
1225    bool hasTransport = false;
1226
1227    // attach to player data current transport data
1228    if(Transport* transport = player->GetTransport())
1229    {
1230        hasTransport = true;
1231        transport->BuildCreateUpdateBlockForPlayer(&data, player);
1232    }
1233
1234    // build data for self presence in world at own client (one time for map)
1235    player->BuildCreateUpdateBlockForPlayer(&data, player);
1236
1237    // build other passengers at transport also (they always visible and marked as visible and will not send at visibility update at add to map
1238    if(Transport* transport = player->GetTransport())
1239    {
1240        for(Transport::PlayerSet::const_iterator itr = transport->GetPassengers().begin();itr!=transport->GetPassengers().end();++itr)
1241        {
1242            if(player!=(*itr) && player->HaveAtClient(*itr))
1243            {
1244                hasTransport = true;
1245                (*itr)->BuildCreateUpdateBlockForPlayer(&data, player);
1246            }
1247        }
1248    }
1249
1250    WorldPacket packet;
1251    data.BuildPacket(&packet, hasTransport);
1252    player->GetSession()->SendPacket(&packet);
1253}
1254
1255void Map::SendInitTransports( Player * player )
1256{
1257    // Hack to send out transports
1258    MapManager::TransportMap& tmap = MapManager::Instance().m_TransportsByMap;
1259
1260    // no transports at map
1261    if (tmap.find(player->GetMapId()) == tmap.end())
1262        return;
1263
1264    UpdateData transData;
1265
1266    MapManager::TransportSet& tset = tmap[player->GetMapId()];
1267
1268    bool hasTransport = false;
1269
1270    for (MapManager::TransportSet::iterator i = tset.begin(); i != tset.end(); ++i)
1271    {
1272        if((*i) != player->GetTransport())                  // send data for current transport in other place
1273        {
1274            hasTransport = true;
1275            (*i)->BuildCreateUpdateBlockForPlayer(&transData, player);
1276        }
1277    }
1278
1279    WorldPacket packet;
1280    transData.BuildPacket(&packet, hasTransport);
1281    player->GetSession()->SendPacket(&packet);
1282}
1283
1284void Map::SendRemoveTransports( Player * player )
1285{
1286    // Hack to send out transports
1287    MapManager::TransportMap& tmap = MapManager::Instance().m_TransportsByMap;
1288
1289    // no transports at map
1290    if (tmap.find(player->GetMapId()) == tmap.end())
1291        return;
1292
1293    UpdateData transData;
1294
1295    MapManager::TransportSet& tset = tmap[player->GetMapId()];
1296
1297    // except used transport
1298    for (MapManager::TransportSet::iterator i = tset.begin(); i != tset.end(); ++i)
1299        if(player->GetTransport() != (*i))
1300            (*i)->BuildOutOfRangeUpdateBlock(&transData);
1301
1302    WorldPacket packet;
1303    transData.BuildPacket(&packet);
1304    player->GetSession()->SendPacket(&packet);
1305}
1306
1307inline void Map::setNGrid(NGridType *grid, uint32 x, uint32 y)
1308{
1309    if(x >= MAX_NUMBER_OF_GRIDS || y >= MAX_NUMBER_OF_GRIDS)
1310    {
1311        sLog.outError("map::setNGrid() Invalid grid coordinates found: %d, %d!",x,y);
1312        assert(false);
1313    }
1314    i_grids[x][y] = grid;
1315}
1316
1317void Map::DoDelayedMovesAndRemoves()
1318{
1319    MoveAllCreaturesInMoveList();
1320    RemoveAllObjectsInRemoveList();
1321}
1322
1323void Map::AddObjectToRemoveList(WorldObject *obj)
1324{
1325    assert(obj->GetMapId()==GetId() && obj->GetInstanceId()==GetInstanceId());
1326
1327    i_objectsToRemove.insert(obj);
1328    //sLog.outDebug("Object (GUID: %u TypeId: %u ) added to removing list.",obj->GetGUIDLow(),obj->GetTypeId());
1329}
1330
1331void Map::RemoveAllObjectsInRemoveList()
1332{
1333    if(i_objectsToRemove.empty())
1334        return;
1335
1336    //sLog.outDebug("Object remover 1 check.");
1337    while(!i_objectsToRemove.empty())
1338    {
1339        WorldObject* obj = *i_objectsToRemove.begin();
1340        i_objectsToRemove.erase(i_objectsToRemove.begin());
1341
1342        switch(obj->GetTypeId())
1343        {
1344            case TYPEID_CORPSE:
1345            {
1346                Corpse* corpse = ObjectAccessor::Instance().GetCorpse(*obj, obj->GetGUID());
1347                if (!corpse)
1348                    sLog.outError("ERROR: Try delete corpse/bones %u that not in map", obj->GetGUIDLow());
1349                else
1350                    Remove(corpse,true);
1351                break;
1352            }
1353        case TYPEID_DYNAMICOBJECT:
1354            Remove((DynamicObject*)obj,true);
1355            break;
1356        case TYPEID_GAMEOBJECT:
1357            Remove((GameObject*)obj,true);
1358            break;
1359        case TYPEID_UNIT:
1360            Remove((Creature*)obj,true);
1361            break;
1362        default:
1363            sLog.outError("Non-grid object (TypeId: %u) in grid object removing list, ignored.",obj->GetTypeId());
1364            break;
1365        }
1366    }
1367    //sLog.outDebug("Object remover 2 check.");
1368}
1369
1370bool Map::CanUnload(const uint32 &diff)
1371{
1372    if(!m_unloadTimer) return false;
1373    if(m_unloadTimer < diff) return true;
1374    m_unloadTimer -= diff;
1375    return false;
1376}
1377
1378template void Map::Add(Corpse *);
1379template void Map::Add(Creature *);
1380template void Map::Add(GameObject *);
1381template void Map::Add(DynamicObject *);
1382
1383template void Map::Remove(Corpse *,bool);
1384template void Map::Remove(Creature *,bool);
1385template void Map::Remove(GameObject *, bool);
1386template void Map::Remove(DynamicObject *, bool);
1387
1388/* ******* Dungeon Instance Maps ******* */
1389
1390InstanceMap::InstanceMap(uint32 id, time_t expiry, uint32 InstanceId, uint8 SpawnMode)
1391  : Map(id, expiry, InstanceId, SpawnMode), i_data(NULL),
1392    m_resetAfterUnload(false), m_unloadWhenEmpty(false)
1393{
1394    // the timer is started by default, and stopped when the first player joins
1395    // this make sure it gets unloaded if for some reason no player joins
1396    m_unloadTimer = std::max(sWorld.getConfig(CONFIG_INSTANCE_UNLOAD_DELAY), (uint32)MIN_UNLOAD_DELAY);
1397}
1398
1399InstanceMap::~InstanceMap()
1400{
1401    if(i_data)
1402    {
1403        delete i_data;
1404        i_data = NULL;
1405    }
1406}
1407
1408/*
1409    Do map specific checks to see if the player can enter
1410*/
1411bool InstanceMap::CanEnter(Player *player)
1412{
1413    if(std::find(i_Players.begin(),i_Players.end(),player)!=i_Players.end())
1414    {
1415        sLog.outError("InstanceMap::CanEnter - player %s(%u) already in map %d,%d,%d!", player->GetName(), player->GetGUIDLow(), GetId(), GetInstanceId(), GetSpawnMode());
1416        assert(false);
1417        return false;
1418    }
1419
1420    // cannot enter if the instance is full (player cap), GMs don't count
1421    InstanceTemplate const* iTemplate = objmgr.GetInstanceTemplate(GetId());
1422    if (!player->isGameMaster() && GetPlayersCountExceptGMs() >= iTemplate->maxPlayers)
1423    {
1424        sLog.outDetail("MAP: Instance '%u' of map '%s' cannot have more than '%u' players. Player '%s' rejected", GetInstanceId(), GetMapName(), iTemplate->maxPlayers, player->GetName());
1425        player->SendTransferAborted(GetId(), TRANSFER_ABORT_MAX_PLAYERS);
1426        return false;
1427    }
1428
1429    // cannot enter while players in the instance are in combat
1430    Group *pGroup = player->GetGroup();
1431    if(!player->isGameMaster() && pGroup && pGroup->InCombatToInstance(GetInstanceId()) && player->isAlive() && player->GetMapId() != GetId())
1432    {
1433        player->SendTransferAborted(GetId(), TRANSFER_ABORT_ZONE_IN_COMBAT);
1434        return false;
1435    }
1436
1437    /*if(!player->isGameMaster() && i_data && i_data->IsEncounterInProgress())
1438    {
1439        sLog.outDebug("InstanceMap::CanEnter - Player '%s' can't enter instance '%s' while an encounter is in progress.", player->GetName(), GetMapName());
1440        player->SendTransferAborted(GetId(), TRANSFER_ABORT_ZONE_IN_COMBAT);
1441        return false;
1442    }*/
1443
1444    return Map::CanEnter(player);
1445}
1446
1447/*
1448    Do map specific checks and add the player to the map if successful.
1449*/
1450bool InstanceMap::Add(Player *player)
1451{
1452    // TODO: Not sure about checking player level: already done in HandleAreaTriggerOpcode
1453    // GMs still can teleport player in instance.
1454    // Is it needed?
1455
1456    {
1457        Guard guard(*this);
1458        if(!CanEnter(player))
1459            return false;
1460
1461        // get or create an instance save for the map
1462        InstanceSave *mapSave = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1463        if(!mapSave)
1464        {
1465            sLog.outDetail("InstanceMap::Add: creating instance save for map %d spawnmode %d with instance id %d", GetId(), GetSpawnMode(), GetInstanceId());
1466            mapSave = sInstanceSaveManager.AddInstanceSave(GetId(), GetInstanceId(), GetSpawnMode(), 0, true);
1467        }
1468
1469        // check for existing instance binds
1470        InstancePlayerBind *playerBind = player->GetBoundInstance(GetId(), GetSpawnMode());
1471        if(playerBind && playerBind->perm)
1472        {
1473            // cannot enter other instances if bound permanently
1474            if(playerBind->save != mapSave)
1475            {
1476                sLog.outError("InstanceMap::Add: player %s(%d) is permanently bound to instance %d,%d,%d,%d,%d,%d but he is being put in instance %d,%d,%d,%d,%d,%d", player->GetName(), player->GetGUIDLow(), playerBind->save->GetMapId(), playerBind->save->GetInstanceId(), playerBind->save->GetDifficulty(), playerBind->save->GetPlayerCount(), playerBind->save->GetGroupCount(), playerBind->save->CanReset(), mapSave->GetMapId(), mapSave->GetInstanceId(), mapSave->GetDifficulty(), mapSave->GetPlayerCount(), mapSave->GetGroupCount(), mapSave->CanReset());
1477                assert(false);
1478            }
1479        }
1480        else
1481        {
1482            Group *pGroup = player->GetGroup();
1483            if(pGroup)
1484            {
1485                // solo saves should be reset when entering a group
1486                InstanceGroupBind *groupBind = pGroup->GetBoundInstance(GetId(), GetSpawnMode());
1487                if(playerBind)
1488                {
1489                    sLog.outError("InstanceMap::Add: player %s(%d) is being put in instance %d,%d,%d,%d,%d,%d but he is in group %d and is bound to instance %d,%d,%d,%d,%d,%d!", player->GetName(), player->GetGUIDLow(), mapSave->GetMapId(), mapSave->GetInstanceId(), mapSave->GetDifficulty(), mapSave->GetPlayerCount(), mapSave->GetGroupCount(), mapSave->CanReset(), GUID_LOPART(pGroup->GetLeaderGUID()), playerBind->save->GetMapId(), playerBind->save->GetInstanceId(), playerBind->save->GetDifficulty(), playerBind->save->GetPlayerCount(), playerBind->save->GetGroupCount(), playerBind->save->CanReset());
1490                    if(groupBind) sLog.outError("InstanceMap::Add: the group is bound to instance %d,%d,%d,%d,%d,%d", groupBind->save->GetMapId(), groupBind->save->GetInstanceId(), groupBind->save->GetDifficulty(), groupBind->save->GetPlayerCount(), groupBind->save->GetGroupCount(), groupBind->save->CanReset());
1491                    assert(false);
1492                }
1493                // bind to the group or keep using the group save
1494                if(!groupBind)
1495                    pGroup->BindToInstance(mapSave, false);
1496                else
1497                {
1498                    // cannot jump to a different instance without resetting it
1499                    if(groupBind->save != mapSave)
1500                    {
1501                        sLog.outError("InstanceMap::Add: player %s(%d) is being put in instance %d,%d,%d but he is in group %d which is bound to instance %d,%d,%d!", player->GetName(), player->GetGUIDLow(), mapSave->GetMapId(), mapSave->GetInstanceId(), mapSave->GetDifficulty(), GUID_LOPART(pGroup->GetLeaderGUID()), groupBind->save->GetMapId(), groupBind->save->GetInstanceId(), groupBind->save->GetDifficulty());
1502                        if(mapSave)
1503                            sLog.outError("MapSave players: %d, group count: %d", mapSave->GetPlayerCount(), mapSave->GetGroupCount());
1504                        else
1505                            sLog.outError("MapSave NULL");
1506                        if(groupBind->save)
1507                            sLog.outError("GroupBind save players: %d, group count: %d", groupBind->save->GetPlayerCount(), groupBind->save->GetGroupCount());
1508                        else
1509                            sLog.outError("GroupBind save NULL");
1510                        assert(false);
1511                    }
1512                    // if the group/leader is permanently bound to the instance
1513                    // players also become permanently bound when they enter
1514                    if(groupBind->perm)
1515                    {
1516                        WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
1517                        data << uint32(0);
1518                        player->GetSession()->SendPacket(&data);
1519                        player->BindToInstance(mapSave, true);
1520                    }
1521                }
1522            }
1523            else
1524            {
1525                // set up a solo bind or continue using it
1526                if(!playerBind)
1527                    player->BindToInstance(mapSave, false);
1528                else
1529                    // cannot jump to a different instance without resetting it
1530                    assert(playerBind->save == mapSave);
1531            }
1532        }
1533
1534        if(i_data) i_data->OnPlayerEnter(player);
1535        SetResetSchedule(false);
1536
1537        i_Players.push_back(player);
1538        player->SendInitWorldStates();
1539        sLog.outDetail("MAP: Player '%s' entered the instance '%u' of map '%s'", player->GetName(), GetInstanceId(), GetMapName());
1540        // initialize unload state
1541        m_unloadTimer = 0;
1542        m_resetAfterUnload = false;
1543        m_unloadWhenEmpty = false;
1544    }
1545
1546    // this will acquire the same mutex so it cannot be in the previous block
1547    Map::Add(player);
1548    return true;
1549}
1550
1551void InstanceMap::Update(const uint32& t_diff)
1552{
1553        Map::Update(t_diff);
1554
1555        if(i_data)
1556                i_data->Update(t_diff);
1557}
1558
1559void InstanceMap::Remove(Player *player, bool remove)
1560{
1561    sLog.outDetail("MAP: Removing player '%s' from instance '%u' of map '%s' before relocating to other map", player->GetName(), GetInstanceId(), GetMapName());
1562    i_Players.remove(player);
1563    SetResetSchedule(true);
1564    if(!m_unloadTimer && i_Players.empty())
1565        m_unloadTimer = m_unloadWhenEmpty ? MIN_UNLOAD_DELAY : std::max(sWorld.getConfig(CONFIG_INSTANCE_UNLOAD_DELAY), (uint32)MIN_UNLOAD_DELAY);
1566    Map::Remove(player, remove);
1567}
1568
1569Creature * Map::GetCreatureInMap(uint64 guid)
1570{
1571    Creature * obj = HashMapHolder<Creature>::Find(guid);
1572    if(obj && obj->GetInstanceId() != GetInstanceId()) obj = NULL;
1573    return obj;
1574}
1575
1576GameObject * Map::GetGameObjectInMap(uint64 guid)
1577{
1578    GameObject * obj = HashMapHolder<GameObject>::Find(guid);
1579    if(obj && obj->GetInstanceId() != GetInstanceId()) obj = NULL;
1580    return obj;
1581}
1582
1583void InstanceMap::CreateInstanceData(bool load)
1584{
1585    if(i_data != NULL)
1586        return;
1587
1588    InstanceTemplate const* mInstance = objmgr.GetInstanceTemplate(GetId());
1589    if (mInstance)
1590    {
1591        i_script = mInstance->script;
1592        i_data = Script->CreateInstanceData(this);
1593    }
1594
1595    if(!i_data)
1596        return;
1597
1598    if(load)
1599    {
1600        // TODO: make a global storage for this
1601        QueryResult* result = CharacterDatabase.PQuery("SELECT data FROM instance WHERE map = '%u' AND id = '%u'", GetId(), i_InstanceId);
1602        if (result)
1603        {
1604            Field* fields = result->Fetch();
1605            const char* data = fields[0].GetString();
1606            if(data)
1607            {
1608                sLog.outDebug("Loading instance data for `%s` with id %u", i_script.c_str(), i_InstanceId);
1609                i_data->Load(data);
1610            }
1611            delete result;
1612        }
1613    }
1614    else
1615    {
1616        sLog.outDebug("New instance data, \"%s\" ,initialized!",i_script.c_str());
1617        i_data->Initialize();
1618    }
1619}
1620
1621/*
1622    Returns true if there are no players in the instance
1623*/
1624bool InstanceMap::Reset(uint8 method)
1625{
1626    // note: since the map may not be loaded when the instance needs to be reset
1627    // the instance must be deleted from the DB by InstanceSaveManager
1628
1629    if(!i_Players.empty())
1630    {
1631        if(method == INSTANCE_RESET_ALL)
1632        {
1633            // notify the players to leave the instance so it can be reset
1634            for(PlayerList::iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1635                (*itr)->SendResetFailedNotify(GetId());
1636        }
1637        else
1638        {
1639            if(method == INSTANCE_RESET_GLOBAL)
1640            {
1641                // set the homebind timer for players inside (1 minute)
1642                for(PlayerList::iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1643                    (*itr)->m_InstanceValid = false;
1644            }
1645
1646            // the unload timer is not started
1647            // instead the map will unload immediately after the players have left
1648            m_unloadWhenEmpty = true;
1649            m_resetAfterUnload = true;
1650        }
1651    }
1652    else
1653    {
1654        // unloaded at next update
1655        m_unloadTimer = MIN_UNLOAD_DELAY;
1656        m_resetAfterUnload = true;
1657    }
1658
1659    return i_Players.empty();
1660}
1661
1662uint32 InstanceMap::GetPlayersCountExceptGMs() const
1663{
1664    uint32 count = 0;
1665    for(PlayerList::const_iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1666        if(!(*itr)->isGameMaster())
1667            ++count;
1668    return count;
1669}
1670
1671void InstanceMap::PermBindAllPlayers(Player *player)
1672{
1673    InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1674    if(!save)
1675    {
1676        sLog.outError("Cannot bind players, no instance save available for map!\n");
1677        return;
1678    }
1679
1680    Group *group = player->GetGroup();
1681    // group members outside the instance group don't get bound
1682    for(PlayerList::iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1683    {
1684        if(*itr)
1685        {
1686            // players inside an instance cannot be bound to other instances
1687            // some players may already be permanently bound, in this case nothing happens
1688            InstancePlayerBind *bind = (*itr)->GetBoundInstance(save->GetMapId(), save->GetDifficulty());
1689            if(!bind || !bind->perm)
1690            {
1691                (*itr)->BindToInstance(save, true);
1692                WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
1693                data << uint32(0);
1694                (*itr)->GetSession()->SendPacket(&data);
1695            }
1696
1697            // if the leader is not in the instance the group will not get a perm bind
1698            if(group && group->GetLeaderGUID() == (*itr)->GetGUID())
1699                group->BindToInstance(save, true);
1700        }
1701    }
1702}
1703
1704time_t InstanceMap::GetResetTime()
1705{
1706    InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1707    return save ? save->GetDifficulty() : DIFFICULTY_NORMAL;
1708}
1709
1710void InstanceMap::UnloadAll(bool pForce)
1711{
1712    if(!i_Players.empty())
1713    {
1714        sLog.outError("InstanceMap::UnloadAll: there are still players in the instance at unload, should not happen!");
1715        for(PlayerList::iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1716            if(*itr) (*itr)->TeleportTo((*itr)->m_homebindMapId, (*itr)->m_homebindX, (*itr)->m_homebindY, (*itr)->m_homebindZ, (*itr)->GetOrientation());
1717    }
1718
1719    if(m_resetAfterUnload == true)
1720        objmgr.DeleteRespawnTimeForInstance(GetInstanceId());
1721
1722    Map::UnloadAll(pForce);
1723}
1724
1725void InstanceMap::SendResetWarnings(uint32 timeLeft)
1726{
1727    for(PlayerList::iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1728        (*itr)->SendInstanceResetWarning(GetId(), timeLeft);
1729}
1730
1731void InstanceMap::SetResetSchedule(bool on)
1732{
1733    // only for normal instances
1734    // the reset time is only scheduled when there are no payers inside
1735    // it is assumed that the reset time will rarely (if ever) change while the reset is scheduled
1736    if(i_Players.empty() && !IsRaid() && !IsHeroic())
1737    {
1738        InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
1739        if(!save) sLog.outError("InstanceMap::SetResetSchedule: cannot turn schedule %s, no save available for instance %d of %d", on ? "on" : "off", GetInstanceId(), GetId());
1740        else sInstanceSaveManager.ScheduleReset(on, save->GetResetTime(), InstanceSaveManager::InstResetEvent(0, GetId(), GetInstanceId()));
1741    }
1742}
1743
1744void InstanceMap::SendToPlayers(WorldPacket const* data) const
1745{
1746    for(PlayerList::const_iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
1747        (*itr)->GetSession()->SendPacket(data);
1748}
1749
1750/* ******* Battleground Instance Maps ******* */
1751
1752BattleGroundMap::BattleGroundMap(uint32 id, time_t expiry, uint32 InstanceId)
1753  : Map(id, expiry, InstanceId, DIFFICULTY_NORMAL)
1754{
1755}
1756
1757BattleGroundMap::~BattleGroundMap()
1758{
1759}
1760
1761bool BattleGroundMap::CanEnter(Player * player)
1762{
1763    if(std::find(i_Players.begin(),i_Players.end(),player)!=i_Players.end())
1764    {
1765        sLog.outError("BGMap::CanEnter - player %u already in map!", player->GetGUIDLow());
1766        assert(false);
1767        return false;
1768    }
1769
1770    if(player->GetBattleGroundId() != GetInstanceId())
1771        return false;
1772
1773    // player number limit is checked in bgmgr, no need to do it here
1774
1775    return Map::CanEnter(player);
1776}
1777
1778bool BattleGroundMap::Add(Player * player)
1779{
1780    {
1781        Guard guard(*this);
1782        if(!CanEnter(player))
1783            return false;
1784        i_Players.push_back(player);
1785        // reset instance validity, battleground maps do not homebind
1786        player->m_InstanceValid = true;
1787    }
1788    return Map::Add(player);
1789}
1790
1791void BattleGroundMap::Remove(Player *player, bool remove)
1792{
1793    sLog.outDetail("MAP: Removing player '%s' from bg '%u' of map '%s' before relocating to other map", player->GetName(), GetInstanceId(), GetMapName());
1794    i_Players.remove(player);
1795    Map::Remove(player, remove);
1796}
1797
1798void BattleGroundMap::SetUnload()
1799{
1800    m_unloadTimer = MIN_UNLOAD_DELAY;
1801}
1802
1803void BattleGroundMap::UnloadAll(bool pForce)
1804{
1805    while(!i_Players.empty())
1806    {
1807        PlayerList::iterator itr = i_Players.begin();
1808        Player * plr = *itr;
1809        if(plr) (plr)->TeleportTo((*itr)->m_homebindMapId, (*itr)->m_homebindX, (*itr)->m_homebindY, (*itr)->m_homebindZ, (*itr)->GetOrientation());
1810        // TeleportTo removes the player from this map (if the map exists) -> calls BattleGroundMap::Remove -> invalidates the iterator.
1811        // just in case, remove the player from the list explicitly here as well to prevent a possible infinite loop
1812        // note that this remove is not needed if the code works well in other places
1813        i_Players.remove(plr);
1814    }
1815
1816    Map::UnloadAll(pForce);
1817}
Note: See TracBrowser for help on using the browser.