﻿using UnityEngine;
using System.Collections;

public class Transformer
{
    /// <summary>
    /// Produces "view" coordinates (aka "eye" or "camera" coordinates)
    /// Applies the view transform of the given camera (transformCamera.worldToCameraMatrix)
    /// to the homogeonous vertex.
    /// </summary>
    public static Vector4 performViewTransform(Vector4 vertex, Camera transformCamera)
    {
        Vector4 result = transformCamera.worldToCameraMatrix * vertex;
        return result;
    }

    /// <summary>
    /// Produces "clip" coordinates by applying the projection transform.
    /// This result can be transformed into "Normalized Device Coordinates" by performing a homogeneous devide.
    /// </summary>
    public static Vector4 performProjectionTransform(Vector4 vertex, Camera transformCamera)
    {
        Vector4 result = transformCamera.projectionMatrix * vertex;
        return result;
    }

    public static bool clip(Vector4 vertex)
    {
        bool result = !(-vertex.w <= vertex.x && vertex.x <= vertex.w
                        && -vertex.w <= vertex.y && vertex.y <= vertex.w
                        && -vertex.w <= vertex.z && vertex.z <= vertex.w);
        return result;
    }

    /// <summary>
    /// Performs a homogeneous divide and then scaling based on viewport (Screen) width and height.
    /// The result is transformed back into a Vector4 simply to keep with 
    /// </summary>
    public static Vector2 performViewportTransform(Vector4 vertex)
    {
        Vector2 viewportSpace = new Vector2(vertex.x / vertex.w, vertex.y / vertex.w);
        
        viewportSpace.x = (viewportSpace.x + 1) * Screen.width * 0.5f;
        viewportSpace.y = (viewportSpace.y + 1) * Screen.height * 0.5f;

        return viewportSpace;
    }
}
