Also pulsate intensity.
[tabakrolletjie.git] / tabakrolletjie / lights.py
1 """ May it be a light for you in dark places, when all other lights go out.
2 """
3
4 import pymunk
5 import pymunk.pygame_util
6 import pygame.display
7 import pygame.draw
8 import pygame.locals as pgl
9 import pygame.rect
10
11 from .constants import LIGHT_CATEGORY, FITTINGS_CATEGORY
12 from .rays import RayPolyManager
13 from .utils import DetailedTimer
14 from .loader import loader
15 from .transforms import Multiply
16
17 LIGHT_FILTER = pymunk.ShapeFilter(
18     mask=pymunk.ShapeFilter.ALL_MASKS ^ (
19         LIGHT_CATEGORY | FITTINGS_CATEGORY),
20     categories=LIGHT_CATEGORY)
21
22 FITTINGS_FILTER = pymunk.ShapeFilter(
23     mask=pymunk.ShapeFilter.ALL_MASKS ^ (
24         LIGHT_CATEGORY | FITTINGS_CATEGORY),
25     categories=FITTINGS_CATEGORY)
26
27 # Just match lights, nothing else
28 LIT_BY_FILTER = pymunk.ShapeFilter(mask=LIGHT_CATEGORY)
29
30
31 class LightManager(object):
32     """ Manages a set of lights. """
33
34     def __init__(self, space, gamestate):
35         self._space = space
36         self._lights = [
37             BaseLight.load(cfg) for cfg in gamestate.station["lights"]]
38         for light in self._lights:
39             light.add(self._space)
40
41     def add_light(self, cfg):
42         light = BaseLight.load(cfg)
43         self._lights.append(light)
44         light.add(self._space)
45
46     def toggle_nearest(self, *args, **kw):
47         light = self.nearest(*args, **kw)
48         if light:
49             light.toggle()
50
51     def nearest(self, pos, surfpos=False, max_distance=1.0):
52         if surfpos:
53             surface = pygame.display.get_surface()
54             pos = pymunk.pygame_util.from_pygame(pos, surface)
55         point_info = self._space.point_query_nearest(
56             pos, max_distance, pymunk.ShapeFilter(mask=FITTINGS_CATEGORY))
57         if point_info is not None:
58             return point_info.shape.body.light
59         return None
60
61     def lit_by(self, pos, surfpos=False, max_distance=0.0):
62         if surfpos:
63             surface = pygame.display.get_surface()
64             pos = pymunk.pygame_util.from_pygame(pos, surface)
65         point_info_list = self._space.point_query(
66             pos, max_distance, pymunk.ShapeFilter(mask=LIGHT_CATEGORY))
67         lights = [p.shape.body.light for p in point_info_list]
68         return [
69             light for light in lights
70             if light.on and light.ray_manager.reaches(pos)
71         ]
72
73     def light_query(self, shape):
74         """Query the lights by shape"""
75         old_filter = shape.filter
76         # We need to restrict matches to only the lights
77         shape.filter = LIT_BY_FILTER
78         shape_info_list = self._space.shape_query(shape)
79         shape.filter = old_filter
80         lights = [p.shape.body.light for p in shape_info_list]
81         return [
82             light for light in lights
83             if light.on and light.ray_manager.reaches(shape.body.position)
84         ]
85
86     def render_light(self, surface):
87         for light in self._lights:
88             light.render_light(surface)
89
90     def render_fittings(self, surface):
91         for light in self._lights:
92             light.render_fitting(surface)
93
94     def tick(self):
95         for light in self._lights:
96             light.tick()
97
98
99 class BaseLight(object):
100     """ Common light functionality. """
101
102     COLOURS = {
103         "red": (255, 0, 0),
104         "green": (0, 255, 0),
105         "blue": (0, 0, 255),
106         "cyan": (0, 255, 255),
107         "yellow": (255, 255, 0),
108         "magenta": (255, 0, 255),
109         "white": (255, 255, 255),
110     }
111
112     # defaults
113     RAY_MANAGER = RayPolyManager
114     FITTING_IMG = None
115     FITTING_RADIUS = 24.0
116
117     # cached surfaces
118     _surface_cache = {}
119
120     def __init__(
121             self, colour, position, intensity=1.0, radius_limits=None,
122             angle_limits=None):
123         self.colour = colour
124         self.on = True
125         self.intensity = intensity
126         self.body = pymunk.Body(0, 0, pymunk.body.Body.STATIC)
127         self.body.light = self
128         self.ray_manager = self.RAY_MANAGER(
129             self.body, position, ray_filter=LIGHT_FILTER,
130             radius_limits=radius_limits, angle_limits=angle_limits)
131         self.fitting = pymunk.Circle(
132             self.body, self.FITTING_RADIUS, self.ray_manager.position)
133         self.fitting.filter = FITTINGS_FILTER
134         self._fitting_image = None
135
136     @property
137     def position(self):
138         return self.ray_manager.position
139
140     @classmethod
141     def load(cls, config):
142         kw = config.copy()
143         light_type = kw.pop("type")
144         [light_class] = [
145             c for c in cls.__subclasses__()
146             if c.__name__.lower() == light_type]
147         return light_class(**kw)
148
149     def add(self, space):
150         if self.body.space is not None:
151             space.remove(self.body, *self.body.shapes)
152         space.add(self.body, self.fitting)
153         self.ray_manager.set_space(space)
154         self.ray_manager.update_shapes()
155
156     def toggle(self):
157         self.on = not self.on
158
159     def _cached_surface(self, name, surface):
160         surf = self._surface_cache.get(name)
161         if surf is None:
162             surf = self._surface_cache[name] = pygame.surface.Surface(
163                 surface.get_size(), pgl.SWSURFACE
164             ).convert_alpha()
165         return surf
166
167     def light_colour(self):
168         light_colour = self.COLOURS[self.colour]
169         intensity = int(255 * self.intensity)
170         return light_colour + (intensity,)
171
172     def render_light(self, surface):
173         if not self.on:
174             return
175
176         dt = DetailedTimer("render_light")
177         dt.start()
178
179         max_radius = self.ray_manager.max_radius
180         min_radius = self.ray_manager.min_radius
181         dest_rect = self.ray_manager.pygame_rect(surface)
182
183         white, black = (255, 255, 255, 255), (0, 0, 0, 0)
184         light_colour = self.light_colour()
185
186         radius_mask = self._cached_surface('radius_mask', surface)
187         radius_mask.set_clip(dest_rect)
188         ray_mask = self._cached_surface('ray_mask', surface)
189         ray_mask.set_clip(dest_rect)
190
191         ray_mask.fill(black)
192         for pygame_poly in self.ray_manager.pygame_polys(surface):
193             pygame.draw.polygon(ray_mask, white, pygame_poly, 0)
194             pygame.draw.polygon(ray_mask, white, pygame_poly, 1)
195         dt.lap("ray mask rendered")
196
197         radius_mask.fill(black)
198         centre = self.ray_manager.pygame_position(surface)
199         pygame.draw.circle(
200             radius_mask, light_colour, centre, int(max_radius), 0)
201         pygame.draw.circle(
202             radius_mask, black, centre, int(min_radius), 0)
203         dt.lap("radius mask rendered")
204
205         ray_mask.blit(radius_mask, dest_rect, dest_rect, pgl.BLEND_RGBA_MULT)
206         dt.lap("blitted radius mask to ray mask")
207
208         surface.blit(ray_mask, dest_rect, dest_rect)
209         dt.lap("blitted surface")
210         dt.end()
211
212     def fitting_image(self):
213         if self._fitting_image is None:
214             fitting_colour = self.COLOURS[self.colour]
215             self._fitting_image = loader.load_image(
216                 "48", self.FITTING_IMG,
217                 transform=Multiply(colour=fitting_colour))
218         return self._fitting_image
219
220     def invalidate_fitting_image(self):
221         self._fitting_image = None
222
223     def render_fitting(self, surface):
224         rx, ry = self.ray_manager.pygame_position(surface)
225         surface.blit(self.fitting_image(), (rx - 24, ry - 24), None, 0)
226
227     def tick(self):
228         pass
229
230
231 class Lamp(BaseLight):
232
233     FITTING_IMG = "lamp.png"
234
235
236 class MultiColourLamp(BaseLight):
237
238     FITTING_IMG = "lamp.png"
239     DEFAULT_COLOURS = sorted(BaseLight.COLOURS.keys())
240
241     def __init__(self, **kw):
242         self.colour_cycle = kw.pop("colours", None)
243         self.colour_pos = 0
244         kw["colour"] = self.colour_cycle[0]
245         super(MultiColourLamp, self).__init__(**kw)
246
247     def toggle(self):
248         self.colour_pos += 1
249         if self.colour_pos >= len(self.colour_cycle):
250             self.colour = self.colour_cycle[0]
251             self.colour_pos = -1
252             self.on = False
253         else:
254             self.colour = self.colour_cycle[self.colour_pos]
255             self.on = True
256         self.invalidate_fitting_image()
257
258
259 class PulsatingLamp(BaseLight):
260
261     FITTING_IMG = "lamp.png"
262     DEFAULT_PULSE_RANGE = (20, 100)
263     DEFAULT_PULSE_VELOCITY = 2
264     DEFAULT_INTENSITY_RANGE = (0.0, 0.9)
265     DEFAULT_INTENSITY_VELOCITY = 0.1
266
267     def __init__(self, **kw):
268         self.pulse_range = kw.pop("pulse_range", self.DEFAULT_PULSE_RANGE)
269         self.pulse_velocity = kw.pop(
270             "pulse_velocity", self.DEFAULT_PULSE_VELOCITY)
271         self.intensity_range = kw.pop(
272             "intensity_range", self.DEFAULT_INTENSITY_RANGE)
273         self.intensity_velocity = kw.pop(
274             "intensity_velocity", self.DEFAULT_INTENSITY_VELOCITY)
275         super(PulsatingLamp, self).__init__(**kw)
276
277     def _update_range(self, value, velocity, value_range):
278         value += velocity
279         if value < value_range[0]:
280             value = value_range[0]
281             velocity = -velocity
282         elif value > value_range[1]:
283             value = value_range[1]
284             velocity = -velocity
285         return value, velocity
286
287     def tick(self):
288         self.ray_manager.max_radius, self.pulse_velocity = self._update_range(
289             self.ray_manager.max_radius, self.pulse_velocity, self.pulse_range)
290         self.intensity, self.intensity_velocity = self._update_range(
291             self.intensity, self.intensity_velocity, self.intensity_range)
292
293
294 class SpotLight(BaseLight):
295
296     FITTING_IMG = "spotlight.png"
297
298     def __init__(self, **kw):
299         self.angular_velocity = kw.pop("angular_velocity", None)
300         super(SpotLight, self).__init__(**kw)
301
302     def tick(self):
303         if self.angular_velocity:
304             self.ray_manager.rotate_degrees(self.angular_velocity)
305             self.ray_manager.update_shapes()