00001
00002
00003
00004
00005
00006
00007
00008
00009
00010 #include <cstdio>
00011 #include <cstring>
00012 #include <cctype>
00013 #include "color.h"
00014
00015 const Color Color::White = Color(1.0f, 1.0f, 1.0f);
00016 const Color Color::Black = Color(0.0f, 0.0f, 0.0f);
00017
00018 template<class T> T clamp(T x)
00019 {
00020 if (x < 0)
00021 return 0;
00022 else if (x > 1)
00023 return 1;
00024 else
00025 return x;
00026 }
00027
00028 Color::Color()
00029 {
00030 c[Red] = c[Green] = c[Blue] = 0;
00031 c[Alpha] = 0xff;
00032 }
00033
00034
00035 Color::Color(float r, float g, float b)
00036 {
00037 c[Red] = (unsigned char) (clamp(r) * 255.99f);
00038 c[Green] = (unsigned char) (clamp(g) * 255.99f);
00039 c[Blue] = (unsigned char) (clamp(b) * 255.99f);
00040 c[Alpha] = 0xff;
00041 }
00042
00043
00044 Color::Color(float r, float g, float b, float a)
00045 {
00046 c[Red] = (unsigned char) (clamp(r) * 255.99f);
00047 c[Green] = (unsigned char) (clamp(g) * 255.99f);
00048 c[Blue] = (unsigned char) (clamp(b) * 255.99f);
00049 c[Alpha] = (unsigned char) (clamp(a) * 255.99f);
00050 }
00051
00052
00053 Color::Color(unsigned char r, unsigned char g, unsigned char b)
00054 {
00055 c[Red] = r;
00056 c[Green] = g;
00057 c[Blue] = b;
00058 c[Alpha] = 0xff;
00059 }
00060
00061
00062 Color::Color(Color& color, float alpha)
00063 {
00064 *this = color;
00065 c[Alpha] = (unsigned char) (clamp(alpha) * 255.99f);
00066 }
00067
00068
00069
00070
00071
00072 bool Color::parse(const char* s, Color& c)
00073 {
00074 if (s[0] == '#')
00075 {
00076 s++;
00077
00078 int length = strlen(s);
00079
00080
00081 for (int i = 0; i < length; i++)
00082 {
00083 if (!isxdigit(s[i]))
00084 return false;
00085 }
00086
00087 unsigned int n;
00088 sscanf(s, "%x", &n);
00089 if (length == 3)
00090 {
00091 c = Color((unsigned char) ((n >> 8) * 17),
00092 (unsigned char) (((n & 0x0f0) >> 4) * 17),
00093 (unsigned char) ((n & 0x00f) * 17));
00094 return true;
00095 }
00096 else if (length == 6)
00097 {
00098 c = Color((unsigned char) (n >> 16),
00099 (unsigned char) ((n & 0x00ff00) >> 8),
00100 (unsigned char) (n & 0x0000ff));
00101 return true;
00102 }
00103 else
00104 {
00105 return false;
00106 }
00107 }
00108 else
00109 {
00110
00111 if (!strcmp(s, "red"))
00112 c = Color(1.0f, 0.0f, 0.0f);
00113 else if (!strcmp(s, "green"))
00114 c = Color(0.0f, 1.0f, 0.0f);
00115 else if (!strcmp(s, "blue"))
00116 c = Color(0.0f, 0.0f, 1.0f);
00117 else if (!strcmp(s, "cyan"))
00118 c = Color(0.0f, 1.0f, 1.0f);
00119 else if (!strcmp(s, "magenta"))
00120 c = Color(1.0f, 0.0f, 1.0f);
00121 else if (!strcmp(s, "yellow"))
00122 c = Color(1.0f, 1.0f, 0.0f);
00123 else if (!strcmp(s, "black"))
00124 c = Color(0.0f, 0.0f, 0.0f);
00125 else if (!strcmp(s, "white"))
00126 c = Color(1.0f, 1.0f, 1.0f);
00127 else
00128 return false;
00129
00130 return true;
00131 }
00132 }