Back to index

kdeartwork  4.3.2
xs_hsv.c
Go to the documentation of this file.
00001 /* xscreensaver, Copyright (c) 1992, 1997 Jamie Zawinski <jwz@jwz.org>
00002  *
00003  * Permission to use, copy, modify, distribute, and sell this software and its
00004  * documentation for any purpose is hereby granted without fee, provided that
00005  * the above copyright notice appear in all copies and that both that
00006  * copyright notice and this permission notice appear in supporting
00007  * documentation.  No representations are made about the suitability of this
00008  * software for any purpose.  It is provided "as is" without express or 
00009  * implied warranty.
00010  */
00011 
00012 /* This file contains some utility routines for randomly picking the colors
00013    to hack the screen with.
00014  */
00015 
00016 /* #include "utils.h" */
00017 #include "xs_hsv.h"
00018 
00019 void
00020 hsv_to_rgb (int h, double s, double v,
00021            unsigned short *r, unsigned short *g, unsigned short *b)
00022 {
00023   double H, S, V, R, G, B;
00024   double p1, p2, p3;
00025   double f;
00026   int i;
00027 
00028   if (s < 0) s = 0;
00029   if (v < 0) v = 0;
00030   if (s > 1) s = 1;
00031   if (v > 1) v = 1;
00032 
00033   S = s; V = v;
00034   H = (h % 360) / 60.0;
00035   i = H;
00036   f = H - i;
00037   p1 = V * (1 - S);
00038   p2 = V * (1 - (S * f));
00039   p3 = V * (1 - (S * (1 - f)));
00040   if     (i == 0) { R = V;  G = p3; B = p1; }
00041   else if (i == 1) { R = p2; G = V;  B = p1; }
00042   else if (i == 2) { R = p1; G = V;  B = p3; }
00043   else if (i == 3) { R = p1; G = p2; B = V;  }
00044   else if (i == 4) { R = p3; G = p1; B = V;  }
00045   else           { R = V;  G = p1; B = p2; }
00046   *r = R * 65535;
00047   *g = G * 65535;
00048   *b = B * 65535;
00049 }
00050 
00051 void
00052 rgb_to_hsv (unsigned short r, unsigned short g, unsigned short b,
00053            int *h, double *s, double *v)
00054 {
00055   double R, G, B, H, S, V;
00056   double cmax, cmin;
00057   double cmm;
00058   int imax;
00059   R = ((double) r) / 65535.0;
00060   G = ((double) g) / 65535.0;
00061   B = ((double) b) / 65535.0;
00062   cmax = R; cmin = G; imax = 1;
00063   if  ( cmax < G ) { cmax = G; cmin = R; imax = 2; }
00064   if  ( cmax < B ) { cmax = B; imax = 3; }
00065   if  ( cmin > B ) { cmin = B; }
00066   cmm = cmax - cmin;
00067   V = cmax;
00068   if (cmm == 0)
00069     S = H = 0;
00070   else
00071     {
00072       S = cmm / cmax;
00073       if       (imax == 1)    H =       (G - B) / cmm;
00074       else  if (imax == 2)    H = 2.0 + (B - R) / cmm;
00075       else /*if (imax == 3)*/ H = 4.0 + (R - G) / cmm;
00076       if (H < 0) H += 6.0;
00077     }
00078   *h = (H * 60.0);
00079   *s = S;
00080   *v = V;
00081 }