Index: binaries/data/mods/public/simulation/components/Capturable.js
===================================================================
--- binaries/data/mods/public/simulation/components/Capturable.js	(revision 16648)
+++ binaries/data/mods/public/simulation/components/Capturable.js	(working copy)
@@ -16,7 +16,6 @@
 	// Cache this value 
 	this.maxCp = +this.template.CapturePoints;
 	this.cp = [];
-	this.StartRegenTimer();
 };
 
 //// Interface functions ////
@@ -56,6 +55,9 @@
  */
 Capturable.prototype.Reduce = function(amount, playerID)
 {
+	if (amount <= 0)
+		return 0;
+
 	var cmpOwnership = Engine.QueryInterface(this.entity, IID_Ownership);
 	if (!cmpOwnership || cmpOwnership.GetOwner() == -1)
 		return 0;
@@ -69,8 +71,7 @@
 	if (cmpFogging)
 		cmpFogging.Activate();
 
-	var enemiesFilter = function(v, i) { return v > 0 && cmpPlayerSource.IsEnemy(i); };
-	var numberOfEnemies = this.cp.filter(enemiesFilter).length;
+	var numberOfEnemies = this.cp.filter((v, i) => v > 0 && cmpPlayerSource.IsEnemy(i)).length;
 
 	if (numberOfEnemies == 0)
 		return 0;
@@ -88,24 +89,11 @@
 	}
 
 	// give all cp taken to the player
-	var takenCp = this.maxCp - this.cp.reduce(function(a, b) { return a + b; });
+	var takenCp = this.maxCp - this.cp.reduce((a, b) => a + b);
 	this.cp[playerID] += takenCp;
 
-	this.StartRegenTimer();
-
-	Engine.PostMessage(this.entity, MT_CapturePointsChanged, { "capturePoints": this.cp })
-
-	if (this.cp[cmpOwnership.GetOwner()] > 0)
-		return takenCp;
-
-	// if all cp has been taken from the owner, convert it to the best player
-	var bestPlayer = 0;
-	for (let i in this.cp)
-		if (this.cp[i] >= this.cp[bestPlayer])
-			bestPlayer = +i;
-
-	cmpOwnership.SetOwner(bestPlayer);
-
+	this.CheckTimer();
+	this.RegisterCapturePointsChanged();
 	return takenCp;
 };
 
@@ -128,17 +116,35 @@
 
 //// Private functions ////
 
+/**
+ * this has to be called whenever the capture points are changed.
+ * It notifies other components of the change, and switches ownership when needed
+ */
+Capturable.prototype.RegisterCapturePointsChanged = function()
+{
+	Engine.PostMessage(this.entity, MT_CapturePointsChanged, { "capturePoints": this.cp })
+
+	var cmpOwnership = Engine.QueryInterface(this.entity, IID_Ownership);
+	if (!cmpOwnership)
+		return
+	var owner = cmpOwnership.GetOwner();
+	if (owner == -1 || this.cp[owner] > 0)
+		return;
+
+	// if all cp has been taken from the owner, convert it to the best player
+	var bestPlayer = 0;
+	for (let i in this.cp)
+		if (this.cp[i] >= this.cp[bestPlayer])
+			bestPlayer = +i;
+
+	cmpOwnership.SetOwner(bestPlayer);
+};
+
 Capturable.prototype.GetRegenRate = function()
 {
 	var regenRate = +this.template.RegenRate;
 	regenRate = ApplyValueModificationsToEntity("Capturable/RegenRate", regenRate, this.entity);
 
-	var cmpTerritoryDecay = Engine.QueryInterface(this.entity, IID_TerritoryDecay);
-	if (cmpTerritoryDecay && cmpTerritoryDecay.IsDecaying())
-		var territoryDecayRate = cmpTerritoryDecay.GetDecayRate();
-	else
-		var territoryDecayRate = 0;
-
 	var cmpGarrisonHolder = Engine.QueryInterface(this.entity, IID_GarrisonHolder);
 	if (cmpGarrisonHolder)
 		var garrisonRegenRate = this.GetGarrisonRegenRate() * cmpGarrisonHolder.GetEntities().length;
@@ -145,49 +151,69 @@
 	else
 		var garrisonRegenRate = 0;
 
-	return regenRate + garrisonRegenRate - territoryDecayRate;
+	return regenRate + garrisonRegenRate;
 };
 
