DWORD
TerrainPatch::BlendValue(double y)
{
	if (terrain && y >= 0 && !water) {
		// find the proper layer:
		for (int i = 0; i < terrain->GetLayers().size(); i++) {
			TerrainLayer* layer = terrain->GetLayers().at(i);

			if (y >= layer->GetMinHeight() && y < layer->GetMaxHeight()) {
				double scale = (y-layer->GetMinHeight()) / (layer->GetMaxHeight()-layer->GetMinHeight());

				if (scale < 0.2)
				scale = 0;
				else if (scale > 0.8)
				scale = 1;
				else
				scale = (scale - 0.2) / 0.6;

				if ((i & 1) == 0) {
					scale = 1 - scale;
				}

				DWORD val = (DWORD) (scale*255);

				return val << 24;
			}
		}
	}

	return 0;
}
int
TerrainPatch::CalcLayer(Poly* poly)
{
	if (terrain && poly) {
		if (water)
		return 0;

		double y = 1e6;

		for (int i = 0; i < poly->nverts; i++) {
			double h = poly->vertex_set->loc[ poly->verts[i] ].y;

			if (h >= 0 && h < y) {
				y = h;
			}
		}

		if (y <= terrain->GetLayers().first()->GetMinHeight())
		return 0;

		for (int i = 0; i < terrain->GetLayers().size(); i++) {
			TerrainLayer* layer = terrain->GetLayers().at(i);

			if (y >= layer->GetMinHeight() && y < layer->GetMaxHeight()) {
				return i;
			}
		}
	}

	return -1;
}