Color Scripts

Written by: Headmaster

The following can be used to convert an HSB (HSV, HSL) vector into an RGB vector:

 

// Checks the limits of a single component.
float checkComp(float v, float t1, float t2)
{
    if (v < 0.0)
        v = v + 1.0;
        
    if (v > 1.0)
        v = v - 1.0;
        
    if ((v * 6) < 1)
        v = t1 + (t2 - t1) * 6.0 * v;
    else
    {
        if ((v * 2.0) < 1.0)
            v = t2;
        else
        {
            if ((v * 3.0) < 2.0)
                v = t1 + (t2 - t1) * ((2.0 / 3.0) - v) * 6.0;
            else
                v = t1;
        }
    }
        
    return v;
}

// Converts an HSB (HSV) colorspace to RGB colorspace
// Input is a vector:
//   x == hue (0 .. 359.9)
//   y == saturation (0 .. 1)
//   z == bright (value, lum) (0 .. 1)
// Output is a vector:
//   x == red (0 .. 1)
//   y == green (0 .. 1)
//   z == blue (0 .. 1)
vector hsb2rgb(vector hsb)
{
    vector rval;
    integer i;
    float t1;
    float t2;
    
    hsb.x /= 360.0;
    
    if (hsb.y == 0.0)
    {
        rval.x = hsb.z;
        rval.y = hsb.z;
        rval.z = hsb.z;
    }
    else
    {
        if (hsb.z < 0.5)
            t2 = hsb.z * (1.0 + hsb.y);
        else
            t2 = hsb.z + hsb.y - hsb.z * hsb.y;
            
        t1 = 2 * hsb.z - t2;
        
        rval.x = checkComp(hsb.x + (1.0 / 3.0), t1, t2);
        rval.y = checkComp(hsb.x, t1, t2);
        rval.z = checkComp(hsb.x - (1.0 / 3.0), t1, t2);
    }
    
    return rval;
}

 

 

Following can be used to convert an RGB vector to HSB:

 

// Converts an RGB colorspace to HSB colorspace
// Input is a vector:
//   x == red (0 .. 1)
//   y == green (0 .. 1)
//   z == blue (0 .. 1)
// Output is a vector:
//   x == hue (0 .. 359.9)
//   y == saturation (0 .. 1)
//   z == bright (value, lum) (0 .. 1)
vector rgb2hsb(vector rgb)
{
    vector rval;
    float min;
    float max;
    float h;
    float d;
    
    min = rgb.x;
    max = rgb.x;
    
    if (rgb.y < min)
        min = rgb.y;
    if (rgb.z < min)
        min = rgb.z;
        
    if (rgb.y > max)
        max = rgb.y;
    if (rgb.z > max)
        max = rgb.z;
        
    h = 0;
    rval.z = (max + min) / 2.0;
    
    d = max - min;
    
    if (max == min)
        rval.y = 0.0;
    else
    {
        if (rval.z < 0.5)
            rval.y = (max - min) / (max + min);
        else
            rval.y = (max - min) / (2.0 - max - min);
    }
        
    if (d != 0.0)
    {
        if (rgb.x == max)
            h = (rgb.y - rgb.z) / d;
        else if (rgb.y == max)
            h = 2.0 + (rgb.z - rgb.x) / d;
        else
            h = 4.0 + (rgb.x - rgb.y) / d;
    }
    
    h /= 6.0;
    if (h < 0.0)
        h = h + 1.0;
        
    rval.x = h * 360.0;
    
    return rval;
}

 

Category: