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