using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.Drawing.Drawing2D;

namespace PointInsidePolygon
{
    public partial class frm60PointInsidePolygon : Form
    {
        public frm60PointInsidePolygon()
        {
            InitializeComponent();
        }

        // The polygon's points.
        private List<Point> PolygonPoints = new List<Point>();

        // The test points.
        private List<Point> TestPoints = new List<Point>();

        // Add a point to the polygon or add a test point.
        private void frm60PointInsidePolygon_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left) PolygonPoints.Add(e.Location);
            else TestPoints.Add(e.Location);

            Refresh();
        }

        // Draw.
        private void frm60PointInsidePolygon_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;

            // Draw the polygon.
            if (PolygonPoints.Count > 2)
                e.Graphics.DrawPolygon(Pens.Blue, PolygonPoints.ToArray());
            foreach (Point point in PolygonPoints)
                DrawPoint(e.Graphics, point, Brushes.Silver, Pens.Black);

            // Draw the test points.
            foreach (Point point in TestPoints)
            {
                if (PointInPolygon(PolygonPoints, point))
                    DrawPoint(e.Graphics, point, Brushes.Black, Pens.Black);
                else
                    DrawPoint(e.Graphics, point, Brushes.White, Pens.Black);
            }
        }

        // Return true if the point is in the polygon.
        public bool PointInPolygon(List<Point> points, Point point)
        {
            // Get the angle between the point and the first and last vertices.
            int max_point = points.Count - 1;
            float total_angle = GetAngle(
                points[max_point].X, points[max_point].Y,
                point.X, point.Y,
                points[0].X, points[0].Y);

            // Add the angles from the point
            // to each other pair of vertices.
            for (int i = 0; i < max_point; i++)
            {
                total_angle += GetAngle(
                    points[i].X, points[i].Y,
                    point.X, point.Y,
                    points[i + 1].X, points[i + 1].Y);
            }

            // The total angle should be 2 * PI or -2 * PI if the point is in
            // the polygon and close to zero if the point is outside the polygon.
            return (Math.Abs(total_angle) > 0.000001);
        }

        // Return the angle ABC between PI and -PI.
        // Note that the value is the opposite of what you might
        // expect because Y coordinates increase downward.
        public static float GetAngle(float Ax, float Ay, float Bx, float By, float Cx, float Cy)
        {
            // Get the dot product.
            float dot_product = DotProduct(Ax, Ay, Bx, By, Cx, Cy);

            // Get the cross product.
            float cross_product = CrossProductLength(Ax, Ay, Bx, By, Cx, Cy);

            // Calculate the angle.
            return (float)Math.Atan2(cross_product, dot_product);
        }

        // Return the length of the cross product AB x BC.
        // The cross product is a vector perpendicular to AB
        // and BC having length |AB| * |BC| * Sin(theta) and
        // with direction given by the right-hand rule.
        // For two vectors in the X-Y plane, the result is a
        // vector with X and Y components 0 so the Z component
        // gives the vector's length and direction.
        public static float CrossProductLength(float Ax, float Ay,
            float Bx, float By, float Cx, float Cy)
        {
            // Get the vectors' coordinates.
            float BAx = Ax - Bx;
            float BAy = Ay - By;
            float BCx = Cx - Bx;
            float BCy = Cy - By;

            // Calculate the Z coordinate of the cross product.
            return (BAx * BCy - BAy * BCx);
        }

        // Return the dot product AB · BC.
        // Note that AB · BC = |AB| * |BC| * Cos(theta).
        private static float DotProduct(float Ax, float Ay,
            float Bx, float By, float Cx, float Cy)
        {
            // Get the vectors' coordinates.
            float BAx = Ax - Bx;
            float BAy = Ay - By;
            float BCx = Cx - Bx;
            float BCy = Cy - By;

            // Calculate the dot product.
            return (BAx * BCx + BAy * BCy);
        }

        // Draw a filled point.
        private void DrawPoint(Graphics gr, Point point, Brush brush, Pen pen)
        {
            const int radius = 4;

            Rectangle rect = new Rectangle(
                point.X - radius, point.Y - radius,
                2 * radius, 2 * radius);
            gr.FillEllipse(brush, rect);
            gr.DrawEllipse(pen, rect);
        }


        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.SuspendLayout();
            // 
            // frm60PointInsidePolygon
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 261);
            this.Name = "frm60PointInsidePolygon";
            this.Text = "PointInsidePolygon";
            this.Paint += new System.Windows.Forms.PaintEventHandler(this.frm60PointInsidePolygon_Paint);
            this.MouseClick += new System.Windows.Forms.MouseEventHandler(this.frm60PointInsidePolygon_MouseClick);
            this.ResumeLayout(false);

        }

        #endregion
    }
}