747ce92e86449ea92102dbbb5b0d73465339dd66
[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 math
5
6 import pymunk
7 import pymunk.pygame_util
8 import pygame.display
9 import pygame.draw
10 import pygame.locals as pgl
11 import pygame.rect
12 import pygame.transform
13
14 from .constants import (
15     LIGHT_CATEGORY, FITTINGS_CATEGORY, OBSTACLE_CATEGORY, TURNIP_CATEGORY,
16     COLOURS)
17 from .rays import RayPolyManager
18 from .utils import DetailedTimer
19 from .loader import loader
20 from .transforms import ColourWedges
21
22 LIGHT_FILTER = pymunk.ShapeFilter(
23     mask=pymunk.ShapeFilter.ALL_MASKS ^ (
24         LIGHT_CATEGORY | FITTINGS_CATEGORY),
25     categories=LIGHT_CATEGORY)
26
27 FITTINGS_FILTER = pymunk.ShapeFilter(
28     mask=pymunk.ShapeFilter.ALL_MASKS ^ (
29         LIGHT_CATEGORY | FITTINGS_CATEGORY),
30     categories=FITTINGS_CATEGORY)
31
32 # Just match lights, nothing else
33 LIT_BY_FILTER = pymunk.ShapeFilter(mask=LIGHT_CATEGORY)
34 SPACE_FOR_LIGHT_FILTER = pymunk.ShapeFilter(
35     mask=FITTINGS_CATEGORY | OBSTACLE_CATEGORY | TURNIP_CATEGORY)
36
37
38 def check_space_for_light(space, pos, max_distance):
39     point_info = space.point_query_nearest(
40         pos, max_distance, SPACE_FOR_LIGHT_FILTER)
41     if point_info is not None:
42         return True
43     return False
44
45
46 class LightManager(object):
47     """ Manages a set of lights. """
48
49     def __init__(self, space, gamestate):
50         self._space = space
51         self._battery_dead = False
52         self._lights = [
53             BaseLight.load(cfg) for cfg in gamestate.station["lights"]]
54         for light in self._lights:
55             light.add(self._space)
56
57     def add_light(self, cfg):
58         light = BaseLight.load(cfg)
59         self._lights.append(light)
60         light.add(self._space)
61
62     def battery_dead(self):
63         self._battery_dead = True
64         for light in self._lights:
65             light.off()
66
67     def serialize_lights(self):
68         result = []
69         for light in self._lights:
70             result.append(light.serialize())
71         return result
72
73     def toggle_nearest(self, *args, **kw):
74         if self._battery_dead:
75             return
76         light = self.nearest(*args, **kw)
77         if light:
78             light.toggle()
79
80     def nearest(self, pos, surfpos=False, max_distance=1.0):
81         if surfpos:
82             surface = pygame.display.get_surface()
83             pos = pymunk.pygame_util.from_pygame(pos, surface)
84         point_info = self._space.point_query_nearest(
85             pos, max_distance, pymunk.ShapeFilter(mask=FITTINGS_CATEGORY))
86         if point_info is not None:
87             return point_info.shape.body.light
88         return None
89
90     def lit_by(self, pos, surfpos=False, max_distance=0.0):
91         if surfpos:
92             surface = pygame.display.get_surface()
93             pos = pymunk.pygame_util.from_pygame(pos, surface)
94         point_info_list = self._space.point_query(
95             pos, max_distance, LIT_BY_FILTER)
96         lights = [p.shape.body.light for p in point_info_list]
97         return [
98             light for light in lights
99             if light.on and light.ray_manager.reaches(pos)
100         ]
101
102     def light_query(self, shape):
103         """Query the lights by shape"""
104         old_filter = shape.filter
105         # We need to restrict matches to only the lights
106         shape.filter = LIT_BY_FILTER
107         shape_info_list = self._space.shape_query(shape)
108         shape.filter = old_filter
109         lights = [p.shape.body.light for p in shape_info_list]
110         return [
111             light for light in lights
112             if light.on and light.ray_manager.reaches(shape.body.position)
113         ]
114
115     def total_power_usage(self):
116         return sum(light.power_usage() for light in self._lights)
117
118     def render_light(self, surface):
119         for light in self._lights:
120             light.render_light(surface)
121
122     def render_fittings(self, surface):
123         for light in self._lights:
124             light.render_fitting(surface)
125
126     def tick(self):
127         for light in self._lights:
128             light.tick()
129
130
131 def light_fitting_by_type(light_type):
132     """ Render a light fitting image for a light type. """
133     return BaseLight.find_cls(light_type).FITTING_IMG
134
135
136 class BaseLight(object):
137     """ Common light functionality. """
138
139     # defaults
140     RAY_MANAGER = RayPolyManager
141     FITTING_IMG = None
142     FITTING_RADIUS = 24.0
143
144     # cached surfaces
145     _surface_cache = {}
146
147     def __init__(
148             self, colours, position, intensity=1.0, radius_limits=None,
149             direction=None, spread=None, on=True, start_colour=None,
150             bounding_radius=None):
151         self.colour_cycle = colours
152         self.colour_pos = 0
153         self.colour = colours[0]
154         if start_colour and start_colour in colours:
155             self.colour_pos = colours.index(start_colour)
156             self.colour = start_colour
157         self.on = on
158         if not on and len(colours) > 1:
159             self.colour_pos = -1
160         self.intensity = intensity
161         self.body = pymunk.Body(0, 0, pymunk.body.Body.STATIC)
162         self.body.light = self
163         self.ray_manager = self.RAY_MANAGER(
164             self.body, position, ray_filter=LIGHT_FILTER,
165             radius_limits=radius_limits, direction=direction, spread=spread,
166             bounding_radius=bounding_radius)
167         self.fitting = pymunk.Circle(
168             self.body, self.FITTING_RADIUS, self.ray_manager.position)
169         self.fitting.filter = FITTINGS_FILTER
170         self._fitting_image = None
171         self._colour_mult_image = None
172
173     def serialize(self):
174         result = self.ray_manager.serialize()
175         result.update({
176             "type": self.__class__.__name__.lower(),
177             "colours": self.colour_cycle,
178             "position": self.position,
179             "intensity": self.intensity,
180             "on": self.on,
181             "start_colour": self.colour,
182         })
183         return result
184
185     @property
186     def position(self):
187         return self.ray_manager.position
188
189     @classmethod
190     def load(cls, config):
191         kw = config.copy()
192         light_type = kw.pop("type")
193         light_class = cls.find_cls(light_type)
194         return light_class(**kw)
195
196     @classmethod
197     def find_cls(cls, light_type):
198         [light_class] = [
199             c for c in cls.__subclasses__()
200             if c.__name__.lower() == light_type]
201         return light_class
202
203     def add(self, space):
204         if self.body.space is not None:
205             space.remove(self.body, *self.body.shapes)
206         space.add(self.body, self.fitting)
207         self.ray_manager.set_space(space)
208         self.ray_manager.update_shapes()
209
210     def _cached_surface(self, name, surface):
211         surf = self._surface_cache.get(name)
212         if surf is None:
213             surf = self._surface_cache[name] = pygame.surface.Surface(
214                 surface.get_size(), pgl.SWSURFACE
215             ).convert_alpha()
216         return surf
217
218     def light_colour(self):
219         light_colour = COLOURS[self.colour]
220         intensity = int(255 * self.intensity)
221         return light_colour + (intensity,)
222
223     def render_light(self, surface):
224         if not self.on:
225             return
226
227         dt = DetailedTimer("render_light")
228         dt.start()
229
230         max_radius = self.ray_manager.max_radius
231         min_radius = self.ray_manager.min_radius
232         dest_rect = self.ray_manager.pygame_rect(surface)
233
234         white, black = (255, 255, 255, 255), (0, 0, 0, 0)
235         light_colour = self.light_colour()
236
237         radius_mask = self._cached_surface('radius_mask', surface)
238         radius_mask.set_clip(dest_rect)
239         ray_mask = self._cached_surface('ray_mask', surface)
240         ray_mask.set_clip(dest_rect)
241
242         ray_mask.fill(black)
243         for pygame_poly in self.ray_manager.pygame_polys(surface):
244             pygame.draw.polygon(ray_mask, white, pygame_poly, 0)
245             pygame.draw.polygon(ray_mask, white, pygame_poly, 1)
246         dt.lap("ray mask rendered")
247
248         radius_mask.fill(black)
249         centre = self.ray_manager.pygame_position(surface)
250         pygame.draw.circle(
251             radius_mask, light_colour, centre, int(max_radius), 0)
252         pygame.draw.circle(
253             radius_mask, black, centre, int(min_radius), 0)
254         dt.lap("radius mask rendered")
255
256         ray_mask.blit(radius_mask, dest_rect, dest_rect, pgl.BLEND_RGBA_MULT)
257         dt.lap("blitted radius mask to ray mask")
258
259         surface.blit(ray_mask, dest_rect, dest_rect)
260         dt.lap("blitted surface")
261         dt.end()
262
263     def fitting_image(self):
264         if self._fitting_image is None:
265             self._fitting_image = loader.load_image(
266                 "48", self.FITTING_IMG,
267                 transform=ColourWedges(colours=self.colour_cycle))
268         return self._fitting_image
269
270     def invalidate_fitting_image(self):
271         self._fitting_image = None
272
273     def render_fitting(self, surface):
274         rx, ry = self.ray_manager.pygame_position(surface)
275         surface.blit(self.fitting_image(), (rx - 24, ry - 24), None, 0)
276
277     def power_usage(self):
278         if not self.on:
279             return 0.0
280         area = math.pi * (self.ray_manager.max_radius ** 2)  # radius
281         area = area * (self.ray_manager.spread / (2 * math.pi))  # spread
282         return 5 * area * self.intensity / 6400  # 80x80 unit area
283
284     def base_damage(self):
285         return 10 * self.intensity
286
287     def off(self):
288         self.on = False
289
290     def toggle(self):
291         self.colour_pos += 1
292         if self.colour_pos >= len(self.colour_cycle):
293             self.colour = self.colour_cycle[0]
294             self.colour_pos = -1
295             self.on = False
296         else:
297             self.colour = self.colour_cycle[self.colour_pos]
298             self.on = True
299
300     def tick(self):
301         pass
302
303
304 class Lamp(BaseLight):
305
306     FITTING_IMG = "lamp.png"
307
308
309 class PulsatingLamp(BaseLight):
310
311     FITTING_IMG = "lamp.png"
312     DEFAULT_PULSE_RANGE = (20, 100)
313     DEFAULT_PULSE_VELOCITY = 2
314     DEFAULT_INTENSITY_RANGE = (0.0, 0.9)
315     DEFAULT_INTENSITY_VELOCITY = 0.1
316
317     def __init__(self, **kw):
318         self.pulse_range = kw.pop("pulse_range", self.DEFAULT_PULSE_RANGE)
319         self.pulse_velocity = kw.pop(
320             "pulse_velocity", self.DEFAULT_PULSE_VELOCITY)
321         self.intensity_range = kw.pop(
322             "intensity_range", self.DEFAULT_INTENSITY_RANGE)
323         self.intensity_velocity = kw.pop(
324             "intensity_velocity", self.DEFAULT_INTENSITY_VELOCITY)
325         super(PulsatingLamp, self).__init__(
326             bounding_radius=self.pulse_range[1], **kw)
327
328     def serialize(self):
329         result = super(PulsatingLamp, self).serialize()
330         result["pulse_velocity"] = self.pulse_velocity
331         result["intensity_range"] = self.intensity_range
332         result["intensity_velocity"] = self.intensity_velocity
333         return result
334
335     def _update_range(self, value, velocity, value_range):
336         value += velocity
337         if value < value_range[0]:
338             value = value_range[0]
339             velocity = -velocity
340         elif value > value_range[1]:
341             value = value_range[1]
342             velocity = -velocity
343         return value, velocity
344
345     def tick(self):
346         self.ray_manager.max_radius, self.pulse_velocity = self._update_range(
347             self.ray_manager.max_radius, self.pulse_velocity, self.pulse_range)
348         self.intensity, self.intensity_velocity = self._update_range(
349             self.intensity, self.intensity_velocity, self.intensity_range)
350
351
352 class SpotLight(BaseLight):
353
354     FITTING_IMG = "spotlight.png"
355
356     def __init__(self, **kw):
357         self.angular_velocity = kw.pop("angular_velocity", None)
358         super(SpotLight, self).__init__(**kw)
359
360     def serialize(self):
361         result = super(SpotLight, self).serialize()
362         result["angular_velocity"] = self.angular_velocity
363         return result
364
365     def fitting_image(self):
366         fitting_image = super(SpotLight, self).fitting_image()
367         rot_fitting_image = pygame.transform.rotozoom(
368             fitting_image, self.ray_manager.direction - 90, 1)
369
370         rot_rect = fitting_image.get_rect().copy()
371         rot_rect.center = rot_fitting_image.get_rect().center
372         rot_fitting_image = rot_fitting_image.subsurface(rot_rect).copy()
373
374         return rot_fitting_image
375
376     def tick(self):
377         if self.angular_velocity:
378             self.ray_manager.direction -= self.angular_velocity
379             self.ray_manager.update_shapes()