ac6f08e38c279ec39d2847e2b181ca43b5a5eb6a
[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 def seed_cost(light_config, num_colours):
141     """Calculate a seed cost for a light from its configuration. """
142     cls = BaseLight.find_cls(light_config["type"])
143     return cls.BASE_COST + int(cls.find_cost(light_config) / 10) + num_colours
144
145 def light_info(light_config):
146     """Generate info about a light to go in the tooltip. """
147     cls = BaseLight.find_cls(light_config["type"])
148     return cls.get_info(light_config)
149
150
151 def light_name(light_config):
152     """Find formatted light name. """
153     cls = BaseLight.find_cls(light_config["type"])
154     return cls.NAME
155
156
157 class BaseLight(object):
158     """ Common light functionality. """
159
160     # defaults
161     RAY_MANAGER = RayPolyManager
162     FITTING_IMG = None
163     FITTING_RADIUS = 24.0
164     BASE_COST = 0
165     NAME = "light"
166
167     # cached surfaces
168     _surface_cache = {}
169
170     def __init__(
171             self, colours, position, intensity=1.0, radius_limits=None,
172             direction=None, spread=None, on=True, start_colour=None,
173             bounding_radius=None):
174         self.colour_cycle = colours
175         self.colour_pos = 0
176         self.colour = colours[0]
177         if start_colour and start_colour in colours:
178             self.colour_pos = colours.index(start_colour)
179             self.colour = start_colour
180         self.on = on
181         if not on:
182             self.colour_pos = -1
183         self.intensity = intensity
184         self.body = pymunk.Body(0, 0, pymunk.body.Body.STATIC)
185         self.body.light = self
186         self.ray_manager = self.RAY_MANAGER(
187             self.body, position, ray_filter=LIGHT_FILTER,
188             radius_limits=radius_limits, direction=direction, spread=spread,
189             bounding_radius=bounding_radius)
190         self.fitting = pymunk.Circle(
191             self.body, self.FITTING_RADIUS, self.ray_manager.position)
192         self.fitting.filter = FITTINGS_FILTER
193         self._fitting_image = None
194         self._colour_mult_image = None
195
196     def serialize(self):
197         result = self.ray_manager.serialize()
198         result.update({
199             "type": self.__class__.__name__.lower(),
200             "colours": self.colour_cycle,
201             "position": self.position,
202             "intensity": self.intensity,
203             "on": self.on,
204             "start_colour": self.colour,
205         })
206         return result
207
208     @property
209     def position(self):
210         return self.ray_manager.position
211
212     @classmethod
213     def load(cls, config):
214         kw = config.copy()
215         light_type = kw.pop("type")
216         light_class = cls.find_cls(light_type)
217         return light_class(**kw)
218
219     @classmethod
220     def find_cls(cls, light_type):
221         [light_class] = [
222             c for c in cls.__subclasses__()
223             if c.__name__.lower() == light_type]
224         return light_class
225
226     @classmethod
227     def find_cost(cls, config):
228         cost = 5 * config["intensity"]
229         return cost
230
231     @classmethod
232     def get_info(cls, config):
233         return ["intensity: %g" % config["intensity"]]
234
235     def add(self, space):
236         if self.body.space is not None:
237             space.remove(self.body, *self.body.shapes)
238         space.add(self.body, self.fitting)
239         self.ray_manager.set_space(space)
240         self.ray_manager.update_shapes()
241
242     def remove(self, space):
243         if self.body.space is not None:
244             space.remove(self.body, *self.body.shapes)
245
246     def _cached_surface(self, name, surface):
247         surf = self._surface_cache.get(name)
248         if surf is None:
249             surf = self._surface_cache[name] = pygame.surface.Surface(
250                 surface.get_size(), pgl.SWSURFACE
251             ).convert_alpha()
252         return surf
253
254     def light_colour(self):
255         light_colour = COLOURS[self.colour]
256         intensity = int(255 * self.intensity)
257         return light_colour + (intensity,)
258
259     def render_light(self, surface):
260         if not self.on:
261             return
262
263         dt = DetailedTimer("render_light")
264         dt.start()
265
266         max_radius = self.ray_manager.max_radius
267         min_radius = self.ray_manager.min_radius
268         dest_rect = self.ray_manager.pygame_rect(surface)
269
270         white, black = (255, 255, 255, 255), (0, 0, 0, 0)
271         light_colour = self.light_colour()
272
273         radius_mask = self._cached_surface('radius_mask', surface)
274         radius_mask.set_clip(dest_rect)
275         ray_mask = self._cached_surface('ray_mask', surface)
276         ray_mask.set_clip(dest_rect)
277
278         ray_mask.fill(black)
279         for pygame_poly in self.ray_manager.pygame_polys(surface):
280             pygame.draw.polygon(ray_mask, white, pygame_poly, 0)
281             pygame.draw.polygon(ray_mask, white, pygame_poly, 1)
282         dt.lap("ray mask rendered")
283
284         radius_mask.fill(black)
285         centre = self.ray_manager.pygame_position(surface)
286         pygame.draw.circle(
287             radius_mask, light_colour, centre, int(max_radius), 0)
288         pygame.draw.circle(
289             radius_mask, black, centre, int(min_radius), 0)
290         dt.lap("radius mask rendered")
291
292         ray_mask.blit(radius_mask, dest_rect, dest_rect, pgl.BLEND_RGBA_MULT)
293         dt.lap("blitted radius mask to ray mask")
294
295         surface.blit(ray_mask, dest_rect, dest_rect)
296         dt.lap("blitted surface")
297         dt.end()
298
299     def fitting_image(self):
300         if self._fitting_image is None:
301             self._fitting_image = loader.load_image(
302                 "48", self.FITTING_IMG,
303                 transform=ColourWedges(colours=self.colour_cycle))
304         return self._fitting_image
305
306     def invalidate_fitting_image(self):
307         self._fitting_image = None
308
309     def render_fitting(self, surface):
310         rx, ry = self.ray_manager.pygame_position(surface)
311         surface.blit(self.fitting_image(), (rx - self.FITTING_RADIUS, ry - self.FITTING_RADIUS), None, 0)
312
313     def power_usage(self):
314         if not self.on:
315             return 0.0
316         area = math.pi * (self.ray_manager.max_radius ** 2)  # radius
317         area = area * (self.ray_manager.spread / (2 * math.pi))  # spread
318         return 5 * area * self.intensity / 6400  # 80x80 unit area
319
320     def base_damage(self):
321         return 10 * self.intensity
322
323     def off(self):
324         self.on = False
325         self.colour_pos = -1
326
327     def toggle(self):
328         self.colour_pos += 1
329         if self.colour_pos >= len(self.colour_cycle):
330             self.colour = self.colour_cycle[0]
331             self.colour_pos = -1
332             self.on = False
333         else:
334             self.colour = self.colour_cycle[self.colour_pos]
335             self.on = True
336
337     def tick(self):
338         pass
339
340
341 class Lamp(BaseLight):
342
343     FITTING_IMG = "lamp.png"
344     BASE_COST = 1
345     NAME = "lamp"
346
347
348 class PulsatingLamp(BaseLight):
349
350     FITTING_IMG = "pulsatinglamp.png"
351     DEFAULT_PULSE_RANGE = (20, 100)
352     DEFAULT_PULSE_VELOCITY = 2
353     DEFAULT_INTENSITY_RANGE = (0.0, 0.9)
354     DEFAULT_INTENSITY_VELOCITY = 0.1
355     BASE_COST = 3
356     NAME = "pulsating lamp"
357
358     def __init__(self, **kw):
359         self.pulse_range = kw.pop("pulse_range", self.DEFAULT_PULSE_RANGE)
360         self.pulse_velocity = kw.pop(
361             "pulse_velocity", self.DEFAULT_PULSE_VELOCITY)
362         self.intensity_range = kw.pop(
363             "intensity_range", self.DEFAULT_INTENSITY_RANGE)
364         self.intensity_velocity = kw.pop(
365             "intensity_velocity", self.DEFAULT_INTENSITY_VELOCITY)
366         super(PulsatingLamp, self).__init__(
367             bounding_radius=self.pulse_range[1], **kw)
368
369     def serialize(self):
370         result = super(PulsatingLamp, self).serialize()
371         result["pulse_velocity"] = self.pulse_velocity
372         result["intensity_range"] = self.intensity_range
373         result["intensity_velocity"] = self.intensity_velocity
374         return result
375
376     def _update_range(self, value, velocity, value_range):
377         value += velocity
378         if value < value_range[0]:
379             value = value_range[0]
380             velocity = -velocity
381         elif value > value_range[1]:
382             value = value_range[1]
383             velocity = -velocity
384         return value, velocity
385
386     def tick(self):
387         self.ray_manager.max_radius, self.pulse_velocity = self._update_range(
388             self.ray_manager.max_radius, self.pulse_velocity, self.pulse_range)
389         self.intensity, self.intensity_velocity = self._update_range(
390             self.intensity, self.intensity_velocity, self.intensity_range)
391
392     @classmethod
393     def find_cost(cls, config):
394         cost = super(PulsatingLamp, cls).find_cost(config)
395         cost += config.get("pulse_velocity", cls.DEFAULT_PULSE_VELOCITY)
396         pr = config.get("pulse_range", cls.DEFAULT_PULSE_RANGE)
397         cost += (pr[1] - pr[0]) / 10
398         cost += 5 * config.get("intensity_velocity", cls.DEFAULT_INTENSITY_VELOCITY)
399         ir = config.get("intensity_range", cls.DEFAULT_INTENSITY_RANGE)
400         cost += 5 * (ir[1] - ir[0])
401         return cost
402
403     @classmethod
404     def get_info(cls, config):
405         pr = config.get("pulse_range", cls.DEFAULT_PULSE_RANGE)
406         pv = config.get("pulse_velocity", cls.DEFAULT_PULSE_VELOCITY)
407         ir = config.get("intensity_range", cls.DEFAULT_INTENSITY_RANGE)
408         iv = config.get("intensity_velocity", cls.DEFAULT_INTENSITY_VELOCITY)
409         return [
410             "intensity: %g - %g, velocity %g" % (ir[0], ir[1], iv),
411             "pulse: %d - %d, velocity %g" % (pr[0], pr[1], pv),
412         ]
413
414
415 class SpotLight(BaseLight):
416
417     FITTING_IMG = "spotlight.png"
418     BASE_COST = 5
419     NAME = "spotlight"
420
421     def __init__(self, **kw):
422         self.angular_velocity = kw.pop("angular_velocity", None)
423         super(SpotLight, self).__init__(**kw)
424
425     def serialize(self):
426         result = super(SpotLight, self).serialize()
427         result["angular_velocity"] = self.angular_velocity
428         return result
429
430     def fitting_image(self):
431         fitting_image = super(SpotLight, self).fitting_image()
432         rot_fitting_image = pygame.transform.rotozoom(
433             fitting_image, self.ray_manager.direction - 90, 1)
434
435         rot_rect = fitting_image.get_rect().copy()
436         rot_rect.center = rot_fitting_image.get_rect().center
437         rot_fitting_image = rot_fitting_image.subsurface(rot_rect).copy()
438
439         return rot_fitting_image
440
441     def tick(self):
442         if self.angular_velocity:
443             self.ray_manager.direction -= self.angular_velocity
444             self.ray_manager.update_shapes()
445
446     @classmethod
447     def find_cost(cls, config):
448         cost = super(SpotLight, cls).find_cost(config)
449         cost += config.get("angular_velocity", 0)
450         cost += config["spread"] / 10
451         rl = config["radius_limits"]
452         cost += (rl[1] - rl[0]) / 10
453         return cost
454
455     @classmethod
456     def get_info(cls, config):
457         info = super(SpotLight, cls).get_info(config)
458         rl = config["radius_limits"]
459         info.extend([
460             "spread: %d" % config["spread"],
461             "length: %d" % (rl[1] - rl[0]),
462             "angular velocity: %g" % config.get("angular_velocity", 0),
463         ])
464         return info