-Capturable.prototype.RegenCapturePoints = function()
+Capturable.prototype.TimerTick = function()
 {
 	var cmpOwnership = Engine.QueryInterface(this.entity, IID_Ownership);
 	if (!cmpOwnership || cmpOwnership.GetOwner() == -1)
 		return;
 
+	var owner = cmpOwnership.GetOwner();
+	var modifiedCp = 0;
+
+	// special handle for the territory decay
+	// reduce cp from the owner in favour of all neighbours (also allies)
+	var cmpTerritoryDecay = Engine.QueryInterface(this.entity, IID_TerritoryDecay);
+	if (cmpTerritoryDecay && cmpTerritoryDecay.IsDecaying())
+	{
+		var neighbours = cmpTerritoryDecay.GetConnectedNeighbours();
+		var totalNeighbours = neighbours.reduce((a, b) => a + b);
+		var decay = Math.min(cmpTerritoryDecay.GetDecayRate(), this.cp[owner]);
+		this.cp[owner] -= decay;
+		modifiedCp += decay;
+		for (let p in neighbours)
+			this.cp[p] += decay * neighbours[p] / totalNeighbours;
+		this.RegisterCapturePointsChanged();
+	}
+
 	var regenRate = this.GetRegenRate();
 	if (regenRate < 0)
-		var takenCp = this.Reduce(-regenRate, 0);
-	else
-		var takenCp = this.Reduce(regenRate, cmpOwnership.GetOwner())
+		modifiedCp += this.Reduce(-regenRate, 0)
+	else if (regenRate > 0)
+		modifiedCp += this.Reduce(regenRate, owner)
 
-	if (takenCp > 0)
+	if (modifiedCp)
 		return;
 
-	// no capture points taken, stop the timer
+	// nothing changed, stop the timer
 	var cmpTimer = Engine.QueryInterface(SYSTEM_ENTITY, IID_Timer);
-	cmpTimer.CancelTimer(this.regenTimer);
-	this.regenTimer = 0;
-	Engine.PostMessage(this.entity, MT_CaptureRegenStateChanged, {"regenerating": false, "rate": 0});
+	cmpTimer.CancelTimer(this.timer);
+	this.timer = 0;
+	Engine.PostMessage(this.entity, MT_CaptureRegenStateChanged, {"regenerating": false, "regenRate": 0, "territoryDecay": 0});
 };
 
 /**
  * Start the regeneration timer when no timer exists
- * When nothing can be regenerated (f.e. because the
- * rate is 0, or because it is fully regenerated),
+ * When nothing can be modified (f.e. because it
+ * is fully regenerated),
  * the timer stops automatically after one execution.
  */
-Capturable.prototype.StartRegenTimer = function()
+Capturable.prototype.CheckTimer = function()
 {
-	if (this.regenTimer)
+	if (this.timer)
 		return;
 
-	var rate = this.GetRegenRate();
-	if (rate == 0)
+	var regenRate = this.GetRegenRate();
+	var cmpDecay = Engine.QueryInterface(this.entity, IID_TerritoryDecay);
+	var decay = cmpDecay && cmpDecay.IsDecaying() ? cmpDecay.GetDecayRate() : 0;
+	if (regenRate == 0 && decay == 0)
 		return;
 
 	var cmpTimer = Engine.QueryInterface(SYSTEM_ENTITY, IID_Timer);
-	this.regenTimer = cmpTimer.SetInterval(this.entity, IID_Capturable, "RegenCapturePoints", 1000, 1000, null);
-	Engine.PostMessage(this.entity, MT_CaptureRegenStateChanged, {"regenerating": true, "rate": rate});
+	this.timer = cmpTimer.SetInterval(this.entity, IID_Capturable, "TimerTick", 1000, 1000, null);
+	Engine.PostMessage(this.entity, MT_CaptureRegenStateChanged, {"ticking": true, "regenRate": regenRate, "territoryDecay": decay});
 };
 
 //// Message Listeners ////
@@ -206,23 +232,23 @@
 	for (let i in this.cp)
 		this.cp[i] *= scale;
 	Engine.PostMessage(this.entity, MT_CapturePointsChanged, { "capturePoints": this.cp });
