//!HOOK MAINPRESUB
//!BIND HOOKED
//!DESC unfish

vec2 pfish,uv;
vec3 p1,p2,p3,p4,p,q,deltah,deltav;
vec3 vp = vec3(0.0, 0.0, 0.0);
vec3 vd = vec3(0.0, 1.0, 0.0);
vec3 vu = vec3(0.0, 0.0, 1.0);
vec3 vr = vec3(1.0, 0.0, 0.0);
vec4 missingcolour = vec4(0.25,0.0,0.0,1.0);
float theta,phi,r,dh,dv,h,v;

float DTOR = 0.0174532925;
float roll = 0.0;
float tilt = -32.0;
float pan = 0.0;
float perspfov = 90.0;

float FISHFOV = 160.0;
float WIDTH = target_size.x;
float HEIGHT = target_size.y;
float CENTERX = WIDTH / 2.0;
float CENTERY = HEIGHT / 2.0;
float RADIUS = WIDTH / 2.0;

vec3 RotateX(vec3 p,float angle)
{
    vec3 q;
    q.x =  p.x;
    q.y =  p.y * cos(angle) + p.z * sin(angle);
    q.z = -p.y * sin(angle) + p.z * cos(angle);
    return q;
}

vec3 RotateY(vec3 p,float angle)
{
    vec3 q;
    q.x =  p.x * cos(angle) + p.z * sin(angle);
    q.y =  p.y;
    q.z = -p.x * sin(angle) + p.z * cos(angle);                       
    return q;
}

vec3 RotateZ(vec3 p,float angle)
{
    vec3 q;
    q.x =  p.x * cos(angle) + p.y * sin(angle);
    q.y = -p.x * sin(angle) + p.y * cos(angle);
    q.z =  p.z;
    return q;
}

vec4 hook()
{
    perspfov *= DTOR;
    FISHFOV *= DTOR;
    roll *= DTOR;
    tilt *= DTOR;
    pan *= DTOR;

    dh = tan(0.5*perspfov);
    dv = target_size.y * dh / target_size.x;
    p1 = vp + vd - dh*vr + dv*vu;
    p2 = vp + vd - dh*vr - dv*vu;
    p3 = vp + vd + dh*vr - dv*vu;
    p4 = vp + vd + dh*vr + dv*vu;
    deltah = p4 - p1;
    deltav = p2 - p1;

    uv = HOOKED_pos;
    p = p1 + uv.x * deltah + uv.y * deltav;

    p = RotateZ(p, pan);
    p = RotateX(p, tilt);
    p = RotateY(p, roll);

    theta = atan(p.z,p.x);
    phi = atan(sqrt(p.x*p.x+p.z*p.z),p.y);
    r =  phi / FISHFOV; 

    r *= (2.0*RADIUS/WIDTH);
    pfish.x = (CENTERX/WIDTH) + r * cos(theta);
    pfish.y = ((HEIGHT-1.0-CENTERY)/HEIGHT) + (WIDTH/HEIGHT) * r * sin(theta);

    if (r > 1.0 || pfish.x < 0.0 || pfish.y < 0.0 || pfish.x > 1.0 || pfish.y > 1.0)
        return missingcolour;
    else
        return HOOKED_tex(pfish);
}