Imported Upstream version 2008.1+svn1553
[opeanno-debian-packaging.git] / game / util / color.py
blob652dc4f8088bd3ebbe286a1aff85711a9507a792
1 # ###################################################
2 # Copyright (C) 2008 The OpenAnno Team
3 # team@openanno.org
4 # This file is part of OpenAnno.
6 # OpenAnno is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the
18 # Free Software Foundation, Inc.,
19 # 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 # ###################################################
22 import game.main
24 class ColorIter(object):
25 def __iter__(self):
26 return self
28 def next(self):
29 try:
30 if hasattr(self, 'last'):
31 id = game.main.db('SELECT rowid from data.colors where rowid > ? order by rowid limit 1', self.last)[0][0]
32 else:
33 id = game.main.db('SELECT rowid from data.colors order by rowid limit 1')[0][0]
34 except:
35 raise StopIteration
36 self.last = id
37 return Color[id]
39 class ColorMeta(type):
40 def __getitem__(cls, key):
41 if key == 0:
42 return None
43 r,g,b = game.main.db('SELECT red,green,blue from data.colors where %s = ?' % ('name' if isinstance(key, str) else 'rowid',), key)[0]
44 c = Color(r, g, b)
45 return c
47 def __iter__(cls):
48 return ColorIter()
50 class Color(object):
51 __metaclass__ = ColorMeta
52 def __init__(self, r = 0, g = 0, b = 0, a = 255):
53 if isinstance(r, float) and r >= 0.0 and r <= 1.0:
54 r = int(r * 255)
55 if isinstance(g, float) and g >= 0.0 and g <= 1.0:
56 g = int(g * 255)
57 if isinstance(b, float) and b >= 0.0 and b <= 1.0:
58 b = int(b * 255)
59 if isinstance(a, float) and a >= 0.0 and a <= 1.0:
60 a = int(a * 255)
61 assert(isinstance(r, int) and isinstance(b, int) and isinstance(b, int) and isinstance(a, int))
62 self.r, self.g, self.b, self.a = r, g, b, a
63 try:
64 self.name, self.id = game.main.db('SELECT name,rowid from data.colors where red = ? and green = ? and blue = ?', self.r, self.g, self.b)[0]
65 except:
66 pass
68 from game.util.encoder import register_classes
69 register_classes(Color)