-	this.StartRegenTimer();
+	this.CheckTimer();
 };
 
 Capturable.prototype.OnGarrisonedUnitsChanged = function(msg)
 {
-	this.StartRegenTimer();
+	this.CheckTimer();
 };
 
 Capturable.prototype.OnTerritoryDecayChanged = function(msg)
 {
 	if (msg.to)
-		this.StartRegenTimer();
+		this.CheckTimer();
 };
 
 Capturable.prototype.OnOwnershipChanged = function(msg)
 {
-	this.StartRegenTimer();
+	this.CheckTimer();
 
 	// if the new owner has no capture points, it means that either
 	// * it's being initialised now, or
Index: binaries/data/mods/public/simulation/components/TerritoryDecay.js
===================================================================
--- binaries/data/mods/public/simulation/components/TerritoryDecay.js	(revision 16648)
+++ binaries/data/mods/public/simulation/components/TerritoryDecay.js	(working copy)
@@ -8,10 +8,14 @@
 TerritoryDecay.prototype.Init = function()
 {
 	this.decaying = false;
+	this.connectedNeighbours = [];
 };
 
 TerritoryDecay.prototype.IsConnected = function()
 {
+	var numPlayers = Engine.QueryInterface(SYSTEM_ENTITY, IID_PlayerManager).GetNumPlayers();
+	this.connectedNeighbours.fill(0, 0, numPlayers);
+
 	var cmpPosition = Engine.QueryInterface(this.entity, IID_Position);
 	if (!cmpPosition || !cmpPosition.IsInWorld())
 		return false;
@@ -31,9 +35,16 @@
 	var pos = cmpPosition.GetPosition2D();
 	var tileOwner = cmpTerritoryManager.GetOwner(pos.x, pos.y);
 	if (tileOwner != cmpOwnership.GetOwner())
+	{
+		this.connectedNeighbours[tileOwner] = 1;
 		return false;
+	}
 
-	return cmpTerritoryManager.IsConnected(pos.x, pos.y);
+	if (cmpTerritoryManager.IsConnected(pos.x, pos.y))
+		return true;
+
+	this.connectedNeighbours = cmpTerritoryManager.GetNeighbours(pos.x, pos.y, true);
+	return false;
 };
 
 TerritoryDecay.prototype.IsDecaying = function()
@@ -49,6 +60,15 @@
 		this.entity);
 };
 
+/**
+ * Get the number of connected bordering tiles to this region
+ * Only valid when this.IsDecaying()
+ */
+TerritoryDecay.prototype.GetConnectedNeighbours = function()
+{
+	return this.connectedNeighbours;
+};
+
 TerritoryDecay.prototype.UpdateDecayState = function()
 {
 	if (this.IsConnected())
@@ -58,7 +78,7 @@
 	if (decaying === this.decaying)
 		return;
 	this.decaying = decaying;
-	Engine.PostMessage(this.entity, MT_TerritoryDecayChanged, { "entity": this.entity, "to": decaying });
+	Engine.PostMessage(this.entity, MT_TerritoryDecayChanged, { "entity": this.entity, "to": decaying, "rate": this.GetDecayRate() });
 };
 
 TerritoryDecay.prototype.OnTerritoriesChanged = function(msg)
Index: source/simulation2/components/CCmpTerritoryManager.cpp
===================================================================
--- source/simulation2/components/CCmpTerritoryManager.cpp	(revision 16648)
+++ source/simulation2/components/CCmpTerritoryManager.cpp	(working copy)
@@ -224,6 +224,7 @@
 	}
 
 	virtual player_id_t GetOwner(entity_pos_t x, entity_pos_t z);
+	virtual std::vector<u32> GetNeighbours(entity_pos_t x, entity_pos_t z, bool filterConnected);
 	virtual bool IsConnected(entity_pos_t x, entity_pos_t z);
 
 	// To support lazy updates of territory render data,
@@ -280,25 +281,26 @@
 
 typedef PriorityQueueHeap<std::pair<u16, u16>, u32, std::greater<u32> > OpenQueue;
 
-static void ProcessNeighbour(u32 falloff, u16 i, u16 j, u32 pg, bool diagonal,
-		Grid<u32>& grid, OpenQueue& queue, const Grid<u8>& costGrid)
+/**
+ * Compute the tile indexes on the grid nearest to a given point
+ */
+static void NearestTile(entity_pos_t x, entity_pos_t z, u16& i, u16& j, u16 w, u16 h)
 {
-	u32 dg = falloff * costGrid.get(i, j);
-	if (diagonal)
-		dg = (dg * 362) / 256;
+	i = (u16)clamp((x / (int)TERRAIN_TILE_SIZE).ToInt_RoundToZero(), 0, w-1);
+	j = (u16)clamp((z / (int)TERRAIN_TILE_SIZE).ToInt_RoundToZero(), 0, h-1);
+}
 
