Skip to content

Instantly share code, notes, and snippets.

@patriciogonzalezvivo
Last active April 15, 2024 20:34
Show Gist options
  • Star 93 You must be signed in to star a gist
  • Fork 15 You must be signed in to fork a gist
  • Save patriciogonzalezvivo/986341af1560138dde52 to your computer and use it in GitHub Desktop.
Save patriciogonzalezvivo/986341af1560138dde52 to your computer and use it in GitHub Desktop.
GLSL Math functions

Trigonometry

const float PI = 3.1415926535897932384626433832795;
const float PI_2 = 1.57079632679489661923;
const float PI_4 = 0.785398163397448309616;

float PHI = (1.0+sqrtf(5.0))/2.0;
float PI180 = float(PI / 180.0);
float sind(float a){return sin(a * PI180);}
float cosd(float a){return cos(a * PI180);}

From http://duriansoftware.com/joe/An-intro-to-modern-OpenGL.-Chapter-3:-3D-transformation-and-projection.html

mat4 scale(float x, float y, float z){
    return mat4(
        vec4(x,   0.0, 0.0, 0.0),
        vec4(0.0, y,   0.0, 0.0),
        vec4(0.0, 0.0, z,   0.0),
        vec4(0.0, 0.0, 0.0, 1.0)
    );
}

mat4 translate(float x, float y, float z){
    return mat4(
        vec4(1.0, 0.0, 0.0, 0.0),
        vec4(0.0, 1.0, 0.0, 0.0),
        vec4(0.0, 0.0, 1.0, 0.0),
        vec4(x,   y,   z,   1.0)
    );
}

mat4 RotateX(float phi){
    return mat4(
        vec4(1.,0.,0.,0),
        vec4(0.,cos(phi),-sin(phi),0.),
        vec4(0.,sin(phi),cos(phi),0.),
        vec4(0.,0.,0.,1.));
}

mat4 RotateY(float theta){
    return mat4(
        vec4(cos(theta),0.,-sin(theta),0),
        vec4(0.,1.,0.,0.),
        vec4(sin(theta),0.,cos(theta),0.),
        vec4(0.,0.,0.,1.));
}

mat4 RotateZ(float psi){
    return mat4(
        vec4(cos(psi),-sin(psi),0.,0),
        vec4(sin(psi),cos(psi),0.,0.),
        vec4(0.,0.,1.,0.),
        vec4(0.,0.,0.,1.));
}

IQ Functions by Iñigo Quilez

float almostIdentity( float x, float m, float n ){
    if( x>m ) return x;

    const float a = 2.0f*n - m
    const float b = 2.0f*m - 3.0f*n;
    const float t = x/m;

    return (a*t + b)*t*t + n;
}
float impulse( float k, float x ){
    const float h = k*x;
    return h*expf(1.0f-h);
}
float cubicPulse( float c, float w, float x ){
    x = fabsf(x - c);
    if( x>w ) return 0.0f;
    x /= w;
    return 1.0f - x*x*(3.0f-2.0f*x);
}
float expStep( float x, float k, float n ){
    return expf( -k*powf(x,n) );
}
float parabola( float x, float k ){
    return powf( 4.0f*x*(1.0f-x), k );
}
float pcurve( float x, float k ){
    float k = powf(a+b,a+b) / (pow(a,a)*pow(b,b));
    return k * powf( x, a ) * powf( 1.0-x, b );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment