Geant4 Cross Reference |
1 // Copyright (C) 2010, Guy Barrand. All rights reserved. 2 // See the file tools.license for terms. 3 4 #ifndef tools_hls 5 #define tools_hls 6 7 namespace tools { 8 9 //T is float or double. 10 11 template <class T> 12 inline T hls_to_rgb2(T rn1,T rn2,T huei) { 13 // taken from CERN-ROOT/TColor. 14 T hue = huei; 15 if (hue > 360) hue = hue - 360; 16 if (hue < 0) hue = hue + 360; 17 if (hue < 60 ) return rn1 + (rn2-rn1)*hue/60; 18 if (hue < 180) return rn2; 19 if (hue < 240) return rn1 + (rn2-rn1)*(240-hue)/60; 20 return rn1; 21 } 22 23 template <class T> 24 inline void hls_to_rgb(T hue,T light,T satur,T& a_r,T& a_g,T& a_b){ 25 // taken from CERN-ROOT/TColor. 26 // Static method to compute RGB from HLS. The l and s are between [0,1] 27 // and h is between [0,360]. The returned r,g,b triplet is between [0,1]. 28 29 T rh, rl, rs, rm1, rm2; 30 rh = rl = rs = 0; 31 32 if (hue > 0) rh = hue; 33 if (rh > 360) rh = 360; 34 35 if (light > 0) rl = light; 36 if (rl > 1) rl = 1; 37 38 if (satur > 0) rs = satur; 39 if (rs > 1) rs = 1; 40 41 if (rl <= T(0.5)) { 42 rm2 = rl*(1 + rs); 43 } else { 44 rm2 = rl + rs - rl*rs; 45 } 46 rm1 = 2*rl - rm2; 47 48 if (!rs) { a_r = rl; a_g = rl; a_b = rl; return; } 49 a_r = hls_to_rgb2(rm1, rm2, rh+120); 50 a_g = hls_to_rgb2(rm1, rm2, rh); 51 a_b = hls_to_rgb2(rm1, rm2, rh-120); 52 } 53 54 template <class T> 55 inline void rgb_to_hls(T rr,T gg,T bb,T& hue,T& light,T& satur) { 56 // The r,g,b triplet is between 57 // [0,1], hue is between [0,360], light and satur are [0,1]. 58 59 T rnorm, gnorm, bnorm, minval, maxval, msum, mdiff, cr, cg, cb; 60 minval = maxval = 0; 61 cr = cg = cb = 0; 62 63 if (rr > 0) cr = rr; 64 if (cr > 1) cr = 1; 65 66 if (gg > 0) cg = gg; 67 if (cg > 1) cg = 1; 68 69 if (bb > 0) cb = bb; 70 if (cb > 1) cb = 1; 71 72 minval = cr; 73 if (cg < minval) minval = cg; 74 if (cb < minval) minval = cb; 75 maxval = cr; 76 if (cg > maxval) maxval = cg; 77 if (cb > maxval) maxval = cb; 78 79 rnorm = gnorm = bnorm = 0; 80 mdiff = maxval - minval; 81 msum = maxval + minval; 82 light = T(0.5) * msum; 83 if (maxval != minval) { 84 rnorm = (maxval - cr)/mdiff; 85 gnorm = (maxval - cg)/mdiff; 86 bnorm = (maxval - cb)/mdiff; 87 } else { 88 satur = hue = 0; 89 return; 90 } 91 92 if (light < T(0.5)) 93 satur = mdiff/msum; 94 else 95 satur = mdiff/(2 - msum); 96 97 if (cr == maxval) 98 hue = 60 * (6 + bnorm - gnorm); 99 else if (cg == maxval) 100 hue = 60 * (2 + rnorm - bnorm); 101 else 102 hue = 60 * (4 + gnorm - rnorm); 103 104 if (hue > 360) 105 hue = hue - 360; 106 } 107 108 109 } 110 111 #endif