-	// Stop if new cost g=pg-dg is not better than previous value for that tile
-	// (arranged to avoid underflow if pg < dg)
-	if (pg <= grid.get(i, j) + dg)
-		return;
+/**
+ * Returns the position of the center of the given tile
+ */
+static void TileCenter(u16 i, u16 j, entity_pos_t& x, entity_pos_t& z)
+{
+	x = entity_pos_t::FromInt(i*(int)TERRAIN_TILE_SIZE + (int)TERRAIN_TILE_SIZE/2);
+	z = entity_pos_t::FromInt(j*(int)TERRAIN_TILE_SIZE + (int)TERRAIN_TILE_SIZE/2);
+}
 
-	u32 g = pg - dg; // cost to this tile = cost to predecessor - falloff from predecessor
+// TODO: would be nice not to duplicate those two functions from CCmpObstructionManager.cpp
 
-	grid.set(i, j, g);
-	OpenQueue::Item tile = { std::make_pair(i, j), g };
-	queue.push(tile);
-}
-
 static void FloodFill(Grid<u32>& grid, Grid<u8>& costGrid, OpenQueue& openTiles, u32 falloff)
 {
 	u16 tilesW = grid.m_W;
@@ -308,25 +310,39 @@
 	{
 		OpenQueue::Item tile = openTiles.pop();
 
-		// Process neighbours (if they're not off the edge of the map)
-		u16 x = tile.id.first;
-		u16 z = tile.id.second;
-		if (x > 0)
-			ProcessNeighbour(falloff, (u16)(x-1), z, tile.rank, false, grid, openTiles, costGrid);
-		if (x < tilesW-1)
-			ProcessNeighbour(falloff, (u16)(x+1), z, tile.rank, false, grid, openTiles, costGrid);
-		if (z > 0)
-			ProcessNeighbour(falloff, x, (u16)(z-1), tile.rank, false, grid, openTiles, costGrid);
-		if (z < tilesH-1)
-			ProcessNeighbour(falloff, x, (u16)(z+1), tile.rank, false, grid, openTiles, costGrid);
-		if (x > 0 && z > 0)
-			ProcessNeighbour(falloff, (u16)(x-1), (u16)(z-1), tile.rank, true, grid, openTiles, costGrid);
-		if (x > 0 && z < tilesH-1)
-			ProcessNeighbour(falloff, (u16)(x-1), (u16)(z+1), tile.rank, true, grid, openTiles, costGrid);
-		if (x < tilesW-1 && z > 0)
-			ProcessNeighbour(falloff, (u16)(x+1), (u16)(z-1), tile.rank, true, grid, openTiles, costGrid);
-		if (x < tilesW-1 && z < tilesH-1)
-			ProcessNeighbour(falloff, (u16)(x+1), (u16)(z+1), tile.rank, true, grid, openTiles, costGrid);
+		// Process neighbours
+		int x = tile.id.first;
+		int z = tile.id.second;
+		u32 pg = tile.rank;
+		for (int i = -1; i < 2; ++i)
+		{
+			int ti = x + i;
+			if (ti < 0 || ti >= tilesW)
+				continue;
+			for (int j = -1; j < 2; ++j)
+			{
+				if (i == 0 && j == 0)
+					continue;
+				int tj = z + j;
+				if (tj < 0 || tj >= tilesH)
+					continue;
+
+				u32 dg = falloff * costGrid.get(ti, tj);
+				if (i * j != 0) // diagonal tile
+					dg = (dg * 362) / 256;
+
+				// Stop if new cost g=pg-dg is not better than previous value for that tile
+				// (arranged to avoid underflow if pg < dg)
+				if (pg <= grid.get(ti, tj) + dg)
+					continue;
+
+				u32 g = pg - dg; // cost to this tile = cost to predecessor - falloff from predecessor
+
+				grid.set(ti, tj, g);
+				OpenQueue::Item tile = { std::make_pair(ti, tj), g };
+				openTiles.push(tile);
+			}
+		}
 	}
 }
 
@@ -382,14 +398,14 @@
 	// Split influence entities into per-player lists, ignoring any with invalid properties
 	std::map<player_id_t, std::vector<entity_id_t> > influenceEntities;
 	std::vector<entity_id_t> rootInfluenceEntities;
