1 """ May it be a light for you in dark places, when all other lights go out.
7 import pymunk.pygame_util
10 import pygame.locals as pgl
12 import pygame.transform
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 Multiply, MultiplyImage
20 LIGHT_FILTER = pymunk.ShapeFilter(
21 mask=pymunk.ShapeFilter.ALL_MASKS ^ (
22 LIGHT_CATEGORY | FITTINGS_CATEGORY),
23 categories=LIGHT_CATEGORY)
25 FITTINGS_FILTER = pymunk.ShapeFilter(
26 mask=pymunk.ShapeFilter.ALL_MASKS ^ (
27 LIGHT_CATEGORY | FITTINGS_CATEGORY),
28 categories=FITTINGS_CATEGORY)
30 # Just match lights, nothing else
31 LIT_BY_FILTER = pymunk.ShapeFilter(mask=LIGHT_CATEGORY)
34 class LightManager(object):
35 """ Manages a set of lights. """
37 def __init__(self, space, gamestate):
40 BaseLight.load(cfg) for cfg in gamestate.station["lights"]]
41 for light in self._lights:
42 light.add(self._space)
44 def add_light(self, cfg):
45 light = BaseLight.load(cfg)
46 self._lights.append(light)
47 light.add(self._space)
49 def toggle_nearest(self, *args, **kw):
50 light = self.nearest(*args, **kw)
54 def nearest(self, pos, surfpos=False, max_distance=1.0):
56 surface = pygame.display.get_surface()
57 pos = pymunk.pygame_util.from_pygame(pos, surface)
58 point_info = self._space.point_query_nearest(
59 pos, max_distance, pymunk.ShapeFilter(mask=FITTINGS_CATEGORY))
60 if point_info is not None:
61 return point_info.shape.body.light
64 def lit_by(self, pos, surfpos=False, max_distance=0.0):
66 surface = pygame.display.get_surface()
67 pos = pymunk.pygame_util.from_pygame(pos, surface)
68 point_info_list = self._space.point_query(
69 pos, max_distance, pymunk.ShapeFilter(mask=LIGHT_CATEGORY))
70 lights = [p.shape.body.light for p in point_info_list]
72 light for light in lights
73 if light.on and light.ray_manager.reaches(pos)
76 def light_query(self, shape):
77 """Query the lights by shape"""
78 old_filter = shape.filter
79 # We need to restrict matches to only the lights
80 shape.filter = LIT_BY_FILTER
81 shape_info_list = self._space.shape_query(shape)
82 shape.filter = old_filter
83 lights = [p.shape.body.light for p in shape_info_list]
85 light for light in lights
86 if light.on and light.ray_manager.reaches(shape.body.position)
89 def total_power_usage(self):
90 return sum(light.power_usage() for light in self._lights)
92 def render_light(self, surface):
93 for light in self._lights:
94 light.render_light(surface)
96 def render_fittings(self, surface):
97 for light in self._lights:
98 light.render_fitting(surface)
101 for light in self._lights:
105 class BaseLight(object):
106 """ Common light functionality. """
109 RAY_MANAGER = RayPolyManager
111 FITTING_RADIUS = 24.0
117 self, colours, position, intensity=1.0, radius_limits=None,
118 direction=None, spread=None):
119 self.colour_cycle = colours
121 self.colour = colours[0]
123 self.intensity = intensity
124 self.body = pymunk.Body(0, 0, pymunk.body.Body.STATIC)
125 self.body.light = self
126 self.ray_manager = self.RAY_MANAGER(
127 self.body, position, ray_filter=LIGHT_FILTER,
128 radius_limits=radius_limits, direction=direction, spread=spread)
129 self.fitting = pymunk.Circle(
130 self.body, self.FITTING_RADIUS, self.ray_manager.position)
131 self.fitting.filter = FITTINGS_FILTER
132 self._fitting_image = None
133 self._colour_mult_image = None
137 return self.ray_manager.position
140 def load(cls, config):
142 light_type = kw.pop("type")
144 c for c in cls.__subclasses__()
145 if c.__name__.lower() == light_type]
146 return light_class(**kw)
148 def add(self, space):
149 if self.body.space is not None:
150 space.remove(self.body, *self.body.shapes)
151 space.add(self.body, self.fitting)
152 self.ray_manager.set_space(space)
153 self.ray_manager.update_shapes()
155 def _cached_surface(self, name, surface):
156 surf = self._surface_cache.get(name)
158 surf = self._surface_cache[name] = pygame.surface.Surface(
159 surface.get_size(), pgl.SWSURFACE
163 def light_colour(self):
164 light_colour = COLOURS[self.colour]
165 intensity = int(255 * self.intensity)
166 return light_colour + (intensity,)
168 def render_light(self, surface):
172 dt = DetailedTimer("render_light")
175 max_radius = self.ray_manager.max_radius
176 min_radius = self.ray_manager.min_radius
177 dest_rect = self.ray_manager.pygame_rect(surface)
179 white, black = (255, 255, 255, 255), (0, 0, 0, 0)
180 light_colour = self.light_colour()
182 radius_mask = self._cached_surface('radius_mask', surface)
183 radius_mask.set_clip(dest_rect)
184 ray_mask = self._cached_surface('ray_mask', surface)
185 ray_mask.set_clip(dest_rect)
188 for pygame_poly in self.ray_manager.pygame_polys(surface):
189 pygame.draw.polygon(ray_mask, white, pygame_poly, 0)
190 pygame.draw.polygon(ray_mask, white, pygame_poly, 1)
191 dt.lap("ray mask rendered")
193 radius_mask.fill(black)
194 centre = self.ray_manager.pygame_position(surface)
196 radius_mask, light_colour, centre, int(max_radius), 0)
198 radius_mask, black, centre, int(min_radius), 0)
199 dt.lap("radius mask rendered")
201 ray_mask.blit(radius_mask, dest_rect, dest_rect, pgl.BLEND_RGBA_MULT)
202 dt.lap("blitted radius mask to ray mask")
204 surface.blit(ray_mask, dest_rect, dest_rect)
205 dt.lap("blitted surface")
208 def fitting_image(self):
209 if self._fitting_image is None:
210 fitting_colours = [COLOURS[c] for c in self.colour_cycle]
211 ncolour = len(fitting_colours)
213 print "Multicoloured light should not have more than 3 colours"
217 self._fitting_image = loader.load_image(
218 "48", self.FITTING_IMG,
219 transform=Multiply(colour=fitting_colours[0]))
221 if self._colour_mult_image is None:
222 self._colour_mult_image = pygame.surface.Surface((48, 48))
224 for i in range(ncolour):
225 sector = loader.load_image(
226 "48", "light_mask_%d_%d.png" % (ncolour, i + 1),
227 transform=Multiply(colour=fitting_colours[i]))
228 self._colour_mult_image.blit(sector, (0, 0), None, 0)
230 self._fitting_image = loader.load_image(
231 "48", self.FITTING_IMG,
232 transform=MultiplyImage(image=self._colour_mult_image))
234 return self._fitting_image
236 def invalidate_fitting_image(self):
237 self._fitting_image = None
239 def render_fitting(self, surface):
240 rx, ry = self.ray_manager.pygame_position(surface)
241 surface.blit(self.fitting_image(), (rx - 24, ry - 24), None, 0)
243 def power_usage(self):
246 area = math.pi * (self.ray_manager.max_radius ** 2) # radius
247 area = area * (self.ray_manager.spread / (2 * math.pi)) # spread
248 return 5 * area * self.intensity / 6400 # 80x80 unit area
250 def base_damage(self):
251 return 5 * self.intensity
255 if self.colour_pos >= len(self.colour_cycle):
256 self.colour = self.colour_cycle[0]
260 self.colour = self.colour_cycle[self.colour_pos]
267 class Lamp(BaseLight):
269 FITTING_IMG = "lamp.png"
272 class PulsatingLamp(BaseLight):
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
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)
290 def _update_range(self, value, velocity, value_range):
292 if value < value_range[0]:
293 value = value_range[0]
295 elif value > value_range[1]:
296 value = value_range[1]
298 return value, velocity
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)
307 class SpotLight(BaseLight):
309 FITTING_IMG = "spotlight.png"
311 def __init__(self, **kw):
312 self.angular_velocity = kw.pop("angular_velocity", None)
313 super(SpotLight, self).__init__(**kw)
315 def fitting_image(self):
316 fitting_image = super(SpotLight, self).fitting_image()
317 rot_fitting_image = pygame.transform.rotozoom(fitting_image, self.ray_manager.direction - 90, 1)
319 rot_rect = fitting_image.get_rect().copy()
320 rot_rect.center = rot_fitting_image.get_rect().center
321 rot_fitting_image = rot_fitting_image.subsurface(rot_rect).copy()
323 return rot_fitting_image
327 if self.angular_velocity:
328 self.ray_manager.direction -= self.angular_velocity
329 self.ray_manager.update_shapes()