多段折线简化算法参考

基本的想法就是对两种情况的点进行忽略,一种是和前一个点非常接近的点,另一种是与局部直线偏移很小的点。虽然代码不长,但是感觉运算量不小,希望未来能找到优化的方法。

参考代码如下:

//points是未经过优化的点数组
//ignoreDist是与前面相邻的点距离小于多少才忽略该点的阈值
//ignoreOffset是与当前局部直线距离小于多少才忽略该点的阈值
public static Vector3[] GetOptimizedPoints(Vector3[] points, float ignoreDist, float ignoreOffset)
	{
		if (points.Length < 2) return points;

		List listPoint = new List();
		float sqrIgnoreDist = ignoreDist * ignoreDist;
		int i = 0;
		Vector3 lastP = points[i];
		listPoint.Add(lastP);
		Vector3 segA = points[i];
		i++;
		while (i < points.Length)
		{
			Vector3 segB = points[i];
			while ((segB - segA).sqrMagnitude < sqrIgnoreDist)
			{
				i++;
				if (i >= points.Length) break;
				segB = points[i];
			}

			lastP = segB;

			i++;

			if (i >= points.Length)
			{
				listPoint.Add(lastP);
				continue;
			}

			float distPointToSeg = DistPointToLine(points[i], segA, segB);
			while (distPointToSeg < ignoreOffset)
			{
				lastP = points[i];
				i++;
				if (i >= points.Length) break;
				distPointToSeg = DistPointToLine(points[i], segA, segB);
			}
			listPoint.Add(lastP);
			segA = lastP;
		}

		return listPoint.ToArray();
	}

	public static float DistPointToLine(Vector3 point, Vector3 linePointA, Vector3 linePointB)
	{
		float distToStart = Vector3.Distance(point, linePointA);
		float distToEnd = Vector3.Distance(point, linePointB);
		float len = Vector3.Distance(linePointA, linePointB);
		float p = (len + distToStart + distToEnd) * 0.5f;
		float area = Mathf.Sqrt(p * (p - distToEnd) * (p - distToStart) * (p - len));
		return 2 * area / len;
	}

你可能感兴趣的:(算法,算法)