-	for (CComponentManager::InterfaceList::iterator it = influences.begin(); it != influences.end(); ++it)
+	for (auto& it : influences)
 	{
 		// Ignore any with no weight or radius (to avoid divide-by-zero later)
-		ICmpTerritoryInfluence* cmpTerritoryInfluence = static_cast<ICmpTerritoryInfluence*>(it->second);
+		ICmpTerritoryInfluence* cmpTerritoryInfluence = static_cast<ICmpTerritoryInfluence*>(it.second);
 		if (cmpTerritoryInfluence->GetWeight() == 0 || cmpTerritoryInfluence->GetRadius() == 0)
 			continue;
 
-		CmpPtr<ICmpOwnership> cmpOwnership(GetSimContext(), it->first);
+		CmpPtr<ICmpOwnership> cmpOwnership(GetSimContext(), it.first);
 		if (!cmpOwnership)
 			continue;
 
@@ -403,14 +419,14 @@
 			continue;
 
 		// Ignore if invalid position
-		CmpPtr<ICmpPosition> cmpPosition(GetSimContext(), it->first);
+		CmpPtr<ICmpPosition> cmpPosition(GetSimContext(), it.first);
 		if (!cmpPosition || !cmpPosition->IsInWorld())
 			continue;
 
-		influenceEntities[owner].push_back(it->first);
+		influenceEntities[owner].push_back(it.first);
 
 		if (cmpTerritoryInfluence->IsRoot())
-			rootInfluenceEntities.push_back(it->first);
+			rootInfluenceEntities.push_back(it.first);
 	}
 
 	// For each player, store the sum of influences on each tile
@@ -418,44 +434,42 @@
 	// TODO: this is a large waste of memory; we don't really need to store
 	// all the intermediate grids
 
-	for (std::map<player_id_t, std::vector<entity_id_t> >::iterator it = influenceEntities.begin(); it != influenceEntities.end(); ++it)
+	for (auto& it : influenceEntities)
 	{
 		Grid<u32> playerGrid(tilesW, tilesH);
+		Grid<u32> entityGrid(tilesW, tilesH);
 
-		std::vector<entity_id_t>& ents = it->second;
-		for (std::vector<entity_id_t>::iterator eit = ents.begin(); eit != ents.end(); ++eit)
+		std::vector<entity_id_t>& ents = it.second;
+		// Compute the influence map of the current entity, then add it to the player grid
+		for (auto& eit : ents)
 		{
-			// Compute the influence map of the current entity, then add it to the player grid
-
-			Grid<u32> entityGrid(tilesW, tilesH);
-
-			CmpPtr<ICmpPosition> cmpPosition(GetSimContext(), *eit);
+			CmpPtr<ICmpPosition> cmpPosition(GetSimContext(), eit);
 			CFixedVector2D pos = cmpPosition->GetPosition2D();
-			u16 i = (u16)clamp((pos.X / (int)TERRAIN_TILE_SIZE).ToInt_RoundToNegInfinity(), 0, tilesW-1);
-			u16 j = (u16)clamp((pos.Y / (int)TERRAIN_TILE_SIZE).ToInt_RoundToNegInfinity(), 0, tilesH-1);
+			u16 i, j;
+			NearestTile(pos.X, pos.Y, i, j, tilesW, tilesH);
 
-			CmpPtr<ICmpTerritoryInfluence> cmpTerritoryInfluence(GetSimContext(), *eit);
+			CmpPtr<ICmpTerritoryInfluence> cmpTerritoryInfluence(GetSimContext(), eit);
 			u32 weight = cmpTerritoryInfluence->GetWeight();
 			u32 radius = cmpTerritoryInfluence->GetRadius() / TERRAIN_TILE_SIZE;
-			u32 falloff = weight / radius; // earlier check for GetRadius() == 0 prevents divide-by-zero
+			u32 falloff = weight / radius + 1; // earlier check for GetRadius() == 0 prevents divide-by-zero
 
-			// TODO: we should have some maximum value on weight, to avoid overflow
-			// when doing all the sums
 
 			// Initialise the tile under the entity
 			entityGrid.set(i, j, weight);
 			OpenQueue openTiles;
-			OpenQueue::Item tile = { std::make_pair((u16)i, (i16)j), weight };
+			OpenQueue::Item tile = { std::make_pair(i, j), weight };
 			openTiles.push(tile);
 
 			// Expand influences outwards
 			FloodFill(entityGrid, influenceGrid, openTiles, falloff);
 
-			// TODO: we should do a sparse grid and only add the non-zero regions, for performance
-			playerGrid.add(entityGrid);
+			// TODO: we should have overflow checks when adding, as the number of added
+			// entities can be arbitrary large
+			playerGrid.addRegion(entityGrid, i-radius, j-radius, i+radius, j+radius);
+			entityGrid.reset();
 		}
 
-		playerGrids.push_back(std::make_pair(it->first, playerGrid));
+		playerGrids.emplace_back(it.first, playerGrid);
 	}
 
 	// Set m_Territories to the player ID with the highest influence for each tile
