﻿/* Programming by Greg Thatcher, http://www.GregThatcher.com */

    /******************* Point Class ****************************/
    function Point (x, y)
    {
        this.x = parseInt(x);
        this.y = parseInt(y);
    }

    /******************* Segment Class ****************************/
    function Segment (x1, y1, x2, y2)
    {
        this.pt1 = new Point(x1, y1);
        this.pt2 = new Point(x2, y2);
    }
    
    /******************* Triangle Class ****************************/
    function Triangle (x1, y1, x2, y2, x3, y3)
    {
        this.vertices = new Array(3);
        this.vertices[0] = new Point(parseInt(x1), parseInt(y1));
        this.vertices[1] = new Point(parseInt(x2), parseInt(y2));
        this.vertices[2] = new Point(parseInt(x3), parseInt(y3));
    }
    Triangle.prototype.GetBoundingRectangle = function()
    {
        var x1 = Math.min(this.vertices[0].x, this.vertices[1].x, this.vertices[2].x);
        var x2 = Math.max(this.vertices[0].x, this.vertices[1].x, this.vertices[2].x);
        var y1 = Math.min(this.vertices[0].y, this.vertices[1].y, this.vertices[2].y);
        var y2 = Math.max(this.vertices[0].y, this.vertices[1].y, this.vertices[2].y);
        
        return new Square(x1, y1, x2, y2);
    }

    function SameSide(p1,p2, a,b)
    {
        var seg1 = new Point(b.x - a.x, b.y - a.y);
        var seg2 = new Point(p1.x - a.x, p1.y - a.y);
        var seg3 = new Point(p2.x - a.x, p2.y - a.y);
        var cp1 = CrossProduct(seg1, seg2)
        var cp2 = CrossProduct(seg1, seg3)
        if (DotProduct(cp1, cp2) >= 0)
        {
            return true
        }
        else 
        {
            return false
        }
    }            

    Triangle.prototype.PointInTriangle = function(p)
    {
        if (SameSide(p, this.vertices[0], this.vertices[1], this.vertices[2]) && 
            SameSide(p, this.vertices[1], this.vertices[0], this.vertices[2]) && 
            SameSide(p, this.vertices[2], this.vertices[0], this.vertices[1]))
        {
            return true;
        }
        else 
        {
            return false
        }

    }
    
    function Square (x1, y1, x2, y2)
    {
        this.x1 = x1;
        this.y1 = y1;
        this.x2 = x2;
        this.y2 = y2;
    }

    // see http://mathworld.wolfram.com/CrossProduct.html
    function CrossProduct (p1, p2)
    {
        return p1.x * p2.y - p1.y * p2.x;
    }
    function DotProduct (v1, v2)
    {
        return v1 * v2;
    }
