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