@@ -467,12 +481,10 @@
 			for (size_t k = 0; k < playerGrids.size(); ++k)
 			{
 				u32 w = playerGrids[k].second.get(i, j);
-				if (w > bestWeight)
-				{
-					player_id_t id = playerGrids[k].first;
-					m_Territories->set(i, j, (u8)id);
-					bestWeight = w;
-				}
+				if (w <= bestWeight)
+					continue;
+				m_Territories->set(i, j, (u8)playerGrids[k].first);
+				bestWeight = w;
 			}
 		}
 	}
@@ -479,15 +491,15 @@
 
 	// Detect territories connected to a 'root' influence (typically a civ center)
 	// belonging to their player, and mark them with the connected flag
-	for (std::vector<entity_id_t>::iterator it = rootInfluenceEntities.begin(); it != rootInfluenceEntities.end(); ++it)
+	for (auto& it : rootInfluenceEntities)
 	{
 		// (These components must be valid else the entities wouldn't be added to this list)
-		CmpPtr<ICmpOwnership> cmpOwnership(GetSimContext(), *it);
-		CmpPtr<ICmpPosition> cmpPosition(GetSimContext(), *it);
+		CmpPtr<ICmpOwnership> cmpOwnership(GetSimContext(), it);
+		CmpPtr<ICmpPosition> cmpPosition(GetSimContext(), it);
 
 		CFixedVector2D pos = cmpPosition->GetPosition2D();
-		u16 i = (u16)clamp((pos.X / (int)TERRAIN_TILE_SIZE).ToInt_RoundToNegInfinity(), 0, tilesW-1);
-		u16 j = (u16)clamp((pos.Y / (int)TERRAIN_TILE_SIZE).ToInt_RoundToNegInfinity(), 0, tilesH-1);
+		u16 i, j;
+		NearestTile(pos.X, pos.Y, i, j, tilesW, tilesH);
 
 		u8 owner = (u8)cmpOwnership->GetOwner();
 
@@ -499,75 +511,47 @@
 
 		Grid<u8>& grid = *m_Territories;
 
-		u16 maxi = (u16)(grid.m_W-1);
-		u16 maxj = (u16)(grid.m_H-1);
-
 		std::vector<std::pair<u16, u16> > tileStack;
+		tileStack.emplace_back(i, j);
 
-#define MARK_AND_PUSH(i, j) STMT(grid.set(i, j, owner | TERRITORY_CONNECTED_MASK); tileStack.push_back(std::make_pair(i, j)); )
-
-		MARK_AND_PUSH(i, j);
 		while (!tileStack.empty())
 		{
-			int ti = tileStack.back().first;
-			int tj = tileStack.back().second;
+			int x = tileStack.back().first;
+			int z = tileStack.back().second;
 			tileStack.pop_back();
-
-			if (ti > 0 && grid.get(ti-1, tj) == owner)
-				MARK_AND_PUSH(ti-1, tj);
-			if (ti < maxi && grid.get(ti+1, tj) == owner)
-				MARK_AND_PUSH(ti+1, tj);
-			if (tj > 0 && grid.get(ti, tj-1) == owner)
-				MARK_AND_PUSH(ti, tj-1);
-			if (tj < maxj && grid.get(ti, tj+1) == owner)
-				MARK_AND_PUSH(ti, tj+1);
-
-			if (ti > 0 && tj > 0 && grid.get(ti-1, tj-1) == owner)
-				MARK_AND_PUSH(ti-1, tj-1);
-			if (ti > 0 && tj < maxj && grid.get(ti-1, tj+1) == owner)
-				MARK_AND_PUSH(ti-1, tj+1);
-			if (ti < maxi && tj > 0 && grid.get(ti+1, tj-1) == owner)
-				MARK_AND_PUSH(ti+1, tj-1);
-			if (ti < maxi && tj < maxj && grid.get(ti+1, tj+1) == owner)
-				MARK_AND_PUSH(ti+1, tj+1);
+			for (int i = -1; i < 2; ++i)
+			{
+				int ti = x + i;
+				if (ti < 0 || ti >= tilesW) // check grid bounds
+					continue;
+				for (int j = -1; j < 2; ++j)
+				{
+					if (i == 0 && j == 0) // don't process the same tile
+						continue;
+					int tj = z + j;
+					if (tj < 0 || tj >= tilesH) // check grid bounds
+						continue;
+					if (grid.get(ti, tj) != owner)
+						continue;
+					grid.set(ti, tj, owner | TERRITORY_CONNECTED_MASK);
+					tileStack.emplace_back(ti, tj);
+				}
+			}
 		}
-
-#undef MARK_AND_PUSH
 	}
 }
 
