aboutsummaryrefslogtreecommitdiff
path: root/src/server/game/Map
diff options
context:
space:
mode:
authorRat <none@none>2010-06-05 23:40:08 +0200
committerRat <none@none>2010-06-05 23:40:08 +0200
commit75b80d9f5b02a643c983b2fb1ededed79fd5d133 (patch)
treeebd1c2cc12a2715909dd04c1ed147a260c6ceb14 /src/server/game/Map
parent6a9357b13d7ea6bd7d77dbfc6587af9028caa401 (diff)
rearranged core files
--HG-- branch : trunk
Diffstat (limited to 'src/server/game/Map')
-rw-r--r--src/server/game/Map/Cell/Cell.h177
-rw-r--r--src/server/game/Map/Cell/CellImpl.h297
-rw-r--r--src/server/game/Map/Grid/GridDefines.h193
-rw-r--r--src/server/game/Map/Grid/GridNotifiers.cpp353
-rw-r--r--src/server/game/Map/Grid/GridNotifiers.h1232
-rw-r--r--src/server/game/Map/Grid/GridNotifiersImpl.h453
-rw-r--r--src/server/game/Map/Grid/GridStates.cpp76
-rw-r--r--src/server/game/Map/Grid/GridStates.h76
-rw-r--r--src/server/game/Map/Grid/ObjectGridLoader.cpp325
-rw-r--r--src/server/game/Map/Grid/ObjectGridLoader.h134
-rw-r--r--src/server/game/Map/Map.cpp3936
-rw-r--r--src/server/game/Map/Map.h689
-rw-r--r--src/server/game/Map/MapInstanced.cpp268
-rw-r--r--src/server/game/Map/MapInstanced.h80
-rw-r--r--src/server/game/Map/MapManager.cpp395
-rw-r--r--src/server/game/Map/MapManager.h158
-rw-r--r--src/server/game/Map/MapRefManager.h45
-rw-r--r--src/server/game/Map/MapReference.h53
-rw-r--r--src/server/game/Map/MapUpdater.cpp129
-rw-r--r--src/server/game/Map/MapUpdater.h40
-rw-r--r--src/server/game/Map/ObjectPosSelector.cpp157
-rw-r--r--src/server/game/Map/ObjectPosSelector.h155
-rw-r--r--src/server/game/Map/ZoneScript.h51
23 files changed, 9472 insertions, 0 deletions
diff --git a/src/server/game/Map/Cell/Cell.h b/src/server/game/Map/Cell/Cell.h
new file mode 100644
index 00000000000..49e0329ace6
--- /dev/null
+++ b/src/server/game/Map/Cell/Cell.h
@@ -0,0 +1,177 @@
+/*
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
+ *
+ * Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
+ *
+ * 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, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef TRINITY_CELL_H
+#define TRINITY_CELL_H
+
+#include <cmath>
+
+#include "GameSystem/TypeContainer.h"
+#include "GameSystem/TypeContainerVisitor.h"
+
+#include "GridDefines.h"
+
+class Map;
+class WorldObject;
+
+enum District
+{
+ UPPER_DISTRICT = 1,
+ LOWER_DISTRICT = 1 << 1,
+ LEFT_DISTRICT = 1 << 2,
+ RIGHT_DISTRICT = 1 << 3,
+ CENTER_DISTRICT = 1 << 4,
+ UPPER_LEFT_DISTRICT = (UPPER_DISTRICT | LEFT_DISTRICT),
+ UPPER_RIGHT_DISTRICT = (UPPER_DISTRICT | RIGHT_DISTRICT),
+ LOWER_LEFT_DISTRICT = (LOWER_DISTRICT | LEFT_DISTRICT),
+ LOWER_RIGHT_DISTRICT = (LOWER_DISTRICT | RIGHT_DISTRICT),
+ ALL_DISTRICT = (UPPER_DISTRICT | LOWER_DISTRICT | LEFT_DISTRICT | RIGHT_DISTRICT | CENTER_DISTRICT)
+};
+
+struct CellArea
+{
+ CellArea() : right_offset(0), left_offset(0), upper_offset(0), lower_offset(0) {}
+ CellArea(int right, int left, int upper, int lower) : right_offset(right), left_offset(left), upper_offset(upper), lower_offset(lower) {}
+ bool operator!() const { return !right_offset && !left_offset && !upper_offset && !lower_offset; }
+
+ void ResizeBorders(CellPair& begin_cell, CellPair& end_cell) const
+ {
+ begin_cell << left_offset;
+ begin_cell -= lower_offset;
+ end_cell >> right_offset;
+ end_cell += upper_offset;
+ }
+
+ int right_offset;
+ int left_offset;
+ int upper_offset;
+ int lower_offset;
+};
+
+struct Cell
+{
+ Cell() { data.All = 0; }
+ Cell(const Cell &cell) { data.All = cell.data.All; }
+ explicit Cell(CellPair const& p);
+
+ void operator|=(Cell &cell)
+ {
+ data.Part.reserved = 0;
+ cell.data.Part.reserved = 0;
+ uint32 x, y, old_x, old_y;
+ Compute(x, y);
+ cell.Compute(old_x, old_y);
+
+ if (std::abs(int(x-old_x)) > 1 || std::abs(int(y-old_y)) > 1)
+ {
+ data.Part.reserved = ALL_DISTRICT;
+ cell.data.Part.reserved = ALL_DISTRICT;
+ return;
+ }
+
+ if (x < old_x)
+ {
+ data.Part.reserved |= LEFT_DISTRICT;
+ cell.data.Part.reserved |= RIGHT_DISTRICT;
+ }
+ else if (old_x < x)
+ {
+ data.Part.reserved |= RIGHT_DISTRICT;
+ cell.data.Part.reserved |= LEFT_DISTRICT;
+ }
+ if (y < old_y)
+ {
+ data.Part.reserved |= UPPER_DISTRICT;
+ cell.data.Part.reserved |= LOWER_DISTRICT;
+ }
+ else if (old_y < y)
+ {
+ data.Part.reserved |= LOWER_DISTRICT;
+ cell.data.Part.reserved |= UPPER_DISTRICT;
+ }
+ }
+
+ void Compute(uint32 &x, uint32 &y) const
+ {
+ x = data.Part.grid_x*MAX_NUMBER_OF_CELLS + data.Part.cell_x;
+ y = data.Part.grid_y*MAX_NUMBER_OF_CELLS + data.Part.cell_y;
+ }
+
+ bool DiffCell(const Cell &cell) const
+ {
+ return(data.Part.cell_x != cell.data.Part.cell_x ||
+ data.Part.cell_y != cell.data.Part.cell_y);
+ }
+
+ bool DiffGrid(const Cell &cell) const
+ {
+ return(data.Part.grid_x != cell.data.Part.grid_x ||
+ data.Part.grid_y != cell.data.Part.grid_y);
+ }
+
+ uint32 CellX() const { return data.Part.cell_x; }
+ uint32 CellY() const { return data.Part.cell_y; }
+ uint32 GridX() const { return data.Part.grid_x; }
+ uint32 GridY() const { return data.Part.grid_y; }
+ bool NoCreate() const { return data.Part.nocreate; }
+ void SetNoCreate() { data.Part.nocreate = 1; }
+
+ CellPair cellPair() const
+ {
+ return CellPair(
+ data.Part.grid_x*MAX_NUMBER_OF_CELLS+data.Part.cell_x,
+ data.Part.grid_y*MAX_NUMBER_OF_CELLS+data.Part.cell_y);
+ }
+
+ Cell& operator=(const Cell &cell)
+ {
+ this->data.All = cell.data.All;
+ return *this;
+ }
+
+ bool operator == (const Cell &cell) const { return (data.All == cell.data.All); }
+ bool operator != (const Cell &cell) const { return !operator == (cell); }
+ union
+ {
+ struct
+ {
+ unsigned grid_x : 6;
+ unsigned grid_y : 6;
+ unsigned cell_x : 6;
+ unsigned cell_y : 6;
+ unsigned nocreate : 1;
+ unsigned reserved : 7;
+ } Part;
+ uint32 All;
+ } data;
+
+ template<class T, class CONTAINER> void Visit(const CellPair&, TypeContainerVisitor<T, CONTAINER> &visitor, Map &) const;
+ template<class T, class CONTAINER> void Visit(const CellPair&, TypeContainerVisitor<T, CONTAINER> &visitor, Map &, const WorldObject&, float) const;
+ template<class T, class CONTAINER> void Visit(const CellPair&, TypeContainerVisitor<T, CONTAINER> &visitor, Map &, float, float, float) const;
+
+ static CellArea CalculateCellArea(const WorldObject &obj, float radius);
+ static CellArea CalculateCellArea(float x, float y, float radius);
+
+private:
+ template<class T, class CONTAINER> void VisitCircle(TypeContainerVisitor<T, CONTAINER> &, Map &, const CellPair&, const CellPair&) const;
+};
+
+#endif
+
diff --git a/src/server/game/Map/Cell/CellImpl.h b/src/server/game/Map/Cell/CellImpl.h
new file mode 100644
index 00000000000..d906e81a5c9
--- /dev/null
+++ b/src/server/game/Map/Cell/CellImpl.h
@@ -0,0 +1,297 @@
+/*
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
+ *
+ * Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
+ *
+ * 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, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef TRINITY_CELLIMPL_H
+#define TRINITY_CELLIMPL_H
+
+#include <cmath>
+
+#include "Cell.h"
+#include "Map.h"
+#include "Object.h"
+
+inline Cell::Cell(CellPair const& p)
+{
+ data.Part.grid_x = p.x_coord / MAX_NUMBER_OF_CELLS;
+ data.Part.grid_y = p.y_coord / MAX_NUMBER_OF_CELLS;
+ data.Part.cell_x = p.x_coord % MAX_NUMBER_OF_CELLS;
+ data.Part.cell_y = p.y_coord % MAX_NUMBER_OF_CELLS;
+ data.Part.nocreate = 0;
+ data.Part.reserved = 0;
+}
+
+template<class T, class CONTAINER>
+inline void
+Cell::Visit(const CellPair& standing_cell, TypeContainerVisitor<T, CONTAINER> &visitor, Map &m) const
+{
+ if (standing_cell.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || standing_cell.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
+ return;
+
+ uint16 district = (District)this->data.Part.reserved;
+ if (district == CENTER_DISTRICT)
+ {
+ m.Visit(*this, visitor);
+ return;
+ }
+
+ // set up the cell range based on the district
+ // the overloaded operators handle range checking
+ CellPair begin_cell = standing_cell;
+ CellPair end_cell = standing_cell;
+
+ switch(district)
+ {
+ case ALL_DISTRICT:
+ {
+ begin_cell << 1; begin_cell -= 1; // upper left
+ end_cell >> 1; end_cell += 1; // lower right
+ break;
+ }
+ case UPPER_LEFT_DISTRICT:
+ {
+ begin_cell << 1; begin_cell -= 1; // upper left
+ break;
+ }
+ case UPPER_RIGHT_DISTRICT:
+ {
+ begin_cell -= 1; // up
+ end_cell >> 1; // right
+ break;
+ }
+ case LOWER_LEFT_DISTRICT:
+ {
+ begin_cell << 1; // left
+ end_cell += 1; // down
+ break;
+ }
+ case LOWER_RIGHT_DISTRICT:
+ {
+ end_cell >> 1; end_cell += 1; // lower right
+ break;
+ }
+ case LEFT_DISTRICT:
+ {
+ begin_cell -= 1; // up
+ end_cell >> 1; end_cell += 1; // lower right
+ break;
+ }
+ case RIGHT_DISTRICT:
+ {
+ begin_cell << 1; begin_cell -= 1; // upper left
+ end_cell += 1; // down
+ break;
+ }
+ case UPPER_DISTRICT:
+ {
+ begin_cell << 1; begin_cell -= 1; // upper left
+ end_cell >> 1; // right
+ break;
+ }
+ case LOWER_DISTRICT:
+ {
+ begin_cell << 1; // left
+ end_cell >> 1; end_cell += 1; // lower right
+ break;
+ }
+ default:
+ {
+ assert(false);
+ break;
+ }
+ }
+
+ // loop the cell range
+ for (uint32 x = begin_cell.x_coord; x <= end_cell.x_coord; x++)
+ {
+ for (uint32 y = begin_cell.y_coord; y <= end_cell.y_coord; y++)
+ {
+ CellPair cell_pair(x,y);
+ Cell r_zone(cell_pair);
+ r_zone.data.Part.nocreate = this->data.Part.nocreate;
+ m.Visit(r_zone, visitor);
+ }
+ }
+}
+
+inline int CellHelper(const float radius)
+{
+ if (radius < 1.0f)
+ return 0;
+
+ return (int)ceilf(radius/SIZE_OF_GRID_CELL);
+}
+
+inline CellArea Cell::CalculateCellArea(const WorldObject &obj, float radius)
+{
+ return Cell::CalculateCellArea(obj.GetPositionX(), obj.GetPositionY(), radius);
+}
+
+inline CellArea Cell::CalculateCellArea(float x, float y, float radius)
+{
+ if (radius <= 0.0f)
+ return CellArea();
+
+ //lets calculate object coord offsets from cell borders.
+ //TODO: add more correct/generic method for this task
+ const float x_offset = (x - CENTER_GRID_CELL_OFFSET)/SIZE_OF_GRID_CELL;
+ const float y_offset = (y - CENTER_GRID_CELL_OFFSET)/SIZE_OF_GRID_CELL;
+
+ const float x_val = floor(x_offset + CENTER_GRID_CELL_ID + 0.5f);
+ const float y_val = floor(y_offset + CENTER_GRID_CELL_ID + 0.5f);
+
+ const float x_off = (x_offset - x_val + CENTER_GRID_CELL_ID) * SIZE_OF_GRID_CELL;
+ const float y_off = (y_offset - y_val + CENTER_GRID_CELL_ID) * SIZE_OF_GRID_CELL;
+
+ const float tmp_diff = radius - CENTER_GRID_CELL_OFFSET;
+ //lets calculate upper/lower/right/left corners for cell search
+ int right = CellHelper(tmp_diff + x_off);
+ int left = CellHelper(tmp_diff - x_off);
+ int upper = CellHelper(tmp_diff + y_off);
+ int lower = CellHelper(tmp_diff - y_off);
+
+ return CellArea(right, left, upper, lower);
+}
+
+template<class T, class CONTAINER>
+inline void
+Cell::Visit(const CellPair& standing_cell, TypeContainerVisitor<T, CONTAINER> &visitor, Map &m, float radius, float x_off, float y_off) const
+{
+ if (standing_cell.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || standing_cell.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
+ return;
+
+ //no jokes here... Actually placing ASSERT() here was good idea, but
+ //we had some problems with DynamicObjects, which pass radius = 0.0f (DB issue?)
+ //maybe it is better to just return when radius <= 0.0f?
+ if (radius <= 0.0f)
+ {
+ m.Visit(*this, visitor);
+ return;
+ }
+ //lets limit the upper value for search radius
+ if (radius > 333.0f)
+ radius = 333.0f;
+
+ //lets calculate object coord offsets from cell borders.
+ CellArea area = Cell::CalculateCellArea(x_off, y_off, radius);
+ //if radius fits inside standing cell
+ if (!area)
+ {
+ m.Visit(*this, visitor);
+ return;
+ }
+
+ CellPair begin_cell = standing_cell;
+ CellPair end_cell = standing_cell;
+
+ area.ResizeBorders(begin_cell, end_cell);
+ //visit all cells, found in CalculateCellArea()
+ //if radius is known to reach cell area more than 4x4 then we should call optimized VisitCircle
+ //currently this technique works with MAX_NUMBER_OF_CELLS 16 and higher, with lower values
+ //there are nothing to optimize because SIZE_OF_GRID_CELL is too big...
+ if (((end_cell.x_coord - begin_cell.x_coord) > 4) && ((end_cell.y_coord - begin_cell.y_coord) > 4))
+ {
+ VisitCircle(visitor, m, begin_cell, end_cell);
+ return;
+ }
+
+ //ALWAYS visit standing cell first!!! Since we deal with small radiuses
+ //it is very essential to call visitor for standing cell firstly...
+ m.Visit(*this, visitor);
+
+ // loop the cell range
+ for (uint32 x = begin_cell.x_coord; x <= end_cell.x_coord; ++x)
+ {
+ for (uint32 y = begin_cell.y_coord; y <= end_cell.y_coord; ++y)
+ {
+ CellPair cell_pair(x,y);
+ //lets skip standing cell since we already visited it
+ if (cell_pair != standing_cell)
+ {
+ Cell r_zone(cell_pair);
+ r_zone.data.Part.nocreate = this->data.Part.nocreate;
+ m.Visit(r_zone, visitor);
+ }
+ }
+ }
+}
+
+template<class T, class CONTAINER>
+inline void
+Cell::Visit(const CellPair& l, TypeContainerVisitor<T, CONTAINER> &visitor, Map &m, const WorldObject &obj, float radius) const
+{
+ //we should increase search radius by object's radius, otherwise
+ //we could have problems with huge creatures, which won't attack nearest players etc
+ Visit(l, visitor, m, radius + obj.GetObjectSize(), obj.GetPositionX(), obj.GetPositionY());
+}
+
+template<class T, class CONTAINER>
+inline void
+Cell::VisitCircle(TypeContainerVisitor<T, CONTAINER> &visitor, Map &m, const CellPair& begin_cell, const CellPair& end_cell) const
+{
+ //here is an algorithm for 'filling' circum-squared octagon
+ uint32 x_shift = (uint32)ceilf((end_cell.x_coord - begin_cell.x_coord) * 0.3f - 0.5f);
+ //lets calculate x_start/x_end coords for central strip...
+ const uint32 x_start = begin_cell.x_coord + x_shift;
+ const uint32 x_end = end_cell.x_coord - x_shift;
+
+ //visit central strip with constant width...
+ for (uint32 x = x_start; x <= x_end; ++x)
+ {
+ for (uint32 y = begin_cell.y_coord; y <= end_cell.y_coord; ++y)
+ {
+ CellPair cell_pair(x,y);
+ Cell r_zone(cell_pair);
+ r_zone.data.Part.nocreate = this->data.Part.nocreate;
+ m.Visit(r_zone, visitor);
+ }
+ }
+
+ //if x_shift == 0 then we have too small cell area, which were already
+ //visited at previous step, so just return from procedure...
+ if (x_shift == 0)
+ return;
+
+ uint32 y_start = end_cell.y_coord;
+ uint32 y_end = begin_cell.y_coord;
+ //now we are visiting borders of an octagon...
+ for (uint32 step = 1; step <= (x_start - begin_cell.x_coord); ++step)
+ {
+ //each step reduces strip height by 2 cells...
+ y_end += 1;
+ y_start -= 1;
+ for (uint32 y = y_start; y >= y_end; --y)
+ {
+ //we visit cells symmetrically from both sides, heading from center to sides and from up to bottom
+ //e.g. filling 2 trapezoids after filling central cell strip...
+ CellPair cell_pair_left(x_start - step, y);
+ Cell r_zone_left(cell_pair_left);
+ r_zone_left.data.Part.nocreate = this->data.Part.nocreate;
+ m.Visit(r_zone_left, visitor);
+
+ //right trapezoid cell visit
+ CellPair cell_pair_right(x_end + step, y);
+ Cell r_zone_right(cell_pair_right);
+ r_zone_right.data.Part.nocreate = this->data.Part.nocreate;
+ m.Visit(r_zone_right, visitor);
+ }
+ }
+}
+#endif
+
diff --git a/src/server/game/Map/Grid/GridDefines.h b/src/server/game/Map/Grid/GridDefines.h
new file mode 100644
index 00000000000..5269d0a094d
--- /dev/null
+++ b/src/server/game/Map/Grid/GridDefines.h
@@ -0,0 +1,193 @@
+/*
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
+ *
+ * Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
+ *
+ * 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, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef TRINITY_GRIDDEFINES_H
+#define TRINITY_GRIDDEFINES_H
+
+#include "Common.h"
+#include "GameSystem/NGrid.h"
+#include <cmath>
+
+// Forward class definitions
+class Corpse;
+class Creature;
+class DynamicObject;
+class GameObject;
+class Pet;
+class Player;
+
+#define MAX_NUMBER_OF_CELLS 8
+
+#define MAX_NUMBER_OF_GRIDS 64
+
+#define SIZE_OF_GRIDS 533.33333f
+#define CENTER_GRID_ID (MAX_NUMBER_OF_GRIDS/2)
+
+#define CENTER_GRID_OFFSET (SIZE_OF_GRIDS/2)
+
+#define MIN_GRID_DELAY (MINUTE*IN_MILISECONDS)
+#define MIN_MAP_UPDATE_DELAY 50
+
+#define SIZE_OF_GRID_CELL (SIZE_OF_GRIDS/MAX_NUMBER_OF_CELLS)
+
+#define CENTER_GRID_CELL_ID (MAX_NUMBER_OF_CELLS*MAX_NUMBER_OF_GRIDS/2)
+#define CENTER_GRID_CELL_OFFSET (SIZE_OF_GRID_CELL/2)
+
+#define TOTAL_NUMBER_OF_CELLS_PER_MAP (MAX_NUMBER_OF_GRIDS*MAX_NUMBER_OF_CELLS)
+
+#define MAP_RESOLUTION 128
+
+#define MAP_SIZE (SIZE_OF_GRIDS*MAX_NUMBER_OF_GRIDS)
+#define MAP_HALFSIZE (MAP_SIZE/2)
+
+// Creature used instead pet to simplify *::Visit templates (not required duplicate code for Creature->Pet case)
+typedef TYPELIST_4(Player, Creature/*pets*/, Corpse/*resurrectable*/, DynamicObject/*farsight target*/) AllWorldObjectTypes;
+typedef TYPELIST_4(GameObject, Creature/*except pets*/, DynamicObject, Corpse/*Bones*/) AllGridObjectTypes;
+
+typedef GridRefManager<Corpse> CorpseMapType;
+typedef GridRefManager<Creature> CreatureMapType;
+typedef GridRefManager<DynamicObject> DynamicObjectMapType;
+typedef GridRefManager<GameObject> GameObjectMapType;
+typedef GridRefManager<Player> PlayerMapType;
+
+typedef Grid<Player, AllWorldObjectTypes,AllGridObjectTypes> GridType;
+typedef NGrid<MAX_NUMBER_OF_CELLS, Player, AllWorldObjectTypes, AllGridObjectTypes> NGridType;
+
+typedef TypeMapContainer<AllGridObjectTypes> GridTypeMapContainer;
+typedef TypeMapContainer<AllWorldObjectTypes> WorldTypeMapContainer;
+
+template<const unsigned int LIMIT>
+struct CoordPair
+{
+ CoordPair(uint32 x=0, uint32 y=0) : x_coord(x), y_coord(y) {}
+ CoordPair(const CoordPair<LIMIT> &obj) : x_coord(obj.x_coord), y_coord(obj.y_coord) {}
+ bool operator == (const CoordPair<LIMIT> &obj) const { return (obj.x_coord == x_coord && obj.y_coord == y_coord); }
+ bool operator != (const CoordPair<LIMIT> &obj) const { return !operator == (obj); }
+ CoordPair<LIMIT>& operator=(const CoordPair<LIMIT> &obj)
+ {
+ x_coord = obj.x_coord;
+ y_coord = obj.y_coord;
+ return *this;
+ }
+
+ void operator<<(const uint32 val)
+ {
+ if (x_coord > val)
+ x_coord -= val;
+ else
+ x_coord = 0;
+ }
+
+ void operator>>(const uint32 val)
+ {
+ if (x_coord+val < LIMIT)
+ x_coord += val;
+ else
+ x_coord = LIMIT - 1;
+ }
+
+ void operator-=(const uint32 val)
+ {
+ if (y_coord > val)
+ y_coord -= val;
+ else
+ y_coord = 0;
+ }
+
+ void operator+=(const uint32 val)
+ {
+ if (y_coord+val < LIMIT)
+ y_coord += val;
+ else
+ y_coord = LIMIT - 1;
+ }
+
+ uint32 x_coord;
+ uint32 y_coord;
+};
+
+typedef CoordPair<MAX_NUMBER_OF_GRIDS> GridPair;
+typedef CoordPair<TOTAL_NUMBER_OF_CELLS_PER_MAP> CellPair;
+
+namespace Trinity
+{
+ template<class RET_TYPE, int CENTER_VAL>
+ inline RET_TYPE Compute(float x, float y, float center_offset, float size)
+ {
+ // calculate and store temporary values in double format for having same result as same mySQL calculations
+ double x_offset = (double(x) - center_offset)/size;
+ double y_offset = (double(y) - center_offset)/size;
+
+ int x_val = int(x_offset+CENTER_VAL + 0.5);
+ int y_val = int(y_offset+CENTER_VAL + 0.5);
+ return RET_TYPE(x_val, y_val);
+ }
+
+ inline GridPair ComputeGridPair(float x, float y)
+ {
+ return Compute<GridPair, CENTER_GRID_ID>(x, y, CENTER_GRID_OFFSET, SIZE_OF_GRIDS);
+ }
+
+ inline CellPair ComputeCellPair(float x, float y)
+ {
+ return Compute<CellPair, CENTER_GRID_CELL_ID>(x, y, CENTER_GRID_CELL_OFFSET, SIZE_OF_GRID_CELL);
+ }
+
+ inline CellPair ComputeCellPair(float x, float y, float &x_off, float &y_off)
+ {
+ double x_offset = (double(x) - CENTER_GRID_CELL_OFFSET)/SIZE_OF_GRID_CELL;
+ double y_offset = (double(y) - CENTER_GRID_CELL_OFFSET)/SIZE_OF_GRID_CELL;
+
+ int x_val = int(x_offset + CENTER_GRID_CELL_ID + 0.5);
+ int y_val = int(y_offset + CENTER_GRID_CELL_ID + 0.5);
+ x_off = (float(x_offset) - x_val + CENTER_GRID_CELL_ID) * SIZE_OF_GRID_CELL;
+ y_off = (float(y_offset) - y_val + CENTER_GRID_CELL_ID) * SIZE_OF_GRID_CELL;
+ return CellPair(x_val, y_val);
+ }
+
+ inline void NormalizeMapCoord(float &c)
+ {
+ if (c > MAP_HALFSIZE - 0.5)
+ c = MAP_HALFSIZE - 0.5;
+ else if (c < -(MAP_HALFSIZE - 0.5))
+ c = -(MAP_HALFSIZE - 0.5);
+ }
+
+ inline bool IsValidMapCoord(float c)
+ {
+ return finite(c) && (std::fabs(c) <= MAP_HALFSIZE - 0.5);
+ }
+
+ inline bool IsValidMapCoord(float x, float y)
+ {
+ return IsValidMapCoord(x) && IsValidMapCoord(y);
+ }
+
+ inline bool IsValidMapCoord(float x, float y, float z)
+ {
+ return IsValidMapCoord(x,y) && finite(z);
+ }
+
+ inline bool IsValidMapCoord(float x, float y, float z, float o)
+ {
+ return IsValidMapCoord(x,y,z) && finite(o);
+ }
+}
+#endif
diff --git a/src/server/game/Map/Grid/GridNotifiers.cpp b/src/server/game/Map/Grid/GridNotifiers.cpp
new file mode 100644
index 00000000000..b10dfa8791e
--- /dev/null
+++ b/src/server/game/Map/Grid/GridNotifiers.cpp
@@ -0,0 +1,353 @@
+/*
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
+ *
+ * Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
+ *
+ * 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, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "GridNotifiers.h"
+#include "GridNotifiersImpl.h"
+#include "WorldPacket.h"
+#include "WorldSession.h"
+#include "UpdateData.h"
+#include "Item.h"
+#include "Map.h"
+#include "Transports.h"
+#include "ObjectAccessor.h"
+#include "CellImpl.h"
+
+using namespace Trinity;
+
+void
+VisibleNotifier::SendToSelf()
+{
+ // at this moment i_clientGUIDs have guids that not iterate at grid level checks
+ // but exist one case when this possible and object not out of range: transports
+ if (Transport* transport = i_player.GetTransport())
+ for (Transport::PlayerSet::const_iterator itr = transport->GetPassengers().begin();itr != transport->GetPassengers().end();++itr)
+ {
+ if (vis_guids.find((*itr)->GetGUID()) != vis_guids.end())
+ {
+ vis_guids.erase((*itr)->GetGUID());
+
+ i_player.UpdateVisibilityOf((*itr), i_data, i_visibleNow);
+
+ if (!(*itr)->isNeedNotify(NOTIFY_VISIBILITY_CHANGED))
+ (*itr)->UpdateVisibilityOf(&i_player);
+ }
+ }
+
+ for (Player::ClientGUIDs::const_iterator it = vis_guids.begin();it != vis_guids.end(); ++it)
+ {
+ i_player.m_clientGUIDs.erase(*it);
+ i_data.AddOutOfRangeGUID(*it);
+
+ if (IS_PLAYER_GUID(*it))
+ {
+ Player* plr = ObjectAccessor::FindPlayer(*it);
+ if (plr && plr->IsInWorld() && !plr->isNeedNotify(NOTIFY_VISIBILITY_CHANGED))
+ plr->UpdateVisibilityOf(&i_player);
+ }
+ }
+
+ if (!i_data.HasData())
+ return;
+
+ WorldPacket packet;
+ i_data.BuildPacket(&packet);
+ i_player.GetSession()->SendPacket(&packet);
+
+ for (std::set<Unit*>::const_iterator it = i_visibleNow.begin(); it != i_visibleNow.end(); ++it)
+ i_player.SendInitialVisiblePackets(*it);
+}
+
+void
+VisibleChangesNotifier::Visit(PlayerMapType &m)
+{
+ for (PlayerMapType::iterator iter=m.begin(); iter != m.end(); ++iter)
+ {
+ if (iter->getSource() == &i_object)
+ continue;
+
+ iter->getSource()->UpdateVisibilityOf(&i_object);
+
+ if (!iter->getSource()->GetSharedVisionList().empty())
+ for (SharedVisionList::const_iterator i = iter->getSource()->GetSharedVisionList().begin();
+ i != iter->getSource()->GetSharedVisionList().end(); ++i)
+ if ((*i)->m_seer == iter->getSource())
+ (*i)->UpdateVisibilityOf(&i_object);
+ }
+}
+
+void
+VisibleChangesNotifier::Visit(CreatureMapType &m)
+{
+ for (CreatureMapType::iterator iter = m.begin(); iter != m.end(); ++iter)
+ if (!iter->getSource()->GetSharedVisionList().empty())
+ for (SharedVisionList::const_iterator i = iter->getSource()->GetSharedVisionList().begin();
+ i != iter->getSource()->GetSharedVisionList().end(); ++i)
+ if ((*i)->m_seer == iter->getSource())
+ (*i)->UpdateVisibilityOf(&i_object);
+}
+
+void
+VisibleChangesNotifier::Visit(DynamicObjectMapType &m)
+{
+ for (DynamicObjectMapType::iterator iter = m.begin(); iter != m.end(); ++iter)
+ if (IS_PLAYER_GUID(iter->getSource()->GetCasterGUID()))
+ if (Player* caster = (Player*)iter->getSource()->GetCaster())
+ if (caster->m_seer == iter->getSource())
+ caster->UpdateVisibilityOf(&i_object);
+}
+
+inline void CreatureUnitRelocationWorker(Creature* c, Unit* u)
+{
+ if (!u->isAlive() || !c->isAlive() || c == u || u->isInFlight())
+ return;
+
+ if (c->HasReactState(REACT_AGGRESSIVE) && !c->hasUnitState(UNIT_STAT_SIGHTLESS))
+ if (c->_IsWithinDist(u, c->m_SightDistance, true) && c->IsAIEnabled)
+ c->AI()->MoveInLineOfSight_Safe(u);
+}
+
+void PlayerRelocationNotifier::Visit(PlayerMapType &m)
+{
+ for (PlayerMapType::iterator iter=m.begin(); iter != m.end(); ++iter)
+ {
+ Player* plr = iter->getSource();
+
+ vis_guids.erase(plr->GetGUID());
+
+ i_player.UpdateVisibilityOf(plr,i_data,i_visibleNow);
+
+ if (plr->m_seer->isNeedNotify(NOTIFY_VISIBILITY_CHANGED))
+ continue;
+
+ plr->UpdateVisibilityOf(&i_player);
+ }
+}
+
+void PlayerRelocationNotifier::Visit(CreatureMapType &m)
+{
+ bool relocated_for_ai = (&i_player == i_player.m_seer);
+
+ for (CreatureMapType::iterator iter=m.begin(); iter != m.end(); ++iter)
+ {
+ Creature * c = iter->getSource();
+
+ vis_guids.erase(c->GetGUID());
+
+ i_player.UpdateVisibilityOf(c,i_data,i_visibleNow);
+
+ if (relocated_for_ai && !c->isNeedNotify(NOTIFY_VISIBILITY_CHANGED))
+ CreatureUnitRelocationWorker(c, &i_player);
+ }
+}
+
+void CreatureRelocationNotifier::Visit(PlayerMapType &m)
+{
+ for (PlayerMapType::iterator iter=m.begin(); iter != m.end(); ++iter)
+ {
+ Player * pl = iter->getSource();
+
+ if (!pl->m_seer->isNeedNotify(NOTIFY_VISIBILITY_CHANGED))
+ pl->UpdateVisibilityOf(&i_creature);
+
+ CreatureUnitRelocationWorker(&i_creature, pl);
+ }
+}
+
+void CreatureRelocationNotifier::Visit(CreatureMapType &m)
+{
+ if (!i_creature.isAlive())
+ return;
+
+ for (CreatureMapType::iterator iter=m.begin(); iter != m.end(); ++iter)
+ {
+ Creature* c = iter->getSource();
+ CreatureUnitRelocationWorker(&i_creature, c);
+
+ if (!c->isNeedNotify(NOTIFY_VISIBILITY_CHANGED))
+ CreatureUnitRelocationWorker(c, &i_creature);
+ }
+}
+
+void DelayedUnitRelocation::Visit(CreatureMapType &m)
+{
+ for (CreatureMapType::iterator iter = m.begin(); iter != m.end(); ++iter)
+ {
+ Creature * unit = iter->getSource();
+ if (!unit->isNeedNotify(NOTIFY_VISIBILITY_CHANGED))
+ continue;
+
+ CreatureRelocationNotifier relocate(*unit);
+
+ TypeContainerVisitor<CreatureRelocationNotifier, WorldTypeMapContainer > c2world_relocation(relocate);
+ TypeContainerVisitor<CreatureRelocationNotifier, GridTypeMapContainer > c2grid_relocation(relocate);
+
+ cell.Visit(p, c2world_relocation, i_map, *unit, i_radius);
+ cell.Visit(p, c2grid_relocation, i_map, *unit, i_radius);
+ }
+}
+
+void DelayedUnitRelocation::Visit(PlayerMapType &m)
+{
+ for (PlayerMapType::iterator iter = m.begin(); iter != m.end(); ++iter)
+ {
+ Player * player = iter->getSource();
+ WorldObject const *viewPoint = player->m_seer;
+
+ if (!viewPoint->isNeedNotify(NOTIFY_VISIBILITY_CHANGED))
+ continue;
+
+ if (player != viewPoint && !viewPoint->IsPositionValid())
+ continue;
+
+ CellPair pair2(Trinity::ComputeCellPair(viewPoint->GetPositionX(), viewPoint->GetPositionY()));
+ Cell cell2(pair2);
+ //cell.SetNoCreate(); need load cells around viewPoint or player, that's why its commented
+
+ PlayerRelocationNotifier relocate(*player);
+ TypeContainerVisitor<PlayerRelocationNotifier, WorldTypeMapContainer > c2world_relocation(relocate);
+ TypeContainerVisitor<PlayerRelocationNotifier, GridTypeMapContainer > c2grid_relocation(relocate);
+
+ cell2.Visit(pair2, c2world_relocation, i_map, *viewPoint, i_radius);
+ cell2.Visit(pair2, c2grid_relocation, i_map, *viewPoint, i_radius);
+
+ relocate.SendToSelf();
+ }
+}
+
+void AIRelocationNotifier::Visit(CreatureMapType &m)
+{
+ for (CreatureMapType::iterator iter = m.begin(); iter != m.end(); ++iter)
+ {
+ Creature *c = iter->getSource();
+ CreatureUnitRelocationWorker(c, &i_unit);
+ if (isCreature)
+ CreatureUnitRelocationWorker((Creature*)&i_unit, c);
+ }
+}
+
+void
+MessageDistDeliverer::Visit(PlayerMapType &m)
+{
+ for (PlayerMapType::iterator iter = m.begin(); iter != m.end(); ++iter)
+ {
+ Player *target = iter->getSource();
+ if (!target->InSamePhase(i_phaseMask))
+ continue;
+
+ if (target->GetExactDistSq(i_source) > i_distSq)
+ continue;
+
+ // Send packet to all who are sharing the player's vision
+ if (!target->GetSharedVisionList().empty())
+ {
+ SharedVisionList::const_iterator i = target->GetSharedVisionList().begin();
+ for (; i != target->GetSharedVisionList().end(); ++i)
+ if ((*i)->m_seer == target)
+ SendPacket(*i);
+ }
+
+ if (target->m_seer == target || target->GetVehicle())
+ SendPacket(target);
+ }
+}
+
+void
+MessageDistDeliverer::Visit(CreatureMapType &m)
+{
+ for (CreatureMapType::iterator iter = m.begin(); iter != m.end(); ++iter)
+ {
+ if (!iter->getSource()->InSamePhase(i_phaseMask))
+ continue;
+
+ if (iter->getSource()->GetExactDistSq(i_source) > i_distSq)
+ continue;
+
+ // Send packet to all who are sharing the creature's vision
+ if (!iter->getSource()->GetSharedVisionList().empty())
+ {
+ SharedVisionList::const_iterator i = iter->getSource()->GetSharedVisionList().begin();
+ for (; i != iter->getSource()->GetSharedVisionList().end(); ++i)
+ if ((*i)->m_seer == iter->getSource())
+ SendPacket(*i);
+ }
+ }
+}
+
+void
+MessageDistDeliverer::Visit(DynamicObjectMapType &m)
+{
+ for (DynamicObjectMapType::iterator iter = m.begin(); iter != m.end(); ++iter)
+ {
+ if (!iter->getSource()->InSamePhase(i_phaseMask))
+ continue;
+
+ if (iter->getSource()->GetExactDistSq(i_source) > i_distSq)
+ continue;
+
+ if (IS_PLAYER_GUID(iter->getSource()->GetCasterGUID()))
+ {
+ // Send packet back to the caster if the caster has vision of dynamic object
+ Player* caster = (Player*)iter->getSource()->GetCaster();
+ if (caster && caster->m_seer == iter->getSource())
+ SendPacket(caster);
+ }
+ }
+}
+
+/*
+void
+MessageDistDeliverer::VisitObject(Player* plr)
+{
+ if (!i_ownTeamOnly || (i_source.GetTypeId() == TYPEID_PLAYER && plr->GetTeam() == ((Player&)i_source).GetTeam()))
+ {
+ SendPacket(plr);
+ }
+}
+*/
+
+template<class T> void
+ObjectUpdater::Visit(GridRefManager<T> &m)
+{
+ for (typename GridRefManager<T>::iterator iter = m.begin(); iter != m.end(); ++iter)
+ {
+ if (iter->getSource()->IsInWorld())
+ iter->getSource()->Update(i_timeDiff);
+ }
+}
+
+bool CannibalizeObjectCheck::operator()(Corpse* u)
+{
+ // ignore bones
+ if (u->GetType() == CORPSE_BONES)
+ return false;
+
+ Player* owner = ObjectAccessor::FindPlayer(u->GetOwnerGUID());
+
+ if (!owner || i_funit->IsFriendlyTo(owner))
+ return false;
+
+ if (i_funit->IsWithinDistInMap(u, i_range))
+ return true;
+
+ return false;
+}
+
+template void ObjectUpdater::Visit<GameObject>(GameObjectMapType &);
+template void ObjectUpdater::Visit<DynamicObject>(DynamicObjectMapType &);
diff --git a/src/server/game/Map/Grid/GridNotifiers.h b/src/server/game/Map/Grid/GridNotifiers.h
new file mode 100644
index 00000000000..b0abf0aae79
--- /dev/null
+++ b/src/server/game/Map/Grid/GridNotifiers.h
@@ -0,0 +1,1232 @@
+/*
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
+ *
+ * Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
+ *
+ * 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, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef TRINITY_GRIDNOTIFIERS_H
+#define TRINITY_GRIDNOTIFIERS_H
+
+#include "ObjectGridLoader.h"
+#include "UpdateData.h"
+#include <iostream>
+
+#include "Corpse.h"
+#include "Object.h"
+#include "DynamicObject.h"
+#include "GameObject.h"
+#include "Player.h"
+#include "Unit.h"
+#include "CreatureAI.h"
+
+class Player;
+//class Map;
+
+namespace Trinity
+{
+ struct VisibleNotifier
+ {
+ Player &i_player;
+ UpdateData i_data;
+ std::set<Unit*> i_visibleNow;
+ Player::ClientGUIDs vis_guids;
+
+ VisibleNotifier(Player &player) : i_player(player), vis_guids(player.m_clientGUIDs) {}
+ template<class T> void Visit(GridRefManager<T> &m);
+ void SendToSelf(void);
+ };
+
+ struct VisibleChangesNotifier
+ {
+ WorldObject &i_object;
+
+ explicit VisibleChangesNotifier(WorldObject &object) : i_object(object) {}
+ template<class T> void Visit(GridRefManager<T> &) {}
+ void Visit(PlayerMapType &);
+ void Visit(CreatureMapType &);
+ void Visit(DynamicObjectMapType &);
+ };
+
+ struct PlayerRelocationNotifier : public VisibleNotifier
+ {
+ PlayerRelocationNotifier(Player &pl) : VisibleNotifier(pl) {}
+
+ template<class T> void Visit(GridRefManager<T> &m) { VisibleNotifier::Visit(m); }
+ void Visit(CreatureMapType &);
+ void Visit(PlayerMapType &);
+ };
+
+ struct CreatureRelocationNotifier
+ {
+ Creature &i_creature;
+ CreatureRelocationNotifier(Creature &c) : i_creature(c) {}
+ template<class T> void Visit(GridRefManager<T> &) {}
+ void Visit(CreatureMapType &);
+ void Visit(PlayerMapType &);
+ };
+
+ struct DelayedUnitRelocation
+ {
+ Map &i_map;
+ Cell &cell;
+ CellPair &p;
+ const float i_radius;
+ DelayedUnitRelocation(Cell &c, CellPair &pair, Map &map, float radius) :
+ cell(c), p(pair), i_map(map), i_radius(radius) {}
+ template<class T> void Visit(GridRefManager<T> &) {}
+ void Visit(CreatureMapType &);
+ void Visit(PlayerMapType &);
+ };
+
+ struct AIRelocationNotifier
+ {
+ Unit &i_unit;
+ bool isCreature;
+ explicit AIRelocationNotifier(Unit &unit) : i_unit(unit), isCreature(unit.GetTypeId() == TYPEID_UNIT) {}
+ template<class T> void Visit(GridRefManager<T> &) {}
+ void Visit(CreatureMapType &);
+ };
+
+ struct GridUpdater
+ {
+ GridType &i_grid;
+ uint32 i_timeDiff;
+ GridUpdater(GridType &grid, uint32 diff) : i_grid(grid), i_timeDiff(diff) {}
+
+ template<class T> void updateObjects(GridRefManager<T> &m)
+ {
+ for (typename GridRefManager<T>::iterator iter = m.begin(); iter != m.end(); ++iter)
+ iter->getSource()->Update(i_timeDiff);
+ }
+
+ void Visit(PlayerMapType &m) { updateObjects<Player>(m); }
+ void Visit(CreatureMapType &m){ updateObjects<Creature>(m); }
+ void Visit(GameObjectMapType &m) { updateObjects<GameObject>(m); }
+ void Visit(DynamicObjectMapType &m) { updateObjects<DynamicObject>(m); }
+ void Visit(CorpseMapType &m) { updateObjects<Corpse>(m); }
+ };
+
+ struct MessageDistDeliverer
+ {
+ WorldObject *i_source;
+ WorldPacket *i_message;
+ uint32 i_phaseMask;
+ float i_distSq;
+ uint32 team;
+ Player const* skipped_receiver;
+ MessageDistDeliverer(WorldObject *src, WorldPacket *msg, float dist, bool own_team_only = false, Player const* skipped = NULL)
+ : i_source(src), i_message(msg), i_distSq(dist * dist), i_phaseMask(src->GetPhaseMask())
+ , team((own_team_only && src->GetTypeId() == TYPEID_PLAYER) ? ((Player*)src)->GetTeam() : 0)
+ , skipped_receiver(skipped)
+ {
+ }
+ void Visit(PlayerMapType &m);
+ void Visit(CreatureMapType &m);
+ void Visit(DynamicObjectMapType &m);
+ template<class SKIP> void Visit(GridRefManager<SKIP> &) {}
+
+ void SendPacket(Player* plr)
+ {
+ // never send packet to self
+ if (plr == i_source || (team && plr->GetTeam() != team) || skipped_receiver == plr)
+ return;
+
+ plr->GetSession()->SendPacket(i_message);
+ }
+ };
+
+ struct ObjectUpdater
+ {
+ uint32 i_timeDiff;
+ explicit ObjectUpdater(const uint32 &diff) : i_timeDiff(diff) {}
+ template<class T> void Visit(GridRefManager<T> &m);
+ void Visit(PlayerMapType &) {}
+ void Visit(CorpseMapType &) {}
+ void Visit(CreatureMapType &);
+ };
+
+ // SEARCHERS & LIST SEARCHERS & WORKERS
+
+ // WorldObject searchers & workers
+
+ template<class Check>
+ struct WorldObjectSearcher
+ {
+ uint32 i_phaseMask;
+ WorldObject* &i_object;
+ Check &i_check;
+
+ WorldObjectSearcher(WorldObject const* searcher, WorldObject* & result, Check& check)
+ : i_phaseMask(searcher->GetPhaseMask()), i_object(result),i_check(check) {}
+
+ void Visit(GameObjectMapType &m);
+ void Visit(PlayerMapType &m);
+ void Visit(CreatureMapType &m);
+ void Visit(CorpseMapType &m);
+ void Visit(DynamicObjectMapType &m);
+
+ template<class NOT_INTERESTED> void Visit(GridRefManager<NOT_INTERESTED> &) {}
+ };
+
+ template<class Check>
+ struct WorldObjectListSearcher
+ {
+ uint32 i_phaseMask;
+ std::list<WorldObject*> &i_objects;
+ Check& i_check;
+
+ WorldObjectListSearcher(WorldObject const* searcher, std::list<WorldObject*> &objects, Check & check)
+ : i_phaseMask(searcher->GetPhaseMask()), i_objects(objects),i_check(check) {}
+
+ void Visit(PlayerMapType &m);
+ void Visit(CreatureMapType &m);
+ void Visit(CorpseMapType &m);
+ void Visit(GameObjectMapType &m);
+ void Visit(DynamicObjectMapType &m);
+
+ template<class NOT_INTERESTED> void Visit(GridRefManager<NOT_INTERESTED> &) {}
+ };
+
+ template<class Do>
+ struct WorldObjectWorker
+ {
+ uint32 i_phaseMask;
+ Do const& i_do;
+
+ WorldObjectWorker(WorldObject const* searcher, Do const& _do)
+ : i_phaseMask(searcher->GetPhaseMask()), i_do(_do) {}
+
+ void Visit(GameObjectMapType &m)
+ {
+ for (GameObjectMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
+ if (itr->getSource()->InSamePhase(i_phaseMask))
+ i_do(itr->getSource());
+ }
+
+ void Visit(PlayerMapType &m)
+ {
+ for (PlayerMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
+ if (itr->getSource()->InSamePhase(i_phaseMask))
+ i_do(itr->getSource());
+ }
+ void Visit(CreatureMapType &m)
+ {
+ for (CreatureMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
+ if (itr->getSource()->InSamePhase(i_phaseMask))
+ i_do(itr->getSource());
+ }
+
+ void Visit(CorpseMapType &m)
+ {
+ for (CorpseMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
+ if (itr->getSource()->InSamePhase(i_phaseMask))
+ i_do(itr->getSource());
+ }
+
+ void Visit(DynamicObjectMapType &m)
+ {
+ for (DynamicObjectMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
+ if (itr->getSource()->InSamePhase(i_phaseMask))
+ i_do(itr->getSource());
+ }
+
+ template<class NOT_INTERESTED> void Visit(GridRefManager<NOT_INTERESTED> &) {}
+ };
+
+ // Gameobject searchers
+
+ template<class Check>
+ struct GameObjectSearcher
+ {
+ uint32 i_phaseMask;
+ GameObject* &i_object;
+ Check &i_check;
+
+ GameObjectSearcher(WorldObject const* searcher, GameObject* & result, Check& check)
+ : i_phaseMask(searcher->GetPhaseMask()), i_object(result),i_check(check) {}
+
+ void Visit(GameObjectMapType &m);
+
+ template<class NOT_INTERESTED> void Visit(GridRefManager<NOT_INTERESTED> &) {}
+ };
+
+ // Last accepted by Check GO if any (Check can change requirements at each call)
+ template<class Check>
+ struct GameObjectLastSearcher
+ {
+ uint32 i_phaseMask;
+ GameObject* &i_object;
+ Check& i_check;
+
+ GameObjectLastSearcher(WorldObject const* searcher, GameObject* & result, Check& check)
+ : i_phaseMask(searcher->GetPhaseMask()), i_object(result), i_check(check) {}
+
+ void Visit(GameObjectMapType &m);
+
+ template<class NOT_INTERESTED> void Visit(GridRefManager<NOT_INTERESTED> &) {}
+ };
+
+ template<class Check>
+ struct GameObjectListSearcher
+ {
+ uint32 i_phaseMask;
+ std::list<GameObject*> &i_objects;
+ Check& i_check;
+
+ GameObjectListSearcher(WorldObject const* searcher, std::list<GameObject*> &objects, Check & check)
+ : i_phaseMask(searcher->GetPhaseMask()), i_objects(objects), i_check(check) {}
+
+ void Visit(GameObjectMapType &m);
+
+ template<class NOT_INTERESTED> void Visit(GridRefManager<NOT_INTERESTED> &) {}
+ };
+
+ // Unit searchers
+
+ // First accepted by Check Unit if any
+ template<class Check>
+ struct UnitSearcher
+ {
+ uint32 i_phaseMask;
+ Unit* &i_object;
+ Check & i_check;
+
+ UnitSearcher(WorldObject const* searcher, Unit* & result, Check & check)
+ : i_phaseMask(searcher->GetPhaseMask()), i_object(result),i_check(check) {}
+
+ void Visit(CreatureMapType &m);
+ void Visit(PlayerMapType &m);
+
+ template<class NOT_INTERESTED> void Visit(GridRefManager<NOT_INTERESTED> &) {}
+ };
+
+ // Last accepted by Check Unit if any (Check can change requirements at each call)
+ template<class Check>
+ struct UnitLastSearcher
+ {
+ uint32 i_phaseMask;
+ Unit* &i_object;
+ Check & i_check;
+
+ UnitLastSearcher(WorldObject const* searcher, Unit* & result, Check & check)
+ : i_phaseMask(searcher->GetPhaseMask()), i_object(result),i_check(check) {}
+
+ void Visit(CreatureMapType &m);
+ void Visit(PlayerMapType &m);
+
+ template<class NOT_INTERESTED> void Visit(GridRefManager<NOT_INTERESTED> &) {}
+ };
+
+ // All accepted by Check units if any
+ template<class Check>
+ struct UnitListSearcher
+ {
+ uint32 i_phaseMask;
+ std::list<Unit*> &i_objects;
+ Check& i_check;
+
+ UnitListSearcher(WorldObject const* searcher, std::list<Unit*> &objects, Check & check)
+ : i_phaseMask(searcher->GetPhaseMask()), i_objects(objects),i_check(check) {}
+
+ void Visit(PlayerMapType &m);
+ void Visit(CreatureMapType &m);
+
+ template<class NOT_INTERESTED> void Visit(GridRefManager<NOT_INTERESTED> &) {}
+ };
+
+ // Creature searchers
+
+ template<class Check>
+ struct CreatureSearcher
+ {
+ uint32 i_phaseMask;
+ Creature* &i_object;
+ Check & i_check;
+
+ CreatureSearcher(WorldObject const* searcher, Creature* & result, Check & check)
+ : i_phaseMask(searcher->GetPhaseMask()), i_object(result),i_check(check) {}
+
+ void Visit(CreatureMapType &m);
+
+ template<class NOT_INTERESTED> void Visit(GridRefManager<NOT_INTERESTED> &) {}
+ };
+
+ // Last accepted by Check Creature if any (Check can change requirements at each call)
+ template<class Check>
+ struct CreatureLastSearcher
+ {
+ uint32 i_phaseMask;
+ Creature* &i_object;
+ Check & i_check;
+
+ CreatureLastSearcher(WorldObject const* searcher, Creature* & result, Check & check)
+ : i_phaseMask(searcher->GetPhaseMask()), i_object(result),i_check(check) {}
+
+ void Visit(CreatureMapType &m);
+
+ template<class NOT_INTERESTED> void Visit(GridRefManager<NOT_INTERESTED> &) {}
+ };
+
+ template<class Check>
+ struct CreatureListSearcher
+ {
+ uint32 i_phaseMask;
+ std::list<Creature*> &i_objects;
+ Check& i_check;
+
+ CreatureListSearcher(WorldObject const* searcher, std::list<Creature*> &objects, Check & check)
+ : i_phaseMask(searcher->GetPhaseMask()), i_objects(objects),i_check(check) {}
+
+ void Visit(CreatureMapType &m);
+
+ template<class NOT_INTERESTED> void Visit(GridRefManager<NOT_INTERESTED> &) {}
+ };
+
+ template<class Do>
+ struct CreatureWorker
+ {
+ uint32 i_phaseMask;
+ Do& i_do;
+
+ CreatureWorker(WorldObject const* searcher, Do& _do)
+ : i_phaseMask(searcher->GetPhaseMask()), i_do(_do) {}
+
+ void Visit(CreatureMapType &m)
+ {
+ for (CreatureMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
+ if (itr->getSource()->InSamePhase(i_phaseMask))
+ i_do(itr->getSource());
+ }
+
+ template<class NOT_INTERESTED> void Visit(GridRefManager<NOT_INTERESTED> &) {}
+ };
+
+ // Player searchers
+
+ template<class Check>
+ struct PlayerSearcher
+ {
+ uint32 i_phaseMask;
+ Player* &i_object;
+ Check & i_check;
+
+ PlayerSearcher(WorldObject const* searcher, Player* & result, Check & check)
+ : i_phaseMask(searcher->GetPhaseMask()), i_object(result),i_check(check) {}
+
+ void Visit(PlayerMapType &m);
+
+ template<class NOT_INTERESTED> void Visit(GridRefManager<NOT_INTERESTED> &) {}
+ };
+
+ template<class Check>
+ struct PlayerListSearcher
+ {
+ uint32 i_phaseMask;
+ std::list<Player*> &i_objects;
+ Check& i_check;
+
+ PlayerListSearcher(WorldObject const* searcher, std::list<Player*> &objects, Check & check)
+ : i_phaseMask(searcher->GetPhaseMask()), i_objects(objects),i_check(check) {}
+
+ void Visit(PlayerMapType &m);
+
+ template<class NOT_INTERESTED> void Visit(GridRefManager<NOT_INTERESTED> &) {}
+ };
+
+ template<class Do>
+ struct PlayerWorker
+ {
+ uint32 i_phaseMask;
+ Do& i_do;
+
+ PlayerWorker(WorldObject const* searcher, Do& _do)
+ : i_phaseMask(searcher->GetPhaseMask()), i_do(_do) {}
+
+ void Visit(PlayerMapType &m)
+ {
+ for (PlayerMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
+ if (itr->getSource()->InSamePhase(i_phaseMask))
+ i_do(itr->getSource());
+ }
+
+ template<class NOT_INTERESTED> void Visit(GridRefManager<NOT_INTERESTED> &) {}
+ };
+
+ template<class Do>
+ struct PlayerDistWorker
+ {
+ WorldObject const* i_searcher;
+ float i_dist;
+ Do& i_do;
+
+ PlayerDistWorker(WorldObject const* searcher, float _dist, Do& _do)
+ : i_searcher(searcher), i_dist(_dist), i_do(_do) {}
+
+ void Visit(PlayerMapType &m)
+ {
+ for (PlayerMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
+ if (itr->getSource()->InSamePhase(i_searcher) && itr->getSource()->IsWithinDist(i_searcher,i_dist))
+ i_do(itr->getSource());
+ }
+
+ template<class NOT_INTERESTED> void Visit(GridRefManager<NOT_INTERESTED> &) {}
+ };
+
+ // CHECKS && DO classes
+
+ // WorldObject check classes
+ class RaiseDeadObjectCheck
+ {
+ public:
+ RaiseDeadObjectCheck(Unit* funit, float range) : i_funit(funit), i_range(range) {}
+ bool operator()(Creature* u)
+ {
+ if (i_funit->GetTypeId() != TYPEID_PLAYER || !((Player*)i_funit)->isHonorOrXPTarget(u) ||
+ u->getDeathState() != CORPSE || u->isDeadByDefault() || u->isInFlight() ||
+ (u->GetCreatureTypeMask() & (1 << (CREATURE_TYPE_HUMANOID-1))) == 0 ||
+ (u->GetDisplayId() != u->GetNativeDisplayId()))
+ return false;
+
+ return i_funit->IsWithinDistInMap(u, i_range);
+ }
+ template<class NOT_INTERESTED> bool operator()(NOT_INTERESTED*) { return false; }
+ private:
+ Unit* const i_funit;
+ float i_range;
+ };
+
+ class ExplodeCorpseObjectCheck
+ {
+ public:
+ ExplodeCorpseObjectCheck(Unit* funit, float range) : i_funit(funit), i_range(range) {}
+ bool operator()(Player* u)
+ {
+ if (u->getDeathState() != CORPSE || u->isInFlight() ||
+ u->HasAuraType(SPELL_AURA_GHOST) || (u->GetDisplayId() != u->GetNativeDisplayId()))
+ return false;
+
+ return i_funit->IsWithinDistInMap(u, i_range);
+ }
+ bool operator()(Creature* u)
+ {
+ if (u->getDeathState() != CORPSE || u->isInFlight() || u->isDeadByDefault() ||
+ (u->GetDisplayId() != u->GetNativeDisplayId()) ||
+ (u->GetCreatureTypeMask() & CREATURE_TYPEMASK_MECHANICAL_OR_ELEMENTAL) != 0)
+ return false;
+
+ return i_funit->IsWithinDistInMap(u, i_range);
+ }
+ template<class NOT_INTERESTED> bool operator()(NOT_INTERESTED*) { return false; }
+ private:
+ Unit* const i_funit;
+ float i_range;
+ };
+
+ class CannibalizeObjectCheck
+ {
+ public:
+ CannibalizeObjectCheck(Unit* funit, float range) : i_funit(funit), i_range(range) {}
+ bool operator()(Player* u)
+ {
+ if (i_funit->IsFriendlyTo(u) || u->isAlive() || u->isInFlight())
+ return false;
+
+ return i_funit->IsWithinDistInMap(u, i_range);
+ }
+ bool operator()(Corpse* u);
+ bool operator()(Creature* u)
+ {
+ if (i_funit->IsFriendlyTo(u) || u->isAlive() || u->isInFlight() ||
+ (u->GetCreatureTypeMask() & CREATURE_TYPEMASK_HUMANOID_OR_UNDEAD) == 0)
+ return false;
+
+ return i_funit->IsWithinDistInMap(u, i_range);
+ }
+ template<class NOT_INTERESTED> bool operator()(NOT_INTERESTED*) { return false; }
+ private:
+ Unit* const i_funit;
+ float i_range;
+ };
+
+ // WorldObject do classes
+
+ class RespawnDo
+ {
+ public:
+ RespawnDo() {}
+ void operator()(Creature* u) const { u->Respawn(); }
+ void operator()(GameObject* u) const { u->Respawn(); }
+ void operator()(WorldObject*) const {}
+ void operator()(Corpse*) const {}
+ };
+
+ // GameObject checks
+
+ class GameObjectFocusCheck
+ {
+ public:
+ GameObjectFocusCheck(Unit const* unit,uint32 focusId) : i_unit(unit), i_focusId(focusId) {}
+ bool operator()(GameObject* go) const
+ {
+ if (go->GetGOInfo()->type != GAMEOBJECT_TYPE_SPELL_FOCUS)
+ return false;
+
+ if (go->GetGOInfo()->spellFocus.focusId != i_focusId)
+ return false;
+
+ float dist = (go->GetGOInfo()->spellFocus.dist)/2;
+
+ return go->IsWithinDistInMap(i_unit, dist);
+ }
+ private:
+ Unit const* i_unit;
+ uint32 i_focusId;
+ };
+
+ // Find the nearest Fishing hole and return true only if source object is in range of hole
+ class NearestGameObjectFishingHole
+ {
+ public:
+ NearestGameObjectFishingHole(WorldObject const& obj, float range) : i_obj(obj), i_range(range) {}
+ bool operator()(GameObject* go)
+ {
+ if (go->GetGOInfo()->type == GAMEOBJECT_TYPE_FISHINGHOLE && go->isSpawned() && i_obj.IsWithinDistInMap(go, i_range) && i_obj.IsWithinDistInMap(go, go->GetGOInfo()->fishinghole.radius))
+ {
+ i_range = i_obj.GetDistance(go);
+ return true;
+ }
+ return false;
+ }
+ float GetLastRange() const { return i_range; }
+ private:
+ WorldObject const& i_obj;
+ float i_range;
+
+ // prevent clone
+ NearestGameObjectFishingHole(NearestGameObjectFishingHole const&);
+ };
+
+ class NearestGameObjectCheck
+ {
+ public:
+ NearestGameObjectCheck(WorldObject const& obj) : i_obj(obj), i_range(999) {}
+ bool operator()(GameObject* go)
+ {
+ if (i_obj.IsWithinDistInMap(go, i_range))
+ {
+ i_range = i_obj.GetDistance(go); // use found GO range as new range limit for next check
+ return true;
+ }
+ return false;
+ }
+ float GetLastRange() const { return i_range; }
+ private:
+ WorldObject const& i_obj;
+ float i_range;
+
+ // prevent clone this object
+ NearestGameObjectCheck(NearestGameObjectCheck const&);
+ };
+
+ // Success at unit in range, range update for next check (this can be use with GameobjectLastSearcher to find nearest GO)
+ class NearestGameObjectEntryInObjectRangeCheck
+ {
+ public:
+ NearestGameObjectEntryInObjectRangeCheck(WorldObject const& obj,uint32 entry, float range) : i_obj(obj), i_entry(entry), i_range(range) {}
+ bool operator()(GameObject* go)
+ {
+ if (go->GetEntry() == i_entry && i_obj.IsWithinDistInMap(go, i_range))
+ {
+ i_range = i_obj.GetDistance(go); // use found GO range as new range limit for next check
+ return true;
+ }
+ return false;
+ }
+ float GetLastRange() const { return i_range; }
+ private:
+ WorldObject const& i_obj;
+ uint32 i_entry;
+ float i_range;
+
+ // prevent clone this object
+ NearestGameObjectEntryInObjectRangeCheck(NearestGameObjectEntryInObjectRangeCheck const&);
+ };
+
+ class GameObjectWithDbGUIDCheck
+ {
+ public:
+ GameObjectWithDbGUIDCheck(WorldObject const& obj,uint32 db_guid) : i_obj(obj), i_db_guid(db_guid) {}
+ bool operator()(GameObject const* go) const
+ {
+ return go->GetDBTableGUIDLow() == i_db_guid;
+ }
+ private:
+ WorldObject const& i_obj;
+ uint32 i_db_guid;
+ };
+
+ // Unit checks
+
+ class MostHPMissingInRange
+ {
+ public:
+ MostHPMissingInRange(Unit const* obj, float range, uint32 hp) : i_obj(obj), i_range(range), i_hp(hp) {}
+ bool operator()(Unit* u)
+ {
+ if (u->isAlive() && u->isInCombat() && !i_obj->IsHostileTo(u) && i_obj->IsWithinDistInMap(u, i_range) && u->GetMaxHealth() - u->GetHealth() > i_hp)
+ {
+ i_hp = u->GetMaxHealth() - u->GetHealth();
+ return true;
+ }
+ return false;
+ }
+ private:
+ Unit const* i_obj;
+ float i_range;
+ uint32 i_hp;
+ };
+
+ class FriendlyCCedInRange
+ {
+ public:
+ FriendlyCCedInRange(Unit const* obj, float range) : i_obj(obj), i_range(range) {}
+ bool operator()(Unit* u)
+ {
+ if (u->isAlive() && u->isInCombat() && !i_obj->IsHostileTo(u) && i_obj->IsWithinDistInMap(u, i_range) &&
+ (u->isFeared() || u->isCharmed() || u->isFrozen() || u->hasUnitState(UNIT_STAT_STUNNED) || u->hasUnitState(UNIT_STAT_CONFUSED)))
+ {
+ return true;
+ }
+ return false;
+ }
+ private:
+ Unit const* i_obj;
+ float i_range;
+ };
+
+ class FriendlyMissingBuffInRange
+ {
+ public:
+ FriendlyMissingBuffInRange(Unit const* obj, float range, uint32 spellid) : i_obj(obj), i_range(range), i_spell(spellid) {}
+ bool operator()(Unit* u)
+ {
+ if (u->isAlive() && u->isInCombat() && !i_obj->IsHostileTo(u) && i_obj->IsWithinDistInMap(u, i_range) &&
+ !(u->HasAura(i_spell)))
+ {
+ return true;
+ }
+ return false;
+ }
+ private:
+ Unit const* i_obj;
+ float i_range;
+ uint32 i_spell;
+ };
+
+ class AnyUnfriendlyUnitInObjectRangeCheck
+ {
+ public:
+ AnyUnfriendlyUnitInObjectRangeCheck(WorldObject const* obj, Unit const* funit, float range) : i_obj(obj), i_funit(funit), i_range(range) {}
+ bool operator()(Unit* u)
+ {
+ if (u->isAlive() && i_obj->IsWithinDistInMap(u, i_range) && !i_funit->IsFriendlyTo(u))
+ return true;
+ else
+ return false;
+ }
+ private:
+ WorldObject const* i_obj;
+ Unit const* i_funit;
+ float i_range;
+ };
+
+ class AnyUnfriendlyNoTotemUnitInObjectRangeCheck
+ {
+ public:
+ AnyUnfriendlyNoTotemUnitInObjectRangeCheck(WorldObject const* obj, Unit const* funit, float range) : i_obj(obj), i_funit(funit), i_range(range) {}
+ bool operator()(Unit* u)
+ {
+ if (!u->isAlive())
+ return false;
+
+ if (u->GetTypeId() == TYPEID_UNIT && ((Creature*)u)->isTotem())
+ return false;
+
+ return i_obj->IsWithinDistInMap(u, i_range) && !i_funit->IsFriendlyTo(u);
+ }
+ private:
+ WorldObject const* i_obj;
+ Unit const* i_funit;
+ float i_range;
+ };
+
+ class AnyUnfriendlyVisibleUnitInObjectRangeCheck
+ {
+ public:
+ AnyUnfriendlyVisibleUnitInObjectRangeCheck(WorldObject const* obj, Unit const* funit, float range)
+ : i_obj(obj), i_funit(funit), i_range(range) {}
+
+ bool operator()(Unit* u)
+ {
+ return u->isAlive()
+ && i_obj->IsWithinDistInMap(u, i_range)
+ && !i_funit->IsFriendlyTo(u)
+ && u->isVisibleForOrDetect(i_funit, false);
+ }
+ private:
+ WorldObject const* i_obj;
+ Unit const* i_funit;
+ float i_range;
+ };
+
+ class CreatureWithDbGUIDCheck
+ {
+ public:
+ CreatureWithDbGUIDCheck(WorldObject const* obj, uint32 lowguid) : i_obj(obj), i_lowguid(lowguid) {}
+ bool operator()(Creature* u)
+ {
+ return u->GetDBTableGUIDLow() == i_lowguid;
+ }
+ private:
+ WorldObject const* i_obj;
+ uint32 i_lowguid;
+ };
+
+ class AnyFriendlyUnitInObjectRangeCheck
+ {
+ public:
+ AnyFriendlyUnitInObjectRangeCheck(WorldObject const* obj, Unit const* funit, float range) : i_obj(obj), i_funit(funit), i_range(range) {}
+ bool operator()(Unit* u)
+ {
+ if (u->isAlive() && i_obj->IsWithinDistInMap(u, i_range) && i_funit->IsFriendlyTo(u))
+ return true;
+ else
+ return false;
+ }
+ private:
+ WorldObject const* i_obj;
+ Unit const* i_funit;
+ float i_range;
+ };
+
+ class AnyUnitInObjectRangeCheck
+ {
+ public:
+ AnyUnitInObjectRangeCheck(WorldObject const* obj, float range) : i_obj(obj), i_range(range) {}
+ bool operator()(Unit* u)
+ {
+ if (u->isAlive() && i_obj->IsWithinDistInMap(u, i_range))
+ return true;
+
+ return false;
+ }
+ private:
+ WorldObject const* i_obj;
+ float i_range;
+ };
+
+ // Success at unit in range, range update for next check (this can be use with UnitLastSearcher to find nearest unit)
+ class NearestAttackableUnitInObjectRangeCheck
+ {
+ public:
+ NearestAttackableUnitInObjectRangeCheck(WorldObject const* obj, Unit const* funit, float range) : i_obj(obj), i_funit(funit), i_range(range) {}
+ bool operator()(Unit* u)
+ {
+ if (u->isTargetableForAttack() && i_obj->IsWithinDistInMap(u, i_range) &&
+ !i_funit->IsFriendlyTo(u) && u->isVisibleForOrDetect(i_funit,false))
+ {
+ i_range = i_obj->GetDistance(u); // use found unit range as new range limit for next check
+ return true;
+ }
+
+ return false;
+ }
+ private:
+ WorldObject const* i_obj;
+ Unit const* i_funit;
+ float i_range;
+
+ // prevent clone this object
+ NearestAttackableUnitInObjectRangeCheck(NearestAttackableUnitInObjectRangeCheck const&);
+ };
+
+ class AnyAoETargetUnitInObjectRangeCheck
+ {
+ public:
+ AnyAoETargetUnitInObjectRangeCheck(WorldObject const* obj, Unit const* funit, float range)
+ : i_obj(obj), i_funit(funit), i_range(range)
+ {
+ Unit const* check = i_funit;
+ Unit const* owner = i_funit->GetOwner();
+ if (owner)
+ check = owner;
+ i_targetForPlayer = (check->GetTypeId() == TYPEID_PLAYER);
+ }
+ bool operator()(Unit* u)
+ {
+ // Check contains checks for: live, non-selectable, non-attackable flags, flight check and GM check, ignore totems
+ if (!u->isTargetableForAttack())
+ return false;
+ if (u->GetTypeId() == TYPEID_UNIT && ((Creature*)u)->isTotem())
+ return false;
+
+ if ((i_targetForPlayer ? !i_funit->IsFriendlyTo(u) : i_funit->IsHostileTo(u))&& i_obj->IsWithinDistInMap(u, i_range))
+ return true;
+
+ return false;
+ }
+ private:
+ bool i_targetForPlayer;
+ WorldObject const* i_obj;
+ Unit const* i_funit;
+ float i_range;
+ };
+
+ // do attack at call of help to friendly crearture
+ class CallOfHelpCreatureInRangeDo
+ {
+ public:
+ CallOfHelpCreatureInRangeDo(Unit* funit, Unit* enemy, float range)
+ : i_funit(funit), i_enemy(enemy), i_range(range)
+ {}
+ void operator()(Creature* u)
+ {
+ if (u == i_funit)
+ return;
+
+ if (!u->CanAssistTo(i_funit, i_enemy, false))
+ return;
+
+ // too far
+ if (!u->IsWithinDistInMap(i_enemy, i_range))
+ return;
+
+ // only if see assisted creature's enemy
+ if (!u->IsWithinLOSInMap(i_enemy))
+ return;
+
+ if (u->AI())
+ u->AI()->AttackStart(i_enemy);
+ }
+ private:
+ Unit* const i_funit;
+ Unit* const i_enemy;
+ float i_range;
+ };
+
+ struct AnyDeadUnitCheck
+ {
+ bool operator()(Unit* u) { return !u->isAlive(); }
+ };
+
+ struct AnyStealthedCheck
+ {
+ bool operator()(Unit* u) { return u->GetVisibility() == VISIBILITY_GROUP_STEALTH; }
+ };
+
+ // Creature checks
+
+ class NearestHostileUnitCheck
+ {
+ public:
+ explicit NearestHostileUnitCheck(Creature const* creature, float dist = 0) : me(creature)
+ {
+ m_range = (dist == 0 ? 9999 : dist);
+ }
+ bool operator()(Unit* u)
+ {
+ if (!me->IsWithinDistInMap(u, m_range))
+ return false;
+
+ if (!me->canAttack(u))
+ return false;
+
+ m_range = me->GetDistance(u); // use found unit range as new range limit for next check
+ return true;
+ }
+
+ private:
+ Creature const *me;
+ float m_range;
+ NearestHostileUnitCheck(NearestHostileUnitCheck const&);
+ };
+
+ class NearestHostileUnitInAttackDistanceCheck
+ {
+ public:
+ explicit NearestHostileUnitInAttackDistanceCheck(Creature const* creature, float dist = 0) : me(creature)
+ {
+ m_range = (dist == 0 ? 9999 : dist);
+ m_force = (dist == 0 ? false : true);
+ }
+ bool operator()(Unit* u)
+ {
+ if (!me->IsWithinDistInMap(u, m_range))
+ return false;
+
+ if (m_force)
+ {
+ if (!me->canAttack(u))
+ return false;
+ }
+ else
+ {
+ if (!me->canStartAttack(u, false))
+ return false;
+ }
+
+ m_range = me->GetDistance(u); // use found unit range as new range limit for next check
+ return true;
+ }
+ float GetLastRange() const { return m_range; }
+ private:
+ Creature const *me;
+ float m_range;
+ bool m_force;
+ NearestHostileUnitInAttackDistanceCheck(NearestHostileUnitInAttackDistanceCheck const&);
+ };
+
+ class AnyAssistCreatureInRangeCheck
+ {
+ public:
+ AnyAssistCreatureInRangeCheck(Unit* funit, Unit* enemy, float range)
+ : i_funit(funit), i_enemy(enemy), i_range(range)
+ {
+ }
+ bool operator()(Creature* u)
+ {
+ if (u == i_funit)
+ return false;
+
+ if (!u->CanAssistTo(i_funit, i_enemy))
+ return false;
+
+ // too far
+ if (!i_funit->IsWithinDistInMap(u, i_range))
+ return false;
+
+ // only if see assisted creature
+ if (!i_funit->IsWithinLOSInMap(u))
+ return false;
+
+ return true;
+ }
+ private:
+ Unit* const i_funit;
+ Unit* const i_enemy;
+ float i_range;
+ };
+
+ class NearestAssistCreatureInCreatureRangeCheck
+ {
+ public:
+ NearestAssistCreatureInCreatureRangeCheck(Creature* obj, Unit* enemy, float range)
+ : i_obj(obj), i_enemy(enemy), i_range(range) {}
+
+ bool operator()(Creature* u)
+ {
+ if (u == i_obj)
+ return false;
+ if (!u->CanAssistTo(i_obj,i_enemy))
+ return false;
+
+ if (!i_obj->IsWithinDistInMap(u, i_range))
+ return false;
+
+ if (!i_obj->IsWithinLOSInMap(u))
+ return false;
+
+ i_range = i_obj->GetDistance(u); // use found unit range as new range limit for next check
+ return true;
+ }
+ float GetLastRange() const { return i_range; }
+ private:
+ Creature* const i_obj;
+ Unit* const i_enemy;
+ float i_range;
+
+ // prevent clone this object
+ NearestAssistCreatureInCreatureRangeCheck(NearestAssistCreatureInCreatureRangeCheck const&);
+ };
+
+ // Success at unit in range, range update for next check (this can be use with CreatureLastSearcher to find nearest creature)
+ class NearestCreatureEntryWithLiveStateInObjectRangeCheck
+ {
+ public:
+ NearestCreatureEntryWithLiveStateInObjectRangeCheck(WorldObject const& obj, uint32 entry, bool alive, float range)
+ : i_obj(obj), i_entry(entry), i_alive(alive), i_range(range) {}
+
+ bool operator()(Creature* u)
+ {
+ if (u->GetEntry() == i_entry && u->isAlive() == i_alive && i_obj.IsWithinDistInMap(u, i_range))
+ {
+ i_range = i_obj.GetDistance(u); // use found unit range as new range limit for next check
+ return true;
+ }
+ return false;
+ }
+ float GetLastRange() const { return i_range; }
+ private:
+ WorldObject const& i_obj;
+ uint32 i_entry;
+ bool i_alive;
+ float i_range;
+
+ // prevent clone this object
+ NearestCreatureEntryWithLiveStateInObjectRangeCheck(NearestCreatureEntryWithLiveStateInObjectRangeCheck const&);
+ };
+
+ class AnyPlayerInObjectRangeCheck
+ {
+ public:
+ AnyPlayerInObjectRangeCheck(WorldObject const* obj, float range) : i_obj(obj), i_range(range) {}
+ bool operator()(Player* u)
+ {
+ if (u->isAlive() && i_obj->IsWithinDistInMap(u, i_range))
+ return true;
+
+ return false;
+ }
+ private:
+ WorldObject const* i_obj;
+ float i_range;
+ };
+
+ class AllFriendlyCreaturesInGrid
+ {
+ public:
+ AllFriendlyCreaturesInGrid(Unit const* obj) : pUnit(obj) {}
+ bool operator() (Unit* u)
+ {
+ if (u->isAlive() && u->GetVisibility() == VISIBILITY_ON && u->IsFriendlyTo(pUnit))
+ return true;
+
+ return false;
+ }
+ private:
+ Unit const* pUnit;
+ };
+
+ class AllGameObjectsWithEntryInRange
+ {
+ public:
+ AllGameObjectsWithEntryInRange(const WorldObject* pObject, uint32 uiEntry, float fMaxRange) : m_pObject(pObject), m_uiEntry(uiEntry), m_fRange(fMaxRange) {}
+ bool operator() (GameObject* pGo)
+ {
+ if (pGo->GetEntry() == m_uiEntry && m_pObject->IsWithinDist(pGo,m_fRange,false))
+ return true;
+
+ return false;
+ }
+ private:
+ const WorldObject* m_pObject;
+ uint32 m_uiEntry;
+ float m_fRange;
+ };
+
+ class AllCreaturesOfEntryInRange
+ {
+ public:
+ AllCreaturesOfEntryInRange(const WorldObject* pObject, uint32 uiEntry, float fMaxRange) : m_pObject(pObject), m_uiEntry(uiEntry), m_fRange(fMaxRange) {}
+ bool operator() (Unit* pUnit)
+ {
+ if (pUnit->GetEntry() == m_uiEntry && m_pObject->IsWithinDist(pUnit,m_fRange,false))
+ return true;
+
+ return false;
+ }
+
+ private:
+ const WorldObject* m_pObject;
+ uint32 m_uiEntry;
+ float m_fRange;
+ };
+
+ class PlayerAtMinimumRangeAway
+ {
+ public:
+ PlayerAtMinimumRangeAway(Unit const* unit, float fMinRange) : pUnit(unit), fRange(fMinRange) {}
+ bool operator() (Player* pPlayer)
+ {
+ //No threat list check, must be done explicit if expected to be in combat with creature
+ if (!pPlayer->isGameMaster() && pPlayer->isAlive() && !pUnit->IsWithinDist(pPlayer,fRange,false))
+ return true;
+
+ return false;
+ }
+
+ private:
+ Unit const* pUnit;
+ float fRange;
+ };
+
+ class GameObjectInRangeCheck
+ {
+ public:
+ GameObjectInRangeCheck(float _x, float _y, float _z, float _range) : x(_x), y(_y), z(_z), range(_range) {}
+ bool operator() (GameObject* go)
+ {
+ return go->IsInRange(x, y, z, range);
+ }
+ private:
+ float x, y, z, range;
+ };
+
+ // Player checks and do
+
+ // Prepare using Builder localized packets with caching and send to player
+ template<class Builder>
+ class LocalizedPacketDo
+ {
+ public:
+ explicit LocalizedPacketDo(Builder& builder) : i_builder(builder) {}
+
+ ~LocalizedPacketDo()
+ {
+ for (size_t i = 0; i < i_data_cache.size(); ++i)
+ delete i_data_cache[i];
+ }
+ void operator()(Player* p);
+
+ private:
+ Builder& i_builder;
+ std::vector<WorldPacket*> i_data_cache; // 0 = default, i => i-1 locale index
+ };
+
+ // Prepare using Builder localized packets with caching and send to player
+ template<class Builder>
+ class LocalizedPacketListDo
+ {
+ public:
+ typedef std::vector<WorldPacket*> WorldPacketList;
+ explicit LocalizedPacketListDo(Builder& builder) : i_builder(builder) {}
+
+ ~LocalizedPacketListDo()
+ {
+ for (size_t i = 0; i < i_data_cache.size(); ++i)
+ for (size_t j = 0; j < i_data_cache[i].size(); ++j)
+ delete i_data_cache[i][j];
+ }
+ void operator()(Player* p);
+
+ private:
+ Builder& i_builder;
+ std::vector<WorldPacketList> i_data_cache;
+ // 0 = default, i => i-1 locale index
+ };
+}
+#endif
diff --git a/src/server/game/Map/Grid/GridNotifiersImpl.h b/src/server/game/Map/Grid/GridNotifiersImpl.h
new file mode 100644
index 00000000000..26a9c0bd328
--- /dev/null
+++ b/src/server/game/Map/Grid/GridNotifiersImpl.h
@@ -0,0 +1,453 @@
+/*
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
+ *
+ * Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
+ *
+ * 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, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef TRINITY_GRIDNOTIFIERSIMPL_H
+#define TRINITY_GRIDNOTIFIERSIMPL_H
+
+#include "GridNotifiers.h"
+#include "WorldPacket.h"
+#include "Corpse.h"
+#include "Player.h"
+#include "UpdateData.h"
+#include "CreatureAI.h"
+#include "SpellAuras.h"
+
+
+template<class T>
+inline void
+Trinity::VisibleNotifier::Visit(GridRefManager<T> &m)
+{
+ for (typename GridRefManager<T>::iterator iter = m.begin(); iter != m.end(); ++iter)
+ {
+ vis_guids.erase(iter->getSource()->GetGUID());
+ i_player.UpdateVisibilityOf(iter->getSource(),i_data,i_visibleNow);
+ }
+}
+
+inline void
+Trinity::ObjectUpdater::Visit(CreatureMapType &m)
+{
+ for (CreatureMapType::iterator iter=m.begin(); iter != m.end(); ++iter)
+ if (iter->getSource()->IsInWorld() && !iter->getSource()->isSpiritService())
+ iter->getSource()->Update(i_timeDiff);
+}
+
+// SEARCHERS & LIST SEARCHERS & WORKERS
+
+// WorldObject searchers & workers
+
+template<class Check>
+void Trinity::WorldObjectSearcher<Check>::Visit(GameObjectMapType &m)
+{
+ // already found
+ if (i_object)
+ return;
+
+ for (GameObjectMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
+ {
+ if (!itr->getSource()->InSamePhase(i_phaseMask))
+ continue;
+
+ if (i_check(itr->getSource()))
+ {
+ i_object = itr->getSource();
+ return;
+ }
+ }
+}
+
+template<class Check>
+void Trinity::WorldObjectSearcher<Check>::Visit(PlayerMapType &m)
+{
+ // already found
+ if (i_object)
+ return;
+
+ for (PlayerMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
+ {
+ if (!itr->getSource()->InSamePhase(i_phaseMask))
+ continue;
+
+ if (i_check(itr->getSource()))
+ {
+ i_object = itr->getSource();
+ return;
+ }
+ }
+}
+
+template<class Check>
+void Trinity::WorldObjectSearcher<Check>::Visit(CreatureMapType &m)
+{
+ // already found
+ if (i_object)
+ return;
+
+ for (CreatureMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
+ {
+ if (!itr->getSource()->InSamePhase(i_phaseMask))
+ continue;
+
+ if (i_check(itr->getSource()))
+ {
+ i_object = itr->getSource();
+ return;
+ }
+ }
+}
+
+template<class Check>
+void Trinity::WorldObjectSearcher<Check>::Visit(CorpseMapType &m)
+{
+ // already found
+ if (i_object)
+ return;
+
+ for (CorpseMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
+ {
+ if (!itr->getSource()->InSamePhase(i_phaseMask))
+ continue;
+
+ if (i_check(itr->getSource()))
+ {
+ i_object = itr->getSource();
+ return;
+ }
+ }
+}
+
+template<class Check>
+void Trinity::WorldObjectSearcher<Check>::Visit(DynamicObjectMapType &m)
+{
+ // already found
+ if (i_object)
+ return;
+
+ for (DynamicObjectMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
+ {
+ if (!itr->getSource()->InSamePhase(i_phaseMask))
+ continue;
+
+ if (i_check(itr->getSource()))
+ {
+ i_object = itr->getSource();
+ return;
+ }
+ }
+}
+
+template<class Check>
+void Trinity::WorldObjectListSearcher<Check>::Visit(PlayerMapType &m)
+{
+ for (PlayerMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
+ if (itr->getSource()->InSamePhase(i_phaseMask))
+ if (i_check(itr->getSource()))
+ i_objects.push_back(itr->getSource());
+}
+
+template<class Check>
+void Trinity::WorldObjectListSearcher<Check>::Visit(CreatureMapType &m)
+{
+ for (CreatureMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
+ if (itr->getSource()->InSamePhase(i_phaseMask))
+ if (i_check(itr->getSource()))
+ i_objects.push_back(itr->getSource());
+}
+
+template<class Check>
+void Trinity::WorldObjectListSearcher<Check>::Visit(CorpseMapType &m)
+{
+ for (CorpseMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
+ if (itr->getSource()->InSamePhase(i_phaseMask))
+ if (i_check(itr->getSource()))
+ i_objects.push_back(itr->getSource());
+}
+
+template<class Check>
+void Trinity::WorldObjectListSearcher<Check>::Visit(GameObjectMapType &m)
+{
+ for (GameObjectMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
+ if (itr->getSource()->InSamePhase(i_phaseMask))
+ if (i_check(itr->getSource()))
+ i_objects.push_back(itr->getSource());
+}
+
+template<class Check>
+void Trinity::WorldObjectListSearcher<Check>::Visit(DynamicObjectMapType &m)
+{
+ for (DynamicObjectMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
+ if (itr->getSource()->InSamePhase(i_phaseMask))
+ if (i_check(itr->getSource()))
+ i_objects.push_back(itr->getSource());
+}
+
+// Gameobject searchers
+
+template<class Check>
+void Trinity::GameObjectSearcher<Check>::Visit(GameObjectMapType &m)
+{
+ // already found
+ if (i_object)
+ return;
+
+ for (GameObjectMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
+ {
+ if (!itr->getSource()->InSamePhase(i_phaseMask))
+ continue;
+
+ if (i_check(itr->getSource()))
+ {
+ i_object = itr->getSource();
+ return;
+ }
+ }
+}
+
+template<class Check>
+void Trinity::GameObjectLastSearcher<Check>::Visit(GameObjectMapType &m)
+{
+ for (GameObjectMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
+ {
+ if (!itr->getSource()->InSamePhase(i_phaseMask))
+ continue;
+
+ if (i_check(itr->getSource()))
+ i_object = itr->getSource();
+ }
+}
+
+template<class Check>
+void Trinity::GameObjectListSearcher<Check>::Visit(GameObjectMapType &m)
+{
+ for (GameObjectMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
+ if (itr->getSource()->InSamePhase(i_phaseMask))
+ if (i_check(itr->getSource()))
+ i_objects.push_back(itr->getSource());
+}
+
+// Unit searchers
+
+template<class Check>
+void Trinity::UnitSearcher<Check>::Visit(CreatureMapType &m)
+{
+ // already found
+ if (i_object)
+ return;
+
+ for (CreatureMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
+ {
+ if (!itr->getSource()->InSamePhase(i_phaseMask))
+ continue;
+
+ if (i_check(itr->getSource()))
+ {
+ i_object = itr->getSource();
+ return;
+ }
+ }
+}
+
+template<class Check>
+void Trinity::UnitSearcher<Check>::Visit(PlayerMapType &m)
+{
+ // already found
+ if (i_object)
+ return;
+
+ for (PlayerMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
+ {
+ if (!itr->getSource()->InSamePhase(i_phaseMask))
+ continue;
+
+ if (i_check(itr->getSource()))
+ {
+ i_object = itr->getSource();
+ return;
+ }
+ }
+}
+
+template<class Check>
+void Trinity::UnitLastSearcher<Check>::Visit(CreatureMapType &m)
+{
+ for (CreatureMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
+ {
+ if (!itr->getSource()->InSamePhase(i_phaseMask))
+ continue;
+
+ if (i_check(itr->getSource()))
+ i_object = itr->getSource();
+ }
+}
+
+template<class Check>
+void Trinity::UnitLastSearcher<Check>::Visit(PlayerMapType &m)
+{
+ for (PlayerMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
+ {
+ if (!itr->getSource()->InSamePhase(i_phaseMask))
+ continue;
+
+ if (i_check(itr->getSource()))
+ i_object = itr->getSource();
+ }
+}
+
+template<class Check>
+void Trinity::UnitListSearcher<Check>::Visit(PlayerMapType &m)
+{
+ for (PlayerMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
+ if (itr->getSource()->InSamePhase(i_phaseMask))
+ if (i_check(itr->getSource()))
+ i_objects.push_back(itr->getSource());
+}
+
+template<class Check>
+void Trinity::UnitListSearcher<Check>::Visit(CreatureMapType &m)
+{
+ for (CreatureMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
+ if (itr->getSource()->InSamePhase(i_phaseMask))
+ if (i_check(itr->getSource()))
+ i_objects.push_back(itr->getSource());
+}
+
+// Creature searchers
+
+template<class Check>
+void Trinity::CreatureSearcher<Check>::Visit(CreatureMapType &m)
+{
+ // already found
+ if (i_object)
+ return;
+
+ for (CreatureMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
+ {
+ if (!itr->getSource()->InSamePhase(i_phaseMask))
+ continue;
+
+ if (i_check(itr->getSource()))
+ {
+ i_object = itr->getSource();
+ return;
+ }
+ }
+}
+
+template<class Check>
+void Trinity::CreatureLastSearcher<Check>::Visit(CreatureMapType &m)
+{
+ for (CreatureMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
+ {
+ if (!itr->getSource()->InSamePhase(i_phaseMask))
+ continue;
+
+ if (i_check(itr->getSource()))
+ i_object = itr->getSource();
+ }
+}
+
+template<class Check>
+void Trinity::CreatureListSearcher<Check>::Visit(CreatureMapType &m)
+{
+ for (CreatureMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
+ if (itr->getSource()->InSamePhase(i_phaseMask))
+ if (i_check(itr->getSource()))
+ i_objects.push_back(itr->getSource());
+}
+
+template<class Check>
+void Trinity::PlayerListSearcher<Check>::Visit(PlayerMapType &m)
+{
+ for (PlayerMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
+ if (itr->getSource()->InSamePhase(i_phaseMask))
+ if (i_check(itr->getSource()))
+ i_objects.push_back(itr->getSource());
+}
+
+template<class Check>
+void Trinity::PlayerSearcher<Check>::Visit(PlayerMapType &m)
+{
+ // already found
+ if (i_object)
+ return;
+
+ for (PlayerMapType::iterator itr=m.begin(); itr != m.end(); ++itr)
+ {
+ if (!itr->getSource()->InSamePhase(i_phaseMask))
+ continue;
+
+ if (i_check(itr->getSource()))
+ {
+ i_object = itr->getSource();
+ return;
+ }
+ }
+}
+
+template<class Builder>
+void Trinity::LocalizedPacketDo<Builder>::operator()(Player* p)
+{
+ int32 loc_idx = p->GetSession()->GetSessionDbLocaleIndex();
+ uint32 cache_idx = loc_idx+1;
+ WorldPacket* data;
+
+ // create if not cached yet
+ if (i_data_cache.size() < cache_idx+1 || !i_data_cache[cache_idx])
+ {
+ if (i_data_cache.size() < cache_idx+1)
+ i_data_cache.resize(cache_idx+1);
+
+ data = new WorldPacket(SMSG_MESSAGECHAT, 200);
+
+ i_builder(*data,loc_idx);
+
+ i_data_cache[cache_idx] = data;
+ }
+ else
+ data = i_data_cache[cache_idx];
+
+ p->SendDirectMessage(data);
+}
+
+template<class Builder>
+void Trinity::LocalizedPacketListDo<Builder>::operator()(Player* p)
+{
+ int32 loc_idx = p->GetSession()->GetSessionDbLocaleIndex();
+ uint32 cache_idx = loc_idx+1;
+ WorldPacketList* data_list;
+
+ // create if not cached yet
+ if (i_data_cache.size() < cache_idx+1 || i_data_cache[cache_idx].empty())
+ {
+ if (i_data_cache.size() < cache_idx+1)
+ i_data_cache.resize(cache_idx+1);
+
+ data_list = &i_data_cache[cache_idx];
+
+ i_builder(*data_list,loc_idx);
+ }
+ else
+ data_list = &i_data_cache[cache_idx];
+
+ for (size_t i = 0; i < data_list->size(); ++i)
+ p->SendDirectMessage((*data_list)[i]);
+}
+
+#endif // TRINITY_GRIDNOTIFIERSIMPL_H
diff --git a/src/server/game/Map/Grid/GridStates.cpp b/src/server/game/Map/Grid/GridStates.cpp
new file mode 100644
index 00000000000..9d39531cfad
--- /dev/null
+++ b/src/server/game/Map/Grid/GridStates.cpp
@@ -0,0 +1,76 @@
+/*
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
+ *
+ * Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
+ *
+ * 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, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "GridStates.h"
+#include "GridNotifiers.h"
+#include "GameSystem/Grid.h"
+#include "Log.h"
+
+void
+InvalidState::Update(Map &, NGridType &, GridInfo &, const uint32 &/*x*/, const uint32 &/*y*/, const uint32 &) const
+{
+}
+
+void
+ActiveState::Update(Map &m, NGridType &grid, GridInfo & info, const uint32 &x, const uint32 &y, const uint32 &t_diff) const
+{
+ // Only check grid activity every (grid_expiry/10) ms, because it's really useless to do it every cycle
+ info.UpdateTimeTracker(t_diff);
+ if (info.getTimeTracker().Passed())
+ {
+ if (grid.ActiveObjectsInGrid() == 0 && !m.ActiveObjectsNearGrid(x, y))
+ {
+ ObjectGridStoper stoper(grid);
+ stoper.StopN();
+ grid.SetGridState(GRID_STATE_IDLE);
+ sLog.outDebug("Grid[%u,%u] on map %u moved to IDLE state", x, y, m.GetId());
+ }
+ else
+ {
+ m.ResetGridExpiry(grid, 0.1f);
+ }
+ }
+}
+
+void
+IdleState::Update(Map &m, NGridType &grid, GridInfo &, const uint32 &x, const uint32 &y, const uint32 &) const
+{
+ m.ResetGridExpiry(grid);
+ grid.SetGridState(GRID_STATE_REMOVAL);
+ sLog.outDebug("Grid[%u,%u] on map %u moved to REMOVAL state", x, y, m.GetId());
+}
+
+void
+RemovalState::Update(Map &m, NGridType &grid, GridInfo &info, const uint32 &x, const uint32 &y, const uint32 &t_diff) const
+{
+ if (!info.getUnloadLock())
+ {
+ info.UpdateTimeTracker(t_diff);
+ if (info.getTimeTracker().Passed())
+ {
+ if (!m.UnloadGrid(x, y, false))
+ {
+ sLog.outDebug("Grid[%u,%u] for map %u differed unloading due to players or active objects nearby", x, y, m.GetId());
+ m.ResetGridExpiry(grid);
+ }
+ }
+ }
+}
+
diff --git a/src/server/game/Map/Grid/GridStates.h b/src/server/game/Map/Grid/GridStates.h
new file mode 100644
index 00000000000..c2a75ec45b7
--- /dev/null
+++ b/src/server/game/Map/Grid/GridStates.h
@@ -0,0 +1,76 @@
+/*
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
+ *
+ * Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
+ *
+ * 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, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef TRINITY_GRIDSTATES_H
+#define TRINITY_GRIDSTATES_H
+
+#include "Map.h"
+#include "Object.h"
+
+class GridState
+{
+ public:
+#ifdef TRINITY_DEBUG
+#define MAGIC_TESTVAL 0xFBE823BA
+ GridState() { i_Magic = MAGIC_TESTVAL; }
+ bool checkMagic()
+ {
+ if (i_Magic != MAGIC_TESTVAL)
+ {
+ sLog.outError("!!! GridState: Magic value gone !!!");
+ return false;
+ }
+ return true;
+ }
+ void setMagic() { i_Magic = MAGIC_TESTVAL; }
+ unsigned int i_Magic;
+#endif
+ virtual void Update(Map &, NGridType&, GridInfo &, const uint32 &x, const uint32 &y, const uint32 &t_diff) const = 0;
+};
+
+class InvalidState : public GridState
+{
+ public:
+
+ void Update(Map &, NGridType &, GridInfo &, const uint32 &x, const uint32 &y, const uint32 &t_diff) const;
+};
+
+class ActiveState : public GridState
+{
+ public:
+
+ void Update(Map &, NGridType &, GridInfo &, const uint32 &x, const uint32 &y, const uint32 &t_diff) const;
+};
+
+class IdleState : public GridState
+{
+ public:
+
+ void Update(Map &, NGridType &, GridInfo &, const uint32 &x, const uint32 &y, const uint32 &t_diff) const;
+};
+
+class RemovalState : public GridState
+{
+ public:
+
+ void Update(Map &, NGridType &, GridInfo &, const uint32 &x, const uint32 &y, const uint32 &t_diff) const;
+};
+#endif
+
diff --git a/src/server/game/Map/Grid/ObjectGridLoader.cpp b/src/server/game/Map/Grid/ObjectGridLoader.cpp
new file mode 100644
index 00000000000..ab69d9a966b
--- /dev/null
+++ b/src/server/game/Map/Grid/ObjectGridLoader.cpp
@@ -0,0 +1,325 @@
+/*
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
+ *
+ * Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
+ *
+ * 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, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "ObjectGridLoader.h"
+#include "ObjectAccessor.h"
+#include "ObjectMgr.h"
+#include "Creature.h"
+#include "Vehicle.h"
+#include "GameObject.h"
+#include "DynamicObject.h"
+#include "Corpse.h"
+#include "World.h"
+#include "CellImpl.h"
+#include "CreatureAI.h"
+
+class ObjectGridRespawnMover
+{
+ public:
+ ObjectGridRespawnMover() {}
+
+ void Move(GridType &grid);
+
+ template<class T> void Visit(GridRefManager<T> &) {}
+ void Visit(CreatureMapType &m);
+};
+
+void
+ObjectGridRespawnMover::Move(GridType &grid)
+{
+ TypeContainerVisitor<ObjectGridRespawnMover, GridTypeMapContainer > mover(*this);
+ grid.Visit(mover);
+}
+
+void
+ObjectGridRespawnMover::Visit(CreatureMapType &m)
+{
+ // creature in unloading grid can have respawn point in another grid
+ // if it will be unloaded then it will not respawn in original grid until unload/load original grid
+ // move to respawn point to prevent this case. For player view in respawn grid this will be normal respawn.
+ for (CreatureMapType::iterator iter = m.begin(); iter != m.end();)
+ {
+ Creature * c = iter->getSource();
+ ++iter;
+
+ assert(!c->isPet() && "ObjectGridRespawnMover don't must be called for pets");
+
+ Cell const& cur_cell = c->GetCurrentCell();
+
+ float resp_x, resp_y, resp_z;
+ c->GetRespawnCoord(resp_x, resp_y, resp_z);
+ CellPair resp_val = Trinity::ComputeCellPair(resp_x, resp_y);
+ Cell resp_cell(resp_val);
+
+ if (cur_cell.DiffGrid(resp_cell))
+ {
+ c->GetMap()->CreatureRespawnRelocation(c);
+ // false result ignored: will be unload with other creatures at grid
+ }
+ }
+}
+
+// for loading world object at grid loading (Corpses)
+class ObjectWorldLoader
+{
+ public:
+ explicit ObjectWorldLoader(ObjectGridLoader& gloader)
+ : i_cell(gloader.i_cell), i_grid(gloader.i_grid), i_map(gloader.i_map), i_corpses (0)
+ {}
+
+ void Visit(CorpseMapType &m);
+
+ template<class T> void Visit(GridRefManager<T>&) { }
+
+ private:
+ Cell i_cell;
+ NGridType &i_grid;
+ Map* i_map;
+ public:
+ uint32 i_corpses;
+};
+
+template<class T> void addUnitState(T* /*obj*/, CellPair const& /*cell_pair*/)
+{
+}
+
+template<> void addUnitState(Creature *obj, CellPair const& cell_pair)
+{
+ Cell cell(cell_pair);
+
+ obj->SetCurrentCell(cell);
+ if (obj->isSpiritService())
+ obj->setDeathState(DEAD);
+}
+
+template <class T>
+void AddObjectHelper(CellPair &cell, GridRefManager<T> &m, uint32 &count, Map* map, T *obj)
+{
+ obj->GetGridRef().link(&m, obj);
+ addUnitState(obj,cell);
+ obj->AddToWorld();
+ if (obj->isActiveObject())
+ map->AddToActive(obj);
+
+ ++count;
+}
+
+template <class T>
+void LoadHelper(CellGuidSet const& guid_set, CellPair &cell, GridRefManager<T> &m, uint32 &count, Map* map)
+{
+ for (CellGuidSet::const_iterator i_guid = guid_set.begin(); i_guid != guid_set.end(); ++i_guid)
+ {
+ T* obj = new T;
+ uint32 guid = *i_guid;
+ //sLog.outString("DEBUG: LoadHelper from table: %s for (guid: %u) Loading",table,guid);
+ if (!obj->LoadFromDB(guid, map))
+ {
+ delete obj;
+ continue;
+ }
+
+ AddObjectHelper(cell, m, count, map, obj);
+ }
+}
+
+void LoadHelper(CellCorpseSet const& cell_corpses, CellPair &cell, CorpseMapType &m, uint32 &count, Map* map)
+{
+ if (cell_corpses.empty())
+ return;
+
+ for (CellCorpseSet::const_iterator itr = cell_corpses.begin(); itr != cell_corpses.end(); ++itr)
+ {
+ if (itr->second != map->GetInstanceId())
+ continue;
+
+ uint32 player_guid = itr->first;
+
+ Corpse *obj = ObjectAccessor::Instance().GetCorpseForPlayerGUID(player_guid);
+ if (!obj)
+ continue;
+
+ // TODO: this is a hack
+ // corpse's map should be reset when the map is unloaded
+ // but it may still exist when the grid is unloaded but map is not
+ // in that case map == currMap
+ obj->SetMap(map);
+
+ AddObjectHelper(cell, m, count, map, obj);
+ }
+}
+
+void
+ObjectGridLoader::Visit(GameObjectMapType &m)
+{
+ uint32 x = (i_cell.GridX()*MAX_NUMBER_OF_CELLS) + i_cell.CellX();
+ uint32 y = (i_cell.GridY()*MAX_NUMBER_OF_CELLS) + i_cell.CellY();
+ CellPair cell_pair(x,y);
+ uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
+
+ CellObjectGuids const& cell_guids = objmgr.GetCellObjectGuids(i_map->GetId(), i_map->GetSpawnMode(), cell_id);
+
+ LoadHelper(cell_guids.gameobjects, cell_pair, m, i_gameObjects, i_map);
+}
+
+void
+ObjectGridLoader::Visit(CreatureMapType &m)
+{
+ uint32 x = (i_cell.GridX()*MAX_NUMBER_OF_CELLS) + i_cell.CellX();
+ uint32 y = (i_cell.GridY()*MAX_NUMBER_OF_CELLS) + i_cell.CellY();
+ CellPair cell_pair(x,y);
+ uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
+
+ CellObjectGuids const& cell_guids = objmgr.GetCellObjectGuids(i_map->GetId(), i_map->GetSpawnMode(), cell_id);
+
+ LoadHelper(cell_guids.creatures, cell_pair, m, i_creatures, i_map);
+}
+
+void
+ObjectWorldLoader::Visit(CorpseMapType &m)
+{
+ uint32 x = (i_cell.GridX()*MAX_NUMBER_OF_CELLS) + i_cell.CellX();
+ uint32 y = (i_cell.GridY()*MAX_NUMBER_OF_CELLS) + i_cell.CellY();
+ CellPair cell_pair(x,y);
+ uint32 cell_id = (cell_pair.y_coord*TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord;
+
+ // corpses are always added to spawn mode 0 and they are spawned by their instance id
+ CellObjectGuids const& cell_guids = objmgr.GetCellObjectGuids(i_map->GetId(), 0, cell_id);
+ LoadHelper(cell_guids.corpses, cell_pair, m, i_corpses, i_map);
+}
+
+void
+ObjectGridLoader::Load(GridType &grid)
+{
+ {
+ TypeContainerVisitor<ObjectGridLoader, GridTypeMapContainer > loader(*this);
+ grid.Visit(loader);
+ }
+
+ {
+ ObjectWorldLoader wloader(*this);
+ TypeContainerVisitor<ObjectWorldLoader, WorldTypeMapContainer > loader(wloader);
+ grid.Visit(loader);
+ i_corpses = wloader.i_corpses;
+ }
+}
+
+void ObjectGridLoader::LoadN(void)
+{
+ i_gameObjects = 0; i_creatures = 0; i_corpses = 0;
+ i_cell.data.Part.cell_y = 0;
+ for (unsigned int x=0; x < MAX_NUMBER_OF_CELLS; ++x)
+ {
+ i_cell.data.Part.cell_x = x;
+ for (unsigned int y=0; y < MAX_NUMBER_OF_CELLS; ++y)
+ {
+ i_cell.data.Part.cell_y = y;
+ GridLoader<Player, AllWorldObjectTypes, AllGridObjectTypes> loader;
+ loader.Load(i_grid(x, y), *this);
+ }
+ }
+ sLog.outDebug("%u GameObjects, %u Creatures, and %u Corpses/Bones loaded for grid %u on map %u", i_gameObjects, i_creatures, i_corpses,i_grid.GetGridId(), i_map->GetId());
+}
+
+void ObjectGridUnloader::MoveToRespawnN()
+{
+ for (unsigned int x=0; x < MAX_NUMBER_OF_CELLS; ++x)
+ {
+ for (unsigned int y=0; y < MAX_NUMBER_OF_CELLS; ++y)
+ {
+ ObjectGridRespawnMover mover;
+ mover.Move(i_grid(x, y));
+ }
+ }
+}
+
+void
+ObjectGridUnloader::Unload(GridType &grid)
+{
+ TypeContainerVisitor<ObjectGridUnloader, GridTypeMapContainer > unloader(*this);
+ grid.Visit(unloader);
+}
+
+template<class T>
+void
+ObjectGridUnloader::Visit(GridRefManager<T> &m)
+{
+ while (!m.isEmpty())
+ {
+ T *obj = m.getFirst()->getSource();
+ // if option set then object already saved at this moment
+ if (!sWorld.getConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATELY))
+ obj->SaveRespawnTime();
+ ///- object will get delinked from the manager when deleted
+ delete obj;
+ }
+}
+
+void
+ObjectGridStoper::Stop(GridType &grid)
+{
+ TypeContainerVisitor<ObjectGridStoper, GridTypeMapContainer > stoper(*this);
+ grid.Visit(stoper);
+}
+
+void
+ObjectGridStoper::Visit(CreatureMapType &m)
+{
+ // stop any fights at grid de-activation and remove dynobjects created at cast by creatures
+ for (CreatureMapType::iterator iter=m.begin(); iter != m.end(); ++iter)
+ {
+ iter->getSource()->RemoveAllDynObjects();
+ if (iter->getSource()->isInCombat())
+ {
+ iter->getSource()->CombatStop();
+ iter->getSource()->DeleteThreatList();
+ iter->getSource()->AI()->EnterEvadeMode();
+ }
+ }
+}
+
+void
+ObjectGridCleaner::Stop(GridType &grid)
+{
+ TypeContainerVisitor<ObjectGridCleaner, GridTypeMapContainer > stoper(*this);
+ grid.Visit(stoper);
+}
+
+void
+ObjectGridCleaner::Visit(CreatureMapType &m)
+{
+ for (CreatureMapType::iterator iter=m.begin(); iter != m.end(); ++iter)
+ iter->getSource()->CleanupsBeforeDelete();
+}
+
+template<class T>
+void
+ObjectGridCleaner::Visit(GridRefManager<T> &m)
+{
+ for (typename GridRefManager<T>::iterator iter = m.begin(); iter != m.end(); ++iter)
+ iter->getSource()->RemoveFromWorld();
+}
+
+template void ObjectGridUnloader::Visit(CreatureMapType &);
+template void ObjectGridUnloader::Visit(GameObjectMapType &);
+template void ObjectGridUnloader::Visit(DynamicObjectMapType &);
+template void ObjectGridUnloader::Visit(CorpseMapType &);
+template void ObjectGridCleaner::Visit<GameObject>(GameObjectMapType &);
+template void ObjectGridCleaner::Visit<DynamicObject>(DynamicObjectMapType &);
+template void ObjectGridCleaner::Visit<Corpse>(CorpseMapType &);
diff --git a/src/server/game/Map/Grid/ObjectGridLoader.h b/src/server/game/Map/Grid/ObjectGridLoader.h
new file mode 100644
index 00000000000..e890bf8d482
--- /dev/null
+++ b/src/server/game/Map/Grid/ObjectGridLoader.h
@@ -0,0 +1,134 @@
+/*
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
+ *
+ * Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
+ *
+ * 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, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef TRINITY_OBJECTGRIDLOADER_H
+#define TRINITY_OBJECTGRIDLOADER_H
+
+#include "Utilities/TypeList.h"
+#include "Platform/Define.h"
+#include "GameSystem/GridLoader.h"
+#include "GridDefines.h"
+#include "Cell.h"
+
+class ObjectWorldLoader;
+
+class ObjectGridLoader
+{
+ friend class ObjectWorldLoader;
+
+ public:
+ ObjectGridLoader(NGridType &grid, Map* map, const Cell &cell)
+ : i_cell(cell), i_grid(grid), i_map(map), i_gameObjects(0), i_creatures(0), i_corpses (0)
+ {}
+
+ void Load(GridType &grid);
+ void Visit(GameObjectMapType &m);
+ void Visit(CreatureMapType &m);
+ void Visit(CorpseMapType &) {}
+
+ void Visit(DynamicObjectMapType&) { }
+
+ void LoadN(void);
+
+ private:
+ Cell i_cell;
+ NGridType &i_grid;
+ Map* i_map;
+ uint32 i_gameObjects;
+ uint32 i_creatures;
+ uint32 i_corpses;
+};
+
+class ObjectGridUnloader
+{
+ public:
+ ObjectGridUnloader(NGridType &grid) : i_grid(grid) {}
+
+ void MoveToRespawnN();
+ void UnloadN()
+ {
+ for (unsigned int x=0; x < MAX_NUMBER_OF_CELLS; ++x)
+ {
+ for (unsigned int y=0; y < MAX_NUMBER_OF_CELLS; ++y)
+ {
+ GridLoader<Player, AllWorldObjectTypes, AllGridObjectTypes> loader;
+ loader.Unload(i_grid(x, y), *this);
+ }
+ }
+ }
+
+ void Unload(GridType &grid);
+ template<class T> void Visit(GridRefManager<T> &m);
+ private:
+ NGridType &i_grid;
+};
+
+class ObjectGridStoper
+{
+ public:
+ ObjectGridStoper(NGridType &grid) : i_grid(grid) {}
+
+ void StopN()
+ {
+ for (unsigned int x=0; x < MAX_NUMBER_OF_CELLS; ++x)
+ {
+ for (unsigned int y=0; y < MAX_NUMBER_OF_CELLS; ++y)
+ {
+ GridLoader<Player, AllWorldObjectTypes, AllGridObjectTypes> loader;
+ loader.Stop(i_grid(x, y), *this);
+ }
+ }
+ }
+
+ void Stop(GridType &grid);
+ void Visit(CreatureMapType &m);
+
+ template<class NONACTIVE> void Visit(GridRefManager<NONACTIVE> &) {}
+ private:
+ NGridType &i_grid;
+};
+
+class ObjectGridCleaner
+{
+ public:
+ ObjectGridCleaner(NGridType &grid) : i_grid(grid) {}
+
+ void CleanN()
+ {
+ for (unsigned int x=0; x < MAX_NUMBER_OF_CELLS; ++x)
+ {
+ for (unsigned int y=0; y < MAX_NUMBER_OF_CELLS; ++y)
+ {
+ GridLoader<Player, AllWorldObjectTypes, AllGridObjectTypes> loader;
+ loader.Stop(i_grid(x, y), *this);
+ }
+ }
+ }
+
+ void Stop(GridType &grid);
+ void Visit(CreatureMapType &m);
+ template<class T> void Visit(GridRefManager<T> &);
+ private:
+ NGridType &i_grid;
+};
+
+typedef GridLoader<Player, AllWorldObjectTypes, AllGridObjectTypes> GridLoaderType;
+#endif
+
diff --git a/src/server/game/Map/Map.cpp b/src/server/game/Map/Map.cpp
new file mode 100644
index 00000000000..11bfdcd6f99
--- /dev/null
+++ b/src/server/game/Map/Map.cpp
@@ -0,0 +1,3936 @@
+/*
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
+ *
+ * Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
+ *
+ * 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, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "MapManager.h"
+#include "Player.h"
+#include "Vehicle.h"
+#include "GridNotifiers.h"
+#include "Log.h"
+#include "GridStates.h"
+#include "CellImpl.h"
+#include "InstanceData.h"
+#include "Map.h"
+#include "GridNotifiersImpl.h"
+#include "Config/ConfigEnv.h"
+#include "Transports.h"
+#include "ObjectAccessor.h"
+#include "ObjectMgr.h"
+#include "World.h"
+#include "Group.h"
+#include "MapRefManager.h"
+#include "Vehicle.h"
+#include "WaypointManager.h"
+#include "DBCEnums.h"
+#include "ScriptMgr.h"
+#include "ScriptedCreature.h"
+#include "GossipDef.h"
+
+#include "MapInstanced.h"
+#include "InstanceSaveMgr.h"
+#include "VMapFactory.h"
+
+#define DEFAULT_GRID_EXPIRY 300
+#define MAX_GRID_LOAD_TIME 50
+#define MAX_CREATURE_ATTACK_RADIUS (45.0f * sWorld.getRate(RATE_CREATURE_AGGRO))
+
+GridState* si_GridStates[MAX_GRID_STATE];
+
+struct ScriptAction
+{
+ uint64 sourceGUID;
+ uint64 targetGUID;
+ uint64 ownerGUID; // owner of source if source is item
+ ScriptInfo const* script; // pointer to static script data
+};
+
+Map::~Map()
+{
+ UnloadAll();
+
+ while (!i_worldObjects.empty())
+ {
+ WorldObject *obj = *i_worldObjects.begin();
+ assert(obj->m_isWorldObject);
+ //assert(obj->GetTypeId() == TYPEID_CORPSE);
+ obj->RemoveFromWorld();
+ obj->ResetMap();
+ }
+
+ if (!m_scriptSchedule.empty())
+ sWorld.DecreaseScheduledScriptCount(m_scriptSchedule.size());
+}
+
+bool Map::ExistMap(uint32 mapid,int gx,int gy)
+{
+ int len = sWorld.GetDataPath().length()+strlen("maps/%03u%02u%02u.map")+1;
+ char* tmp = new char[len];
+ snprintf(tmp, len, (char *)(sWorld.GetDataPath()+"maps/%03u%02u%02u.map").c_str(),mapid,gx,gy);
+
+ FILE *pf=fopen(tmp,"rb");
+
+ if (!pf)
+ {
+ sLog.outError("Map file '%s': does not exist!",tmp);
+ delete[] tmp;
+ return false;
+ }
+
+ map_fileheader header;
+ fread(&header, sizeof(header), 1, pf);
+ if (header.mapMagic != uint32(MAP_MAGIC) ||
+ header.versionMagic != uint32(MAP_VERSION_MAGIC))
+ {
+ sLog.outError("Map file '%s' is non-compatible version (outdated?). Please, create new using ad.exe program.",tmp);
+ delete [] tmp;
+ fclose(pf); //close file before return
+ return false;
+ }
+
+ delete [] tmp;
+ fclose(pf);
+ return true;
+}
+
+bool Map::ExistVMap(uint32 mapid,int gx,int gy)
+{
+ if (VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager())
+ {
+ if (vmgr->isMapLoadingEnabled())
+ {
+ // x and y are swapped !! => fixed now
+ bool exists = vmgr->existsMap((sWorld.GetDataPath()+ "vmaps").c_str(), mapid, gx,gy);
+ if (!exists)
+ {
+ std::string name = vmgr->getDirFileName(mapid,gx,gy);
+ sLog.outError("VMap file '%s' is missing or points to wrong version of vmap file. Redo vmaps with latest version of vmap_assembler.exe.", (sWorld.GetDataPath()+"vmaps/"+name).c_str());
+ return false;
+ }
+ }
+ }
+
+ return true;
+}
+
+void Map::LoadVMap(int gx,int gy)
+{
+ // x and y are swapped !!
+ int vmapLoadResult = VMAP::VMapFactory::createOrGetVMapManager()->loadMap((sWorld.GetDataPath()+ "vmaps").c_str(), GetId(), gx,gy);
+ switch(vmapLoadResult)
+ {
+ case VMAP::VMAP_LOAD_RESULT_OK:
+ sLog.outDetail("VMAP loaded name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", GetMapName(), GetId(), gx,gy,gx,gy);
+ break;
+ case VMAP::VMAP_LOAD_RESULT_ERROR:
+ sLog.outDetail("Could not load VMAP name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", GetMapName(), GetId(), gx,gy,gx,gy);
+ break;
+ case VMAP::VMAP_LOAD_RESULT_IGNORED:
+ DEBUG_LOG("Ignored VMAP name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", GetMapName(), GetId(), gx,gy,gx,gy);
+ break;
+ }
+}
+
+void Map::LoadMap(int gx,int gy, bool reload)
+{
+ if (i_InstanceId != 0)
+ {
+ if (GridMaps[gx][gy])
+ return;
+
+ // load grid map for base map
+ if (!m_parentMap->GridMaps[gx][gy])
+ m_parentMap->EnsureGridCreated(GridPair(63-gx,63-gy));
+
+ ((MapInstanced*)(m_parentMap))->AddGridMapReference(GridPair(gx,gy));
+ GridMaps[gx][gy] = m_parentMap->GridMaps[gx][gy];
+ return;
+ }
+
+ if (GridMaps[gx][gy] && !reload)
+ return;
+
+ //map already load, delete it before reloading (Is it necessary? Do we really need the ability the reload maps during runtime?)
+ if (GridMaps[gx][gy])
+ {
+ sLog.outDetail("Unloading previously loaded map %u before reloading.",GetId());
+ delete (GridMaps[gx][gy]);
+ GridMaps[gx][gy]=NULL;
+ }
+
+ // map file name
+ char *tmp=NULL;
+ int len = sWorld.GetDataPath().length()+strlen("maps/%03u%02u%02u.map")+1;
+ tmp = new char[len];
+ snprintf(tmp, len, (char *)(sWorld.GetDataPath()+"maps/%03u%02u%02u.map").c_str(),GetId(),gx,gy);
+ sLog.outDetail("Loading map %s",tmp);
+ // loading data
+ GridMaps[gx][gy] = new GridMap();
+ if (!GridMaps[gx][gy]->loadData(tmp))
+ {
+ sLog.outError("Error loading map file: \n %s\n", tmp);
+ }
+ delete [] tmp;
+}
+
+void Map::LoadMapAndVMap(int gx,int gy)
+{
+ LoadMap(gx,gy);
+ if (i_InstanceId == 0)
+ LoadVMap(gx, gy); // Only load the data for the base map
+}
+
+void Map::InitStateMachine()
+{
+ si_GridStates[GRID_STATE_INVALID] = new InvalidState;
+ si_GridStates[GRID_STATE_ACTIVE] = new ActiveState;
+ si_GridStates[GRID_STATE_IDLE] = new IdleState;
+ si_GridStates[GRID_STATE_REMOVAL] = new RemovalState;
+}
+
+void Map::DeleteStateMachine()
+{
+ delete si_GridStates[GRID_STATE_INVALID];
+ delete si_GridStates[GRID_STATE_ACTIVE];
+ delete si_GridStates[GRID_STATE_IDLE];
+ delete si_GridStates[GRID_STATE_REMOVAL];
+}
+
+Map::Map(uint32 id, time_t expiry, uint32 InstanceId, uint8 SpawnMode, Map* _parent)
+ : i_mapEntry (sMapStore.LookupEntry(id)), i_spawnMode(SpawnMode), i_InstanceId(InstanceId), m_unloadTimer(0),
+ m_activeNonPlayersIter(m_activeNonPlayers.end()),
+ i_gridExpiry(expiry), m_parentMap(_parent ? _parent : this),
+ m_VisibleDistance(DEFAULT_VISIBILITY_DISTANCE),
+ m_VisibilityNotifyPeriod(DEFAULT_VISIBILITY_NOTIFY_PERIOD),
+ i_scriptLock(false)
+{
+ for (unsigned int idx=0; idx < MAX_NUMBER_OF_GRIDS; ++idx)
+ {
+ for (unsigned int j=0; j < MAX_NUMBER_OF_GRIDS; ++j)
+ {
+ //z code
+ GridMaps[idx][j] =NULL;
+ setNGrid(NULL, idx, j);
+ }
+ }
+
+ //lets initialize visibility distance for map
+ Map::InitVisibilityDistance();
+}
+
+void Map::InitVisibilityDistance()
+{
+ //init visibility for continents
+ m_VisibleDistance = World::GetMaxVisibleDistanceOnContinents();
+ m_VisibilityNotifyPeriod = World::GetVisibilityNotifyPeriodOnContinents();
+}
+
+// Template specialization of utility methods
+template<class T>
+void Map::AddToGrid(T* obj, NGridType *grid, Cell const& cell)
+{
+ if (obj->m_isWorldObject)
+ (*grid)(cell.CellX(), cell.CellY()).template AddWorldObject<T>(obj);
+ else
+ (*grid)(cell.CellX(), cell.CellY()).template AddGridObject<T>(obj);
+}
+
+template<>
+void Map::AddToGrid(Creature* obj, NGridType *grid, Cell const& cell)
+{
+ if (obj->m_isWorldObject)
+ (*grid)(cell.CellX(), cell.CellY()).AddWorldObject(obj);
+ else
+ (*grid)(cell.CellX(), cell.CellY()).AddGridObject(obj);
+
+ obj->SetCurrentCell(cell);
+}
+
+template<class T>
+void Map::RemoveFromGrid(T* obj, NGridType *grid, Cell const& cell)
+{
+ if (obj->m_isWorldObject)
+ (*grid)(cell.CellX(), cell.CellY()).template RemoveWorldObject<T>(obj);
+ else
+ (*grid)(cell.CellX(), cell.CellY()).template RemoveGridObject<T>(obj);
+}
+
+template<class T>
+void Map::SwitchGridContainers(T* obj, bool on)
+{
+ CellPair p = Trinity::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
+ if (p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
+ {
+ sLog.outError("Map::SwitchGridContainers: Object " I64FMT " has invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUID(), obj->GetPositionX(), obj->GetPositionY(), p.x_coord, p.y_coord);
+ return;
+ }
+
+ Cell cell(p);
+ if (!loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)))
+ return;
+
+ DEBUG_LOG("Switch object " I64FMT " from grid[%u,%u] %u", obj->GetGUID(), cell.data.Part.grid_x, cell.data.Part.grid_y, on);
+ NGridType *ngrid = getNGrid(cell.GridX(), cell.GridY());
+ assert(ngrid != NULL);
+
+ GridType &grid = (*ngrid)(cell.CellX(), cell.CellY());
+
+ if (on)
+ {
+ grid.RemoveGridObject<T>(obj);
+ grid.AddWorldObject<T>(obj);
+ /*if (!grid.RemoveGridObject<T>(obj, obj->GetGUID())
+ || !grid.AddWorldObject<T>(obj, obj->GetGUID()))
+ {
+ assert(false);
+ }*/
+ }
+ else
+ {
+ grid.RemoveWorldObject<T>(obj);
+ grid.AddGridObject<T>(obj);
+ /*if (!grid.RemoveWorldObject<T>(obj, obj->GetGUID())
+ || !grid.AddGridObject<T>(obj, obj->GetGUID()))
+ {
+ assert(false);
+ }*/
+ }
+ obj->m_isWorldObject = on;
+}
+
+template void Map::SwitchGridContainers(Creature *, bool);
+//template void Map::SwitchGridContainers(DynamicObject *, bool);
+
+template<class T>
+void Map::DeleteFromWorld(T* obj)
+{
+ // Note: In case resurrectable corpse and pet its removed from global lists in own destructor
+ delete obj;
+}
+
+template<>
+void Map::DeleteFromWorld(Player* pl)
+{
+ ObjectAccessor::Instance().RemoveObject(pl);
+ delete pl;
+}
+
+void
+Map::EnsureGridCreated(const GridPair &p)
+{
+ if (!getNGrid(p.x_coord, p.y_coord))
+ {
+ Guard guard(*this);
+ if (!getNGrid(p.x_coord, p.y_coord))
+ {
+ sLog.outDebug("Creating grid[%u,%u] for map %u instance %u", p.x_coord, p.y_coord, GetId(), i_InstanceId);
+
+ 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)),
+ p.x_coord, p.y_coord);
+
+ // build a linkage between this map and NGridType
+ buildNGridLinkage(getNGrid(p.x_coord, p.y_coord));
+
+ getNGrid(p.x_coord, p.y_coord)->SetGridState(GRID_STATE_IDLE);
+
+ //z coord
+ int gx = (MAX_NUMBER_OF_GRIDS - 1) - p.x_coord;
+ int gy = (MAX_NUMBER_OF_GRIDS - 1) - p.y_coord;
+
+ if (!GridMaps[gx][gy])
+ LoadMapAndVMap(gx,gy);
+ }
+ }
+}
+
+void
+Map::EnsureGridLoadedAtEnter(const Cell &cell, Player *player)
+{
+ EnsureGridLoaded(cell);
+ NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
+ assert(grid != NULL);
+
+ if (player)
+ {
+ DEBUG_LOG("Player %s enter cell[%u,%u] triggers loading of grid[%u,%u] on map %u", player->GetName(), cell.CellX(), cell.CellY(), cell.GridX(), cell.GridY(), GetId());
+ }
+ else
+ {
+ DEBUG_LOG("Active object nearby triggers loading of grid [%u,%u] on map %u", cell.GridX(), cell.GridY(), GetId());
+ }
+
+ // refresh grid state & timer
+ if (grid->GetGridState() != GRID_STATE_ACTIVE)
+ {
+ ResetGridExpiry(*grid, 0.1f);
+ grid->SetGridState(GRID_STATE_ACTIVE);
+ }
+}
+
+bool Map::EnsureGridLoaded(const Cell &cell)
+{
+ EnsureGridCreated(GridPair(cell.GridX(), cell.GridY()));
+ NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
+
+ assert(grid != NULL);
+ if (!isGridObjectDataLoaded(cell.GridX(), cell.GridY()))
+ {
+ sLog.outDebug("Loading grid[%u,%u] for map %u instance %u", cell.GridX(), cell.GridY(), GetId(), i_InstanceId);
+
+ ObjectGridLoader loader(*grid, this, cell);
+ loader.LoadN();
+
+ // Add resurrectable corpses to world object list in grid
+ ObjectAccessor::Instance().AddCorpsesToGrid(GridPair(cell.GridX(),cell.GridY()),(*grid)(cell.CellX(), cell.CellY()), this);
+
+ setGridObjectDataLoaded(true,cell.GridX(), cell.GridY());
+ return true;
+ }
+
+ return false;
+}
+
+void Map::LoadGrid(float x, float y)
+{
+ CellPair pair = Trinity::ComputeCellPair(x, y);
+ Cell cell(pair);
+ EnsureGridLoaded(cell);
+}
+
+bool Map::Add(Player *player)
+{
+ // Check if we are adding to correct map
+ assert (player->GetMap() == this);
+ CellPair p = Trinity::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
+ if (p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
+ {
+ sLog.outError("Map::Add: Player (GUID: %u) has invalid coordinates X:%f Y:%f grid cell [%u:%u]", player->GetGUIDLow(), player->GetPositionX(), player->GetPositionY(), p.x_coord, p.y_coord);
+ return false;
+ }
+
+ player->SetMap(this);
+
+ Cell cell(p);
+ EnsureGridLoadedAtEnter(cell, player);
+ NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
+ assert(grid != NULL);
+ AddToGrid(player, grid, cell);
+
+ player->AddToWorld();
+
+ SendInitSelf(player);
+ SendInitTransports(player);
+
+ player->m_clientGUIDs.clear();
+ player->UpdateObjectVisibility(true);
+
+ return true;
+}
+
+template<class T>
+void
+Map::Add(T *obj)
+{
+ CellPair p = Trinity::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
+ if (p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
+ {
+ sLog.outError("Map::Add: Object " UI64FMTD " has invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUID(), obj->GetPositionX(), obj->GetPositionY(), p.x_coord, p.y_coord);
+ return;
+ }
+
+ Cell cell(p);
+ if (obj->IsInWorld()) // need some clean up later
+ {
+ obj->UpdateObjectVisibility(true);
+ return;
+ }
+
+ if (obj->isActiveObject())
+ EnsureGridLoadedAtEnter(cell);
+ else
+ EnsureGridCreated(GridPair(cell.GridX(), cell.GridY()));
+
+ NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
+ assert(grid != NULL);
+
+ AddToGrid(obj,grid,cell);
+ //obj->SetMap(this);
+ obj->AddToWorld();
+
+ if (obj->isActiveObject())
+ AddToActive(obj);
+
+ DEBUG_LOG("Object %u enters grid[%u,%u]", GUID_LOPART(obj->GetGUID()), cell.GridX(), cell.GridY());
+
+ //something, such as vehicle, needs to be update immediately
+ //also, trigger needs to cast spell, if not update, cannot see visual
+ obj->UpdateObjectVisibility(true);
+}
+
+/*
+void Map::MessageBroadcast(Player *player, WorldPacket *msg, bool to_self)
+{
+ CellPair p = Trinity::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
+
+ if (p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
+ {
+ 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);
+ return;
+ }
+
+ Cell cell(p);
+ cell.data.Part.reserved = ALL_DISTRICT;
+ cell.SetNoCreate();
+
+ if (!loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)))
+ return;
+
+ Trinity::MessageDeliverer post_man(*player, msg, to_self);
+ TypeContainerVisitor<Trinity::MessageDeliverer, WorldTypeMapContainer > message(post_man);
+ CellLock<ReadGuard> cell_lock(cell, p);
+ cell_lock->Visit(cell_lock, message, *this, *player, GetVisibilityDistance());
+}
+
+void Map::MessageBroadcast(WorldObject *obj, WorldPacket *msg)
+{
+ CellPair p = Trinity::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
+
+ if (p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
+ {
+ sLog.outError("Map::MessageBroadcast: Object (GUID: %u TypeId: %u) have invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUIDLow(), obj->GetTypeId(), obj->GetPositionX(), obj->GetPositionY(), p.x_coord, p.y_coord);
+ return;
+ }
+
+ Cell cell(p);
+ cell.data.Part.reserved = ALL_DISTRICT;
+ cell.SetNoCreate();
+
+ if (!loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)))
+ return;
+
+ //TODO: currently on continents when Visibility.Distance.InFlight > Visibility.Distance.Continents
+ //we have alot of blinking mobs because monster move packet send is broken...
+ Trinity::ObjectMessageDeliverer post_man(*obj,msg);
+ TypeContainerVisitor<Trinity::ObjectMessageDeliverer, WorldTypeMapContainer > message(post_man);
+ CellLock<ReadGuard> cell_lock(cell, p);
+ cell_lock->Visit(cell_lock, message, *this, *obj, GetVisibilityDistance());
+}
+
+void Map::MessageDistBroadcast(Player *player, WorldPacket *msg, float dist, bool to_self, bool own_team_only)
+{
+ CellPair p = Trinity::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
+
+ if (p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
+ {
+ 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);
+ return;
+ }
+
+ Cell cell(p);
+ cell.data.Part.reserved = ALL_DISTRICT;
+ cell.SetNoCreate();
+
+ if (!loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)))
+ return;
+
+ Trinity::MessageDistDeliverer post_man(*player, msg, dist, to_self, own_team_only);
+ TypeContainerVisitor<Trinity::MessageDistDeliverer , WorldTypeMapContainer > message(post_man);
+ CellLock<ReadGuard> cell_lock(cell, p);
+ cell_lock->Visit(cell_lock, message, *this, *player, dist);
+}
+
+void Map::MessageDistBroadcast(WorldObject *obj, WorldPacket *msg, float dist)
+{
+ CellPair p = Trinity::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
+
+ if (p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
+ {
+ sLog.outError("Map::MessageBroadcast: Object (GUID: %u TypeId: %u) have invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUIDLow(), obj->GetTypeId(), obj->GetPositionX(), obj->GetPositionY(), p.x_coord, p.y_coord);
+ return;
+ }
+
+ Cell cell(p);
+ cell.data.Part.reserved = ALL_DISTRICT;
+ cell.SetNoCreate();
+
+ if (!loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)))
+ return;
+
+ Trinity::ObjectMessageDistDeliverer post_man(*obj, msg, dist);
+ TypeContainerVisitor<Trinity::ObjectMessageDistDeliverer, WorldTypeMapContainer > message(post_man);
+ CellLock<ReadGuard> cell_lock(cell, p);
+ cell_lock->Visit(cell_lock, message, *this, *obj, dist);
+}
+*/
+
+bool Map::loaded(const GridPair &p) const
+{
+ return (getNGrid(p.x_coord, p.y_coord) && isGridObjectDataLoaded(p.x_coord, p.y_coord));
+}
+
+void Map::Update(const uint32 &t_diff)
+{
+ /// update players at tick
+ for (m_mapRefIter = m_mapRefManager.begin(); m_mapRefIter != m_mapRefManager.end(); ++m_mapRefIter)
+ {
+ Player* plr = m_mapRefIter->getSource();
+ if (plr && plr->IsInWorld())
+ plr->Update(t_diff);
+ }
+
+ /// update active cells around players and active objects
+ resetMarkedCells();
+
+ Trinity::ObjectUpdater updater(t_diff);
+ // for creature
+ TypeContainerVisitor<Trinity::ObjectUpdater, GridTypeMapContainer > grid_object_update(updater);
+ // for pets
+ TypeContainerVisitor<Trinity::ObjectUpdater, WorldTypeMapContainer > world_object_update(updater);
+
+ // the player iterator is stored in the map object
+ // to make sure calls to Map::Remove don't invalidate it
+ for (m_mapRefIter = m_mapRefManager.begin(); m_mapRefIter != m_mapRefManager.end(); ++m_mapRefIter)
+ {
+ Player* plr = m_mapRefIter->getSource();
+
+ if (!plr->IsInWorld())
+ continue;
+
+ CellPair standing_cell(Trinity::ComputeCellPair(plr->GetPositionX(), plr->GetPositionY()));
+
+ // Check for correctness of standing_cell, it also avoids problems with update_cell
+ if (standing_cell.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || standing_cell.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
+ continue;
+
+ // the overloaded operators handle range checking
+ // so ther's no need for range checking inside the loop
+ CellPair begin_cell(standing_cell), end_cell(standing_cell);
+ //lets update mobs/objects in ALL visible cells around player!
+ CellArea area = Cell::CalculateCellArea(*plr, GetVisibilityDistance());
+ area.ResizeBorders(begin_cell, end_cell);
+
+ for (uint32 x = begin_cell.x_coord; x <= end_cell.x_coord; ++x)
+ {
+ for (uint32 y = begin_cell.y_coord; y <= end_cell.y_coord; ++y)
+ {
+ // marked cells are those that have been visited
+ // don't visit the same cell twice
+ uint32 cell_id = (y * TOTAL_NUMBER_OF_CELLS_PER_MAP) + x;
+ if (!isCellMarked(cell_id))
+ {
+ markCell(cell_id);
+ CellPair pair(x,y);
+ Cell cell(pair);
+ cell.data.Part.reserved = CENTER_DISTRICT;
+ //cell.SetNoCreate();
+ cell.Visit(pair, grid_object_update, *this);
+ cell.Visit(pair, world_object_update, *this);
+ }
+ }
+ }
+ }
+
+ // non-player active objects
+ if (!m_activeNonPlayers.empty())
+ {
+ for (m_activeNonPlayersIter = m_activeNonPlayers.begin(); m_activeNonPlayersIter != m_activeNonPlayers.end();)
+ {
+ // skip not in world
+ WorldObject* obj = *m_activeNonPlayersIter;
+
+ // step before processing, in this case if Map::Remove remove next object we correctly
+ // step to next-next, and if we step to end() then newly added objects can wait next update.
+ ++m_activeNonPlayersIter;
+
+ if (!obj->IsInWorld())
+ continue;
+
+ CellPair standing_cell(Trinity::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY()));
+
+ // Check for correctness of standing_cell, it also avoids problems with update_cell
+ if (standing_cell.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || standing_cell.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
+ continue;
+
+ // the overloaded operators handle range checking
+ // so ther's no need for range checking inside the loop
+ CellPair begin_cell(standing_cell), end_cell(standing_cell);
+ begin_cell << 1; begin_cell -= 1; // upper left
+ end_cell >> 1; end_cell += 1; // lower right
+
+ for (uint32 x = begin_cell.x_coord; x <= end_cell.x_coord; ++x)
+ {
+ for (uint32 y = begin_cell.y_coord; y <= end_cell.y_coord; ++y)
+ {
+ // marked cells are those that have been visited
+ // don't visit the same cell twice
+ uint32 cell_id = (y * TOTAL_NUMBER_OF_CELLS_PER_MAP) + x;
+ if (!isCellMarked(cell_id))
+ {
+ markCell(cell_id);
+ CellPair pair(x,y);
+ Cell cell(pair);
+ cell.data.Part.reserved = CENTER_DISTRICT;
+ //cell.SetNoCreate();
+ cell.Visit(pair, grid_object_update, *this);
+ cell.Visit(pair, world_object_update, *this);
+ }
+ }
+ }
+ }
+ }
+
+ ///- Process necessary scripts
+ if (!m_scriptSchedule.empty())
+ {
+ i_scriptLock = true;
+ ScriptsProcess();
+ i_scriptLock = false;
+ }
+
+ MoveAllCreaturesInMoveList();
+
+ if (!m_mapRefManager.isEmpty() || !m_activeNonPlayers.empty())
+ ProcessRelocationNotifies(t_diff);
+}
+
+struct ResetNotifier
+{
+ template<class T>inline void resetNotify(GridRefManager<T> &m)
+ {
+ for (typename GridRefManager<T>::iterator iter=m.begin(); iter != m.end(); ++iter)
+ iter->getSource()->ResetAllNotifies();
+ }
+ template<class T> void Visit(GridRefManager<T> &) {}
+ void Visit(CreatureMapType &m) { resetNotify<Creature>(m);}
+ void Visit(PlayerMapType &m) { resetNotify<Player>(m);}
+};
+
+void Map::ProcessRelocationNotifies(const uint32 & diff)
+{
+ for (GridRefManager<NGridType>::iterator i = GridRefManager<NGridType>::begin(); i != GridRefManager<NGridType>::end(); ++i)
+ {
+ NGridType *grid = i->getSource();
+
+ if (grid->GetGridState() != GRID_STATE_ACTIVE)
+ continue;
+
+ grid->getGridInfoRef()->getRelocationTimer().TUpdate(diff);
+ if (!grid->getGridInfoRef()->getRelocationTimer().TPassed())
+ continue;
+
+ uint32 gx = grid->getX(), gy = grid->getY();
+
+ CellPair cell_min(gx*MAX_NUMBER_OF_CELLS, gy*MAX_NUMBER_OF_CELLS);
+ CellPair cell_max(cell_min.x_coord + MAX_NUMBER_OF_CELLS, cell_min.y_coord+MAX_NUMBER_OF_CELLS);
+
+ for (uint32 x = cell_min.x_coord; x < cell_max.x_coord; ++x)
+ {
+ for (uint32 y = cell_min.y_coord; y < cell_max.y_coord; ++y)
+ {
+ uint32 cell_id = (y * TOTAL_NUMBER_OF_CELLS_PER_MAP) + x;
+ if (!isCellMarked(cell_id))
+ continue;
+
+ CellPair pair(x,y);
+ Cell cell(pair);
+ cell.SetNoCreate();
+
+ Trinity::DelayedUnitRelocation cell_relocation(cell, pair, *this, GetVisibilityDistance());
+ TypeContainerVisitor<Trinity::DelayedUnitRelocation, GridTypeMapContainer > grid_object_relocation(cell_relocation);
+ TypeContainerVisitor<Trinity::DelayedUnitRelocation, WorldTypeMapContainer > world_object_relocation(cell_relocation);
+ Visit(cell, grid_object_relocation);
+ Visit(cell, world_object_relocation);
+ }
+ }
+ }
+
+ ResetNotifier reset;
+ TypeContainerVisitor<ResetNotifier, GridTypeMapContainer > grid_notifier(reset);
+ TypeContainerVisitor<ResetNotifier, WorldTypeMapContainer > world_notifier(reset);
+ for (GridRefManager<NGridType>::iterator i = GridRefManager<NGridType>::begin(); i != GridRefManager<NGridType>::end(); ++i)
+ {
+ NGridType *grid = i->getSource();
+
+ if (grid->GetGridState() != GRID_STATE_ACTIVE)
+ continue;
+
+ if (!grid->getGridInfoRef()->getRelocationTimer().TPassed())
+ continue;
+
+ grid->getGridInfoRef()->getRelocationTimer().TReset(diff, m_VisibilityNotifyPeriod);
+
+ uint32 gx = grid->getX(), gy = grid->getY();
+
+ CellPair cell_min(gx*MAX_NUMBER_OF_CELLS, gy*MAX_NUMBER_OF_CELLS);
+ CellPair cell_max(cell_min.x_coord + MAX_NUMBER_OF_CELLS, cell_min.y_coord+MAX_NUMBER_OF_CELLS);
+
+ for (uint32 x = cell_min.x_coord; x < cell_max.x_coord; ++x)
+ {
+ for (uint32 y = cell_min.y_coord; y < cell_max.y_coord; ++y)
+ {
+ uint32 cell_id = (y * TOTAL_NUMBER_OF_CELLS_PER_MAP) + x;
+ if (!isCellMarked(cell_id))
+ continue;
+
+ CellPair pair(x,y);
+ Cell cell(pair);
+ cell.SetNoCreate();
+ Visit(cell, grid_notifier);
+ Visit(cell, world_notifier);
+ }
+ }
+ }
+}
+
+void Map::Remove(Player *player, bool remove)
+{
+ player->RemoveFromWorld();
+ SendRemoveTransports(player);
+
+ CellPair p = Trinity::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
+ if (p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
+ sLog.outCrash("Map::Remove: Player is in invalid cell!");
+ else
+ {
+ Cell cell(p);
+ if (!getNGrid(cell.data.Part.grid_x, cell.data.Part.grid_y))
+ sLog.outError("Map::Remove() i_grids was NULL x:%d, y:%d",cell.data.Part.grid_x,cell.data.Part.grid_y);
+ else
+ {
+ DEBUG_LOG("Remove player %s from grid[%u,%u]", player->GetName(), cell.GridX(), cell.GridY());
+ NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
+ assert(grid != NULL);
+
+ player->UpdateObjectVisibility(true);
+ RemoveFromGrid(player,grid,cell);
+ }
+ }
+
+ if (remove)
+ DeleteFromWorld(player);
+}
+
+bool Map::RemoveBones(uint64 guid, float x, float y)
+{
+ if (IsRemovalGrid(x, y))
+ {
+ Corpse * corpse = ObjectAccessor::Instance().GetObjectInWorld(GetId(), x, y, guid, (Corpse*)NULL);
+ if (corpse && corpse->GetTypeId() == TYPEID_CORPSE && corpse->GetType() == CORPSE_BONES)
+ corpse->DeleteBonesFromWorld();
+ else
+ return false;
+ }
+ return true;
+}
+
+template<class T>
+void
+Map::Remove(T *obj, bool remove)
+{
+ obj->RemoveFromWorld();
+ if (obj->isActiveObject())
+ RemoveFromActive(obj);
+
+ CellPair p = Trinity::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
+ if (p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
+ sLog.outError("Map::Remove: Object " I64FMT " has invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUID(), obj->GetPositionX(), obj->GetPositionY(), p.x_coord, p.y_coord);
+ else
+ {
+ Cell cell(p);
+ if (loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)))
+ {
+ DEBUG_LOG("Remove object " I64FMT " from grid[%u,%u]", obj->GetGUID(), cell.data.Part.grid_x, cell.data.Part.grid_y);
+ NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
+ assert(grid != NULL);
+
+ obj->UpdateObjectVisibility(true);
+ RemoveFromGrid(obj,grid,cell);
+ }
+ }
+
+ obj->ResetMap();
+
+ if (remove)
+ {
+ // if option set then object already saved at this moment
+ if (!sWorld.getConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATELY))
+ obj->SaveRespawnTime();
+ DeleteFromWorld(obj);
+ }
+}
+
+void
+Map::PlayerRelocation(Player *player, float x, float y, float z, float orientation)
+{
+ assert(player);
+
+ CellPair old_val = Trinity::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
+ CellPair new_val = Trinity::ComputeCellPair(x, y);
+
+ Cell old_cell(old_val);
+ Cell new_cell(new_val);
+
+ player->Relocate(x, y, z, orientation);
+
+ if (old_cell.DiffGrid(new_cell) || old_cell.DiffCell(new_cell))
+ {
+ 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());
+
+ NGridType* oldGrid = getNGrid(old_cell.GridX(), old_cell.GridY());
+ RemoveFromGrid(player, oldGrid,old_cell);
+
+ if (old_cell.DiffGrid(new_cell))
+ EnsureGridLoadedAtEnter(new_cell, player);
+
+ NGridType* newGrid = getNGrid(new_cell.GridX(), new_cell.GridY());
+ AddToGrid(player, newGrid,new_cell);
+ }
+
+ player->UpdateObjectVisibility(false);
+}
+
+void
+Map::CreatureRelocation(Creature *creature, float x, float y, float z, float ang)
+{
+ assert(CheckGridIntegrity(creature,false));
+
+ Cell old_cell = creature->GetCurrentCell();
+
+ CellPair new_val = Trinity::ComputeCellPair(x, y);
+ Cell new_cell(new_val);
+
+ // delay creature move for grid/cell to grid/cell moves
+ if (old_cell.DiffCell(new_cell) || old_cell.DiffGrid(new_cell))
+ {
+ #ifdef TRINITY_DEBUG
+ if ((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES) == 0)
+ 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());
+ #endif
+ AddCreatureToMoveList(creature, x, y, z, ang);
+ // in diffcell/diffgrid case notifiers called at finishing move creature in Map::MoveAllCreaturesInMoveList
+ }
+ else
+ {
+ creature->Relocate(x, y, z, ang);
+ creature->UpdateObjectVisibility(false);
+ }
+
+ assert(CheckGridIntegrity(creature,true));
+}
+
+void Map::AddCreatureToMoveList(Creature *c, float x, float y, float z, float ang)
+{
+ if (!c)
+ return;
+
+ i_creaturesToMove[c] = CreatureMover(x, y, z, ang);
+}
+
+void Map::MoveAllCreaturesInMoveList()
+{
+ while (!i_creaturesToMove.empty())
+ {
+ // get data and remove element;
+ CreatureMoveList::iterator iter = i_creaturesToMove.begin();
+ Creature* c = iter->first;
+ CreatureMover cm = iter->second;
+ i_creaturesToMove.erase(iter);
+
+ // calculate cells
+ CellPair new_val = Trinity::ComputeCellPair(cm.x, cm.y);
+ Cell new_cell(new_val);
+
+ // do move or do move to respawn or remove creature if previous all fail
+ if (CreatureCellRelocation(c,new_cell))
+ {
+ // update pos
+ c->Relocate(cm.x, cm.y, cm.z, cm.ang);
+ //CreatureRelocationNotify(c,new_cell,new_cell.cellPair());
+ c->UpdateObjectVisibility(false);
+ }
+ else
+ {
+ // if creature can't be move in new cell/grid (not loaded) move it to repawn cell/grid
+ // creature coordinates will be updated and notifiers send
+ if (!CreatureRespawnRelocation(c))
+ {
+ // ... or unload (if respawn grid also not loaded)
+ #ifdef TRINITY_DEBUG
+ if ((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES) == 0)
+ sLog.outDebug("Creature (GUID: %u Entry: %u) cannot be move to unloaded respawn grid.",c->GetGUIDLow(),c->GetEntry());
+ #endif
+ AddObjectToRemoveList(c);
+ }
+ }
+ }
+}
+
+bool Map::CreatureCellRelocation(Creature *c, Cell new_cell)
+{
+ Cell const& old_cell = c->GetCurrentCell();
+ if (!old_cell.DiffGrid(new_cell)) // in same grid
+ {
+ // if in same cell then none do
+ if (old_cell.DiffCell(new_cell))
+ {
+ #ifdef TRINITY_DEBUG
+ if ((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES) == 0)
+ 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());
+ #endif
+
+ RemoveFromGrid(c,getNGrid(old_cell.GridX(), old_cell.GridY()),old_cell);
+ AddToGrid(c,getNGrid(new_cell.GridX(), new_cell.GridY()),new_cell);
+ }
+ else
+ {
+ #ifdef TRINITY_DEBUG
+ if ((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES) == 0)
+ sLog.outDebug("Creature (GUID: %u Entry: %u) moved in same grid[%u,%u]cell[%u,%u].", c->GetGUIDLow(), c->GetEntry(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY());
+ #endif
+ }
+
+ return true;
+ }
+
+ // in diff. grids but active creature
+ if (c->isActiveObject())
+ {
+ EnsureGridLoadedAtEnter(new_cell);
+
+ #ifdef TRINITY_DEBUG
+ if ((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES) == 0)
+ sLog.outDebug("Active creature (GUID: %u Entry: %u) moved from grid[%u,%u]cell[%u,%u] to grid[%u,%u]cell[%u,%u].", c->GetGUIDLow(), c->GetEntry(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY(), new_cell.GridX(), new_cell.GridY(), new_cell.CellX(), new_cell.CellY());
+ #endif
+
+ RemoveFromGrid(c,getNGrid(old_cell.GridX(), old_cell.GridY()),old_cell);
+ AddToGrid(c,getNGrid(new_cell.GridX(), new_cell.GridY()),new_cell);
+
+ return true;
+ }
+
+ // in diff. loaded grid normal creature
+ if (loaded(GridPair(new_cell.GridX(), new_cell.GridY())))
+ {
+ #ifdef TRINITY_DEBUG
+ if ((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES) == 0)
+ 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());
+ #endif
+
+ RemoveFromGrid(c,getNGrid(old_cell.GridX(), old_cell.GridY()),old_cell);
+ EnsureGridCreated(GridPair(new_cell.GridX(), new_cell.GridY()));
+ AddToGrid(c,getNGrid(new_cell.GridX(), new_cell.GridY()),new_cell);
+
+ return true;
+ }
+
+ // fail to move: normal creature attempt move to unloaded grid
+ #ifdef TRINITY_DEBUG
+ if ((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES) == 0)
+ sLog.outDebug("Creature (GUID: %u Entry: %u) attempted to 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());
+ #endif
+ return false;
+}
+
+bool Map::CreatureRespawnRelocation(Creature *c)
+{
+ float resp_x, resp_y, resp_z, resp_o;
+ c->GetRespawnCoord(resp_x, resp_y, resp_z, &resp_o);
+
+ CellPair resp_val = Trinity::ComputeCellPair(resp_x, resp_y);
+ Cell resp_cell(resp_val);
+
+ c->CombatStop();
+ c->GetMotionMaster()->Clear();
+
+ #ifdef TRINITY_DEBUG
+ if ((sLog.getLogFilter() & LOG_FILTER_CREATURE_MOVES) == 0)
+ sLog.outDebug("Creature (GUID: %u Entry: %u) 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());
+ #endif
+
+ // teleport it to respawn point (like normal respawn if player see)
+ if (CreatureCellRelocation(c,resp_cell))
+ {
+ c->Relocate(resp_x, resp_y, resp_z, resp_o);
+ c->GetMotionMaster()->Initialize(); // prevent possible problems with default move generators
+ //CreatureRelocationNotify(c,resp_cell,resp_cell.cellPair());
+ c->UpdateObjectVisibility(false);
+ return true;
+ }
+ else
+ return false;
+}
+
+bool Map::UnloadGrid(const uint32 &x, const uint32 &y, bool unloadAll)
+{
+ NGridType *grid = getNGrid(x, y);
+ assert(grid != NULL);
+
+ {
+ if (!unloadAll && ActiveObjectsNearGrid(x, y))
+ return false;
+
+ sLog.outDebug("Unloading grid[%u,%u] for map %u", x,y, GetId());
+
+ ObjectGridUnloader unloader(*grid);
+
+ if (!unloadAll)
+ {
+ // Finish creature moves, remove and delete all creatures with delayed remove before moving to respawn grids
+ // Must know real mob position before move
+ MoveAllCreaturesInMoveList();
+
+ // move creatures to respawn grids if this is diff.grid or to remove list
+ unloader.MoveToRespawnN();
+
+ // Finish creature moves, remove and delete all creatures with delayed remove before unload
+ MoveAllCreaturesInMoveList();
+ }
+
+ ObjectGridCleaner cleaner(*grid);
+ cleaner.CleanN();
+
+ RemoveAllObjectsInRemoveList();
+
+ unloader.UnloadN();
+
+ assert(i_objectsToRemove.empty());
+
+ delete grid;
+ setNGrid(NULL, x, y);
+ }
+ int gx = (MAX_NUMBER_OF_GRIDS - 1) - x;
+ int gy = (MAX_NUMBER_OF_GRIDS - 1) - y;
+
+ // delete grid map, but don't delete if it is from parent map (and thus only reference)
+ //+++if (GridMaps[gx][gy]) don't check for GridMaps[gx][gy], we might have to unload vmaps
+ {
+ if (i_InstanceId == 0)
+ {
+ if (GridMaps[gx][gy])
+ {
+ GridMaps[gx][gy]->unloadData();
+ delete GridMaps[gx][gy];
+ }
+ // x and y are swapped
+ VMAP::VMapFactory::createOrGetVMapManager()->unloadMap(GetId(), gx, gy);
+ }
+ else
+ ((MapInstanced*)m_parentMap)->RemoveGridMapReference(GridPair(gx, gy));
+
+ GridMaps[gx][gy] = NULL;
+ }
+ DEBUG_LOG("Unloading grid[%u,%u] for map %u finished", x,y, GetId());
+ return true;
+}
+
+void Map::RemoveAllPlayers()
+{
+ if (HavePlayers())
+ {
+ for (MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
+ {
+ Player* plr = itr->getSource();
+ if (!plr->IsBeingTeleportedFar())
+ {
+ // this is happening for bg
+ sLog.outError("Map::UnloadAll: player %s is still in map %u during unload, this should not happen!", plr->GetName(), GetId());
+ plr->TeleportTo(plr->m_homebindMapId, plr->m_homebindX, plr->m_homebindY, plr->m_homebindZ, plr->GetOrientation());
+ }
+ }
+ }
+}
+
+void Map::UnloadAll()
+{
+ // clear all delayed moves, useless anyway do this moves before map unload.
+ i_creaturesToMove.clear();
+
+ for (GridRefManager<NGridType>::iterator i = GridRefManager<NGridType>::begin(); i != GridRefManager<NGridType>::end();)
+ {
+ NGridType &grid(*i->getSource());
+ ++i;
+ UnloadGrid(grid.getX(), grid.getY(), true); // deletes the grid and removes it from the GridRefManager
+ }
+}
+
+//*****************************
+// Grid function
+//*****************************
+GridMap::GridMap()
+{
+ m_flags = 0;
+ // Area data
+ m_gridArea = 0;
+ m_area_map = NULL;
+ // Height level data
+ m_gridHeight = INVALID_HEIGHT;
+ m_gridGetHeight = &GridMap::getHeightFromFlat;
+ m_V9 = NULL;
+ m_V8 = NULL;
+ // Liquid data
+ m_liquidType = 0;
+ m_liquid_offX = 0;
+ m_liquid_offY = 0;
+ m_liquid_width = 0;
+ m_liquid_height = 0;
+ m_liquidLevel = INVALID_HEIGHT;
+ m_liquid_type = NULL;
+ m_liquid_map = NULL;
+}
+
+GridMap::~GridMap()
+{
+ unloadData();
+}
+
+bool GridMap::loadData(char *filename)
+{
+ // Unload old data if exist
+ unloadData();
+
+ map_fileheader header;
+ // Not return error if file not found
+ FILE *in = fopen(filename, "rb");
+ if (!in)
+ return true;
+ fread(&header, sizeof(header),1,in);
+ if (header.mapMagic == uint32(MAP_MAGIC) &&
+ header.versionMagic == uint32(MAP_VERSION_MAGIC))
+ {
+ // loadup area data
+ if (header.areaMapOffset && !loadAreaData(in, header.areaMapOffset, header.areaMapSize))
+ {
+ sLog.outError("Error loading map area data\n");
+ fclose(in);
+ return false;
+ }
+ // loadup height data
+ if (header.heightMapOffset && !loadHeihgtData(in, header.heightMapOffset, header.heightMapSize))
+ {
+ sLog.outError("Error loading map height data\n");
+ fclose(in);
+ return false;
+ }
+ // loadup liquid data
+ if (header.liquidMapOffset && !loadLiquidData(in, header.liquidMapOffset, header.liquidMapSize))
+ {
+ sLog.outError("Error loading map liquids data\n");
+ fclose(in);
+ return false;
+ }
+ fclose(in);
+ return true;
+ }
+ sLog.outError("Map file '%s' is a non-compatible version (outdated?). Please, create new using the ad.exe program.", filename);
+ fclose(in);
+ return false;
+}
+
+void GridMap::unloadData()
+{
+ if (m_area_map) delete[] m_area_map;
+ if (m_V9) delete[] m_V9;
+ if (m_V8) delete[] m_V8;
+ if (m_liquid_type) delete[] m_liquid_type;
+ if (m_liquid_map) delete[] m_liquid_map;
+ m_area_map = NULL;
+ m_V9 = NULL;
+ m_V8 = NULL;
+ m_liquid_type = NULL;
+ m_liquid_map = NULL;
+ m_gridGetHeight = &GridMap::getHeightFromFlat;
+}
+
+bool GridMap::loadAreaData(FILE *in, uint32 offset, uint32 /*size*/)
+{
+ map_areaHeader header;
+ fseek(in, offset, SEEK_SET);
+ fread(&header, sizeof(header), 1, in);
+ if (header.fourcc != uint32(MAP_AREA_MAGIC))
+ return false;
+
+ m_gridArea = header.gridArea;
+ if (!(header.flags & MAP_AREA_NO_AREA))
+ {
+ m_area_map = new uint16 [16*16];
+ fread(m_area_map, sizeof(uint16), 16*16, in);
+ }
+ return true;
+}
+
+bool GridMap::loadHeihgtData(FILE *in, uint32 offset, uint32 /*size*/)
+{
+ map_heightHeader header;
+ fseek(in, offset, SEEK_SET);
+ fread(&header, sizeof(header), 1, in);
+ if (header.fourcc != uint32(MAP_HEIGHT_MAGIC))
+ return false;
+
+ m_gridHeight = header.gridHeight;
+ if (!(header.flags & MAP_HEIGHT_NO_HEIGHT))
+ {
+ if ((header.flags & MAP_HEIGHT_AS_INT16))
+ {
+ m_uint16_V9 = new uint16 [129*129];
+ m_uint16_V8 = new uint16 [128*128];
+ fread(m_uint16_V9, sizeof(uint16), 129*129, in);
+ fread(m_uint16_V8, sizeof(uint16), 128*128, in);
+ m_gridIntHeightMultiplier = (header.gridMaxHeight - header.gridHeight) / 65535;
+ m_gridGetHeight = &GridMap::getHeightFromUint16;
+ }
+ else if ((header.flags & MAP_HEIGHT_AS_INT8))
+ {
+ m_uint8_V9 = new uint8 [129*129];
+ m_uint8_V8 = new uint8 [128*128];
+ fread(m_uint8_V9, sizeof(uint8), 129*129, in);
+ fread(m_uint8_V8, sizeof(uint8), 128*128, in);
+ m_gridIntHeightMultiplier = (header.gridMaxHeight - header.gridHeight) / 255;
+ m_gridGetHeight = &GridMap::getHeightFromUint8;
+ }
+ else
+ {
+ m_V9 = new float [129*129];
+ m_V8 = new float [128*128];
+ fread(m_V9, sizeof(float), 129*129, in);
+ fread(m_V8, sizeof(float), 128*128, in);
+ m_gridGetHeight = &GridMap::getHeightFromFloat;
+ }
+ }
+ else
+ m_gridGetHeight = &GridMap::getHeightFromFlat;
+ return true;
+}
+
+bool GridMap::loadLiquidData(FILE *in, uint32 offset, uint32 /*size*/)
+{
+ map_liquidHeader header;
+ fseek(in, offset, SEEK_SET);
+ fread(&header, sizeof(header), 1, in);
+ if (header.fourcc != uint32(MAP_LIQUID_MAGIC))
+ return false;
+
+ m_liquidType = header.liquidType;
+ m_liquid_offX = header.offsetX;
+ m_liquid_offY = header.offsetY;
+ m_liquid_width = header.width;
+ m_liquid_height= header.height;
+ m_liquidLevel = header.liquidLevel;
+
+ if (!(header.flags & MAP_LIQUID_NO_TYPE))
+ {
+ m_liquid_type = new uint8 [16*16];
+ fread(m_liquid_type, sizeof(uint8), 16*16, in);
+ }
+ if (!(header.flags & MAP_LIQUID_NO_HEIGHT))
+ {
+ m_liquid_map = new float [m_liquid_width*m_liquid_height];
+ fread(m_liquid_map, sizeof(float), m_liquid_width*m_liquid_height, in);
+ }
+ return true;
+}
+
+uint16 GridMap::getArea(float x, float y)
+{
+ if (!m_area_map)
+ return m_gridArea;
+
+ x = 16 * (32 - x/SIZE_OF_GRIDS);
+ y = 16 * (32 - y/SIZE_OF_GRIDS);
+ int lx = (int)x & 15;
+ int ly = (int)y & 15;
+ return m_area_map[lx*16 + ly];
+}
+
+float GridMap::getHeightFromFlat(float /*x*/, float /*y*/) const
+{
+ return m_gridHeight;
+}
+
+float GridMap::getHeightFromFloat(float x, float y) const
+{
+ if (!m_V8 || !m_V9)
+ return m_gridHeight;
+
+ x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
+ y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
+
+ int x_int = (int)x;
+ int y_int = (int)y;
+ x -= x_int;
+ y -= y_int;
+ x_int&=(MAP_RESOLUTION - 1);
+ y_int&=(MAP_RESOLUTION - 1);
+
+ // Height stored as: h5 - its v8 grid, h1-h4 - its v9 grid
+ // +--------------> X
+ // | h1-------h2 Coordinates is:
+ // | | \ 1 / | h1 0,0
+ // | | \ / | h2 0,1
+ // | | 2 h5 3 | h3 1,0
+ // | | / \ | h4 1,1
+ // | | / 4 \ | h5 1/2,1/2
+ // | h3-------h4
+ // V Y
+ // For find height need
+ // 1 - detect triangle
+ // 2 - solve linear equation from triangle points
+ // Calculate coefficients for solve h = a*x + b*y + c
+
+ float a,b,c;
+ // Select triangle:
+ if (x+y < 1)
+ {
+ if (x > y)
+ {
+ // 1 triangle (h1, h2, h5 points)
+ float h1 = m_V9[(x_int)*129 + y_int];
+ float h2 = m_V9[(x_int+1)*129 + y_int];
+ float h5 = 2 * m_V8[x_int*128 + y_int];
+ a = h2-h1;
+ b = h5-h1-h2;
+ c = h1;
+ }
+ else
+ {
+ // 2 triangle (h1, h3, h5 points)
+ float h1 = m_V9[x_int*129 + y_int ];
+ float h3 = m_V9[x_int*129 + y_int+1];
+ float h5 = 2 * m_V8[x_int*128 + y_int];
+ a = h5 - h1 - h3;
+ b = h3 - h1;
+ c = h1;
+ }
+ }
+ else
+ {
+ if (x > y)
+ {
+ // 3 triangle (h2, h4, h5 points)
+ float h2 = m_V9[(x_int+1)*129 + y_int ];
+ float h4 = m_V9[(x_int+1)*129 + y_int+1];
+ float h5 = 2 * m_V8[x_int*128 + y_int];
+ a = h2 + h4 - h5;
+ b = h4 - h2;
+ c = h5 - h4;
+ }
+ else
+ {
+ // 4 triangle (h3, h4, h5 points)
+ float h3 = m_V9[(x_int)*129 + y_int+1];
+ float h4 = m_V9[(x_int+1)*129 + y_int+1];
+ float h5 = 2 * m_V8[x_int*128 + y_int];
+ a = h4 - h3;
+ b = h3 + h4 - h5;
+ c = h5 - h4;
+ }
+ }
+ // Calculate height
+ return a * x + b * y + c;
+}
+
+float GridMap::getHeightFromUint8(float x, float y) const
+{
+ if (!m_uint8_V8 || !m_uint8_V9)
+ return m_gridHeight;
+
+ x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
+ y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
+
+ int x_int = (int)x;
+ int y_int = (int)y;
+ x -= x_int;
+ y -= y_int;
+ x_int&=(MAP_RESOLUTION - 1);
+ y_int&=(MAP_RESOLUTION - 1);
+
+ int32 a, b, c;
+ uint8 *V9_h1_ptr = &m_uint8_V9[x_int*128 + x_int + y_int];
+ if (x+y < 1)
+ {
+ if (x > y)
+ {
+ // 1 triangle (h1, h2, h5 points)
+ int32 h1 = V9_h1_ptr[ 0];
+ int32 h2 = V9_h1_ptr[129];
+ int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int];
+ a = h2-h1;
+ b = h5-h1-h2;
+ c = h1;
+ }
+ else
+ {
+ // 2 triangle (h1, h3, h5 points)
+ int32 h1 = V9_h1_ptr[0];
+ int32 h3 = V9_h1_ptr[1];
+ int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int];
+ a = h5 - h1 - h3;
+ b = h3 - h1;
+ c = h1;
+ }
+ }
+ else
+ {
+ if (x > y)
+ {
+ // 3 triangle (h2, h4, h5 points)
+ int32 h2 = V9_h1_ptr[129];
+ int32 h4 = V9_h1_ptr[130];
+ int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int];
+ a = h2 + h4 - h5;
+ b = h4 - h2;
+ c = h5 - h4;
+ }
+ else
+ {
+ // 4 triangle (h3, h4, h5 points)
+ int32 h3 = V9_h1_ptr[ 1];
+ int32 h4 = V9_h1_ptr[130];
+ int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int];
+ a = h4 - h3;
+ b = h3 + h4 - h5;
+ c = h5 - h4;
+ }
+ }
+ // Calculate height
+ return (float)((a * x) + (b * y) + c)*m_gridIntHeightMultiplier + m_gridHeight;
+}
+
+float GridMap::getHeightFromUint16(float x, float y) const
+{
+ if (!m_uint16_V8 || !m_uint16_V9)
+ return m_gridHeight;
+
+ x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
+ y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
+
+ int x_int = (int)x;
+ int y_int = (int)y;
+ x -= x_int;
+ y -= y_int;
+ x_int&=(MAP_RESOLUTION - 1);
+ y_int&=(MAP_RESOLUTION - 1);
+
+ int32 a, b, c;
+ uint16 *V9_h1_ptr = &m_uint16_V9[x_int*128 + x_int + y_int];
+ if (x+y < 1)
+ {
+ if (x > y)
+ {
+ // 1 triangle (h1, h2, h5 points)
+ int32 h1 = V9_h1_ptr[ 0];
+ int32 h2 = V9_h1_ptr[129];
+ int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int];
+ a = h2-h1;
+ b = h5-h1-h2;
+ c = h1;
+ }
+ else
+ {
+ // 2 triangle (h1, h3, h5 points)
+ int32 h1 = V9_h1_ptr[0];
+ int32 h3 = V9_h1_ptr[1];
+ int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int];
+ a = h5 - h1 - h3;
+ b = h3 - h1;
+ c = h1;
+ }
+ }
+ else
+ {
+ if (x > y)
+ {
+ // 3 triangle (h2, h4, h5 points)
+ int32 h2 = V9_h1_ptr[129];
+ int32 h4 = V9_h1_ptr[130];
+ int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int];
+ a = h2 + h4 - h5;
+ b = h4 - h2;
+ c = h5 - h4;
+ }
+ else
+ {
+ // 4 triangle (h3, h4, h5 points)
+ int32 h3 = V9_h1_ptr[ 1];
+ int32 h4 = V9_h1_ptr[130];
+ int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int];
+ a = h4 - h3;
+ b = h3 + h4 - h5;
+ c = h5 - h4;
+ }
+ }
+ // Calculate height
+ return (float)((a * x) + (b * y) + c)*m_gridIntHeightMultiplier + m_gridHeight;
+}
+
+float GridMap::getLiquidLevel(float x, float y)
+{
+ if (!m_liquid_map)
+ return m_liquidLevel;
+
+ x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
+ y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
+
+ int cx_int = ((int)x & (MAP_RESOLUTION-1)) - m_liquid_offY;
+ int cy_int = ((int)y & (MAP_RESOLUTION-1)) - m_liquid_offX;
+
+ if (cx_int < 0 || cx_int >=m_liquid_height)
+ return INVALID_HEIGHT;
+ if (cy_int < 0 || cy_int >=m_liquid_width)
+ return INVALID_HEIGHT;
+
+ return m_liquid_map[cx_int*m_liquid_width + cy_int];
+}
+
+uint8 GridMap::getTerrainType(float x, float y)
+{
+ if (!m_liquid_type)
+ return m_liquidType;
+
+ x = 16 * (32 - x/SIZE_OF_GRIDS);
+ y = 16 * (32 - y/SIZE_OF_GRIDS);
+ int lx = (int)x & 15;
+ int ly = (int)y & 15;
+ return m_liquid_type[lx*16 + ly];
+}
+
+// Get water state on map
+inline ZLiquidStatus GridMap::getLiquidStatus(float x, float y, float z, uint8 ReqLiquidType, LiquidData *data)
+{
+ // Check water type (if no water return)
+ if (!m_liquid_type && !m_liquidType)
+ return LIQUID_MAP_NO_WATER;
+
+ // Get cell
+ float cx = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
+ float cy = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
+
+ int x_int = (int)cx & (MAP_RESOLUTION-1);
+ int y_int = (int)cy & (MAP_RESOLUTION-1);
+
+ // Check water type in cell
+ uint8 type = m_liquid_type ? m_liquid_type[(x_int>>3)*16 + (y_int>>3)] : m_liquidType;
+ if (type == 0)
+ return LIQUID_MAP_NO_WATER;
+
+ // Check req liquid type mask
+ if (ReqLiquidType && !(ReqLiquidType&type))
+ return LIQUID_MAP_NO_WATER;
+
+ // Check water level:
+ // Check water height map
+ int lx_int = x_int - m_liquid_offY;
+ int ly_int = y_int - m_liquid_offX;
+ if (lx_int < 0 || lx_int >=m_liquid_height)
+ return LIQUID_MAP_NO_WATER;
+ if (ly_int < 0 || ly_int >=m_liquid_width)
+ return LIQUID_MAP_NO_WATER;
+
+ // Get water level
+ float liquid_level = m_liquid_map ? m_liquid_map[lx_int*m_liquid_width + ly_int] : m_liquidLevel;
+ // Get ground level (sub 0.2 for fix some errors)
+ float ground_level = getHeight(x, y);
+
+ // Check water level and ground level
+ if (liquid_level < ground_level || z < ground_level - 2)
+ return LIQUID_MAP_NO_WATER;
+
+ // All ok in water -> store data
+ if (data)
+ {
+ data->type = type;
+ data->level = liquid_level;
+ data->depth_level = ground_level;
+ }
+
+ // For speed check as int values
+ int delta = int((liquid_level - z) * 10);
+
+ // Get position delta
+ if (delta > 20) // Under water
+ return LIQUID_MAP_UNDER_WATER;
+ if (delta > 0) // In water
+ return LIQUID_MAP_IN_WATER;
+ if (delta > -1) // Walk on water
+ return LIQUID_MAP_WATER_WALK;
+ // Above water
+ return LIQUID_MAP_ABOVE_WATER;
+}
+
+inline GridMap *Map::GetGrid(float x, float y)
+{
+ // half opt method
+ int gx=(int)(32-x/SIZE_OF_GRIDS); //grid x
+ int gy=(int)(32-y/SIZE_OF_GRIDS); //grid y
+
+ // ensure GridMap is loaded
+ EnsureGridCreated(GridPair(63-gx,63-gy));
+
+ return GridMaps[gx][gy];
+}
+
+float Map::GetHeight(float x, float y, float z, bool pUseVmaps) const
+{
+ // find raw .map surface under Z coordinates
+ float mapHeight;
+ if (GridMap *gmap = const_cast<Map*>(this)->GetGrid(x, y))
+ {
+ float _mapheight = gmap->getHeight(x,y);
+
+ // look from a bit higher pos to find the floor, ignore under surface case
+ if (z + 2.0f > _mapheight)
+ mapHeight = _mapheight;
+ else
+ mapHeight = VMAP_INVALID_HEIGHT_VALUE;
+ }
+ else
+ mapHeight = VMAP_INVALID_HEIGHT_VALUE;
+
+ float vmapHeight;
+ if (pUseVmaps)
+ {
+ VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager();
+ if (vmgr->isHeightCalcEnabled())
+ {
+ // look from a bit higher pos to find the floor
+ vmapHeight = vmgr->getHeight(GetId(), x, y, z + 2.0f);
+ }
+ else
+ vmapHeight = VMAP_INVALID_HEIGHT_VALUE;
+ }
+ else
+ vmapHeight = VMAP_INVALID_HEIGHT_VALUE;
+
+ // mapHeight set for any above raw ground Z or <= INVALID_HEIGHT
+ // vmapheight set for any under Z value or <= INVALID_HEIGHT
+
+ if (vmapHeight > INVALID_HEIGHT)
+ {
+ if (mapHeight > INVALID_HEIGHT)
+ {
+ // we have mapheight and vmapheight and must select more appropriate
+
+ // we are already under the surface or vmap height above map heigt
+ // or if the distance of the vmap height is less the land height distance
+ if (z < mapHeight || vmapHeight > mapHeight || fabs(mapHeight-z) > fabs(vmapHeight-z))
+ return vmapHeight;
+ else
+ return mapHeight; // better use .map surface height
+
+ }
+ else
+ return vmapHeight; // we have only vmapHeight (if have)
+ }
+ else
+ {
+ if (!pUseVmaps)
+ return mapHeight; // explicitly use map data (if have)
+ else if (mapHeight > INVALID_HEIGHT && (z < mapHeight + 2 || z == MAX_HEIGHT))
+ return mapHeight; // explicitly use map data if original z < mapHeight but map found (z+2 > mapHeight)
+ else
+ return VMAP_INVALID_HEIGHT_VALUE; // we not have any height
+ }
+}
+
+inline bool IsOutdoorWMO(uint32 mogpFlags, int32 adtId, int32 rootId, int32 groupId, WMOAreaTableEntry const* wmoEntry, AreaTableEntry const* atEntry)
+{
+ bool outdoor = true;
+
+ if(wmoEntry && atEntry)
+ {
+ if(atEntry->flags & AREA_FLAG_OUTSIDE)
+ return true;
+ if(atEntry->flags & AREA_FLAG_INSIDE)
+ return false;
+ }
+
+ outdoor = mogpFlags&0x8;
+
+ if(wmoEntry)
+ {
+ if(wmoEntry->Flags & 4)
+ return true;
+ if((wmoEntry->Flags & 2)!=0)
+ outdoor = false;
+ }
+ return outdoor;
+}
+
+bool Map::IsOutdoors(float x, float y, float z) const
+{
+ uint32 mogpFlags;
+ int32 adtId, rootId, groupId;
+
+ // no wmo found? -> outside by default
+ if(!GetAreaInfo(x, y, z, mogpFlags, adtId, rootId, groupId))
+ return true;
+
+ AreaTableEntry const* atEntry = 0;
+ WMOAreaTableEntry const* wmoEntry= GetWMOAreaTableEntryByTripple(rootId, adtId, groupId);
+ if(wmoEntry)
+ {
+ DEBUG_LOG("Got WMOAreaTableEntry! flag %u, areaid %u", wmoEntry->Flags, wmoEntry->areaId);
+ atEntry = GetAreaEntryByAreaID(wmoEntry->areaId);
+ }
+ return IsOutdoorWMO(mogpFlags, adtId, rootId, groupId, wmoEntry, atEntry);
+}
+
+bool Map::GetAreaInfo(float x, float y, float z, uint32 &flags, int32 &adtId, int32 &rootId, int32 &groupId) const
+{
+ float vmap_z = z;
+ VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager();
+ if (vmgr->getAreaInfo(GetId(), x, y, vmap_z, flags, adtId, rootId, groupId))
+ {
+ // check if there's terrain between player height and object height
+ if(GridMap *gmap = const_cast<Map*>(this)->GetGrid(x, y))
+ {
+ float _mapheight = gmap->getHeight(x,y);
+ // z + 2.0f condition taken from GetHeight(), not sure if it's such a great choice...
+ if(z + 2.0f > _mapheight && _mapheight > vmap_z)
+ return false;
+ }
+ return true;
+ }
+ return false;
+}
+
+uint16 Map::GetAreaFlag(float x, float y, float z, bool *isOutdoors) const
+{
+ uint32 mogpFlags;
+ int32 adtId, rootId, groupId;
+ WMOAreaTableEntry const* wmoEntry = 0;
+ AreaTableEntry const* atEntry = 0;
+ bool haveAreaInfo = false;
+
+ if (GetAreaInfo(x, y, z, mogpFlags, adtId, rootId, groupId))
+ {
+ haveAreaInfo = true;
+ if (wmoEntry = GetWMOAreaTableEntryByTripple(rootId, adtId, groupId))
+ atEntry = GetAreaEntryByAreaID(wmoEntry->areaId);
+ }
+
+ uint16 areaflag;
+
+ if (atEntry)
+ areaflag = atEntry->exploreFlag;
+ else
+ {
+ if (GridMap *gmap = const_cast<Map*>(this)->GetGrid(x, y))
+ areaflag = gmap->getArea(x, y);
+ // this used while not all *.map files generated (instances)
+ else
+ areaflag = GetAreaFlagByMapId(i_mapEntry->MapID);
+ }
+
+ if (isOutdoors)
+ {
+ if (haveAreaInfo)
+ *isOutdoors = IsOutdoorWMO(mogpFlags, adtId, rootId, groupId, wmoEntry, atEntry);
+ else
+ *isOutdoors = true;
+ }
+ return areaflag;
+ }
+
+uint8 Map::GetTerrainType(float x, float y) const
+{
+ if (GridMap *gmap = const_cast<Map*>(this)->GetGrid(x, y))
+ return gmap->getTerrainType(x, y);
+ else
+ return 0;
+}
+
+ZLiquidStatus Map::getLiquidStatus(float x, float y, float z, uint8 ReqLiquidType, LiquidData *data) const
+{
+ ZLiquidStatus result = LIQUID_MAP_NO_WATER;
+ VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager();
+ float liquid_level, ground_level = INVALID_HEIGHT;
+ uint32 liquid_type;
+ if (vmgr->GetLiquidLevel(GetId(), x, y, z, ReqLiquidType, liquid_level, ground_level, liquid_type))
+ {
+ sLog.outDebug("getLiquidStatus(): vmap liquid level: %f ground: %f type: %u", liquid_level, ground_level, liquid_type);
+ // Check water level and ground level
+ if (liquid_level > ground_level && z > ground_level - 2)
+ {
+ // All ok in water -> store data
+ if (data)
+ {
+ data->type = liquid_type;
+ data->level = liquid_level;
+ data->depth_level = ground_level;
+ }
+
+ // For speed check as int values
+ int delta = int((liquid_level - z) * 10);
+
+ // Get position delta
+ if (delta > 20) // Under water
+ return LIQUID_MAP_UNDER_WATER;
+ if (delta > 0 ) // In water
+ return LIQUID_MAP_IN_WATER;
+ if (delta > -1) // Walk on water
+ return LIQUID_MAP_WATER_WALK;
+ result = LIQUID_MAP_ABOVE_WATER;
+ }
+ }
+
+ if(GridMap* gmap = const_cast<Map*>(this)->GetGrid(x, y))
+ {
+ LiquidData map_data;
+ ZLiquidStatus map_result = gmap->getLiquidStatus(x, y, z, ReqLiquidType, &map_data);
+ // Not override LIQUID_MAP_ABOVE_WATER with LIQUID_MAP_NO_WATER:
+ if (map_result != LIQUID_MAP_NO_WATER && (map_data.level > ground_level))
+ {
+ if (data)
+ *data = map_data;
+ return map_result;
+ }
+ }
+ return result;
+}
+
+float Map::GetWaterLevel(float x, float y) const
+{
+ if (GridMap* gmap = const_cast<Map*>(this)->GetGrid(x, y))
+ return gmap->getLiquidLevel(x, y);
+ else
+ return 0;
+}
+
+uint32 Map::GetAreaIdByAreaFlag(uint16 areaflag,uint32 map_id)
+{
+ AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
+
+ if (entry)
+ return entry->ID;
+ else
+ return 0;
+}
+
+uint32 Map::GetZoneIdByAreaFlag(uint16 areaflag,uint32 map_id)
+{
+ AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
+
+ if (entry)
+ return (entry->zone != 0) ? entry->zone : entry->ID;
+ else
+ return 0;
+}
+
+void Map::GetZoneAndAreaIdByAreaFlag(uint32& zoneid, uint32& areaid, uint16 areaflag,uint32 map_id)
+{
+ AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
+
+ areaid = entry ? entry->ID : 0;
+ zoneid = entry ? ((entry->zone != 0) ? entry->zone : entry->ID) : 0;
+}
+
+bool Map::IsInWater(float x, float y, float pZ, LiquidData *data) const
+{
+ // Check surface in x, y point for liquid
+ if (const_cast<Map*>(this)->GetGrid(x, y))
+ {
+ LiquidData liquid_status;
+ LiquidData *liquid_ptr = data ? data : &liquid_status;
+ if (getLiquidStatus(x, y, pZ, MAP_ALL_LIQUIDS, liquid_ptr))
+ return true;
+ }
+ return false;
+}
+
+bool Map::IsUnderWater(float x, float y, float z) const
+{
+ if (const_cast<Map*>(this)->GetGrid(x, y))
+ {
+ if (getLiquidStatus(x, y, z, MAP_LIQUID_TYPE_WATER|MAP_LIQUID_TYPE_OCEAN)&LIQUID_MAP_UNDER_WATER)
+ return true;
+ }
+ return false;
+}
+
+bool Map::CheckGridIntegrity(Creature* c, bool moved) const
+{
+ Cell const& cur_cell = c->GetCurrentCell();
+
+ CellPair xy_val = Trinity::ComputeCellPair(c->GetPositionX(), c->GetPositionY());
+ Cell xy_cell(xy_val);
+ if (xy_cell != cur_cell)
+ {
+ sLog.outDebug("Creature (GUID: %u) X: %f Y: %f (%s) is in grid[%u,%u]cell[%u,%u] instead of grid[%u,%u]cell[%u,%u]",
+ c->GetGUIDLow(),
+ c->GetPositionX(),c->GetPositionY(),(moved ? "final" : "original"),
+ cur_cell.GridX(), cur_cell.GridY(), cur_cell.CellX(), cur_cell.CellY(),
+ xy_cell.GridX(), xy_cell.GridY(), xy_cell.CellX(), xy_cell.CellY());
+ return true; // not crash at error, just output error in debug mode
+ }
+
+ return true;
+}
+
+const char* Map::GetMapName() const
+{
+ return i_mapEntry ? i_mapEntry->name[sWorld.GetDefaultDbcLocale()] : "UNNAMEDMAP\x0";
+}
+
+void Map::UpdateObjectVisibility(WorldObject* obj, Cell cell, CellPair cellpair)
+{
+ cell.data.Part.reserved = ALL_DISTRICT;
+ cell.SetNoCreate();
+ Trinity::VisibleChangesNotifier notifier(*obj);
+ TypeContainerVisitor<Trinity::VisibleChangesNotifier, WorldTypeMapContainer > player_notifier(notifier);
+ cell.Visit(cellpair, player_notifier, *this, *obj, GetVisibilityDistance());
+}
+
+void Map::UpdateObjectsVisibilityFor(Player* player, Cell cell, CellPair cellpair)
+{
+ Trinity::VisibleNotifier notifier(*player);
+
+ cell.data.Part.reserved = ALL_DISTRICT;
+ cell.SetNoCreate();
+ TypeContainerVisitor<Trinity::VisibleNotifier, WorldTypeMapContainer > world_notifier(notifier);
+ TypeContainerVisitor<Trinity::VisibleNotifier, GridTypeMapContainer > grid_notifier(notifier);
+ cell.Visit(cellpair, world_notifier, *this, *player, GetVisibilityDistance());
+ cell.Visit(cellpair, grid_notifier, *this, *player, GetVisibilityDistance());
+
+ // send data
+ notifier.SendToSelf();
+}
+/*
+void Map::PlayerRelocationNotify(Player* player, Cell cell, CellPair cellpair)
+{
+ Trinity::PlayerRelocationNotifier relocationNotifier(*player);
+ cell.data.Part.reserved = ALL_DISTRICT;
+
+ TypeContainerVisitor<Trinity::PlayerRelocationNotifier, GridTypeMapContainer > p2grid_relocation(relocationNotifier);
+ TypeContainerVisitor<Trinity::PlayerRelocationNotifier, WorldTypeMapContainer > p2world_relocation(relocationNotifier);
+
+ cell.Visit(cellpair, p2grid_relocation, *this, *player, MAX_CREATURE_ATTACK_RADIUS);
+ cell.Visit(cellpair, p2world_relocation, *this, *player, MAX_CREATURE_ATTACK_RADIUS);
+}
+
+void Map::CreatureRelocationNotify(Creature *creature, Cell cell, CellPair cellpair)
+{
+ Trinity::CreatureRelocationNotifier relocationNotifier(*creature);
+ cell.data.Part.reserved = ALL_DISTRICT;
+ cell.SetNoCreate(); // not trigger load unloaded grids at notifier call
+
+ TypeContainerVisitor<Trinity::CreatureRelocationNotifier, WorldTypeMapContainer > c2world_relocation(relocationNotifier);
+ TypeContainerVisitor<Trinity::CreatureRelocationNotifier, GridTypeMapContainer > c2grid_relocation(relocationNotifier);
+
+ cell.Visit(cellpair, c2world_relocation, *this, *creature, MAX_CREATURE_ATTACK_RADIUS);
+ cell.Visit(cellpair, c2grid_relocation, *this, *creature, MAX_CREATURE_ATTACK_RADIUS);
+}
+*/
+
+void Map::SendInitSelf(Player * player)
+{
+ sLog.outDetail("Creating player data for himself %u", player->GetGUIDLow());
+
+ UpdateData data;
+
+ // attach to player data current transport data
+ if (Transport* transport = player->GetTransport())
+ {
+ transport->BuildCreateUpdateBlockForPlayer(&data, player);
+ }
+
+ // build data for self presence in world at own client (one time for map)
+ player->BuildCreateUpdateBlockForPlayer(&data, player);
+
+ // build other passengers at transport also (they always visible and marked as visible and will not send at visibility update at add to map
+ if (Transport* transport = player->GetTransport())
+ {
+ for (Transport::PlayerSet::const_iterator itr = transport->GetPassengers().begin(); itr != transport->GetPassengers().end(); ++itr)
+ {
+ if (player != (*itr) && player->HaveAtClient(*itr))
+ {
+ (*itr)->BuildCreateUpdateBlockForPlayer(&data, player);
+ }
+ }
+ }
+
+ WorldPacket packet;
+ data.BuildPacket(&packet);
+ player->GetSession()->SendPacket(&packet);
+}
+
+void Map::SendInitTransports(Player * player)
+{
+ // Hack to send out transports
+ MapManager::TransportMap& tmap = MapManager::Instance().m_TransportsByMap;
+
+ // no transports at map
+ if (tmap.find(player->GetMapId()) == tmap.end())
+ return;
+
+ UpdateData transData;
+
+ MapManager::TransportSet& tset = tmap[player->GetMapId()];
+
+ for (MapManager::TransportSet::const_iterator i = tset.begin(); i != tset.end(); ++i)
+ {
+ // send data for current transport in other place
+ if ((*i) != player->GetTransport() && (*i)->GetMapId() == GetId())
+ {
+ (*i)->BuildCreateUpdateBlockForPlayer(&transData, player);
+ }
+ }
+
+ WorldPacket packet;
+ transData.BuildPacket(&packet);
+ player->GetSession()->SendPacket(&packet);
+}
+
+void Map::SendRemoveTransports(Player * player)
+{
+ // Hack to send out transports
+ MapManager::TransportMap& tmap = MapManager::Instance().m_TransportsByMap;
+
+ // no transports at map
+ if (tmap.find(player->GetMapId()) == tmap.end())
+ return;
+
+ UpdateData transData;
+
+ MapManager::TransportSet& tset = tmap[player->GetMapId()];
+
+ // except used transport
+ for (MapManager::TransportSet::const_iterator i = tset.begin(); i != tset.end(); ++i)
+ if ((*i) != player->GetTransport() && (*i)->GetMapId() != GetId())
+ (*i)->BuildOutOfRangeUpdateBlock(&transData);
+
+ WorldPacket packet;
+ transData.BuildPacket(&packet);
+ player->GetSession()->SendPacket(&packet);
+}
+
+inline void Map::setNGrid(NGridType *grid, uint32 x, uint32 y)
+{
+ if (x >= MAX_NUMBER_OF_GRIDS || y >= MAX_NUMBER_OF_GRIDS)
+ {
+ sLog.outError("map::setNGrid() Invalid grid coordinates found: %d, %d!",x,y);
+ assert(false);
+ }
+ i_grids[x][y] = grid;
+}
+
+void Map::DelayedUpdate(const uint32 t_diff)
+{
+ RemoveAllObjectsInRemoveList();
+
+ // 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 !
+ // This isn't really bother us, since as soon as we have instanced BG-s, the whole map unloads as the BG gets ended
+ if (!IsBattleGroundOrArena())
+ {
+ for (GridRefManager<NGridType>::iterator i = GridRefManager<NGridType>::begin(); i != GridRefManager<NGridType>::end();)
+ {
+ NGridType *grid = i->getSource();
+ GridInfo *info = i->getSource()->getGridInfoRef();
+ ++i; // The update might delete the map and we need the next map before the iterator gets invalid
+ assert(grid->GetGridState() >= 0 && grid->GetGridState() < MAX_GRID_STATE);
+ si_GridStates[grid->GetGridState()]->Update(*this, *grid, *info, grid->getX(), grid->getY(), t_diff);
+ }
+ }
+}
+
+void Map::AddObjectToRemoveList(WorldObject *obj)
+{
+ assert(obj->GetMapId() == GetId() && obj->GetInstanceId() == GetInstanceId());
+
+ obj->CleanupsBeforeDelete(false); // remove or simplify at least cross referenced links
+
+ i_objectsToRemove.insert(obj);
+ //sLog.outDebug("Object (GUID: %u TypeId: %u) added to removing list.",obj->GetGUIDLow(),obj->GetTypeId());
+}
+
+void Map::AddObjectToSwitchList(WorldObject *obj, bool on)
+{
+ assert(obj->GetMapId() == GetId() && obj->GetInstanceId() == GetInstanceId());
+
+ std::map<WorldObject*, bool>::iterator itr = i_objectsToSwitch.find(obj);
+ if (itr == i_objectsToSwitch.end())
+ i_objectsToSwitch.insert(itr, std::make_pair(obj, on));
+ else if (itr->second != on)
+ i_objectsToSwitch.erase(itr);
+ else
+ assert(false);
+}
+
+void Map::RemoveAllObjectsInRemoveList()
+{
+ while (!i_objectsToSwitch.empty())
+ {
+ std::map<WorldObject*, bool>::iterator itr = i_objectsToSwitch.begin();
+ WorldObject *obj = itr->first;
+ bool on = itr->second;
+ i_objectsToSwitch.erase(itr);
+
+ switch(obj->GetTypeId())
+ {
+ case TYPEID_UNIT:
+ if (!obj->ToCreature()->isPet())
+ SwitchGridContainers(obj->ToCreature(), on);
+ break;
+ }
+ }
+
+ //sLog.outDebug("Object remover 1 check.");
+ while (!i_objectsToRemove.empty())
+ {
+ std::set<WorldObject*>::iterator itr = i_objectsToRemove.begin();
+ WorldObject* obj = *itr;
+
+ switch(obj->GetTypeId())
+ {
+ case TYPEID_CORPSE:
+ {
+ Corpse* corpse = ObjectAccessor::Instance().GetCorpse(*obj, obj->GetGUID());
+ if (!corpse)
+ sLog.outError("Tried to delete corpse/bones %u that is not in map.", obj->GetGUIDLow());
+ else
+ Remove(corpse,true);
+ break;
+ }
+ case TYPEID_DYNAMICOBJECT:
+ Remove((DynamicObject*)obj,true);
+ break;
+ case TYPEID_GAMEOBJECT:
+ Remove((GameObject*)obj,true);
+ break;
+ case TYPEID_UNIT:
+ // in case triggered sequence some spell can continue casting after prev CleanupsBeforeDelete call
+ // make sure that like sources auras/etc removed before destructor start
+ obj->ToCreature()->CleanupsBeforeDelete();
+ Remove(obj->ToCreature(),true);
+ break;
+ default:
+ sLog.outError("Non-grid object (TypeId: %u) is in grid object remove list, ignored.",obj->GetTypeId());
+ break;
+ }
+
+ i_objectsToRemove.erase(itr);
+ }
+
+ //sLog.outDebug("Object remover 2 check.");
+}
+
+uint32 Map::GetPlayersCountExceptGMs() const
+{
+ uint32 count = 0;
+ for (MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
+ if (!itr->getSource()->isGameMaster())
+ ++count;
+ return count;
+}
+
+void Map::SendToPlayers(WorldPacket const* data) const
+{
+ for (MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
+ itr->getSource()->GetSession()->SendPacket(data);
+}
+
+bool Map::ActiveObjectsNearGrid(uint32 x, uint32 y) const
+{
+ ASSERT(x < MAX_NUMBER_OF_GRIDS);
+ ASSERT(y < MAX_NUMBER_OF_GRIDS);
+
+ CellPair cell_min(x*MAX_NUMBER_OF_CELLS, y*MAX_NUMBER_OF_CELLS);
+ CellPair cell_max(cell_min.x_coord + MAX_NUMBER_OF_CELLS, cell_min.y_coord+MAX_NUMBER_OF_CELLS);
+
+ //we must find visible range in cells so we unload only non-visible cells...
+ float viewDist = GetVisibilityDistance();
+ int cell_range = (int)ceilf(viewDist / SIZE_OF_GRID_CELL) + 1;
+
+ cell_min << cell_range;
+ cell_min -= cell_range;
+ cell_max >> cell_range;
+ cell_max += cell_range;
+
+ for (MapRefManager::const_iterator iter = m_mapRefManager.begin(); iter != m_mapRefManager.end(); ++iter)
+ {
+ Player* plr = iter->getSource();
+
+ CellPair p = Trinity::ComputeCellPair(plr->GetPositionX(), plr->GetPositionY());
+ if ((cell_min.x_coord <= p.x_coord && p.x_coord <= cell_max.x_coord) &&
+ (cell_min.y_coord <= p.y_coord && p.y_coord <= cell_max.y_coord))
+ return true;
+ }
+
+ for (ActiveNonPlayers::const_iterator iter = m_activeNonPlayers.begin(); iter != m_activeNonPlayers.end(); ++iter)
+ {
+ WorldObject* obj = *iter;
+
+ CellPair p = Trinity::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
+ if ((cell_min.x_coord <= p.x_coord && p.x_coord <= cell_max.x_coord) &&
+ (cell_min.y_coord <= p.y_coord && p.y_coord <= cell_max.y_coord))
+ return true;
+ }
+
+ return false;
+}
+
+void Map::AddToActive(Creature* c)
+{
+ AddToActiveHelper(c);
+
+ // also not allow unloading spawn grid to prevent creating creature clone at load
+ if (!c->isPet() && c->GetDBTableGUIDLow())
+ {
+ float x,y,z;
+ c->GetRespawnCoord(x,y,z);
+ GridPair p = Trinity::ComputeGridPair(x, y);
+ if (getNGrid(p.x_coord, p.y_coord))
+ getNGrid(p.x_coord, p.y_coord)->incUnloadActiveLock();
+ else
+ {
+ GridPair p2 = Trinity::ComputeGridPair(c->GetPositionX(), c->GetPositionY());
+ sLog.outError("Active creature (GUID: %u Entry: %u) added to grid[%u,%u] but spawn grid[%u,%u] was not loaded.",
+ c->GetGUIDLow(), c->GetEntry(), p.x_coord, p.y_coord, p2.x_coord, p2.y_coord);
+ }
+ }
+}
+
+void Map::RemoveFromActive(Creature* c)
+{
+ RemoveFromActiveHelper(c);
+
+ // also allow unloading spawn grid
+ if (!c->isPet() && c->GetDBTableGUIDLow())
+ {
+ float x,y,z;
+ c->GetRespawnCoord(x,y,z);
+ GridPair p = Trinity::ComputeGridPair(x, y);
+ if (getNGrid(p.x_coord, p.y_coord))
+ getNGrid(p.x_coord, p.y_coord)->decUnloadActiveLock();
+ else
+ {
+ GridPair p2 = Trinity::ComputeGridPair(c->GetPositionX(), c->GetPositionY());
+ sLog.outError("Active creature (GUID: %u Entry: %u) removed from grid[%u,%u] but spawn grid[%u,%u] was not loaded.",
+ c->GetGUIDLow(), c->GetEntry(), p.x_coord, p.y_coord, p2.x_coord, p2.y_coord);
+ }
+ }
+}
+
+template void Map::Add(Corpse *);
+template void Map::Add(Creature *);
+template void Map::Add(GameObject *);
+template void Map::Add(DynamicObject *);
+
+template void Map::Remove(Corpse *,bool);
+template void Map::Remove(Creature *,bool);
+template void Map::Remove(GameObject *, bool);
+template void Map::Remove(DynamicObject *, bool);
+
+/* ******* Dungeon Instance Maps ******* */
+
+InstanceMap::InstanceMap(uint32 id, time_t expiry, uint32 InstanceId, uint8 SpawnMode, Map* _parent)
+ : Map(id, expiry, InstanceId, SpawnMode, _parent),
+ m_resetAfterUnload(false), m_unloadWhenEmpty(false),
+ i_data(NULL), i_script_id(0)
+{
+ //lets initialize visibility distance for dungeons
+ InstanceMap::InitVisibilityDistance();
+
+ // the timer is started by default, and stopped when the first player joins
+ // this make sure it gets unloaded if for some reason no player joins
+ m_unloadTimer = std::max(sWorld.getConfig(CONFIG_INSTANCE_UNLOAD_DELAY), (uint32)MIN_UNLOAD_DELAY);
+}
+
+InstanceMap::~InstanceMap()
+{
+ if (i_data)
+ {
+ delete i_data;
+ i_data = NULL;
+ }
+}
+
+void InstanceMap::InitVisibilityDistance()
+{
+ //init visibility distance for instances
+ m_VisibleDistance = World::GetMaxVisibleDistanceInInstances();
+ m_VisibilityNotifyPeriod = World::GetVisibilityNotifyPeriodInInstances();
+}
+
+/*
+ Do map specific checks to see if the player can enter
+*/
+bool InstanceMap::CanEnter(Player *player)
+{
+ if (player->GetMapRef().getTarget() == this)
+ {
+ sLog.outError("InstanceMap::CanEnter - player %s(%u) already in map %d,%d,%d!", player->GetName(), player->GetGUIDLow(), GetId(), GetInstanceId(), GetSpawnMode());
+ assert(false);
+ return false;
+ }
+
+ // allow GM's to enter
+ if (player->isGameMaster())
+ return Map::CanEnter(player);
+
+ // cannot enter if the instance is full (player cap), GMs don't count
+ uint32 maxPlayers = GetMaxPlayers();
+ if (GetPlayersCountExceptGMs() >= maxPlayers)
+ {
+ sLog.outDetail("MAP: Instance '%u' of map '%s' cannot have more than '%u' players. Player '%s' rejected", GetInstanceId(), GetMapName(), maxPlayers, player->GetName());
+ player->SendTransferAborted(GetId(), TRANSFER_ABORT_MAX_PLAYERS);
+ return false;
+ }
+
+ // cannot enter while an encounter is in progress on raids
+ /*Group *pGroup = player->GetGroup();
+ if (!player->isGameMaster() && pGroup && pGroup->InCombatToInstance(GetInstanceId()) && player->GetMapId() != GetId())*/
+ if (IsRaid() && GetInstanceData() && GetInstanceData()->IsEncounterInProgress())
+ {
+ player->SendTransferAborted(GetId(), TRANSFER_ABORT_ZONE_IN_COMBAT);
+ return false;
+ }
+
+ return Map::CanEnter(player);
+}
+
+/*
+ Do map specific checks and add the player to the map if successful.
+*/
+bool InstanceMap::Add(Player *player)
+{
+ // TODO: Not sure about checking player level: already done in HandleAreaTriggerOpcode
+ // GMs still can teleport player in instance.
+ // Is it needed?
+
+ {
+ Guard guard(*this);
+ // Check moved to void WorldSession::HandleMoveWorldportAckOpcode()
+ //if (!CanEnter(player))
+ //return false;
+
+ // Dungeon only code
+ if (IsDungeon())
+ {
+ // get or create an instance save for the map
+ InstanceSave *mapSave = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
+ if (!mapSave)
+ {
+ sLog.outDetail("InstanceMap::Add: creating instance save for map %d spawnmode %d with instance id %d", GetId(), GetSpawnMode(), GetInstanceId());
+ mapSave = sInstanceSaveManager.AddInstanceSave(GetId(), GetInstanceId(), Difficulty(GetSpawnMode()), 0, true);
+ }
+
+ // check for existing instance binds
+ InstancePlayerBind *playerBind = player->GetBoundInstance(GetId(), Difficulty(GetSpawnMode()));
+ if (playerBind && playerBind->perm)
+ {
+ // cannot enter other instances if bound permanently
+ if (playerBind->save != mapSave)
+ {
+ sLog.outError("InstanceMap::Add: player %s(%d) is permanently bound to instance %d,%d,%d,%d,%d,%d but he is being put into 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());
+ return false;
+ }
+ }
+ else
+ {
+ Group *pGroup = player->GetGroup();
+ if (pGroup)
+ {
+ // solo saves should be reset when entering a group
+ InstanceGroupBind *groupBind = pGroup->GetBoundInstance(this);
+ if (playerBind)
+ {
+ sLog.outError("InstanceMap::Add: player %s(%d) is being put into 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());
+ if (groupBind) sLog.outError("InstanceMap::Add: the group is bound to the 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());
+ //assert(false);
+ return false;
+ }
+ // bind to the group or keep using the group save
+ if (!groupBind)
+ pGroup->BindToInstance(mapSave, false);
+ else
+ {
+ // cannot jump to a different instance without resetting it
+ if (groupBind->save != mapSave)
+ {
+ sLog.outError("InstanceMap::Add: player %s(%d) is being put into 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());
+ if (mapSave)
+ sLog.outError("MapSave players: %d, group count: %d", mapSave->GetPlayerCount(), mapSave->GetGroupCount());
+ else
+ sLog.outError("MapSave NULL");
+ if (groupBind->save)
+ sLog.outError("GroupBind save players: %d, group count: %d", groupBind->save->GetPlayerCount(), groupBind->save->GetGroupCount());
+ else
+ sLog.outError("GroupBind save NULL");
+ return false;
+ }
+ // if the group/leader is permanently bound to the instance
+ // players also become permanently bound when they enter
+ if (groupBind->perm)
+ {
+ WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
+ data << uint32(0);
+ player->GetSession()->SendPacket(&data);
+ player->BindToInstance(mapSave, true);
+ }
+ }
+ }
+ else
+ {
+ // set up a solo bind or continue using it
+ if (!playerBind)
+ player->BindToInstance(mapSave, false);
+ else
+ // cannot jump to a different instance without resetting it
+ assert(playerBind->save == mapSave);
+ }
+ }
+ }
+
+ // for normal instances cancel the reset schedule when the
+ // first player enters (no players yet)
+ SetResetSchedule(false);
+
+ sLog.outDetail("MAP: Player '%s' entered instance '%u' of map '%s'", player->GetName(), GetInstanceId(), GetMapName());
+ // initialize unload state
+ m_unloadTimer = 0;
+ m_resetAfterUnload = false;
+ m_unloadWhenEmpty = false;
+ }
+
+ // this will acquire the same mutex so it cannot be in the previous block
+ Map::Add(player);
+
+ if (i_data)
+ i_data->OnPlayerEnter(player);
+
+ return true;
+}
+
+void InstanceMap::Update(const uint32& t_diff)
+{
+ Map::Update(t_diff);
+
+ if (i_data)
+ i_data->Update(t_diff);
+}
+
+void InstanceMap::Remove(Player *player, bool remove)
+{
+ sLog.outDetail("MAP: Removing player '%s' from instance '%u' of map '%s' before relocating to another map", player->GetName(), GetInstanceId(), GetMapName());
+ //if last player set unload timer
+ if (!m_unloadTimer && m_mapRefManager.getSize() == 1)
+ m_unloadTimer = m_unloadWhenEmpty ? MIN_UNLOAD_DELAY : std::max(sWorld.getConfig(CONFIG_INSTANCE_UNLOAD_DELAY), (uint32)MIN_UNLOAD_DELAY);
+ Map::Remove(player, remove);
+ // for normal instances schedule the reset after all players have left
+ SetResetSchedule(true);
+}
+
+void InstanceMap::CreateInstanceData(bool load)
+{
+ if (i_data != NULL)
+ return;
+
+ InstanceTemplate const* mInstance = objmgr.GetInstanceTemplate(GetId());
+ if (mInstance)
+ {
+ i_script_id = mInstance->script_id;
+ i_data = sScriptMgr.CreateInstanceData(this);
+ }
+
+ if (!i_data)
+ return;
+
+ i_data->Initialize();
+
+ if (load)
+ {
+ // TODO: make a global storage for this
+ QueryResult_AutoPtr result = CharacterDatabase.PQuery("SELECT data FROM instance WHERE map = '%u' AND id = '%u'", GetId(), i_InstanceId);
+ if (result)
+ {
+ Field* fields = result->Fetch();
+ std::string data = fields[0].GetString();
+ if (data != "")
+ {
+ sLog.outDebug("Loading instance data for `%s` with id %u", objmgr.GetScriptName(i_script_id), i_InstanceId);
+ i_data->Load(data.c_str());
+ }
+ }
+ }
+}
+
+/*
+ Returns true if there are no players in the instance
+*/
+bool InstanceMap::Reset(uint8 method)
+{
+ // note: since the map may not be loaded when the instance needs to be reset
+ // the instance must be deleted from the DB by InstanceSaveManager
+
+ if (HavePlayers())
+ {
+ if (method == INSTANCE_RESET_ALL)
+ {
+ // notify the players to leave the instance so it can be reset
+ for (MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
+ itr->getSource()->SendResetFailedNotify(GetId());
+ }
+ else
+ {
+ if (method == INSTANCE_RESET_GLOBAL)
+ // set the homebind timer for players inside (1 minute)
+ for (MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
+ itr->getSource()->m_InstanceValid = false;
+
+ // the unload timer is not started
+ // instead the map will unload immediately after the players have left
+ m_unloadWhenEmpty = true;
+ m_resetAfterUnload = true;
+ }
+ }
+ else
+ {
+ // unloaded at next update
+ m_unloadTimer = MIN_UNLOAD_DELAY;
+ m_resetAfterUnload = true;
+ }
+
+ return m_mapRefManager.isEmpty();
+}
+
+void InstanceMap::PermBindAllPlayers(Player *player)
+{
+ if (!IsDungeon())
+ return;
+
+ InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
+ if (!save)
+ {
+ sLog.outError("Cannot bind players, no instance save available for map!");
+ return;
+ }
+
+ Group *group = player->GetGroup();
+ // group members outside the instance group don't get bound
+ for (MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
+ {
+ Player* plr = itr->getSource();
+ // players inside an instance cannot be bound to other instances
+ // some players may already be permanently bound, in this case nothing happens
+ InstancePlayerBind *bind = plr->GetBoundInstance(save->GetMapId(), save->GetDifficulty());
+ if (!bind || !bind->perm)
+ {
+ plr->BindToInstance(save, true);
+ WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
+ data << uint32(0);
+ plr->GetSession()->SendPacket(&data);
+ }
+
+ // if the leader is not in the instance the group will not get a perm bind
+ if (group && group->GetLeaderGUID() == plr->GetGUID())
+ group->BindToInstance(save, true);
+ }
+}
+
+void InstanceMap::UnloadAll()
+{
+ assert(!HavePlayers());
+
+ if (m_resetAfterUnload == true)
+ objmgr.DeleteRespawnTimeForInstance(GetInstanceId());
+
+ Map::UnloadAll();
+}
+
+void InstanceMap::SendResetWarnings(uint32 timeLeft) const
+{
+ for (MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
+ itr->getSource()->SendInstanceResetWarning(GetId(), itr->getSource()->GetDifficulty(IsRaid()), timeLeft);
+}
+
+void InstanceMap::SetResetSchedule(bool on)
+{
+ // only for normal instances
+ // the reset time is only scheduled when there are no payers inside
+ // it is assumed that the reset time will rarely (if ever) change while the reset is scheduled
+ if (IsDungeon() && !HavePlayers() && !IsRaidOrHeroicDungeon())
+ {
+ InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
+ if (!save) sLog.outError("InstanceMap::SetResetSchedule: cannot turn schedule %s, no save available for instance %d of %d", on ? "on" : "off", GetInstanceId(), GetId());
+ else sInstanceSaveManager.ScheduleReset(on, save->GetResetTime(), InstanceSaveManager::InstResetEvent(0, GetId(), Difficulty(GetSpawnMode()), GetInstanceId()));
+ }
+}
+
+MapDifficulty const* Map::GetMapDifficulty() const
+{
+ return GetMapDifficultyData(GetId(),GetDifficulty());
+}
+
+uint32 InstanceMap::GetMaxPlayers() const
+{
+ if (MapDifficulty const* mapDiff = GetMapDifficulty())
+ {
+ if (mapDiff->maxPlayers || IsRegularDifficulty()) // Normal case (expect that regular difficulty always have correct maxplayers)
+ return mapDiff->maxPlayers;
+ else // DBC have 0 maxplayers for heroic instances with expansion < 2
+ { // The heroic entry exists, so we don't have to check anything, simply return normal max players
+ MapDifficulty const* normalDiff = GetMapDifficultyData(GetId(), REGULAR_DIFFICULTY);
+ return normalDiff ? normalDiff->maxPlayers : 0;
+ }
+ }
+ else // I'd rather assert(false);
+ return 0;
+}
+
+uint32 InstanceMap::GetMaxResetDelay() const
+{
+ MapDifficulty const* mapDiff = GetMapDifficulty();
+ return mapDiff ? mapDiff->resetTime : 0;
+}
+
+/* ******* Battleground Instance Maps ******* */
+
+BattleGroundMap::BattleGroundMap(uint32 id, time_t expiry, uint32 InstanceId, Map* _parent, uint8 spawnMode)
+ : Map(id, expiry, InstanceId, spawnMode, _parent)
+{
+ //lets initialize visibility distance for BG/Arenas
+ BattleGroundMap::InitVisibilityDistance();
+}
+
+BattleGroundMap::~BattleGroundMap()
+{
+}
+
+void BattleGroundMap::InitVisibilityDistance()
+{
+ //init visibility distance for BG/Arenas
+ m_VisibleDistance = World::GetMaxVisibleDistanceInBGArenas();
+ m_VisibilityNotifyPeriod = World::GetVisibilityNotifyPeriodInBGArenas();
+}
+
+bool BattleGroundMap::CanEnter(Player * player)
+{
+ if (player->GetMapRef().getTarget() == this)
+ {
+ sLog.outError("BGMap::CanEnter - player %u is already in map!", player->GetGUIDLow());
+ assert(false);
+ return false;
+ }
+
+ if (player->GetBattleGroundId() != GetInstanceId())
+ return false;
+
+ // player number limit is checked in bgmgr, no need to do it here
+
+ return Map::CanEnter(player);
+}
+
+bool BattleGroundMap::Add(Player * player)
+{
+ {
+ Guard guard(*this);
+ //Check moved to void WorldSession::HandleMoveWorldportAckOpcode()
+ //if (!CanEnter(player))
+ //return false;
+ // reset instance validity, battleground maps do not homebind
+ player->m_InstanceValid = true;
+ }
+ return Map::Add(player);
+}
+
+void BattleGroundMap::Remove(Player *player, bool remove)
+{
+ sLog.outDetail("MAP: Removing player '%s' from bg '%u' of map '%s' before relocating to another map", player->GetName(), GetInstanceId(), GetMapName());
+ Map::Remove(player, remove);
+}
+
+void BattleGroundMap::SetUnload()
+{
+ m_unloadTimer = MIN_UNLOAD_DELAY;
+}
+
+void BattleGroundMap::RemoveAllPlayers()
+{
+ if (HavePlayers())
+ for (MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
+ if (Player* plr = itr->getSource())
+ if (!plr->IsBeingTeleportedFar())
+ plr->TeleportTo(plr->GetBattleGroundEntryPoint());
+
+}
+
+/// Put scripts in the execution queue
+void Map::ScriptsStart(ScriptMapMap const& scripts, uint32 id, Object* source, Object* target)
+{
+ ///- Find the script map
+ ScriptMapMap::const_iterator s = scripts.find(id);
+ if (s == scripts.end())
+ return;
+
+ // prepare static data
+ uint64 sourceGUID = source ? source->GetGUID() : (uint64)0; //some script commands doesn't have source
+ uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
+ uint64 ownerGUID = (source->GetTypeId() == TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
+
+ ///- Schedule script execution for all scripts in the script map
+ ScriptMap const *s2 = &(s->second);
+ bool immedScript = false;
+ for (ScriptMap::const_iterator iter = s2->begin(); iter != s2->end(); ++iter)
+ {
+ ScriptAction sa;
+ sa.sourceGUID = sourceGUID;
+ sa.targetGUID = targetGUID;
+ sa.ownerGUID = ownerGUID;
+
+ sa.script = &iter->second;
+ m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(time_t(sWorld.GetGameTime() + iter->first), sa));
+ if (iter->first == 0)
+ immedScript = true;
+
+ sWorld.IncreaseScheduledScriptsCount();
+ }
+ ///- If one of the effects should be immediate, launch the script execution
+ if (/*start &&*/ immedScript && !i_scriptLock)
+ {
+ i_scriptLock = true;
+ ScriptsProcess();
+ i_scriptLock = false;
+ }
+}
+
+void Map::ScriptCommandStart(ScriptInfo const& script, uint32 delay, Object* source, Object* target)
+{
+ // NOTE: script record _must_ exist until command executed
+
+ // prepare static data
+ uint64 sourceGUID = source ? source->GetGUID() : (uint64)0;
+ uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
+ uint64 ownerGUID = (source->GetTypeId() == TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
+
+ ScriptAction sa;
+ sa.sourceGUID = sourceGUID;
+ sa.targetGUID = targetGUID;
+ sa.ownerGUID = ownerGUID;
+
+ sa.script = &script;
+ m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(time_t(sWorld.GetGameTime() + delay), sa));
+
+ sWorld.IncreaseScheduledScriptsCount();
+
+ ///- If effects should be immediate, launch the script execution
+ if (delay == 0 && !i_scriptLock)
+ {
+ i_scriptLock = true;
+ ScriptsProcess();
+ i_scriptLock = false;
+ }
+}
+
+/// Process queued scripts
+void Map::ScriptsProcess()
+{
+ if (m_scriptSchedule.empty())
+ return;
+
+ ///- Process overdue queued scripts
+ std::multimap<time_t, ScriptAction>::iterator iter = m_scriptSchedule.begin();
+ // ok as multimap is a *sorted* associative container
+ while (!m_scriptSchedule.empty() && (iter->first <= sWorld.GetGameTime()))
+ {
+ ScriptAction const& step = iter->second;
+
+ Object* source = NULL;
+
+ if (step.sourceGUID)
+ {
+ switch (GUID_HIPART(step.sourceGUID))
+ {
+ case HIGHGUID_ITEM:
+ // case HIGHGUID_CONTAINER: == HIGHGUID_ITEM
+ {
+ Player* player = HashMapHolder<Player>::Find(step.ownerGUID);
+ if (player)
+ source = player->GetItemByGuid(step.sourceGUID);
+ break;
+ }
+ case HIGHGUID_UNIT:
+ source = HashMapHolder<Creature>::Find(step.sourceGUID);
+ break;
+ case HIGHGUID_PET:
+ source = HashMapHolder<Pet>::Find(step.sourceGUID);
+ break;
+ //case HIGHGUID_VEHICLE:
+ // source = HashMapHolder<Vehicle>::Find(step.sourceGUID);
+ // break;
+ case HIGHGUID_PLAYER:
+ source = HashMapHolder<Player>::Find(step.sourceGUID);
+ break;
+ case HIGHGUID_GAMEOBJECT:
+ source = HashMapHolder<GameObject>::Find(step.sourceGUID);
+ break;
+ case HIGHGUID_CORPSE:
+ source = HashMapHolder<Corpse>::Find(step.sourceGUID);
+ break;
+ case HIGHGUID_MO_TRANSPORT:
+ for (MapManager::TransportSet::iterator iter = MapManager::Instance().m_Transports.begin(); iter != MapManager::Instance().m_Transports.end(); ++iter)
+ {
+ if ((*iter)->GetGUID() == step.sourceGUID)
+ {
+ source = reinterpret_cast<Object*>(*iter);
+ break;
+ }
+ }
+ break;
+ default:
+ sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.sourceGUID));
+ break;
+ }
+ }
+
+ //if (source && !source->IsInWorld()) source = NULL;
+
+ Object* target = NULL;
+
+ if (step.targetGUID)
+ {
+ switch (GUID_HIPART(step.targetGUID))
+ {
+ case HIGHGUID_UNIT:
+ target = HashMapHolder<Creature>::Find(step.targetGUID);
+ break;
+ case HIGHGUID_PET:
+ target = HashMapHolder<Pet>::Find(step.targetGUID);
+ break;
+ //case HIGHGUID_VEHICLE:
+ // target = HashMapHolder<Vehicle>::Find(step.targetGUID);
+ // break;
+ case HIGHGUID_PLAYER: // empty GUID case also
+ target = HashMapHolder<Player>::Find(step.targetGUID);
+ break;
+ case HIGHGUID_GAMEOBJECT:
+ target = HashMapHolder<GameObject>::Find(step.targetGUID);
+ break;
+ case HIGHGUID_CORPSE:
+ target = HashMapHolder<Corpse>::Find(step.targetGUID);
+ break;
+ default:
+ sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.targetGUID));
+ break;
+ }
+ }
+
+ //if (target && !target->IsInWorld()) target = NULL;
+
+ switch (step.script->command)
+ {
+ case SCRIPT_COMMAND_TALK:
+ {
+ if (!source)
+ {
+ sLog.outError("SCRIPT_COMMAND_TALK (script id: %u) call for NULL source.", step.script->id);
+ break;
+ }
+
+ Creature* cSource = NULL;
+ cSource = source->ToCreature() != NULL ? source->ToCreature() : target->ToCreature();
+
+ if (!cSource)
+ {
+ sLog.outError("SCRIPT_COMMAND_TALK (script id: %u) call for non supported source (TypeId: %u, Entry: %u, GUID: %u), skipping.",
+ step.script->id, source->GetTypeId(), source->GetEntry(), source->GetGUIDLow());
+ break;
+ }
+
+ if (step.script->datalong > CHAT_TYPE_WHISPER)
+ {
+ sLog.outError("SCRIPT_COMMAND_TALK (script id: %u) invalid chat type (%u), skipping.", step.script->id, step.script->datalong);
+ break;
+ }
+
+ uint64 unit_target = target ? target->GetGUID() : 0;
+
+ //datalong 0=normal say, 1=whisper, 2=yell, 3=emote text, 4=boss emote text
+ //TODO: Update for more chat types
+ switch (step.script->datalong)
+ {
+ case CHAT_TYPE_SAY: // Say
+ cSource->Say(step.script->dataint, LANG_UNIVERSAL, unit_target);
+ break;
+ case CHAT_TYPE_YELL: // Yell
+ cSource->Yell(step.script->dataint, LANG_UNIVERSAL, unit_target);
+ break;
+ case CHAT_TYPE_TEXT_EMOTE: // Emote text
+ cSource->TextEmote(step.script->dataint, unit_target);
+ break;
+ case CHAT_TYPE_BOSS_EMOTE: // Boss Emote text
+ cSource->MonsterTextEmote(step.script->dataint, unit_target, true);
+ break;
+ case CHAT_TYPE_WHISPER: // Whisper
+ if (!unit_target || !IS_PLAYER_GUID(unit_target))
+ {
+ sLog.outError("SCRIPT_COMMAND_TALK (script id: %u) attempt to whisper (%u) NULL, skipping.", step.script->id,
+ step.script->datalong);
+ break;
+ }
+ cSource->Whisper(step.script->dataint,unit_target);
+ break;
+ default:
+ break; // must be already checked at load
+ }
+ break;
+ }
+
+ case SCRIPT_COMMAND_EMOTE:
+ {
+ if (!source)
+ {
+ sLog.outError("SCRIPT_COMMAND_EMOTE (script id: %u) call for NULL source.", step.script->id);
+ break;
+ }
+
+ Creature* cSource = NULL;
+ cSource = source->ToCreature() != NULL ? source->ToCreature() : target->ToCreature();
+
+ if (!cSource)
+ {
+ sLog.outError("SCRIPT_COMMAND_TALK (script id: %u) call for non supported source (TypeId: %u, Entry: %u, GUID: %u), skipping.",
+ step.script->id, source->GetTypeId(), source->GetEntry(), source->GetGUIDLow());
+ break;
+ }
+
+ if (step.script->datalong2)
+ cSource->SetUInt32Value(UNIT_NPC_EMOTESTATE, step.script->datalong);
+ else
+ cSource->HandleEmoteCommand(step.script->datalong);
+ break;
+ }
+
+ case SCRIPT_COMMAND_FIELD_SET:
+ {
+ if (!source)
+ {
+ sLog.outError("SCRIPT_COMMAND_FIELD_SET (script id: %u) call for NULL source.", step.script->id);
+ break;
+ }
+
+ Creature* cSource = source->ToCreature() != NULL ? source->ToCreature() : target->ToCreature();
+ if (!cSource)
+ {
+ sLog.outError("SCRIPT_COMMAND_FIELD_SET (script id: %u) call for non-creature source.", step.script->id);
+ break;
+ }
+
+ if (step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= cSource->GetValuesCount())
+ {
+ sLog.outError("SCRIPT_COMMAND_FIELD_SET (script id: %u) call for wrong field %u (max count: %u) in object (TypeId: %u, Entry: %u, GUID: %u).",
+ step.script->id, step.script->datalong,source->GetValuesCount(),source->GetTypeId(),source->GetEntry(),source->GetGUIDLow());
+ break;
+ }
+
+ cSource->SetUInt32Value(step.script->datalong, step.script->datalong2);
+ break;
+ }
+
+ case SCRIPT_COMMAND_MOVE_TO:
+ {
+ if (!source)
+ {
+ sLog.outError("SCRIPT_COMMAND_MOVE_TO (script id: %u) call for NULL creature.", step.script->id);
+ break;
+ }
+
+ Creature* cSource = source->ToCreature() != NULL ? source->ToCreature() : target->ToCreature();
+ if (!cSource)
+ {
+ sLog.outError("SCRIPT_COMMAND_MOVE_TO (script id: %u) call for non-creature (TypeId: %u, Entry: %u, GUID: %u), skipping.",
+ step.script->id, source->GetTypeId(),source->GetEntry(),source->GetGUIDLow());
+ break;
+ }
+
+ cSource->SendMonsterMoveWithSpeed(step.script->x, step.script->y, step.script->z, step.script->datalong2);
+ cSource->GetMap()->CreatureRelocation(cSource, step.script->x, step.script->y, step.script->z, 0);
+ break;
+ }
+
+ case SCRIPT_COMMAND_FLAG_SET:
+ {
+ if (!source)
+ {
+ sLog.outError("SCRIPT_COMMAND_FLAG_SET (script id: %u) call for NULL object.", step.script->id);
+ break;
+ }
+
+ Creature* cSource = source->ToCreature() != NULL ? source->ToCreature() : target->ToCreature();
+ if (!cSource)
+ {
+ sLog.outError("SCRIPT_COMMAND_FLAG_SET (script id: %u) call for non-creature source.", step.script->id);
+ break;
+ }
+
+ if (step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= cSource->GetValuesCount())
+ {
+ sLog.outError("SCRIPT_COMMAND_FLAG_SET (script id: %u) call for wrong field %u (max count: %u) in object (TypeId: %u, Entry: %u, GUID: %u).",
+ step.script->id, step.script->datalong,source->GetValuesCount(),source->GetTypeId(),source->GetEntry(),source->GetGUIDLow());
+ break;
+ }
+
+ cSource->SetFlag(step.script->datalong, step.script->datalong2);
+ break;
+ }
+
+ case SCRIPT_COMMAND_FLAG_REMOVE:
+ {
+ if (!source)
+ {
+ sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE (script id: %u) call for NULL object.", step.script->id);
+ break;
+ }
+
+ Creature* cSource = source->ToCreature() != NULL ? source->ToCreature() : target->ToCreature();
+ if (!cSource)
+ {
+ sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE (script id: %u) call for non-creature source.", step.script->id);
+ break;
+ }
+
+ if (step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= cSource->GetValuesCount())
+ {
+ sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE (script id: %u) call for wrong field %u (max count: %u) in object (TypeId: %u, Entry: %u, GUID: %u).",
+ step.script->id, step.script->datalong,source->GetValuesCount(),source->GetTypeId(),source->GetEntry(),source->GetGUIDLow());
+ break;
+ }
+
+ cSource->RemoveFlag(step.script->datalong, step.script->datalong2);
+ break;
+ }
+
+ case SCRIPT_COMMAND_TELEPORT_TO:
+ {
+ // accept object in any one from target/source arg
+ if (!target && !source)
+ {
+ sLog.outError("SCRIPT_COMMAND_TELEPORT_TO (script id: %u) call for NULL object.", step.script->id);
+ break;
+ }
+
+ if (step.script->datalong2 == 0)
+ {
+ Player* pSource = target->ToPlayer() != NULL ? target->ToPlayer() : source->ToPlayer();
+ // must be only Player
+ if (!pSource)
+ {
+ sLog.outError("SCRIPT_COMMAND_TELEPORT_TO (script id: %u) call for non-player (TypeIdSource: %u)(TypeIdTarget: %u), skipping.",
+ step.script->id, source ? source->GetTypeId() : 0, target ? target->GetTypeId() : 0);
+ break;
+ }
+
+ pSource->TeleportTo(step.script->datalong, step.script->x, step.script->y, step.script->z, step.script->o);
+ }
+ else if (step.script->datalong2 == 1)
+ {
+ Creature *cSource = target->ToCreature() != NULL ? target->ToCreature() : source->ToCreature();
+ // must be only Creature
+ if (!cSource)
+ {
+ sLog.outError("SCRIPT_COMMAND_TELEPORT_TO (script id: %u) call for non-creature (TypeIdSource: %u)(TypeIdTarget: %u), skipping.",
+ step.script->id, source ? source->GetTypeId() : 0, target ? target->GetTypeId() : 0);
+ break;
+ }
+
+ cSource->NearTeleportTo(step.script->x, step.script->y, step.script->z, step.script->o);
+ }
+ break;
+ }
+
+ case SCRIPT_COMMAND_KILL_CREDIT:
+ {
+ // accept player in any one from target/source arg
+ if (!target && !source)
+ {
+ sLog.outError("SCRIPT_COMMAND_KILL_CREDIT (script id: %u) call for NULL object.", step.script->id);
+ break;
+ }
+
+ Player* pSource = target->ToPlayer() != NULL ? target->ToPlayer() : source->ToPlayer();
+ // must be only Player
+ if (!pSource)
+ {
+ sLog.outError("SCRIPT_COMMAND_KILL_CREDIT (script id: %u) call for non-player (TypeIdSource: %u)(TypeIdTarget: %u), skipping.",
+ step.script->id, source ? source->GetTypeId() : 0, target ? target->GetTypeId() : 0);
+ break;
+ }
+
+ if (step.script->datalong2)
+ pSource->RewardPlayerAndGroupAtEvent(step.script->datalong, pSource);
+ else
+ pSource->KilledMonsterCredit(step.script->datalong, 0);
+
+ break;
+ }
+
+ case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
+ {
+ if (!step.script->datalong) // creature not specified
+ {
+ sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE (script id: %u) call with no creature parameter.", step.script->id);
+ break;
+ }
+
+ if (!source)
+ {
+ sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE (script id: %u) call for NULL source object.", step.script->id);
+ break;
+ }
+
+ WorldObject* summoner = dynamic_cast<WorldObject*>(source);
+
+ if (!summoner)
+ {
+ sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE (script id: %u) call for non-WorldObject (TypeId: %u, Entry: %u, GUID: %u), skipping.",
+ step.script->id, source->GetTypeId(),source->GetEntry(),source->GetGUIDLow());
+ break;
+ }
+
+ float x = step.script->x;
+ float y = step.script->y;
+ float z = step.script->z;
+ float o = step.script->o;
+
+ Creature* pCreature = summoner->SummonCreature(step.script->datalong, x, y, z, o,TEMPSUMMON_TIMED_OR_DEAD_DESPAWN,step.script->datalong2);
+ if (!pCreature)
+ {
+ sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON (script id: %u) failed for creature (entry: %u).", step.script->id, step.script->datalong);
+ break;
+ }
+
+ break;
+ }
+
+ case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
+ {
+ if (!step.script->datalong) // gameobject not specified
+ {
+ sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT (script id: %u) call with no gameobject parameter.", step.script->id);
+ break;
+ }
+
+ if (!source)
+ {
+ sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT (script id: %u) call for NULL source object.", step.script->id);
+ break;
+ }
+
+ WorldObject* summoner = dynamic_cast<WorldObject*>(source);
+
+ if (!summoner)
+ {
+ sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT (script id: %u) call for non-WorldObject (TypeId: %u, Entry: %u, GUID: %u), skipping.",
+ step.script->id, source->GetTypeId(),source->GetEntry(),source->GetGUIDLow());
+ break;
+ }
+
+ GameObject *go = NULL;
+ int32 time_to_despawn = step.script->datalong2<5 ? 5 : (int32)step.script->datalong2;
+
+ CellPair p(Trinity::ComputeCellPair(summoner->GetPositionX(), summoner->GetPositionY()));
+ Cell cell(p);
+ cell.data.Part.reserved = ALL_DISTRICT;
+
+ Trinity::GameObjectWithDbGUIDCheck go_check(*summoner,step.script->datalong);
+ Trinity::GameObjectSearcher<Trinity::GameObjectWithDbGUIDCheck> checker(summoner, go,go_check);
+
+ TypeContainerVisitor<Trinity::GameObjectSearcher<Trinity::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
+ cell.Visit(p, object_checker, *summoner->GetMap());
+
+ if (!go)
+ {
+ sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT (script id: %u) failed for gameobject(guid: %u).", step.script->id, step.script->datalong);
+ break;
+ }
+
+ if (go->GetGoType() == GAMEOBJECT_TYPE_FISHINGNODE ||
+ go->GetGoType() == GAMEOBJECT_TYPE_DOOR ||
+ go->GetGoType() == GAMEOBJECT_TYPE_BUTTON ||
+ go->GetGoType() == GAMEOBJECT_TYPE_TRAP)
+ {
+ sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT (script id: %u) can not be used with gameobject of type %u (guid: %u).",
+ step.script->id, uint32(go->GetGoType()), step.script->datalong);
+ break;
+ }
+
+ if (go->isSpawned())
+ break; //gameobject already spawned
+
+ go->SetLootState(GO_READY);
+ go->SetRespawnTime(time_to_despawn); //despawn object in ? seconds
+
+ go->GetMap()->Add(go);
+ break;
+ }
+ case SCRIPT_COMMAND_OPEN_DOOR:
+ {
+ if (!step.script->datalong) // door not specified
+ {
+ sLog.outError("SCRIPT_COMMAND_OPEN_DOOR (script id: %u) call for NULL target door.", step.script->id);
+ break;
+ }
+
+ if (!source)
+ {
+ sLog.outError("SCRIPT_COMMAND_OPEN_DOOR (script id: %u) call for NULL source unit.", step.script->id);
+ break;
+ }
+
+ if (!source->isType(TYPEMASK_UNIT)) // must be any Unit (creature or player)
+ {
+ sLog.outError("SCRIPT_COMMAND_OPEN_DOOR (script id: %u) call for non-unit (TypeId: %u, Entry: %u, GUID: %u), skipping.",
+ step.script->id, source->GetTypeId(),source->GetEntry(),source->GetGUIDLow());
+ break;
+ }
+
+ GameObject *door = NULL;
+ WorldObject* wSource = (WorldObject*)source;
+
+ int32 time_to_close = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
+
+ CellPair p(Trinity::ComputeCellPair(wSource->GetPositionX(), wSource->GetPositionY()));
+ Cell cell(p);
+ cell.data.Part.reserved = ALL_DISTRICT;
+
+ Trinity::GameObjectWithDbGUIDCheck go_check(*wSource, step.script->datalong);
+ Trinity::GameObjectSearcher<Trinity::GameObjectWithDbGUIDCheck> checker(wSource, door, go_check);
+
+ TypeContainerVisitor<Trinity::GameObjectSearcher<Trinity::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
+ cell.Visit(p, object_checker, *wSource->GetMap());
+
+ if (!door)
+ {
+ sLog.outError("SCRIPT_COMMAND_OPEN_DOOR (script id: %u) failed for gameobject(guid: %u).", step.script->id, step.script->datalong);
+ break;
+ }
+ if (door->GetGoType() != GAMEOBJECT_TYPE_DOOR)
+ {
+ sLog.outError("SCRIPT_COMMAND_OPEN_DOOR (script id: %u) failed for non-door(GoType: %u, Entry: %u, GUID: %u).",
+ step.script->id, door->GetGoType(),door->GetEntry(),door->GetGUIDLow());
+ break;
+ }
+
+ if (door->GetGoState() != GO_STATE_READY)
+ break; //door already open
+
+ door->UseDoorOrButton(time_to_close);
+
+ if (target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType() == GAMEOBJECT_TYPE_BUTTON)
+ ((GameObject*)target)->UseDoorOrButton(time_to_close);
+ break;
+ }
+ case SCRIPT_COMMAND_CLOSE_DOOR:
+ {
+ if (!step.script->datalong) // guid for door not specified
+ {
+ sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR (script id: %u) call for NULL door.", step.script->id);
+ break;
+ }
+
+ if (!source)
+ {
+ sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR (script id: %u) call for NULL unit.", step.script->id);
+ break;
+ }
+
+ if (!source->isType(TYPEMASK_UNIT)) // must be any Unit (creature or player)
+ {
+ sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR (script id: %u) call for non-unit (TypeId: %u, Entry: %u, GUID: %u), skipping.",
+ step.script->id, source->GetTypeId(),source->GetEntry(),source->GetGUIDLow());
+ break;
+ }
+
+ GameObject *door = NULL;
+ WorldObject* wSource = (WorldObject*)source;
+
+ int32 time_to_open = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
+
+ CellPair p(Trinity::ComputeCellPair(wSource->GetPositionX(), wSource->GetPositionY()));
+ Cell cell(p);
+ cell.data.Part.reserved = ALL_DISTRICT;
+
+ Trinity::GameObjectWithDbGUIDCheck go_check(*wSource, step.script->datalong);
+ Trinity::GameObjectSearcher<Trinity::GameObjectWithDbGUIDCheck> checker(wSource, door, go_check);
+
+ TypeContainerVisitor<Trinity::GameObjectSearcher<Trinity::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
+ cell.Visit(p, object_checker, *wSource->GetMap());
+
+ if (!door)
+ {
+ sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR (script id: %u) failed for gameobject(guid: %u).", step.script->id, step.script->datalong);
+ break;
+ }
+ if (door->GetGoType() != GAMEOBJECT_TYPE_DOOR)
+ {
+ sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR (script id: %u) failed for non-door(GoType: %u, Entry: %u, GUID: %u).",
+ step.script->id, door->GetGoType(),door->GetEntry(),door->GetGUIDLow());
+ break;
+ }
+
+ if (door->GetGoState() == GO_STATE_READY)
+ break; //door already closed
+
+ door->UseDoorOrButton(time_to_open);
+
+ if (target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType() == GAMEOBJECT_TYPE_BUTTON)
+ ((GameObject*)target)->UseDoorOrButton(time_to_open);
+
+ break;
+ }
+ case SCRIPT_COMMAND_QUEST_EXPLORED:
+ {
+ if (!source)
+ {
+ sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED (script id %u) call for NULL source.", step.script->id);
+ break;
+ }
+
+ if (!target)
+ {
+ sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED (script id %u) call for NULL target.", step.script->id);
+ break;
+ }
+
+ // when script called for item spell casting then target == (unit or GO) and source is player
+ WorldObject* worldObject;
+ Player* pTarget;
+
+ pTarget = target->ToPlayer();
+ if (pTarget)
+ {
+ if (source->GetTypeId() != TYPEID_UNIT && source->GetTypeId() != TYPEID_GAMEOBJECT && source->GetTypeId() != TYPEID_PLAYER)
+ {
+ sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED (script id %u) call for non-creature, non-gameobject or non-player (TypeId: %u), skipping.",
+ step.script->id, source->GetTypeId());
+ break;
+ }
+
+ worldObject = (WorldObject*)source;
+ }
+ else
+ {
+ if (target->GetTypeId() != TYPEID_UNIT && target->GetTypeId() != TYPEID_GAMEOBJECT && target->GetTypeId() != TYPEID_PLAYER)
+ {
+ sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED (script id %u) call for non-creature, non-gameobject or non-player (TypeId: %u), skipping.",
+ step.script->id, target->GetTypeId());
+ break;
+ }
+
+ pTarget = source->ToPlayer();
+ if (!pTarget)
+ {
+ sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED (script id %u) call for non-player (TypeId: %u), skipping.", step.script->id, source->GetTypeId());
+ break;
+ }
+
+ worldObject = (WorldObject*)target;
+ }
+
+ // quest id and flags checked at script loading
+ if ((worldObject->GetTypeId() != TYPEID_UNIT || ((Unit*)worldObject)->isAlive()) &&
+ (step.script->datalong2 == 0 || worldObject->IsWithinDistInMap(pTarget, float(step.script->datalong2))))
+ pTarget->AreaExploredOrEventHappens(step.script->datalong);
+ else
+ pTarget->FailQuest(step.script->datalong);
+
+ break;
+ }
+
+ case SCRIPT_COMMAND_ACTIVATE_OBJECT:
+ {
+ if (!source)
+ {
+ sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT (script id: %u) must have source caster.", step.script->id);
+ break;
+ }
+
+ if (!source->isType(TYPEMASK_UNIT))
+ {
+ sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT (script id: %u) source caster isn't unit (TypeId: %u, Entry: %u, GUID: %u), skipping.",
+ step.script->id, source->GetTypeId(),source->GetEntry(),source->GetGUIDLow());
+ break;
+ }
+
+ if (!target)
+ {
+ sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT (script id: %u) call for NULL gameobject.", step.script->id);
+ break;
+ }
+
+ if (target->GetTypeId() != TYPEID_GAMEOBJECT)
+ {
+ sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT (script id: %u) call for non-gameobject (TypeId: %u, Entry: %u, GUID: %u), skipping.",
+ step.script->id, target->GetTypeId(),target->GetEntry(),target->GetGUIDLow());
+ break;
+ }
+
+ Unit* caster = (Unit*)source;
+
+ GameObject *go = (GameObject*)target;
+
+ go->Use(caster);
+ break;
+ }
+
+ case SCRIPT_COMMAND_REMOVE_AURA:
+ {
+ Object* cmdTarget = step.script->datalong2 ? source : target;
+
+ if (!cmdTarget)
+ {
+ sLog.outError("SCRIPT_COMMAND_REMOVE_AURA (script id: %u) call for NULL %s.", step.script->id, step.script->datalong2 ? "source" : "target");
+ break;
+ }
+
+ if (!cmdTarget->isType(TYPEMASK_UNIT))
+ {
+ sLog.outError("SCRIPT_COMMAND_REMOVE_AURA (script id: %u) %s isn't unit (TypeId: %u, Entry: %u, GUID: %u), skipping.",
+ step.script->id, step.script->datalong2 ? "source" : "target",cmdTarget->GetTypeId(),cmdTarget->GetEntry(),cmdTarget->GetGUIDLow());
+ break;
+ }
+
+ ((Unit*)cmdTarget)->RemoveAurasDueToSpell(step.script->datalong);
+ break;
+ }
+
+ case SCRIPT_COMMAND_CAST_SPELL:
+ {
+ // TODO: Allow gameobjects to be targets and casters
+ if (!source)
+ {
+ sLog.outError("SCRIPT_COMMAND_CAST_SPELL (script id: %u) must have source caster.", step.script->id);
+ break;
+ }
+
+ Unit* uSource = NULL;
+ Unit* uTarget = NULL;
+ // source/target cast spell at target/source (script->datalong2: 0: s->t 1: s->s 2: t->t 3: t->s
+ switch (step.script->datalong2)
+ {
+ case 0: // source -> target
+ uSource = dynamic_cast<Unit*>(source);
+ uTarget = dynamic_cast<Unit*>(target);
+ break;
+ case 1: // source -> source
+ uSource = dynamic_cast<Unit*>(source);
+ uTarget = dynamic_cast<Unit*>(source);
+ break;
+ case 2: // target -> target
+ uSource = dynamic_cast<Unit*>(target);
+ uTarget = dynamic_cast<Unit*>(target);
+ break;
+ case 3: // target -> source
+ uSource = dynamic_cast<Unit*>(target);
+ uTarget = dynamic_cast<Unit*>(source);
+ break;
+ case 4: // creature
+ uSource = dynamic_cast<Unit*>(source);
+ uTarget = GetClosestCreatureWithEntry(uSource, step.script->dataint, step.script->x);
+ break;
+ }
+
+ if (!uSource || !uSource->isType(TYPEMASK_UNIT))
+ {
+ sLog.outError("SCRIPT_COMMAND_CAST_SPELL (script id: %u) no source unit found for spell %u", step.script->id, step.script->datalong);
+ break;
+ }
+
+ if (!uTarget || !uTarget->isType(TYPEMASK_UNIT))
+ {
+ sLog.outError("SCRIPT_COMMAND_CAST_SPELL (script id: %u) no target unit found for spell %u", step.script->id, step.script->datalong);
+ break;
+ }
+
+ uSource->CastSpell(uTarget, step.script->datalong, false);
+ break;
+ }
+
+ case SCRIPT_COMMAND_PLAY_SOUND:
+ {
+ if (!source)
+ {
+ sLog.outError("SCRIPT_COMMAND_PLAY_SOUND (script id: %u) call for NULL creature.", step.script->id);
+ break;
+ }
+
+ WorldObject* pSource = dynamic_cast<WorldObject*>(source);
+ if (!pSource)
+ {
+ sLog.outError("SCRIPT_COMMAND_PLAY_SOUND (script id: %u) call for non-world object (TypeId: %u, Entry: %u, GUID: %u), skipping.",
+ step.script->id, source->GetTypeId(),source->GetEntry(),source->GetGUIDLow());
+ break;
+ }
+
+ // bitmask: 0/1=anyone/target, 0/2=with distance dependent
+ Player* pTarget;
+ if (step.script->datalong2 & 1)
+ {
+ if (!target)
+ {
+ sLog.outError("SCRIPT_COMMAND_PLAY_SOUND (script id: %u) in targeted mode call for NULL target.", step.script->id);
+ break;
+ }
+
+ pTarget = target->ToPlayer();
+ if (!pTarget)
+ {
+ sLog.outError("SCRIPT_COMMAND_PLAY_SOUND (script id: %u) in targeted mode call for non-player (TypeId: %u, Entry: %u, GUID: %u), skipping.",
+ step.script->id, target->GetTypeId(),target->GetEntry(),target->GetGUIDLow());
+ break;
+ }
+ }
+
+ // bitmask: 0/1=anyone/target, 0/2=with distance dependent
+ if (step.script->datalong2 & 2)
+ pSource->PlayDistanceSound(step.script->datalong, pTarget);
+ else
+ pSource->PlayDirectSound(step.script->datalong, pTarget);
+ break;
+ }
+
+ case SCRIPT_COMMAND_CREATE_ITEM:
+ {
+ if (!target && !source)
+ {
+ sLog.outError("SCRIPT_COMMAND_CREATE_ITEM (script id: %u) call for NULL object.", step.script->id);
+ break;
+ }
+
+ Player *pReceiver = target->ToPlayer() != NULL ? target->ToPlayer() : source->ToPlayer();
+ // only Player
+ if (!pReceiver)
+ {
+ sLog.outError("SCRIPT_COMMAND_CREATE_ITEM (script id: %u) call for non-player (TypeIdSource: %u)(TypeIdTarget: %u), skipping.",
+ step.script->id, source ? source->GetTypeId() : 0, target ? target->GetTypeId() : 0);
+ break;
+ }
+
+ ItemPosCountVec dest;
+ uint8 msg = pReceiver->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, step.script->datalong, step.script->datalong2);
+ if (msg == EQUIP_ERR_OK)
+ {
+ if (Item* item = pReceiver->StoreNewItem(dest, step.script->datalong, true))
+ pReceiver->SendNewItem(item, step.script->datalong2, false, true);
+ }
+ else
+ pReceiver->SendEquipError(msg,NULL,NULL);
+
+ break;
+ }
+
+ case SCRIPT_COMMAND_DESPAWN_SELF:
+ {
+ if (!target && !source)
+ {
+ sLog.outError("SCRIPT_COMMAND_DESPAWN_SELF (script id: %u) call for NULL object.", step.script->id);
+ break;
+ }
+
+ Creature* cSource = target->ToCreature();
+ // only creature
+ if (!cSource)
+ {
+ sLog.outError("SCRIPT_COMMAND_DESPAWN_SELF (script id: %u) call for non-creature (TypeIdSource: %u)(TypeIdTarget: %u), skipping.",
+ step.script->id, source ? source->GetTypeId() : 0, target ? target->GetTypeId() : 0);
+ break;
+ }
+
+ cSource->ForcedDespawn(step.script->datalong);
+ break;
+ }
+
+ case SCRIPT_COMMAND_LOAD_PATH:
+ {
+ if (!source)
+ {
+ sLog.outError("SCRIPT_COMMAND_START_MOVE (script id: %u) cannot be applied to NON-existing unit.", step.script->id);
+ break;
+ }
+
+ if (!source->isType(TYPEMASK_UNIT))
+ {
+ sLog.outError("SCRIPT_COMMAND_START_MOVE (script id: %u) source mover isn't unit (TypeId: %u, Entry: %u, GUID: %u), skipping.",
+ step.script->id, source->GetTypeId(),source->GetEntry(),source->GetGUIDLow());
+ break;
+ }
+
+ if (!sWaypointMgr->GetPath(step.script->datalong))
+ {
+ sLog.outError("SCRIPT_COMMAND_START_MOVE (script id: %u) source mover has an invalid path, skipping.", step.script->id, step.script->datalong2);
+ break;
+ }
+
+ ((Unit*)source)->GetMotionMaster()->MovePath(step.script->datalong, step.script->datalong2);
+ break;
+ }
+
+ case SCRIPT_COMMAND_CALLSCRIPT_TO_UNIT:
+ {
+ if (!step.script->datalong || !step.script->datalong2)
+ {
+ sLog.outError("SCRIPT_COMMAND_CALLSCRIPT (script id: %u) calls invalid db_script_id or lowguid not present: skipping.", step.script->id);
+ break;
+ }
+
+ Creature* cTarget;
+ if (source) //using grid searcher
+ {
+ WorldObject* wSource = (WorldObject*)source;
+ CellPair p(Trinity::ComputeCellPair(wSource->GetPositionX(), wSource->GetPositionY()));
+ Cell cell(p);
+ cell.data.Part.reserved = ALL_DISTRICT;
+
+ Trinity::CreatureWithDbGUIDCheck target_check(wSource, step.script->datalong);
+ Trinity::CreatureSearcher<Trinity::CreatureWithDbGUIDCheck> checker(wSource, cTarget, target_check);
+
+ TypeContainerVisitor<Trinity::CreatureSearcher <Trinity::CreatureWithDbGUIDCheck>, GridTypeMapContainer > unit_checker(checker);
+ cell.Visit(p, unit_checker, *wSource->GetMap());
+ }
+ else //check hashmap holders
+ {
+ if (CreatureData const* data = objmgr.GetCreatureData(step.script->datalong))
+ cTarget = ObjectAccessor::GetObjectInWorld<Creature>(data->mapid, data->posX, data->posY, MAKE_NEW_GUID(step.script->datalong, data->id, HIGHGUID_UNIT), cTarget);
+ }
+
+ if (!cTarget)
+ {
+ sLog.outError("SCRIPT_COMMAND_CALLSCRIPT (script id: %u) target not found, creature entry %u", step.script->id, step.script->datalong);
+ break;
+ }
+
+ //Lets choose our ScriptMap map
+ ScriptMapMap *datamap = NULL;
+ switch (step.script->dataint)
+ {
+ case 1: //QUEST END SCRIPTMAP
+ datamap = &sQuestEndScripts;
+ break;
+ case 2: //QUEST START SCRIPTMAP
+ datamap = &sQuestStartScripts;
+ break;
+ case 3: //SPELLS SCRIPTMAP
+ datamap = &sSpellScripts;
+ break;
+ case 4: //GAMEOBJECTS SCRIPTMAP
+ datamap = &sGameObjectScripts;
+ break;
+ case 5: //EVENTS SCRIPTMAP
+ datamap = &sEventScripts;
+ break;
+ case 6: //WAYPOINTS SCRIPTMAP
+ datamap = &sWaypointScripts;
+ break;
+ default:
+ sLog.outError("SCRIPT_COMMAND_CALLSCRIPT ERROR: no scriptmap present... ignoring");
+ break;
+ }
+ //if no scriptmap present...
+ if (!datamap)
+ break;
+
+ uint32 script_id = step.script->datalong2;
+ //insert script into schedule but do not start it
+ ScriptsStart(*datamap, script_id, cTarget, NULL/*, false*/);
+ break;
+ }
+
+ case SCRIPT_COMMAND_KILL:
+ {
+ // TODO: Allow to kill objects other than self?
+ if (!source)
+ break;
+
+ Creature* cSource = source->ToCreature();
+ if (!cSource)
+ break;
+
+ if (cSource->isDead())
+ {
+ sLog.outError("SCRIPT_COMMAND_KILL (script id: %u) called for already dead creature, entry %u, guidLow %u",
+ step.script->id, cSource->GetEntry(), cSource->GetGUIDLow());
+ break;
+ }
+
+ cSource->setDeathState(JUST_DIED);
+ if (step.script->dataint == 1)
+ cSource->RemoveCorpse();
+
+ break;
+ }
+
+ case SCRIPT_COMMAND_ORIENTATION:
+ {
+ if (!source || !source->isType(TYPEMASK_UNIT))
+ {
+ sLog.outError("SCRIPT_COMMAND_ORIENTATION (script id: %u) call for NULL or non-unit source.", step.script->id);
+ break;
+ }
+
+ Unit* uSource = (Unit*)source;
+
+ if (!step.script->datalong)
+ uSource->SetOrientation(step.script->o);
+ else
+ {
+ if (!target || !target->isType(TYPEMASK_UNIT))
+ {
+ sLog.outError("SCRIPT_COMMAND_ORIENTATION (script id: %u) call for NULL or non-unit target.", step.script->id);
+ break;
+ }
+ uSource->SetInFront((Unit*)target);
+ }
+
+ uSource->SendMovementFlagUpdate();
+ break;
+ }
+ case SCRIPT_COMMAND_EQUIP:
+ {
+ if (!source)
+ {
+ sLog.outError("SCRIPT_COMMAND_EQUIP (script id: %u) call for NULL source.", step.script->id);
+ break;
+ }
+
+ Creature* cSource = source->ToCreature();
+ if (!cSource)
+ {
+ sLog.outError("SCRIPT_COMMAND_EQUIP (script id: %u) call, source is non-creature.", step.script->id);
+ break;
+ }
+
+ cSource->LoadEquipment(step.script->datalong);
+ break;
+ }
+ case SCRIPT_COMMAND_MODEL:
+ {
+ if (!source)
+ {
+ sLog.outError("SCRIPT_COMMAND_EQUIP (script id: %u) call for NULL source.", step.script->id);
+ break;
+ }
+
+ Creature* cSource = source->ToCreature();
+ if (!cSource)
+ {
+ sLog.outError("SCRIPT_COMMAND_EQUIP (script id: %u) call, source is non-creature.", step.script->id);
+ break;
+ }
+
+ cSource->SetDisplayId(step.script->datalong);
+ break;
+ }
+
+ case SCRIPT_COMMAND_CLOSE_GOSSIP:
+ {
+ if (!source)
+ {
+ sLog.outError("SCRIPT_COMMAND_CLOSE_GOSSIP (script id: %u) for null source", step.script->id);
+ break;
+ }
+
+ Player *pSource = source->ToPlayer();
+ if (!pSource)
+ {
+ sLog.outError("SCRIPT_COMMAND_CLOSE_GOSSIP (script id: %u) for non-player source.", step.script->id);
+ break;
+ }
+
+ pSource->PlayerTalkClass->CloseGossip();
+ break;
+ }
+
+ case SCRIPT_COMMAND_PLAYMOVIE:
+ {
+ if (!source)
+ {
+ sLog.outError("SCRIPT_COMMAND_PLAYMOVIE (script id: %u) call for NULL source.", step.script->id);
+ break;
+ }
+
+ Player* pSource = source->ToPlayer();
+ if (!pSource)
+ {
+ sLog.outError("SCRIPT_COMMAND_PLAYMOVIE (script id: %u) call for non-player source.", step.script->id);
+ break;
+ }
+ pSource->SendMovieStart(step.script->datalong);
+ break;
+ }
+
+ default:
+ sLog.outError("Unknown script command %u called.", step.script->command);
+ break;
+ }
+
+ m_scriptSchedule.erase(iter);
+ sWorld.DecreaseScheduledScriptCount();
+
+ iter = m_scriptSchedule.begin();
+ }
+}
+
+Creature*
+Map::GetCreature(uint64 guid)
+{
+ Creature * ret = NULL;
+ if (IS_CRE_OR_VEH_GUID(guid))
+ ret = ObjectAccessor::GetObjectInWorld(guid, (Creature*)NULL);
+
+ if (!ret)
+ return NULL;
+
+ if (ret->GetMapId() != GetId())
+ return NULL;
+
+ if (ret->GetInstanceId() != GetInstanceId())
+ return NULL;
+
+ return ret;
+}
+
+GameObject*
+Map::GetGameObject(uint64 guid)
+{
+ GameObject * ret = ObjectAccessor::GetObjectInWorld(guid, (GameObject*)NULL);
+ if (!ret)
+ return NULL;
+ if (ret->GetMapId() != GetId())
+ return NULL;
+ if (ret->GetInstanceId() != GetInstanceId())
+ return NULL;
+ return ret;
+}
+
+DynamicObject*
+Map::GetDynamicObject(uint64 guid)
+{
+ DynamicObject * ret = ObjectAccessor::GetObjectInWorld(guid, (DynamicObject*)NULL);
+ if (!ret)
+ return NULL;
+ if (ret->GetMapId() != GetId())
+ return NULL;
+ if (ret->GetInstanceId() != GetInstanceId())
+ return NULL;
+ return ret;
+}
+
+void Map::UpdateIteratorBack(Player *player)
+{
+ if (m_mapRefIter == player->GetMapRef())
+ m_mapRefIter = m_mapRefIter->nocheck_prev();
+}
diff --git a/src/server/game/Map/Map.h b/src/server/game/Map/Map.h
new file mode 100644
index 00000000000..ceb526b8244
--- /dev/null
+++ b/src/server/game/Map/Map.h
@@ -0,0 +1,689 @@
+/*
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
+ *
+ * Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
+ *
+ * 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, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef TRINITY_MAP_H
+#define TRINITY_MAP_H
+
+#include "Platform/Define.h"
+#include "Policies/ThreadingModel.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 "GameSystem/GridRefManager.h"
+#include "MapRefManager.h"
+#include "mersennetwister/MersenneTwister.h"
+
+#include <bitset>
+#include <list>
+
+class Unit;
+class WorldPacket;
+class InstanceData;
+class Group;
+class InstanceSave;
+class Object;
+class WorldObject;
+class TempSummon;
+class Player;
+class CreatureGroup;
+struct ScriptInfo;
+struct ScriptAction;
+struct Position;
+class BattleGround;
+
+//******************************************
+// Map file format defines
+//******************************************
+#define MAP_MAGIC 'SPAM'
+#define MAP_VERSION_MAGIC '0.1w'
+#define MAP_AREA_MAGIC 'AERA'
+#define MAP_HEIGHT_MAGIC 'TGHM'
+#define MAP_LIQUID_MAGIC 'QILM'
+
+struct map_fileheader
+{
+ uint32 mapMagic;
+ uint32 versionMagic;
+ 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;
+ float level;
+ float depth_level;
+};
+
+class GridMap
+{
+ uint32 m_flags;
+ // Area data
+ uint16 m_gridArea;
+ uint16 *m_area_map;
+ // Height level data
+ float m_gridHeight;
+ float m_gridIntHeightMultiplier;
+ union{
+ float *m_V9;
+ uint16 *m_uint16_V9;
+ uint8 *m_uint8_V9;
+ };
+ union{
+ float *m_V8;
+ uint16 *m_uint16_V8;
+ uint8 *m_uint8_V8;
+ };
+ // Liquid data
+ uint16 m_liquidType;
+ uint8 m_liquid_offX;
+ uint8 m_liquid_offY;
+ uint8 m_liquid_width;
+ uint8 m_liquid_height;
+ float m_liquidLevel;
+ uint8 *m_liquid_type;
+ float *m_liquid_map;
+
+ bool loadAreaData(FILE *in, uint32 offset, uint32 size);
+ bool loadHeihgtData(FILE *in, uint32 offset, uint32 size);
+ bool loadLiquidData(FILE *in, uint32 offset, uint32 size);
+
+ // Get height functions and pointers
+ typedef float (GridMap::*pGetHeightPtr) (float x, float y) const;
+ pGetHeightPtr m_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);
+ inline float getHeight(float x, float y) {return (this->*m_gridGetHeight)(x, y);}
+ float getLiquidLevel(float x, float y);
+ uint8 getTerrainType(float x, float y);
+ ZLiquidStatus getLiquidStatus(float x, float y, float z, uint8 ReqLiquidType, LiquidData *data = 0);
+};
+
+struct CreatureMover
+{
+ CreatureMover() : x(0), y(0), z(0), ang(0) {}
+ CreatureMover(float _x, float _y, float _z, float _ang) : x(_x), y(_y), z(_z), ang(_ang) {}
+
+ float x, y, z, ang;
+};
+
+// 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 map;
+ uint32 parent;
+ uint32 access_id;
+ float startLocX;
+ float startLocY;
+ float startLocZ;
+ float startLocO;
+ uint32 script_id;
+ bool allowMount;
+};
+
+enum LevelRequirementVsMode
+{
+ LEVELREQUIREMENT_HEROIC = 70
+};
+
+#if defined(__GNUC__)
+#pragma pack()
+#else
+#pragma pack(pop)
+#endif
+
+typedef UNORDERED_MAP<Creature*, CreatureMover> CreatureMoveList;
+
+#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 MIN_UNLOAD_DELAY 1 // immediate unload
+
+typedef std::map<uint32/*leaderDBGUID*/, CreatureGroup*> CreatureGroupHolderType;
+
+class Map : public GridRefManager<NGridType>, public Trinity::ObjectLevelLockable<Map, ACE_Thread_Mutex>
+{
+ friend class MapReference;
+ public:
+ Map(uint32 id, time_t, uint32 InstanceId, uint8 SpawnMode, Map* _parent = NULL);
+ virtual ~Map();
+
+ // 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 Add(Player *);
+ virtual void Remove(Player *, bool);
+ template<class T> void Add(T *);
+ template<class T> void Remove(T *, bool);
+
+ virtual void Update(const uint32&);
+
+ /*
+ void MessageBroadcast(Player *, WorldPacket *, bool to_self);
+ void MessageBroadcast(WorldObject *, WorldPacket *);
+ void MessageDistBroadcast(Player *, WorldPacket *, float dist, bool to_self, bool own_team_only = false);
+ void MessageDistBroadcast(WorldObject *, WorldPacket *, float dist);
+ */
+
+ float GetVisibilityDistance() const { return m_VisibleDistance; }
+ //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 orientation);
+ void CreatureRelocation(Creature *creature, float x, float y, float z, float ang);
+
+ template<class T, class CONTAINER> void Visit(const Cell& cell, TypeContainerVisitor<T, CONTAINER> &visitor);
+
+ bool IsRemovalGrid(float x, float y) const
+ {
+ GridPair p = Trinity::ComputeGridPair(x, y);
+ return !getNGrid(p.x_coord, p.y_coord) || getNGrid(p.x_coord, p.y_coord)->GetGridState() == GRID_STATE_REMOVAL;
+ }
+
+ bool IsLoaded(float x, float y) const
+ {
+ GridPair p = Trinity::ComputeGridPair(x, y);
+ return loaded(p);
+ }
+
+ bool GetUnloadLock(const GridPair &p) const { return getNGrid(p.x_coord, p.y_coord)->getUnloadLock(); }
+ void SetUnloadLock(const GridPair &p, bool on) { getNGrid(p.x_coord, p.y_coord)->setUnloadExplicitLock(on); }
+ void LoadGrid(float x, float y);
+ bool UnloadGrid(const uint32 &x, const uint32 &y, bool pForce);
+ virtual void UnloadAll();
+
+ void ResetGridExpiry(NGridType &grid, float factor = 1) const
+ {
+ grid.ResetTimeTracker(time_t(float(i_gridExpiry)*factor));
+ }
+
+ time_t GetGridExpiry(void) const { return i_gridExpiry; }
+ 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);
+
+ static void InitStateMachine();
+ static void DeleteStateMachine();
+
+ Map const * GetParent() const { return m_parentMap; }
+
+ // 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 pCheckVMap=true) const;
+
+ 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 RemoveAllObjectsInRemoveList();
+ virtual void RemoveAllPlayers();
+
+ bool CreatureRespawnRelocation(Creature *c); // used only in MoveAllCreaturesInMoveList and ObjectGridUnloader
+
+ // assert print helper
+ bool CheckGridIntegrity(Creature* c, bool moved) const;
+
+ uint32 GetInstanceId() const { return i_InstanceId; }
+ uint8 GetSpawnMode() const { return (i_spawnMode); }
+ virtual bool CanEnter(Player* /*player*/) { 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(); }
+ // NOTE: this duplicate of Instanceable(), but Instanceable() can be changed when BG also will be 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 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);
+
+ virtual bool RemoveBones(uint64 guid, float x, float y);
+
+ void UpdateObjectVisibility(WorldObject* obj, Cell cell, CellPair cellpair);
+ void UpdateObjectsVisibilityFor(Player* player, Cell cell, CellPair 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;
+ bool ActiveObjectsNearGrid(uint32 x, uint32 y) 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) { AddToActiveHelper(obj); }
+
+ void AddToActive(Creature* obj);
+
+ // must called with RemoveFromWorld
+ template<class T>
+ void RemoveFromActive(T* obj) { RemoveFromActiveHelper(obj); }
+
+ void RemoveFromActive(Creature* obj);
+
+ template<class T> void SwitchGridContainers(T* obj, bool active);
+ template<class NOTIFIER> void VisitAll(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);
+
+#ifdef MAP_BASED_RAND_GEN
+ MTRand mtRand;
+ int32 irand(int32 min, int32 max) { return int32 (mtRand.randInt(max - min)) + min; }
+ uint32 urand(uint32 min, uint32 max) { return mtRand.randInt(max - min) + min; }
+ int32 rand32() { return mtRand.randInt(); }
+ double rand_norm() { return mtRand.randExc(); }
+ double rand_chance() { return mtRand.randExc(100.0); }
+#endif
+
+ TempSummon *SummonCreature(uint32 entry, const Position &pos, SummonPropertiesEntry const *properties = NULL, uint32 duration = 0, Unit *summoner = NULL, uint32 vehId = 0);
+ Creature* GetCreature(uint64 guid);
+ GameObject* GetGameObject(uint64 guid);
+ DynamicObject* GetDynamicObject(uint64 guid);
+ private:
+ void LoadMapAndVMap(int gx, int gy);
+ void LoadVMap(int gx, int gy);
+ void LoadMap(int gx,int gy, bool reload = false);
+ GridMap *GetGrid(float x, float y);
+
+ void SetTimer(uint32 t) { i_gridExpiry = t < MIN_GRID_DELAY ? MIN_GRID_DELAY : t; }
+
+ void SendInitSelf(Player * player);
+
+ void SendInitTransports(Player * player);
+ void SendRemoveTransports(Player * player);
+
+ bool CreatureCellRelocation(Creature *creature, Cell new_cell);
+
+ void AddCreatureToMoveList(Creature *c, float x, float y, float z, float ang);
+ CreatureMoveList i_creaturesToMove;
+
+ bool loaded(const GridPair &) const;
+ void EnsureGridCreated(const GridPair &);
+ bool EnsureGridLoaded(Cell const&);
+ void EnsureGridLoadedAtEnter(Cell const&, Player* player = NULL);
+
+ void buildNGridLinkage(NGridType* pNGridType) { pNGridType->link(this); }
+
+ template<class T> void AddType(T *obj);
+ template<class T> void RemoveType(T *obj, bool);
+
+ NGridType* getNGrid(uint32 x, uint32 y) const
+ {
+ ASSERT(x < MAX_NUMBER_OF_GRIDS);
+ ASSERT(y < MAX_NUMBER_OF_GRIDS);
+ return i_grids[x][y];
+ }
+
+ 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:
+ void SetUnloadReferenceLock(const GridPair &p, bool on) { getNGrid(p.x_coord, p.y_coord)->setUnloadReferenceLock(on); }
+
+ typedef Trinity::ObjectLevelLockable<Map, ACE_Thread_Mutex>::Lock Guard;
+
+ MapEntry const* i_mapEntry;
+ uint8 i_spawnMode;
+ uint32 i_InstanceId;
+ uint32 m_unloadTimer;
+ float m_VisibleDistance;
+
+ MapRefManager m_mapRefManager;
+ MapRefManager::iterator m_mapRefIter;
+
+ int32 m_VisibilityNotifyPeriod;
+
+ typedef std::set<WorldObject*> ActiveNonPlayers;
+ ActiveNonPlayers m_activeNonPlayers;
+ ActiveNonPlayers::iterator m_activeNonPlayersIter;
+
+ private:
+ time_t i_gridExpiry;
+
+ //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;
+
+ //these functions used to process player/mob aggro reactions and
+ //visibility calculations. Highly optimized for massive calculations
+ void ProcessRelocationNotifies(const uint32 &diff);
+
+ bool i_scriptLock;
+ std::set<WorldObject *> i_objectsToRemove;
+ std::map<WorldObject*, bool> i_objectsToSwitch;
+ std::set<WorldObject*> i_worldObjects;
+ std::multimap<time_t, ScriptAction> m_scriptSchedule;
+
+ // Type specific code for add/remove to/from grid
+ template<class T>
+ void AddToGrid(T*, NGridType *, Cell const&);
+
+ template<class T>
+ void RemoveFromGrid(T*, NGridType *, Cell const&);
+
+ template<class T>
+ void DeleteFromWorld(T*);
+
+ template<class T>
+ void AddToActiveHelper(T* obj)
+ {
+ m_activeNonPlayers.insert(obj);
+ }
+
+ template<class T>
+ void RemoveFromActiveHelper(T* 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);
+ }
+};
+
+enum InstanceResetMethod
+{
+ INSTANCE_RESET_ALL,
+ INSTANCE_RESET_CHANGE_DIFFICULTY,
+ INSTANCE_RESET_GLOBAL,
+ INSTANCE_RESET_GROUP_DISBAND,
+ INSTANCE_RESET_GROUP_JOIN,
+ INSTANCE_RESET_RESPAWN_DELAY
+};
+
+class InstanceMap : public Map
+{
+ public:
+ InstanceMap(uint32 id, time_t, uint32 InstanceId, uint8 SpawnMode, Map* _parent);
+ ~InstanceMap();
+ bool Add(Player *);
+ void Remove(Player *, bool);
+ void Update(const uint32&);
+ void CreateInstanceData(bool load);
+ bool Reset(uint8 method);
+ uint32 GetScriptId() { return i_script_id; }
+ InstanceData* GetInstanceData() { return i_data; }
+ void PermBindAllPlayers(Player *player);
+ void UnloadAll();
+ bool CanEnter(Player* player);
+ void SendResetWarnings(uint32 timeLeft) const;
+ void SetResetSchedule(bool on);
+
+ uint32 GetMaxPlayers() const;
+ uint32 GetMaxResetDelay() const;
+
+ virtual void InitVisibilityDistance();
+ private:
+ bool m_resetAfterUnload;
+ bool m_unloadWhenEmpty;
+ InstanceData* i_data;
+ uint32 i_script_id;
+};
+
+class BattleGroundMap : public Map
+{
+ public:
+ BattleGroundMap(uint32 id, time_t, uint32 InstanceId, Map* _parent, uint8 spawnMode);
+ ~BattleGroundMap();
+
+ bool Add(Player *);
+ void Remove(Player *, bool);
+ bool CanEnter(Player* player);
+ 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;
+};
+
+/*inline
+uint64
+Map::CalculateGridMask(const uint32 &y) const
+{
+ uint64 mask = 1;
+ mask <<= y;
+ return mask;
+}
+*/
+
+template<class T, class CONTAINER>
+inline void
+Map::Visit(const Cell& 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() || loaded(GridPair(x,y)))
+ {
+ EnsureGridLoaded(cell);
+ getNGrid(x, y)->Visit(cell_x, cell_y, visitor);
+ }
+}
+
+template<class NOTIFIER>
+inline void
+Map::VisitAll(const float &x, const float &y, float radius, NOTIFIER &notifier)
+{
+ CellPair p(Trinity::ComputeCellPair(x, y));
+ Cell cell(p);
+ cell.data.Part.reserved = ALL_DISTRICT;
+ 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);
+}
+
+template<class NOTIFIER>
+inline void
+Map::VisitWorld(const float &x, const float &y, float radius, NOTIFIER &notifier)
+{
+ CellPair p(Trinity::ComputeCellPair(x, y));
+ Cell cell(p);
+ cell.data.Part.reserved = ALL_DISTRICT;
+ 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)
+{
+ CellPair p(Trinity::ComputeCellPair(x, y));
+ Cell cell(p);
+ cell.data.Part.reserved = ALL_DISTRICT;
+ cell.SetNoCreate();
+
+ TypeContainerVisitor<NOTIFIER, GridTypeMapContainer > grid_object_notifier(notifier);
+ cell.Visit(p, grid_object_notifier, *this, radius, x, y);
+}
+#endif
diff --git a/src/server/game/Map/MapInstanced.cpp b/src/server/game/Map/MapInstanced.cpp
new file mode 100644
index 00000000000..0736bfa6fb3
--- /dev/null
+++ b/src/server/game/Map/MapInstanced.cpp
@@ -0,0 +1,268 @@
+/*
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
+ *
+ * Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
+ *
+ * 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, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "MapInstanced.h"
+#include "ObjectMgr.h"
+#include "MapManager.h"
+#include "BattleGround.h"
+#include "VMapFactory.h"
+#include "InstanceSaveMgr.h"
+#include "World.h"
+
+MapInstanced::MapInstanced(uint32 id, time_t expiry) : Map(id, expiry, 0, DUNGEON_DIFFICULTY_NORMAL)
+{
+ // initialize instanced maps list
+ m_InstancedMaps.clear();
+ // fill with zero
+ memset(&GridMapReference, 0, MAX_NUMBER_OF_GRIDS*MAX_NUMBER_OF_GRIDS*sizeof(uint16));
+}
+
+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)
+{
+ // take care of loaded GridMaps (when unused, unload it!)
+ Map::Update(t);
+
+ // 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
+ i->second->Update(t);
+ ++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();
+}
+*/
+
+bool MapInstanced::RemoveBones(uint64 guid, float x, float y)
+{
+ bool remove_result = false;
+
+ for (InstancedMaps::iterator i = m_InstancedMaps.begin(); i != m_InstancedMaps.end(); ++i)
+ {
+ remove_result = remove_result || i->second->RemoveBones(guid, x, y);
+ }
+
+ return remove_result || Map::RemoveBones(guid,x,y);
+}
+
+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::CreateInstance(const uint32 mapId, Player * player)
+{
+ if (GetId() != mapId || !player)
+ return NULL;
+
+ Map* map = NULL;
+ uint32 NewInstanceId = 0; // instanceId of the resulting map
+
+ if (IsBattleGroundOrArena())
+ {
+ // instantiate or find existing bg map for player
+ // the instance id is set in battlegroundid
+ NewInstanceId = player->GetBattleGroundId();
+ if (!NewInstanceId) return NULL;
+ map = _FindMap(NewInstanceId);
+ if (!map)
+ map = CreateBattleGround(NewInstanceId, player->GetBattleGround());
+ }
+ else
+ {
+ InstancePlayerBind *pBind = player->GetBoundInstance(GetId(), player->GetDifficulty(IsRaid()));
+ InstanceSave *pSave = pBind ? pBind->save : NULL;
+
+ // the player's permanent player bind is taken into consideration first
+ // then the player's group bind and finally the solo bind.
+ if (!pBind || !pBind->perm)
+ {
+ InstanceGroupBind *groupBind = NULL;
+ Group *group = player->GetGroup();
+ // use the player's difficulty setting (it may not be the same as the group's)
+ if (group)
+ {
+ groupBind = group->GetBoundInstance(this);
+ if (groupBind)
+ pSave = groupBind->save;
+ }
+ }
+ if (pSave)
+ {
+ // solo/perm/group
+ NewInstanceId = pSave->GetInstanceId();
+ map = _FindMap(NewInstanceId);
+ // it is possible that the save exists but the map doesn't
+ if (!map)
+ map = CreateInstance(NewInstanceId, pSave, pSave->GetDifficulty());
+ }
+ else
+ {
+ // if no instanceId via group members or instance saves is found
+ // the instance will be created for the first time
+ NewInstanceId = MapManager::Instance().GenerateInstanceId();
+
+ 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
+ Guard guard(*this);
+
+ // 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 = objmgr.GetInstanceTemplate(GetId());
+ if (!iTemplate)
+ {
+ sLog.outError("CreateInstance: no instance template for map %d", GetId());
+ assert(false);
+ }
+
+ // some instances only have one difficulty
+ MapDifficulty const* mapDiff = GetMapDifficultyData(GetId(),difficulty);
+ if (!mapDiff)
+ difficulty = DUNGEON_DIFFICULTY_NORMAL;
+
+ sLog.outDebug("MapInstanced::CreateInstance: %s map instance %d for %d created with difficulty %s", save?"":"new ", InstanceId, GetId(), difficulty?"heroic":"normal");
+
+ InstanceMap *map = new InstanceMap(GetId(), GetGridExpiry(), InstanceId, difficulty, this);
+ ASSERT(map->IsDungeon());
+
+ bool load_data = save != NULL;
+ map->CreateInstanceData(load_data);
+
+ m_InstancedMaps[InstanceId] = map;
+ return map;
+}
+
+BattleGroundMap* MapInstanced::CreateBattleGround(uint32 InstanceId, BattleGround* bg)
+{
+ // load/create a map
+ Guard guard(*this);
+
+ sLog.outDebug("MapInstanced::CreateBattleGround: map bg %d for %d created.", InstanceId, GetId());
+
+ PvPDifficultyEntry const* bracketEntry = GetBattlegroundBracketByLevel(bg->GetMapId(),bg->GetMinLevel());
+
+ uint8 spawnMode = bracketEntry ? bracketEntry->difficulty : REGULAR_DIFFICULTY;
+
+ BattleGroundMap *map = new BattleGroundMap(GetId(), GetGridExpiry(), 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();
+ // should only unload VMaps if this is the last instance and grid unloading is enabled
+ if (m_InstancedMaps.size() <= 1 && sWorld.getConfig(CONFIG_GRID_UNLOAD))
+ {
+ VMAP::VMapFactory::createOrGetVMapManager()->unloadMap(itr->second->GetId());
+ // in that case, unload grids of the base map, too
+ // so in the next map creation, (EnsureGridCreated actually) VMaps will be reloaded
+ Map::UnloadAll();
+ }
+ // erase map
+ delete itr->second;
+ m_InstancedMaps.erase(itr++);
+ return true;
+}
+
+bool MapInstanced::CanEnter(Player * /*player*/)
+{
+ //assert(false);
+ return true;
+}
diff --git a/src/server/game/Map/MapInstanced.h b/src/server/game/Map/MapInstanced.h
new file mode 100644
index 00000000000..536257da011
--- /dev/null
+++ b/src/server/game/Map/MapInstanced.h
@@ -0,0 +1,80 @@
+/*
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
+ *
+ * Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
+ *
+ * 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, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#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, time_t expiry);
+ ~MapInstanced() {}
+
+ // functions overwrite Map versions
+ void Update(const uint32&);
+ void DelayedUpdate(const uint32 diff);
+ //void RelocationNotify();
+ bool RemoveBones(uint64 guid, float x, float y);
+ void UnloadAll();
+ bool CanEnter(Player* player);
+
+ Map* CreateInstance(const uint32 mapId, Player * player);
+ Map* FindMap(uint32 InstanceId) const { return _FindMap(InstanceId); }
+ bool DestroyInstance(InstancedMaps::iterator &itr);
+
+ void AddGridMapReference(const GridPair &p)
+ {
+ ++GridMapReference[p.x_coord][p.y_coord];
+ SetUnloadReferenceLock(GridPair(63-p.x_coord, 63-p.y_coord), true);
+ }
+
+ void RemoveGridMapReference(GridPair const& p)
+ {
+ --GridMapReference[p.x_coord][p.y_coord];
+ if (!GridMapReference[p.x_coord][p.y_coord])
+ SetUnloadReferenceLock(GridPair(63-p.x_coord, 63-p.y_coord), false);
+ }
+
+ 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;
+
+ Map* _FindMap(uint32 InstanceId) const
+ {
+ InstancedMaps::const_iterator i = m_InstancedMaps.find(InstanceId);
+ return(i == m_InstancedMaps.end() ? NULL : i->second);
+ }
+
+ uint16 GridMapReference[MAX_NUMBER_OF_GRIDS][MAX_NUMBER_OF_GRIDS];
+};
+#endif
diff --git a/src/server/game/Map/MapManager.cpp b/src/server/game/Map/MapManager.cpp
new file mode 100644
index 00000000000..de3d0ebbaff
--- /dev/null
+++ b/src/server/game/Map/MapManager.cpp
@@ -0,0 +1,395 @@
+/*
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
+ *
+ * Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
+ *
+ * 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, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "MapManager.h"
+#include "InstanceSaveMgr.h"
+#include "Policies/SingletonImp.h"
+#include "Database/DatabaseEnv.h"
+#include "Log.h"
+#include "ObjectAccessor.h"
+#include "Transports.h"
+#include "GridDefines.h"
+#include "MapInstanced.h"
+#include "InstanceData.h"
+#include "DestinationHolderImp.h"
+#include "Config/ConfigEnv.h"
+#include "World.h"
+#include "CellImpl.h"
+#include "Corpse.h"
+#include "ObjectMgr.h"
+#include "Language.h"
+#include "WorldPacket.h"
+
+#define CLASS_LOCK Trinity::ClassLevelLockable<MapManager, ACE_Thread_Mutex>
+INSTANTIATE_SINGLETON_2(MapManager, CLASS_LOCK);
+INSTANTIATE_CLASS_MUTEX(MapManager, ACE_Thread_Mutex);
+
+extern GridState* si_GridStates[]; // debugging code, should be deleted some day
+
+MapManager::MapManager()
+{
+ i_gridCleanUpDelay = sWorld.getConfig(CONFIG_INTERVAL_GRIDCLEAN);
+ i_timer.SetInterval(sWorld.getConfig(CONFIG_INTERVAL_MAPUPDATE));
+}
+
+MapManager::~MapManager()
+{
+ for (MapMapType::iterator iter=i_maps.begin(); iter != i_maps.end(); ++iter)
+ delete iter->second;
+
+ for (TransportSet::iterator i = m_Transports.begin(); i != m_Transports.end(); ++i)
+ delete *i;
+
+ Map::DeleteStateMachine();
+}
+
+void MapManager::Initialize()
+{
+ Map::InitStateMachine();
+
+ // debugging code, should be deleted some day
+ {
+ for (uint8 i = 0; i < MAX_GRID_STATE; ++i)
+ i_GridStates[i] = si_GridStates[i];
+
+ i_GridStateErrorCount = 0;
+ }
+ int num_threads(sWorld.getConfig(CONFIG_NUMTHREADS));
+ // Start mtmaps if needed.
+ if (num_threads > 0 && m_updater.activate(num_threads) == -1)
+ abort();
+
+ InitMaxInstanceId();
+}
+
+void MapManager::InitializeVisibilityDistanceInfo()
+{
+ for (MapMapType::iterator iter=i_maps.begin(); iter != i_maps.end(); ++iter)
+ (*iter).second->InitVisibilityDistance();
+}
+
+// debugging code, should be deleted some day
+void MapManager::checkAndCorrectGridStatesArray()
+{
+ bool ok = true;
+ for (int i=0; i<MAX_GRID_STATE; i++)
+ {
+ if (i_GridStates[i] != si_GridStates[i])
+ {
+ sLog.outError("MapManager::checkGridStates(), GridState: si_GridStates is currupt !!!");
+ ok = false;
+ si_GridStates[i] = i_GridStates[i];
+ }
+ #ifdef TRINITY_DEBUG
+ // inner class checking only when compiled with debug
+ if (!si_GridStates[i]->checkMagic())
+ {
+ ok = false;
+ si_GridStates[i]->setMagic();
+ }
+ #endif
+ }
+ if (!ok)
+ ++i_GridStateErrorCount;
+}
+
+Map* MapManager::_createBaseMap(uint32 id)
+{
+ Map *m = _findMap(id);
+
+ if (m == NULL)
+ {
+ Guard guard(*this);
+
+ const MapEntry* entry = sMapStore.LookupEntry(id);
+ if (entry && entry->Instanceable())
+ {
+ m = new MapInstanced(id, i_gridCleanUpDelay);
+ }
+ else
+ {
+ m = new Map(id, i_gridCleanUpDelay, 0, REGULAR_DIFFICULTY);
+ }
+ i_maps[id] = m;
+ }
+
+ assert(m != NULL);
+ return m;
+}
+
+Map* MapManager::CreateMap(uint32 id, const WorldObject* obj, uint32 /*instanceId*/)
+{
+ ASSERT(obj);
+ //if (!obj->IsInWorld()) sLog.outError("GetMap: called for map %d with object (typeid %d, guid %d, mapid %d, instanceid %d) who is not in world!", id, obj->GetTypeId(), obj->GetGUIDLow(), obj->GetMapId(), obj->GetInstanceId());
+ Map *m = _createBaseMap(id);
+
+ if (m && (obj->GetTypeId() == TYPEID_PLAYER) && m->Instanceable()) m = ((MapInstanced*)m)->CreateInstance(id, (Player*)obj);
+
+ return m;
+}
+
+Map* MapManager::FindMap(uint32 mapid, uint32 instanceId) const
+{
+ Map *map = _findMap(mapid);
+ if (!map)
+ return NULL;
+
+ if (!map->Instanceable())
+ return instanceId == 0 ? map : NULL;
+
+ return ((MapInstanced*)map)->FindMap(instanceId);
+}
+
+bool MapManager::CanPlayerEnter(uint32 mapid, Player* player, bool loginCheck)
+{
+ const MapEntry *entry = sMapStore.LookupEntry(mapid);
+ if (!entry)
+ return false;
+
+ if (!entry->IsDungeon())
+ return true;
+
+ const char *mapName = entry->name[player->GetSession()->GetSessionDbcLocale()];
+
+ Group* pGroup = player->GetGroup();
+ if (entry->IsRaid())
+ {
+ // can only enter in a raid group
+ // GMs can avoid raid limitations
+ if ((!pGroup || !pGroup->isRaidGroup()) && !player->isGameMaster() && !sWorld.getConfig(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("MAP: Player '%s' must be in a raid group to enter instance '%s'", player->GetName(), mapName);
+ return false;
+ }
+ }
+
+ //The player has a heroic mode and tries to enter into instance which has no a heroic mode
+ MapDifficulty const* mapDiff = GetMapDifficultyData(entry->MapID,player->GetDifficulty(entry->IsRaid()));
+ if (!mapDiff)
+ {
+ bool isNormalTargetMap = entry->IsRaid()
+ ? (player->GetRaidDifficulty() == RAID_DIFFICULTY_10MAN_NORMAL)
+ : (player->GetDungeonDifficulty() == DUNGEON_DIFFICULTY_NORMAL);
+
+ // Send aborted message
+ // FIX ME: what about absent normal/heroic mode with specific players limit...
+ player->SendTransferAborted(mapid, TRANSFER_ABORT_DIFFICULTY, isNormalTargetMap ? DUNGEON_DIFFICULTY_NORMAL : DUNGEON_DIFFICULTY_HEROIC);
+ 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 instance_map = corpse->GetMapId();
+ do
+ {
+ if (instance_map == mapid)
+ break;
+
+ InstanceTemplate const* instance = objmgr.GetInstanceTemplate(instance_map);
+ instance_map = instance ? instance->parent : 0;
+ }
+ while (instance_map);
+
+ if (!instance_map)
+ {
+ WorldPacket data(SMSG_CORPSE_NOT_IN_INSTANCE);
+ player->GetSession()->SendPacket(&data);
+ sLog.outDebug("MAP: Player '%s' does not have a corpse in instance '%s' and cannot enter.", player->GetName(), mapName);
+ return false;
+ }
+ sLog.outDebug("MAP: Player '%s' has corpse in instance '%s' and can enter.", player->GetName(), mapName);
+ }
+ else
+ sLog.outDebug("Map::CanPlayerEnter - player '%s' is dead but does not have a corpse!", player->GetName());
+ }
+
+ InstanceTemplate const* instance = objmgr.GetInstanceTemplate(mapid);
+ if (!instance)
+ return false;
+
+ //Get instance where player's group is bound & its map
+ if (pGroup)
+ {
+ InstanceGroupBind* boundedInstance = pGroup->GetBoundInstance(player);
+ if (boundedInstance && boundedInstance->save)
+ {
+ if (Map *boundedMap = MapManager::Instance().FindMap(mapid,boundedInstance->save->GetInstanceId()))
+ {
+ // Player permanently bounded to different instance than groups one
+ InstancePlayerBind* playerBoundedInstance = player->GetBoundInstance(mapid, player->GetDungeonDifficulty());
+ if (playerBoundedInstance && playerBoundedInstance->perm && playerBoundedInstance->save &&
+ boundedInstance->save->GetInstanceId() != playerBoundedInstance->save->GetInstanceId())
+ {
+ //TODO: send some kind of error message to the player
+ return false;
+ }
+
+ // Encounters in progress
+ if (!loginCheck && entry->IsRaid() && ((InstanceMap*)boundedMap)->GetInstanceData() && ((InstanceMap*)boundedMap)->GetInstanceData()->IsEncounterInProgress())
+ {
+ sLog.outDebug("MAP: Player '%s' cannot enter instance '%s' while an encounter is in progress.", player->GetName(), mapName);
+ player->SendTransferAborted(mapid, TRANSFER_ABORT_ZONE_IN_COMBAT);
+ return false;
+ }
+
+ // Instance is full
+ MapDifficulty const* mapDiff = ((InstanceMap*)boundedMap)->GetMapDifficulty();
+ int8 maxPlayers = mapDiff ? mapDiff->maxPlayers : 0;
+ if (maxPlayers != -1) //-1: unlimited access
+ {
+ if (boundedMap->GetPlayersCountExceptGMs() >= (loginCheck ? maxPlayers+1 : maxPlayers))
+ {
+ sLog.outDebug("MAP: Player '%s' cannot enter instance '%s' because it is full.", player->GetName(), mapName);
+ player->SendTransferAborted(mapid, TRANSFER_ABORT_MAX_PLAYERS);
+ return false;
+ }
+ }
+ }
+ }
+ }
+
+ //Other requirements
+ return player->Satisfy(objmgr.GetAccessRequirement(instance->access_id), mapid, true);
+}
+
+void MapManager::RemoveBonesFromMap(uint32 mapid, uint64 guid, float x, float y)
+{
+ bool remove_result = _createBaseMap(mapid)->RemoveBones(guid, x, y);
+
+ if (!remove_result)
+ {
+ sLog.outDebug("Bones %u not found in world. Delete from DB also.", GUID_LOPART(guid));
+ }
+}
+
+void MapManager::Update(uint32 diff)
+{
+ i_timer.Update(diff);
+ if (!i_timer.Passed())
+ return;
+
+ MapMapType::iterator iter = i_maps.begin();
+ for (; iter != i_maps.end(); ++iter)
+ {
+ if (m_updater.activated())
+ m_updater.schedule_update(*iter->second, i_timer.GetCurrent());
+ else
+ {
+ iter->second->Update(i_timer.GetCurrent());
+ }
+ }
+ if (m_updater.activated())
+ m_updater.wait();
+
+ for (iter = i_maps.begin(); iter != i_maps.end(); ++iter)
+ iter->second->DelayedUpdate(i_timer.GetCurrent());
+
+ ObjectAccessor::Instance().Update(i_timer.GetCurrent());
+ for (TransportSet::iterator iter = m_Transports.begin(); iter != m_Transports.end(); ++iter)
+ (*iter)->Update(i_timer.GetCurrent());
+
+ i_timer.SetCurrent(0);
+}
+
+void MapManager::DoDelayedMovesAndRemoves()
+{
+}
+
+bool MapManager::ExistMapAndVMap(uint32 mapid, float x,float y)
+{
+ GridPair p = Trinity::ComputeGridPair(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)
+{
+ MapEntry const* mEntry = sMapStore.LookupEntry(mapid);
+ return mEntry && (!mEntry->IsDungeon() || objmgr.GetInstanceTemplate(mapid));
+ // TODO: add check for battleground template
+}
+
+void MapManager::UnloadAll()
+{
+ for (MapMapType::iterator iter=i_maps.begin(); iter != i_maps.end(); ++iter)
+ iter->second->UnloadAll();
+
+ while (!i_maps.empty())
+ {
+ delete i_maps.begin()->second;
+ i_maps.erase(i_maps.begin());
+ }
+
+ if (m_updater.activated())
+ m_updater.deactivate();
+}
+
+void MapManager::InitMaxInstanceId()
+{
+ i_MaxInstanceId = 0;
+
+ QueryResult_AutoPtr result = CharacterDatabase.Query("SELECT MAX(id) FROM instance");
+ if (result)
+ i_MaxInstanceId = result->Fetch()[0].GetUInt32();
+}
+
+uint32 MapManager::GetNumInstances()
+{
+ Guard guard(*this);
+
+ uint32 ret = 0;
+ 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()) ret++;
+ }
+ return ret;
+}
+
+uint32 MapManager::GetNumPlayersInInstances()
+{
+ Guard guard(*this);
+
+ uint32 ret = 0;
+ 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())
+ ret += ((InstanceMap*)mitr->second)->GetPlayers().getSize();
+ }
+ return ret;
+}
diff --git a/src/server/game/Map/MapManager.h b/src/server/game/Map/MapManager.h
new file mode 100644
index 00000000000..d94f9fced0e
--- /dev/null
+++ b/src/server/game/Map/MapManager.h
@@ -0,0 +1,158 @@
+/*
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
+ *
+ * Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
+ *
+ * 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, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef TRINITY_MAPMANAGER_H
+#define TRINITY_MAPMANAGER_H
+
+#include "Platform/Define.h"
+#include "Policies/Singleton.h"
+#include "ace/Thread_Mutex.h"
+#include "Common.h"
+#include "Map.h"
+#include "GridStates.h"
+#include "MapUpdater.h"
+
+class Transport;
+
+class MapManager : public Trinity::Singleton<MapManager, Trinity::ClassLevelLockable<MapManager, ACE_Thread_Mutex> >
+{
+
+ friend class Trinity::OperatorNew<MapManager>;
+ typedef UNORDERED_MAP<uint32, Map*> MapMapType;
+ typedef std::pair<UNORDERED_MAP<uint32, Map*>::iterator, bool> MapMapPair;
+
+ public:
+
+ Map* CreateMap(uint32, const WorldObject* obj, uint32 instanceId);
+ Map const* CreateBaseMap(uint32 id) const { return const_cast<MapManager*>(this)->_createBaseMap(id); }
+ Map* FindMap(uint32 mapid, uint32 instanceId = 0) const;
+
+ uint16 GetAreaFlag(uint32 mapid, float x, float y, float z) const
+ {
+ Map const* m = 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 SetGridCleanUpDelay(uint32 t)
+ {
+ if (t < MIN_GRID_DELAY)
+ i_gridCleanUpDelay = MIN_GRID_DELAY;
+ else
+ i_gridCleanUpDelay = t;
+ }
+
+ void SetMapUpdateInterval(uint32 t)
+ {
+ if (t > MIN_MAP_UPDATE_DELAY)
+ t = MIN_MAP_UPDATE_DELAY;
+
+ i_timer.SetInterval(t);
+ i_timer.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);
+
+ static bool IsValidMapCoord(uint32 mapid, float x,float y)
+ {
+ return IsValidMAP(mapid) && Trinity::IsValidMapCoord(x,y);
+ }
+
+ static bool IsValidMapCoord(uint32 mapid, float x,float y,float z)
+ {
+ return IsValidMAP(mapid) && Trinity::IsValidMapCoord(x,y,z);
+ }
+
+ static bool IsValidMapCoord(uint32 mapid, float x,float y,float z,float o)
+ {
+ return IsValidMAP(mapid) && Trinity::IsValidMapCoord(x,y,z,o);
+ }
+
+ static bool IsValidMapCoord(WorldLocation const& loc)
+ {
+ return IsValidMapCoord(loc.GetMapId(), loc.GetPositionX(), loc.GetPositionY(), loc.GetPositionZ(), loc.GetOrientation());
+ }
+
+ void DoDelayedMovesAndRemoves();
+
+ void LoadTransports();
+
+ typedef std::set<Transport *> TransportSet;
+ TransportSet m_Transports;
+
+ typedef std::map<uint32, TransportSet> TransportMap;
+ TransportMap m_TransportsByMap;
+
+ bool CanPlayerEnter(uint32 mapid, Player* player, bool loginCheck = false);
+ void RemoveBonesFromMap(uint32 mapid, uint64 guid, float x, float y);
+ uint32 GenerateInstanceId() { return ++i_MaxInstanceId; }
+ void InitMaxInstanceId();
+ void InitializeVisibilityDistanceInfo();
+
+ /* statistics */
+ uint32 GetNumInstances();
+ uint32 GetNumPlayersInInstances();
+
+ private:
+ // debugging code, should be deleted some day
+ void checkAndCorrectGridStatesArray(); // just for debugging to find some memory overwrites
+ GridState* i_GridStates[MAX_GRID_STATE]; // shadow entries to the global array in Map.cpp
+ int i_GridStateErrorCount;
+ private:
+ MapManager();
+ ~MapManager();
+
+ MapManager(const MapManager &);
+ MapManager& operator=(const MapManager &);
+
+ Map* _createBaseMap(uint32 id);
+ Map* _findMap(uint32 id) const
+ {
+ MapMapType::const_iterator iter = i_maps.find(id);
+ return (iter == i_maps.end() ? NULL : iter->second);
+ }
+
+ typedef Trinity::ClassLevelLockable<MapManager, ACE_Thread_Mutex>::Lock Guard;
+ uint32 i_gridCleanUpDelay;
+ MapMapType i_maps;
+ IntervalTimer i_timer;
+
+ uint32 i_MaxInstanceId;
+ MapUpdater m_updater;
+};
+#endif
diff --git a/src/server/game/Map/MapRefManager.h b/src/server/game/Map/MapRefManager.h
new file mode 100644
index 00000000000..4337aa75fd9
--- /dev/null
+++ b/src/server/game/Map/MapRefManager.h
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
+ *
+ * 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, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef _MAPREFMANAGER
+#define _MAPREFMANAGER
+
+#include "Utilities/LinkedReference/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
+
diff --git a/src/server/game/Map/MapReference.h b/src/server/game/Map/MapReference.h
new file mode 100644
index 00000000000..7cd4fcde76c
--- /dev/null
+++ b/src/server/game/Map/MapReference.h
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
+ *
+ * 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, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef _MAPREFERENCE_H
+#define _MAPREFERENCE_H
+
+#include "Utilities/LinkedReference/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
+
diff --git a/src/server/game/Map/MapUpdater.cpp b/src/server/game/Map/MapUpdater.cpp
new file mode 100644
index 00000000000..f9bb5e2bbbc
--- /dev/null
+++ b/src/server/game/Map/MapUpdater.cpp
@@ -0,0 +1,129 @@
+#include "MapUpdater.h"
+#include "DelayExecutor.h"
+#include "Map.h"
+#include "Database/DatabaseEnv.h"
+
+#include <ace/Guard_T.h>
+#include <ace/Method_Request.h>
+
+class WDBThreadStartReq1 : public ACE_Method_Request
+{
+ public:
+
+ WDBThreadStartReq1()
+ {
+ }
+
+ virtual int call()
+ {
+ WorldDatabase.ThreadStart();
+ return 0;
+ }
+};
+
+class WDBThreadEndReq1 : public ACE_Method_Request
+{
+ public:
+
+ WDBThreadEndReq1()
+ {
+ }
+
+ virtual int call()
+ {
+ WorldDatabase.ThreadEnd();
+ return 0;
+ }
+};
+
+class MapUpdateRequest : public ACE_Method_Request
+{
+ private:
+
+ Map& m_map;
+ MapUpdater& m_updater;
+ ACE_UINT32 m_diff;
+
+ public:
+
+ MapUpdateRequest(Map& m, MapUpdater& u, ACE_UINT32 d)
+ : m_map(m), m_updater(u), m_diff(d)
+ {
+ }
+
+ virtual int call()
+ {
+ m_map.Update (m_diff);
+ m_updater.update_finished ();
+ return 0;
+ }
+};
+
+MapUpdater::MapUpdater()
+ : m_mutex(), m_condition(m_mutex), m_executor(), pending_requests(0)
+{
+}
+
+MapUpdater::~MapUpdater()
+{
+ deactivate();
+}
+
+int MapUpdater::activate(size_t num_threads)
+{
+ return m_executor.activate((int)num_threads, new WDBThreadStartReq1, new WDBThreadEndReq1);
+}
+
+int MapUpdater::deactivate()
+{
+ wait();
+
+ return m_executor.deactivate();
+}
+
+int MapUpdater::wait()
+{
+ ACE_GUARD_RETURN(ACE_Thread_Mutex, guard, m_mutex, -1);
+
+ while (pending_requests > 0)
+ m_condition.wait();
+
+ return 0;
+}
+
+int MapUpdater::schedule_update(Map& map, ACE_UINT32 diff)
+{
+ ACE_GUARD_RETURN(ACE_Thread_Mutex, guard, m_mutex, -1);
+
+ ++pending_requests;
+
+ if (m_executor.execute(new MapUpdateRequest(map, *this, diff)) == -1)
+ {
+ ACE_DEBUG((LM_ERROR, ACE_TEXT("(%t) \n"), ACE_TEXT("Failed to schedule Map Update")));
+
+ --pending_requests;
+ return -1;
+ }
+
+ return 0;
+}
+
+bool MapUpdater::activated()
+{
+ return m_executor.activated();
+}
+
+void MapUpdater::update_finished()
+{
+ ACE_GUARD(ACE_Thread_Mutex, guard, m_mutex);
+
+ if (pending_requests == 0)
+ {
+ ACE_ERROR((LM_ERROR, ACE_TEXT("(%t)\n"), ACE_TEXT("MapUpdater::update_finished BUG, report to devs")));
+ return;
+ }
+
+ --pending_requests;
+
+ m_condition.broadcast();
+}
diff --git a/src/server/game/Map/MapUpdater.h b/src/server/game/Map/MapUpdater.h
new file mode 100644
index 00000000000..f301b15ca2f
--- /dev/null
+++ b/src/server/game/Map/MapUpdater.h
@@ -0,0 +1,40 @@
+#ifndef _MAP_UPDATER_H_INCLUDED
+#define _MAP_UPDATER_H_INCLUDED
+
+#include <ace/Thread_Mutex.h>
+#include <ace/Condition_Thread_Mutex.h>
+
+#include "DelayExecutor.h"
+
+class Map;
+
+class MapUpdater
+{
+ public:
+
+ MapUpdater();
+ virtual ~MapUpdater();
+
+ friend class MapUpdateRequest;
+
+ int schedule_update(Map& map, ACE_UINT32 diff);
+
+ int wait();
+
+ int activate(size_t num_threads);
+
+ int deactivate();
+
+ bool activated();
+
+ private:
+
+ DelayExecutor m_executor;
+ ACE_Condition_Thread_Mutex m_condition;
+ ACE_Thread_Mutex m_mutex;
+ size_t pending_requests;
+
+ void update_finished();
+};
+
+#endif //_MAP_UPDATER_H_INCLUDED
diff --git a/src/server/game/Map/ObjectPosSelector.cpp b/src/server/game/Map/ObjectPosSelector.cpp
new file mode 100644
index 00000000000..899dfec3fdb
--- /dev/null
+++ b/src/server/game/Map/ObjectPosSelector.cpp
@@ -0,0 +1,157 @@
+/*
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
+ *
+ * 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, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "ObjectPosSelector.h"
+
+ObjectPosSelector::ObjectPosSelector(float x,float y,float size,float dist)
+: m_center_x(x),m_center_y(y),m_size(size),m_dist(dist)
+{
+ m_anglestep = acos(m_dist/(m_dist+2*m_size));
+
+ m_nextUsedPos[USED_POS_PLUS] = m_UsedPosLists[USED_POS_PLUS].end();
+ m_nextUsedPos[USED_POS_MINUS] = m_UsedPosLists[USED_POS_MINUS].end();
+
+ m_smallStepAngle[USED_POS_PLUS] = 0;
+ m_smallStepAngle[USED_POS_MINUS] = 0;
+
+ m_smallStepOk[USED_POS_PLUS] = false;
+ m_smallStepOk[USED_POS_MINUS] = false;
+
+ m_smallStepNextUsedPos[USED_POS_PLUS] = NULL;
+ m_smallStepNextUsedPos[USED_POS_MINUS] = NULL;
+}
+
+ObjectPosSelector::UsedPosList::value_type const* ObjectPosSelector::nextUsedPos(UsedPosType uptype)
+{
+ UsedPosList::const_iterator itr = m_nextUsedPos[uptype];
+ if(itr!=m_UsedPosLists[uptype].end())
+ ++itr;
+
+ if(itr==m_UsedPosLists[uptype].end())
+ {
+ if(!m_UsedPosLists[~uptype].empty())
+ return &*m_UsedPosLists[~uptype].rbegin();
+ else
+ return NULL;
+ }
+ else
+ return &*itr;
+}
+
+void ObjectPosSelector::AddUsedPos(float size,float angle,float dist)
+{
+ if(angle>=0)
+ m_UsedPosLists[USED_POS_PLUS].insert(UsedPosList::value_type(angle,UsedPos(1.0,size,dist)));
+ else
+ m_UsedPosLists[USED_POS_MINUS].insert(UsedPosList::value_type(-angle,UsedPos(-1.0,size,dist)));
+}
+
+void ObjectPosSelector::InitializeAngle()
+{
+ m_nextUsedPos[USED_POS_PLUS] = m_UsedPosLists[USED_POS_PLUS].begin();
+ m_nextUsedPos[USED_POS_MINUS] = m_UsedPosLists[USED_POS_MINUS].begin();
+
+ m_smallStepAngle[USED_POS_PLUS] = 0;
+ m_smallStepAngle[USED_POS_MINUS] = 0;
+
+ m_smallStepOk[USED_POS_PLUS] = true;
+ m_smallStepOk[USED_POS_MINUS] = true;
+}
+
+bool ObjectPosSelector::FirstAngle(float& angle)
+{
+ if(m_UsedPosLists[USED_POS_PLUS].empty() && !m_UsedPosLists[USED_POS_MINUS].empty() )
+ return NextAngleFor(*m_UsedPosLists[USED_POS_MINUS].begin(),1.0,USED_POS_PLUS,angle);
+ else if(m_UsedPosLists[USED_POS_MINUS].empty() && !m_UsedPosLists[USED_POS_PLUS].empty() )
+ return NextAngleFor(*m_UsedPosLists[USED_POS_PLUS].begin(),-1.0,USED_POS_MINUS,angle);
+
+ return false;
+}
+
+bool ObjectPosSelector::NextAngle(float& angle)
+{
+ while(m_nextUsedPos[USED_POS_PLUS]!=m_UsedPosLists[USED_POS_PLUS].end() ||
+ m_nextUsedPos[USED_POS_MINUS]!=m_UsedPosLists[USED_POS_MINUS].end() ||
+ m_smallStepOk[USED_POS_PLUS] || m_smallStepOk[USED_POS_MINUS] )
+ {
+ // calculate next possible angle
+ if(NextPosibleAngle(angle))
+ return true;
+ }
+
+ return false;
+}
+
+bool ObjectPosSelector::NextUsedAngle(float& angle)
+{
+ while(m_nextUsedPos[USED_POS_PLUS]!=m_UsedPosLists[USED_POS_PLUS].end() ||
+ m_nextUsedPos[USED_POS_MINUS]!=m_UsedPosLists[USED_POS_MINUS].end() )
+ {
+ // calculate next possible angle
+ if(!NextPosibleAngle(angle))
+ return true;
+ }
+
+ return false;
+}
+
+bool ObjectPosSelector::NextPosibleAngle( float& angle )
+{
+ // ++ direction less updated
+ if( m_nextUsedPos[USED_POS_PLUS]!=m_UsedPosLists[USED_POS_PLUS].end() &&
+ (m_nextUsedPos[USED_POS_MINUS]==m_UsedPosLists[USED_POS_MINUS].end() || m_nextUsedPos[USED_POS_PLUS]->first <= m_nextUsedPos[USED_POS_MINUS]->first) )
+ {
+ bool ok;
+ if(m_smallStepOk[USED_POS_PLUS])
+ ok = NextSmallStepAngle(1.0,USED_POS_PLUS,angle);
+ else
+ ok = NextAngleFor(*m_nextUsedPos[USED_POS_PLUS],1.0,USED_POS_PLUS,angle);
+
+ if(!ok)
+ ++m_nextUsedPos[USED_POS_PLUS]; // increase. only at fail (original or checked)
+ return ok;
+ }
+ // -- direction less updated
+ else if( m_nextUsedPos[USED_POS_MINUS]!=m_UsedPosLists[USED_POS_MINUS].end())
+ {
+ bool ok;
+ if(m_smallStepOk[USED_POS_MINUS])
+ ok = NextSmallStepAngle(-1.0,USED_POS_MINUS,angle);
+ else
+ ok = NextAngleFor(*m_nextUsedPos[USED_POS_MINUS],-1.0,USED_POS_MINUS,angle);
+
+ if(!ok)
+ ++m_nextUsedPos[USED_POS_MINUS];
+ return ok;
+ }
+ else // both list empty
+ {
+ if( m_smallStepOk[USED_POS_PLUS] && (!m_smallStepOk[USED_POS_MINUS] || m_smallStepAngle[USED_POS_PLUS] <= m_smallStepAngle[USED_POS_MINUS]) )
+ {
+ return NextSmallStepAngle(1.0,USED_POS_PLUS,angle);
+ }
+ // -- direction less updated
+ else if( m_smallStepOk[USED_POS_MINUS] )
+ {
+ return NextSmallStepAngle(-1.0,USED_POS_MINUS,angle);
+ }
+ }
+
+ // no angles
+ return false;
+}
diff --git a/src/server/game/Map/ObjectPosSelector.h b/src/server/game/Map/ObjectPosSelector.h
new file mode 100644
index 00000000000..84050611121
--- /dev/null
+++ b/src/server/game/Map/ObjectPosSelector.h
@@ -0,0 +1,155 @@
+/*
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
+ *
+ * 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, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef _OBJECT_POS_SELECTOR_H
+#define _OBJECT_POS_SELECTOR_H
+
+#include<Common.h>
+
+#include<map>
+
+enum UsedPosType { USED_POS_PLUS, USED_POS_MINUS };
+
+inline UsedPosType operator ~(UsedPosType uptype)
+{
+ return uptype==USED_POS_PLUS ? USED_POS_MINUS : USED_POS_PLUS;
+}
+
+struct ObjectPosSelector
+{
+ struct UsedPos
+ {
+ UsedPos(float sign_, float size_,float dist_) : sign(sign_), size(size_),dist(dist_) {}
+
+ float sign;
+
+ float size; // size of point
+ float dist; // dist to central point (including central point size)
+ };
+
+ typedef std::multimap<float,UsedPos> UsedPosList; // abs(angle)->Node
+
+ ObjectPosSelector(float x,float y,float size,float dist);
+
+ void AddUsedPos(float size,float angle,float dist);
+ void InitializeAngle();
+
+ bool FirstAngle(float& angle);
+ bool NextAngle(float& angle);
+ bool NextUsedAngle(float& angle);
+
+ bool NextPosibleAngle( float& angle );
+
+ bool CheckAngle(UsedPosList::value_type const& nextUsedPos, float sign, float angle ) const
+ {
+ float angle_step2 = GetAngle(nextUsedPos.second);
+
+ float next_angle = nextUsedPos.first;
+ if(nextUsedPos.second.sign * sign < 0) // last node from diff. list (-pi+alpha)
+ next_angle = 2*M_PI-next_angle; // move to positive
+
+ return fabs(angle)+angle_step2 <= next_angle;
+ }
+
+ bool CheckOriginal() const
+ {
+ return (m_UsedPosLists[USED_POS_PLUS].empty() || CheckAngle( *m_UsedPosLists[USED_POS_PLUS].begin(),1.0,0)) &&
+ (m_UsedPosLists[USED_POS_MINUS].empty() || CheckAngle( *m_UsedPosLists[USED_POS_MINUS].begin(),-1.0,0));
+ }
+
+ bool IsNonBalanced() const { return m_UsedPosLists[USED_POS_PLUS].empty() != m_UsedPosLists[USED_POS_MINUS].empty(); }
+
+ bool NextAngleFor( UsedPosList::value_type const& usedPos, float sign, UsedPosType uptype, float &angle )
+ {
+ float angle_step = GetAngle(usedPos.second);
+
+ // next possible angle
+ angle = usedPos.first * usedPos.second.sign + angle_step * sign;
+
+ UsedPosList::value_type const* nextNode = nextUsedPos(uptype);
+ if(nextNode)
+ {
+ // if next node permit use selected angle, then do it
+ if(!CheckAngle(*nextNode, sign, angle))
+ {
+ m_smallStepOk[uptype] = false;
+ return false;
+ }
+ }
+
+ // possible more points
+ m_smallStepOk[uptype] = true;
+ m_smallStepAngle[uptype] = angle;
+ m_smallStepNextUsedPos[uptype] = nextNode;
+
+ return true;
+ }
+
+ bool NextSmallStepAngle( float sign, UsedPosType uptype, float &angle )
+ {
+ // next possible angle
+ angle = m_smallStepAngle[uptype] + m_anglestep * sign;
+
+ if(fabs(angle) > M_PI)
+ {
+ m_smallStepOk[uptype] = false;
+ return false;
+ }
+
+ if(m_smallStepNextUsedPos[uptype])
+ {
+ if(fabs(angle) >= m_smallStepNextUsedPos[uptype]->first)
+ {
+ m_smallStepOk[uptype] = false;
+ return false;
+ }
+
+ // if next node permit use selected angle, then do it
+ if(!CheckAngle(*m_smallStepNextUsedPos[uptype], sign, angle))
+ {
+ m_smallStepOk[uptype] = false;
+ return false;
+ }
+ }
+
+ // possible more points
+ m_smallStepAngle[uptype] = angle;
+ return true;
+ }
+
+ // next used post for m_nextUsedPos[uptype]
+ UsedPosList::value_type const* nextUsedPos(UsedPosType uptype);
+
+ // angle from used pos to next possible free pos
+ float GetAngle(UsedPos const& usedPos) const { return acos(m_dist/(usedPos.dist+usedPos.size+m_size)); }
+
+ float m_center_x;
+ float m_center_y;
+ float m_size; // size of object in center
+ float m_dist; // distance for searching pos (including central object size)
+ float m_anglestep;
+
+ UsedPosList m_UsedPosLists[2];
+ UsedPosList::const_iterator m_nextUsedPos[2];
+
+ // field for small step from first after next used pos until next pos
+ float m_smallStepAngle[2];
+ bool m_smallStepOk[2];
+ UsedPosList::value_type const* m_smallStepNextUsedPos[2];
+};
+#endif
diff --git a/src/server/game/Map/ZoneScript.h b/src/server/game/Map/ZoneScript.h
new file mode 100644
index 00000000000..ab74c8aa5d4
--- /dev/null
+++ b/src/server/game/Map/ZoneScript.h
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
+ *
+ * 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, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef ZONE_SCRIPT_H_
+#define ZONE_SCRIPT_H_
+
+#include "Common.h"
+#include "Creature.h"
+
+//struct CreatureData;
+class Creature;
+class GameObject;
+
+class ZoneScript
+{
+ public:
+ explicit ZoneScript() {}
+
+ virtual uint32 GetCreatureEntry(uint32 /*guidlow*/, const CreatureData *data) { return data->id; }
+ virtual uint32 GetGameObjectEntry(uint32 /*guidlow*/, uint32 entry) { return entry; }
+
+ virtual void OnCreatureCreate(Creature *, bool /*add*/) {}
+ virtual void OnGameObjectCreate(GameObject * /*go*/, bool /*add*/) {}
+
+ //All-purpose data storage 64 bit
+ virtual uint64 GetData64(uint32 /*DataId*/) { return 0; }
+ virtual void SetData64(uint32 /*DataId*/, uint64 /*Value*/) {}
+
+ //All-purpose data storage 32 bit
+ virtual uint32 GetData(uint32 /*DataId*/) { return 0; }
+ virtual void SetData(uint32 /*DataId*/, uint32 /*Value*/) {}
+
+ virtual void ProcessEvent(GameObject * /*obj*/, uint32 /*eventId*/) {}
+};
+
+#endif \ No newline at end of file