Ticket #3205: new_common_color_file.patch

File new_common_color_file.patch, 1.5 KB (added by fpre_O_O_O_O_O_O, 9 years ago)

new file for merging hsl to rgb function necessary for lobby and gamesetup colors into one file spreading them over to both

  • gui/common/color.js

    old new  
     1////////////////////////////////////////////////////////////////////////////////////////////////
     2// some color functions previously used from lobby.js
     3// now spread over lobby.js and gamesetup.js
     4
     5// Ensure `value` is between 0 and 1.
     6function clampColorValue(value)
     7{
     8    return Math.abs(1 - Math.abs(value - 1));
     9}
     10
     11function rgbToHsl(r, g, b)
     12{
     13    r /= 255;
     14    g /= 255;
     15    b /= 255;
     16    var max = Math.max(r, g, b), min = Math.min(r, g, b);
     17    var h, s, l = (max + min) / 2;
     18
     19    if (max == min)
     20        h = s = 0; // achromatic
     21    else
     22    {
     23        var d = max - min;
     24        s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
     25        switch (max)
     26        {
     27            case r: h = (g - b) / d + (g < b ? 6 : 0); break;
     28            case g: h = (b - r) / d + 2; break;
     29            case b: h = (r - g) / d + 4; break;
     30        }
     31        h /= 6;
     32    }
     33
     34    return [h, s, l];
     35}
     36
     37function hslToRgb(h, s, l)
     38{
     39    function hue2rgb(p, q, t)
     40    {
     41        if (t < 0) t += 1;
     42        if (t > 1) t -= 1;
     43        if (t < 1/6) return p + (q - p) * 6 * t;
     44        if (t < 1/2) return q;
     45        if (t < 2/3) return p + (q - p) * (2/3 - t) * 6;
     46        return p;
     47    }
     48
     49    [h, s, l] = [h, s, l].map(clampColorValue);
     50    var r, g, b;
     51
     52    if (s == 0)
     53        r = g = b = l; // achromatic
     54    else {
     55        var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
     56        var p = 2 * l - q;
     57        r = hue2rgb(p, q, h + 1/3);
     58        g = hue2rgb(p, q, h);
     59        b = hue2rgb(p, q, h - 1/3);
     60    }
     61
     62    return [r, g, b].map(function (n) Math.round(n * 255));
     63}
     64
     65