-/**
- * Compute the tile indexes on the grid nearest to a given point
- */
-static void NearestTile(entity_pos_t x, entity_pos_t z, u16& i, u16& j, u16 w, u16 h)
-{
-	i = (u16)clamp((x / (int)TERRAIN_TILE_SIZE).ToInt_RoundToZero(), 0, w-1);
-	j = (u16)clamp((z / (int)TERRAIN_TILE_SIZE).ToInt_RoundToZero(), 0, h-1);
-}
-
-/**
- * Returns the position of the center of the given tile
- */
-static void TileCenter(u16 i, u16 j, entity_pos_t& x, entity_pos_t& z)
-{
-	x = entity_pos_t::FromInt(i*(int)TERRAIN_TILE_SIZE + (int)TERRAIN_TILE_SIZE/2);
-	z = entity_pos_t::FromInt(j*(int)TERRAIN_TILE_SIZE + (int)TERRAIN_TILE_SIZE/2);
-}
-
-// TODO: would be nice not to duplicate those two functions from CCmpObstructionManager.cpp
-
-
 void CCmpTerritoryManager::RasteriseInfluences(CComponentManager::InterfaceList& infls, Grid<u8>& grid)
 {
-	for (CComponentManager::InterfaceList::iterator it = infls.begin(); it != infls.end(); ++it)
+	for (auto& it : infls)
 	{
-		ICmpTerritoryInfluence* cmpTerritoryInfluence = static_cast<ICmpTerritoryInfluence*>(it->second);
+		ICmpTerritoryInfluence* cmpTerritoryInfluence = static_cast<ICmpTerritoryInfluence*>(it.second);
 
 		i32 cost = cmpTerritoryInfluence->GetCost();
 		if (cost == -1)
 			continue;
 
-		CmpPtr<ICmpObstruction> cmpObstruction(GetSimContext(), it->first);
+		CmpPtr<ICmpObstruction> cmpObstruction(GetSimContext(), it.first);
 		if (!cmpObstruction)
 			continue;
 
@@ -722,6 +706,64 @@
 	return m_Territories->get(i, j) & TERRITORY_PLAYER_MASK;
 }
 
+std::vector<u32> CCmpTerritoryManager::GetNeighbours(entity_pos_t x, entity_pos_t z, bool filterConnected)
+{
+	CmpPtr<ICmpPlayerManager> cmpPlayerManager(GetSystemEntity());
+	if (!cmpPlayerManager)
+		return std::vector<u32>();
+
+	std::vector<u32> ret(cmpPlayerManager->GetNumPlayers(), 0);
+	CalculateTerritories();
+	if (!m_Territories)
+		return ret;
+
+	u16 i, j;
+	NearestTile(x, z, i, j, m_Territories->m_W, m_Territories->m_H);
+
+	// calculate the neighbours
+	player_id_t thisOwner = m_Territories->get(i, j) & TERRITORY_PLAYER_MASK;
+
+	u16 tilesW = m_Territories->m_W;
+	u16 tilesH = m_Territories->m_H;
+
+	// use a flood-fill algorithm that fills up to the borders and remembers the owners
+	Grid<bool>* markerGrid = new Grid<bool>(tilesW, tilesH);
+	std::vector<std::pair<u16, u16> > tileStack;
+	tileStack.emplace_back(i, j);
+	markerGrid->set(i, j, true);
+	while (!tileStack.empty())
+	{
+		int x = tileStack.back().first;
+		int z = tileStack.back().second;
+		tileStack.pop_back();
+		for (int i = -1; i < 2; ++i)
+		{
+			int ti = x + i;
+			if (ti < 0 || ti >= tilesW)
+				continue;
+			for (int j = -1; j < 2; ++j)
+			{
+				if (i == 0 && j == 0)
+					continue;
+				int tj = z + j;
+				if (tj < 0 || tj >= tilesH)
+					continue;
+
+				if (markerGrid->get(ti, tj))
+					continue;
+				// mark the tile as visited in any case
+				markerGrid->set(ti, tj, true);
+				int owner = m_Territories->get(ti, tj) & TERRITORY_PLAYER_MASK;
+				if (owner == thisOwner)
+					tileStack.emplace_back(ti, tj); // expand the tile
+				else if (owner == 0 || !filterConnected || (m_Territories->get(ti, tj) & TERRITORY_CONNECTED_MASK) != 0)
+					ret[owner]++; // add player to the neighbours when requested
+			}
+		}
+	}
+	return ret;
+}
+
 bool CCmpTerritoryManager::IsConnected(entity_pos_t x, entity_pos_t z)
 {
 	u16 i, j;
Index: source/simulation2/components/ICmpTerritoryManager.cpp
===================================================================
--- source/simulation2/components/ICmpTerritoryManager.cpp	(revision 16648)
+++ source/simulation2/components/ICmpTerritoryManager.cpp	(working copy)
@@ -23,5 +23,6 @@
 
 BEGIN_INTERFACE_WRAPPER(TerritoryManager)
 DEFINE_INTERFACE_METHOD_2("GetOwner", player_id_t, ICmpTerritoryManager, GetOwner, entity_pos_t, entity_pos_t)
+DEFINE_INTERFACE_METHOD_3("GetNeighbours", std::vector<u32>, ICmpTerritoryManager, GetNeighbours, entity_pos_t, entity_pos_t, bool)
 DEFINE_INTERFACE_METHOD_2("IsConnected", bool, ICmpTerritoryManager, IsConnected, entity_pos_t, entity_pos_t)
 END_INTERFACE_WRAPPER(TerritoryManager)
Index: source/simulation2/components/ICmpTerritoryManager.h
===================================================================
--- source/simulation2/components/ICmpTerritoryManager.h	(revision 16648)
+++ source/simulation2/components/ICmpTerritoryManager.h	(working copy)
@@ -47,6 +47,12 @@
 	virtual player_id_t GetOwner(entity_pos_t x, entity_pos_t z) = 0;
 
 	/**
+	 * get the number of neighbour tiles for per player for the selected position
+	 * @return A list with the number of neighbour tiles per player
+	 */
+	virtual std::vector<u32> GetNeighbours(entity_pos_t x, entity_pos_t z, bool filterConnected) = 0;
+
+	/**
 	 * Get whether territory at given position is connected to a root object
 	 * (civ center etc) owned by that territory's player.
 	 */
Index: source/simulation2/helpers/Grid.h
===================================================================
--- source/simulation2/helpers/Grid.h	(revision 16648)
+++ source/simulation2/helpers/Grid.h	(working copy)
@@ -92,6 +92,26 @@
 			m_Data[i] += g.m_Data[i];
 	}
 
+	// Add a region of a grid to this grid
+	void addRegion(const Grid& g, int minI, int minJ, int maxI, int maxJ)
+	{
+#if GRID_BOUNDS_DEBUG
+		ENSURE(g.m_W == m_W && g.m_H == m_H);
+		ENSURE(minI <= maxI && minJ <= maxJ);
+#endif
+		minI = std::min(std::max(minI, 0), (int)g.m_W);
+		maxI = std::min(std::max(maxI, 0), (int)g.m_W);
+		minJ = std::min(std::max(minJ, 0), (int)g.m_H);
+		maxJ = std::min(std::max(maxJ, 0), (int)g.m_H);
+		for (int j = minJ; j <= maxJ; ++j)
+		{
+			for (int i = minI; i <= maxI; ++i)
+			{
+				m_Data[j*m_W + i] += g.m_Data[j*m_W + i];
+			}
+		}
+	}
+
 	void set(int i, int j, const T& value)
 	{
 #if GRID_BOUNDS_DEBUG
