
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;

namespace XELF {

	static partial class GeometryHelper {

		/// <summary>
		/// 点群の重心（平均位置）を求める。
		/// </summary>
		/// <param name="points">点群</param>
		/// <returns>平均位置</returns>
		public static Vector2 Centroid(this List<Vector2> points) {
			Vector2 centroid = Vector2.Zero;
			int count = points.Count;
			for (int i = 0; i < count; i++) {
				var point = points[i];
				Vector2.Add(ref centroid, ref point, out centroid);
			}
			float scale = 1.0f / count;
			centroid.X *= scale;
			centroid.Y *= scale;
			return centroid;
		}

		public static float RadiusSquared(this List<Vector2> points, Vector2 centroid) {
			int count = points.Count;
			float distanceSquared = 0;
			float d;
			for (int i = 0; i < count; i++) {
				var point = points[i];
				Vector2.DistanceSquared(ref point, ref centroid, out d);
				distanceSquared = Math.Max(d, distanceSquared);
			}
			return distanceSquared;
		}
		public static float Radius(this List<Vector2> points, Vector2 centroid) {
			return (float)Math.Sqrt(points.RadiusSquared(centroid));
		}

		/// <summary>
		/// 符号つき面積
		/// </summary>
		/// <param name="a"></param>
		/// <param name="b"></param>
		/// <param name="c"></param>
		/// <returns></returns>
		public static float SignedArea(ref Vector2 a, ref Vector2 b, ref Vector2 c) {
			Vector2 ab, cb;
			Vector2.Subtract(ref a, ref b, out ab);
			Vector2.Subtract(ref c, ref b, out cb);
			return Cross(ref ab, ref cb);
		}
		public static float Cross(ref Vector2 a, ref Vector2 b) {
			return a.X * b.Y - a.Y * b.X;
		}

	}

}
