8eca5c36a1bf1a37e1d64da88237b635f268c071
[project/luci.git] / applications / luci-app-statistics / luasrc / statistics / rrdtool / colors.lua
1 -- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
2 -- Licensed to the public under the Apache License 2.0.
3
4 module("luci.statistics.rrdtool.colors", package.seeall)
5
6 require("luci.util")
7
8
9 Instance = luci.util.class()
10
11 function Instance.from_string( self, s )
12         return {
13                 tonumber(s:sub(1,2), 16),
14                 tonumber(s:sub(3,4), 16),
15                 tonumber(s:sub(5,6), 16)
16         }
17 end
18
19 function Instance.to_string( self, c )
20         return string.format(
21                 "%02x%02x%02x",
22                 math.floor(c[1]),
23                 math.floor(c[2]),
24                 math.floor(c[3])
25         )
26 end
27
28 function Instance.random( self )
29         local r   = math.random(255)
30         local g   = math.random(255)
31         local min = 0
32         local max = 255
33
34         if ( r + g ) < 255 then
35                 min = 255 - r - g
36         else
37                 max = 511 - r - g
38         end
39
40         local b = min + math.floor( math.random() * ( max - min ) )
41
42         return { r, g, b }
43 end
44
45 function Instance.faded( self, fg, opts )
46         opts = opts or {}
47         opts.background = opts.background or { 255, 255, 255 }
48         opts.alpha      = opts.alpha      or 0.25
49
50         if type(opts.background) == "string" then
51                 opts.background = _string_to_color(opts.background)
52         end
53
54         local bg = opts.background
55
56         return {
57                 ( opts.alpha * fg[1] ) + ( ( 1.0 - opts.alpha ) * bg[1] ),
58                 ( opts.alpha * fg[2] ) + ( ( 1.0 - opts.alpha ) * bg[2] ),
59                 ( opts.alpha * fg[3] ) + ( ( 1.0 - opts.alpha ) * bg[3] )
60         }
61 end