// Definition of overloaded functions for trigonometric functions sin, cos, atan.
// These are needed for cartesian<->polar coordinate conversions.
// The functions in this file use simple approximation functions for use with GLSL.

const float RAD_90  = 1.57079632680;
const float RAD_180 = 3.14159265359;
const float RAD_270 = 4.71238898039;
const float RAD_360 = 6.28318530718;

const float ONEQTR_PI = RAD_180 / 4.0;
const float THRQTR_PI = 3.0 * RAD_180 / 4.0;

float cos (in float ang) {
    float sign = 1.0, ang2, ang4;

    if (ang < 0.0) {
        ang += RAD_360;
    }
    if (ang <= RAD_90) {
        sign = 1.0;
        ang = ang;
    } else if ( ang <= RAD_180 ) {
        sign = -1.0;
        ang = RAD_180 - ang;
    } else if ( ang <= RAD_270 ) {
        sign = -1.0;
        ang -= RAD_180;
    } else if ( ang <= RAD_360 ) {
        sign = 1.0;
        ang = RAD_360 - ang;
    }
    ang2 = ang*ang;
    ang4 = ang2*ang2;
    return sign * (1.0 - 0.4967*ang2 + 0.03705*ang4);
}

float sin (in float ang) {
    return cos(ang-RAD_90);
}

float atan (in float y, in float x) {
    float r, angle;
    float abs_y = abs(y) + 1e-10;
    if ( x < 0.0 ) {
        r = (x + abs_y) / (abs_y - x);
        angle = THRQTR_PI;
    } else {
        r = (x - abs_y) / (x + abs_y);
        angle = ONEQTR_PI;
    }
    angle += (0.1963 * r * r - 0.9817) * r;
    if ( y < 0.0 ) {
        return -angle;     /* negate if in quad III or IV */
    } else {
        return angle;
    }
}
