88f516169e02dfe46ff22523eb28a353ad421a75
[tabakrolletjie.git] / tabakrolletjie / transforms.py
1 """ Image transformations for use with the image loader. """
2
3 import pygame.surface
4
5 import pygame.locals as pgl
6
7
8 class Transform(object):
9
10     ARGS = []
11
12     def __init__(self, **kw):
13         for k in self.ARGS:
14             setattr(self, k, kw.pop(k))
15         assert not kw
16         self._repr = "%s: <%s>" % (
17             self.__class__.__name__,
18             ", ".join("%s=%s" % (k, getattr(self, k)) for k in self.ARGS))
19         return
20
21     def __repr__(self):
22         return self._repr
23
24     def __hash__(self):
25         return hash(self._repr)
26
27     def __eq__(self, other):
28         if not isinstance(other, Transform):
29             return NotImplemented
30         return self._repr == other._repr
31
32     def apply(self, surface):
33         raise NotImplementedError("Transforms should implement .apply")
34
35
36 class NullTransform(Transform):
37     """ Do nothing. """
38
39     def apply(self, surface):
40         return surface
41
42
43 class Overlay(Transform):
44     """ Apply a colour overlay. """
45
46     ARGS = ["colour"]
47
48     def apply(self, surface):
49         over = pygame.surface.Surface(surface.get_size())
50         over = over.convert_alpha()
51         over.fill(self.colour)
52         surface.blit(over, (0, 0), None)
53         return surface
54
55
56 class Multiply(Transform):
57     """ Apply a colour by multiplying. """
58
59     ARGS = ["colour"]
60
61     def apply(self, surface):
62         mult = pygame.surface.Surface(surface.get_size())
63         mult = mult.convert_alpha()
64         mult.fill(self.colour)
65         surface.blit(mult, (0, 0), None, pgl.BLEND_RGBA_MULT)
66         return surface
67
68
69 class Alpha(Transform):
70     """ Make translucent. """
71
72     ARGS = ["alpha"]
73
74     def apply(self, surface):
75         surface.fill((255, 255, 255, self.alpha), None, pgl.BLEND_RGBA_MULT)
76         return surface