Slightly better ray poly updating.
[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
10 from .constants import LIGHT_CATEGORY, FITTINGS_CATEGORY
11 from .rays import RayPolyManager
12
13 LIGHT_FILTER = pymunk.ShapeFilter(
14     mask=pymunk.ShapeFilter.ALL_MASKS ^ (
15         LIGHT_CATEGORY | FITTINGS_CATEGORY),
16     categories=LIGHT_CATEGORY)
17
18 FITTINGS_FILTER = pymunk.ShapeFilter(
19     mask=pymunk.ShapeFilter.ALL_MASKS ^ (
20         LIGHT_CATEGORY | FITTINGS_CATEGORY),
21     categories=FITTINGS_CATEGORY)
22
23 # Just match lights, nothing else
24 LIT_BY_FILTER = pymunk.ShapeFilter(mask=LIGHT_CATEGORY)
25
26
27 class LightManager(object):
28     """ Manages a set of lights. """
29
30     def __init__(self, space, gamestate):
31         self._space = space
32         self._lights = [
33             BaseLight.load(cfg) for cfg in gamestate.station["lights"]]
34         for light in self._lights:
35             light.add(self._space)
36
37     def toggle_nearest(self, *args, **kw):
38         light = self.nearest(*args, **kw)
39         if light:
40             light.toggle()
41
42     def nearest(self, pos, surfpos=False, max_distance=1.0):
43         if surfpos:
44             surface = pygame.display.get_surface()
45             pos = pymunk.pygame_util.from_pygame(pos, surface)
46         point_info = self._space.point_query_nearest(
47             pos, max_distance, pymunk.ShapeFilter(mask=FITTINGS_CATEGORY))
48         if point_info is not None:
49             return point_info.shape.body.light
50         return None
51
52     def lit_by(self, pos, surfpos=False, max_distance=0.0):
53         if surfpos:
54             surface = pygame.display.get_surface()
55             pos = pymunk.pygame_util.from_pygame(pos, surface)
56         point_info_list = self._space.point_query(
57             pos, max_distance, pymunk.ShapeFilter(mask=LIGHT_CATEGORY))
58         lights = [p.shape.body.light for p in point_info_list]
59         return [light for light in lights if light.on]
60
61     def light_query(self, shape):
62         """Query the lights by shape"""
63         old_filter = shape.filter
64         # We need to restrict matches to only the lights
65         shape.filter = LIT_BY_FILTER
66         shape_info_list = self._space.shape_query(shape)
67         shape.filter = old_filter
68         lights = [p.shape.body.light for p in shape_info_list]
69         return [light for light in lights if light.on]
70
71     def render_light(self, surface):
72         for light in self._lights:
73             light.render_light(surface)
74
75     def render_fittings(self, surface):
76         for light in self._lights:
77             light.render_fitting(surface)
78
79     def tick(self):
80         for light in self._lights:
81             light.tick()
82
83
84 class BaseLight(object):
85     """ Common light functionality. """
86
87     COLOURS = {
88         "red": (255, 0, 0),
89         "green": (0, 255, 0),
90         "blue": (0, 255, 255),
91         "yellow": (255, 255, 0),
92         "white": (255, 255, 255),
93     }
94
95     # cached surfaces
96     _surface_cache = {}
97
98     def __init__(
99             self, colour, position, intensity=1.0,
100             radius_limits=(None, None), angle_limits=None):
101         self.colour = colour
102         self.position = pymunk.Vec2d(position)
103         self.on = True
104         self.intensity = intensity
105         self.radius_limits = radius_limits
106         self.angle_limits = angle_limits
107         self.body = pymunk.Body(0, 0, pymunk.body.Body.STATIC)
108         self.fitting = pymunk.Circle(self.body, 10.0, self.position)
109         self.fitting.filter = FITTINGS_FILTER
110         self.body.light = self
111         self.ray_manager = RayPolyManager(self.body, LIGHT_FILTER)
112
113     @classmethod
114     def load(cls, config):
115         kw = config.copy()
116         light_type = kw.pop("type")
117         [light_class] = [
118             c for c in cls.__subclasses__()
119             if c.__name__.lower() == light_type]
120         return light_class(**kw)
121
122     def add(self, space):
123         if self.body.space is not None:
124             space.remove(self.body, *self.body.shapes)
125         self.ray_manager.generate_rays(space, self.position)
126         self.ray_manager.set_angle_limits(self.angle_limits)
127         ray_shapes = self.ray_manager.polys()
128         space.add(self.body, self.fitting, *ray_shapes)
129
130     def shapes_for_ray_polys(self, ray_polys):
131         return ray_polys
132
133     def toggle(self):
134         self.on = not self.on
135
136     def _cached_surfaces(self, surface):
137         radius_mask = self._surface_cache.get('radius_mask')
138         if radius_mask is None:
139             radius_mask = self._surface_cache['radius_mask'] = (
140                 pygame.surface.Surface(surface.get_size(), pgl.SWSURFACE))
141
142         ray_mask = self._surface_cache.get('ray_mask')
143         if ray_mask is None:
144             ray_mask = self._surface_cache['ray_mask'] = (
145                 pygame.surface.Surface(surface.get_size(), pgl.SWSURFACE))
146
147         overlay_surf = self._surface_cache.get('overlay_surf')
148         if overlay_surf is None:
149             overlay_surf = self._surface_cache['overlay_surf'] = (
150                 pygame.surface.Surface(
151                     surface.get_size(), pgl.SWSURFACE | pgl.SRCALPHA))
152
153         return radius_mask, ray_mask, overlay_surf
154
155     def render_light(self, surface):
156         if not self.on:
157             return
158
159         radius_mask, ray_mask, overlay_surf = self._cached_surfaces(surface)
160         white, black = (255, 255, 255), (0, 0, 0)
161
162         ray_mask.fill(black)
163         for pygame_poly in self.ray_manager.pygame_polys(surface):
164             pygame.draw.polygon(ray_mask, white, pygame_poly, 0)
165             pygame.draw.aalines(ray_mask, white, True, pygame_poly, 1)
166
167         radius_mask.fill(black)
168         centre = pymunk.pygame_util.to_pygame(self.position, surface)
169         max_radius = self.radius_limits[1] or 50.0
170         min_radius = self.radius_limits[0] or 0
171         width = max_radius - min_radius
172         pygame.draw.circle(
173             radius_mask, white, centre, int(max_radius), int(width))
174         pygame.draw.circle(
175             radius_mask, white, (centre[0] + 1, centre[1]),
176             int(max_radius), int(width))
177
178         ray_mask.blit(radius_mask, (0, 0), None, pgl.BLEND_RGB_MULT)
179         ray_mask.set_colorkey(black)
180
181         light_colour = self.COLOURS[self.colour]
182         intensity = int(255 * self.intensity)
183         light_colour = light_colour + (intensity,)
184
185         overlay_surf.blit(ray_mask, (0, 0), None)
186         overlay_surf.fill(light_colour, None, pgl.BLEND_RGBA_MULT)
187
188         surface.blit(overlay_surf, (0, 0), None)
189
190     def render_fitting(self, surface):
191         pygame.draw.circle(
192             surface, (255, 255, 0),
193             pymunk.pygame_util.to_pygame(self.fitting.offset, surface),
194             int(self.fitting.radius))
195
196     def tick(self):
197         pass
198
199
200 class SpotLight(BaseLight):
201     def __init__(self, **kw):
202         kw.pop("direction", None)
203         kw.pop("spread", None)
204         self.angular_velocity = kw.pop("angular_velocity", None)
205         super(SpotLight, self).__init__(**kw)
206
207     def tick(self):
208         if self.angular_velocity:
209             start, end = self.angle_limits
210             start = (start + self.angular_velocity) % 360.0
211             end = (end + self.angular_velocity) % 360.0
212             self.angle_limits = (start, end)
213             self.ray_manager.set_angle_limits(self.angle_limits)