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 (
15 LIGHT_CATEGORY, FITTINGS_CATEGORY, OBSTACLE_CATEGORY, TURNIP_CATEGORY,
17 from .rays import RayPolyManager
18 from .utils import DetailedTimer
19 from .loader import loader
20 from .transforms import ColourWedges
22 LIGHT_FILTER = pymunk.ShapeFilter(
23 mask=pymunk.ShapeFilter.ALL_MASKS ^ (
24 LIGHT_CATEGORY | FITTINGS_CATEGORY),
25 categories=LIGHT_CATEGORY)
27 FITTINGS_FILTER = pymunk.ShapeFilter(
28 mask=pymunk.ShapeFilter.ALL_MASKS ^ (
29 LIGHT_CATEGORY | FITTINGS_CATEGORY),
30 categories=FITTINGS_CATEGORY)
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)
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:
46 class LightManager(object):
47 """ Manages a set of lights. """
49 def __init__(self, space, gamestate):
51 self._battery_dead = False
53 BaseLight.load(cfg) for cfg in gamestate.station["lights"]]
54 for light in self._lights:
55 light.add(self._space)
57 def add_light(self, cfg):
58 light = BaseLight.load(cfg)
59 self._lights.append(light)
60 light.add(self._space)
62 def battery_dead(self):
63 self._battery_dead = True
64 for light in self._lights:
67 def serialize_lights(self):
69 for light in self._lights:
70 result.append(light.serialize())
73 def toggle_nearest(self, *args, **kw):
74 if self._battery_dead:
76 light = self.nearest(*args, **kw)
80 def nearest(self, pos, surfpos=False, max_distance=1.0):
82 surface = pygame.display.get_surface()
83 pos = pymunk.pygame_util.from_pygame(pos, surface)
84 point_info = self._space.point_query_nearest(
85 pos, max_distance, pymunk.ShapeFilter(mask=FITTINGS_CATEGORY))
86 if point_info is not None:
87 return point_info.shape.body.light
90 def lit_by(self, pos, surfpos=False, max_distance=0.0):
92 surface = pygame.display.get_surface()
93 pos = pymunk.pygame_util.from_pygame(pos, surface)
94 point_info_list = self._space.point_query(
95 pos, max_distance, LIT_BY_FILTER)
96 lights = [p.shape.body.light for p in point_info_list]
98 light for light in lights
99 if light.on and light.ray_manager.reaches(pos)
102 def light_query(self, shape):
103 """Query the lights by shape"""
104 old_filter = shape.filter
105 # We need to restrict matches to only the lights
106 shape.filter = LIT_BY_FILTER
107 shape_info_list = self._space.shape_query(shape)
108 shape.filter = old_filter
109 lights = [p.shape.body.light for p in shape_info_list]
111 light for light in lights
112 if light.on and light.ray_manager.reaches(shape.body.position)
115 def total_power_usage(self):
116 return sum(light.power_usage() for light in self._lights)
118 def render_light(self, surface):
119 for light in self._lights:
120 light.render_light(surface)
122 def render_fittings(self, surface):
123 for light in self._lights:
124 light.render_fitting(surface)
127 for light in self._lights:
131 def light_fitting_by_type(light_type):
132 """ Render a light fitting image for a light type. """
133 return BaseLight.find_cls(light_type).FITTING_IMG
136 class BaseLight(object):
137 """ Common light functionality. """
140 RAY_MANAGER = RayPolyManager
142 FITTING_RADIUS = 24.0
148 self, colours, position, intensity=1.0, radius_limits=None,
149 direction=None, spread=None, on=True, start_colour=None):
150 self.colour_cycle = colours
152 self.colour = colours[0]
153 if start_colour and start_colour in colours:
154 self.colour_pos = colours.index(start_colour)
155 self.colour = start_colour
157 if not on and len(colours) > 1:
159 self.intensity = intensity
160 self.body = pymunk.Body(0, 0, pymunk.body.Body.STATIC)
161 self.body.light = self
162 self.ray_manager = self.RAY_MANAGER(
163 self.body, position, ray_filter=LIGHT_FILTER,
164 radius_limits=radius_limits, direction=direction, spread=spread)
165 self.fitting = pymunk.Circle(
166 self.body, self.FITTING_RADIUS, self.ray_manager.position)
167 self.fitting.filter = FITTINGS_FILTER
168 self._fitting_image = None
169 self._colour_mult_image = None
172 result = self.ray_manager.serialize()
174 "type": self.__class__.__name__.lower(),
175 "colours": self.colour_cycle,
176 "position": self.position,
177 "intensity": self.intensity,
179 "start_colour": self.colour,
185 return self.ray_manager.position
188 def load(cls, config):
190 light_type = kw.pop("type")
191 light_class = cls.find_cls(light_type)
192 return light_class(**kw)
195 def find_cls(cls, light_type):
197 c for c in cls.__subclasses__()
198 if c.__name__.lower() == light_type]
201 def add(self, space):
202 if self.body.space is not None:
203 space.remove(self.body, *self.body.shapes)
204 space.add(self.body, self.fitting)
205 self.ray_manager.set_space(space)
206 self.ray_manager.update_shapes()
208 def _cached_surface(self, name, surface):
209 surf = self._surface_cache.get(name)
211 surf = self._surface_cache[name] = pygame.surface.Surface(
212 surface.get_size(), pgl.SWSURFACE
216 def light_colour(self):
217 light_colour = COLOURS[self.colour]
218 intensity = int(255 * self.intensity)
219 return light_colour + (intensity,)
221 def render_light(self, surface):
225 dt = DetailedTimer("render_light")
228 max_radius = self.ray_manager.max_radius
229 min_radius = self.ray_manager.min_radius
230 dest_rect = self.ray_manager.pygame_rect(surface)
232 white, black = (255, 255, 255, 255), (0, 0, 0, 0)
233 light_colour = self.light_colour()
235 radius_mask = self._cached_surface('radius_mask', surface)
236 radius_mask.set_clip(dest_rect)
237 ray_mask = self._cached_surface('ray_mask', surface)
238 ray_mask.set_clip(dest_rect)
241 for pygame_poly in self.ray_manager.pygame_polys(surface):
242 pygame.draw.polygon(ray_mask, white, pygame_poly, 0)
243 pygame.draw.polygon(ray_mask, white, pygame_poly, 1)
244 dt.lap("ray mask rendered")
246 radius_mask.fill(black)
247 centre = self.ray_manager.pygame_position(surface)
249 radius_mask, light_colour, centre, int(max_radius), 0)
251 radius_mask, black, centre, int(min_radius), 0)
252 dt.lap("radius mask rendered")
254 ray_mask.blit(radius_mask, dest_rect, dest_rect, pgl.BLEND_RGBA_MULT)
255 dt.lap("blitted radius mask to ray mask")
257 surface.blit(ray_mask, dest_rect, dest_rect)
258 dt.lap("blitted surface")
261 def fitting_image(self):
262 if self._fitting_image is None:
263 self._fitting_image = loader.load_image(
264 "48", self.FITTING_IMG,
265 transform=ColourWedges(colours=self.colour_cycle))
266 return self._fitting_image
268 def invalidate_fitting_image(self):
269 self._fitting_image = None
271 def render_fitting(self, surface):
272 rx, ry = self.ray_manager.pygame_position(surface)
273 surface.blit(self.fitting_image(), (rx - 24, ry - 24), None, 0)
275 def power_usage(self):
278 area = math.pi * (self.ray_manager.max_radius ** 2) # radius
279 area = area * (self.ray_manager.spread / (2 * math.pi)) # spread
280 return 5 * area * self.intensity / 6400 # 80x80 unit area
282 def base_damage(self):
283 return 10 * self.intensity
290 if self.colour_pos >= len(self.colour_cycle):
291 self.colour = self.colour_cycle[0]
295 self.colour = self.colour_cycle[self.colour_pos]
302 class Lamp(BaseLight):
304 FITTING_IMG = "lamp.png"
307 class PulsatingLamp(BaseLight):
309 FITTING_IMG = "lamp.png"
310 DEFAULT_PULSE_RANGE = (20, 100)
311 DEFAULT_PULSE_VELOCITY = 2
312 DEFAULT_INTENSITY_RANGE = (0.0, 0.9)
313 DEFAULT_INTENSITY_VELOCITY = 0.1
315 def __init__(self, **kw):
316 self.pulse_range = kw.pop("pulse_range", self.DEFAULT_PULSE_RANGE)
317 self.pulse_velocity = kw.pop(
318 "pulse_velocity", self.DEFAULT_PULSE_VELOCITY)
319 self.intensity_range = kw.pop(
320 "intensity_range", self.DEFAULT_INTENSITY_RANGE)
321 self.intensity_velocity = kw.pop(
322 "intensity_velocity", self.DEFAULT_INTENSITY_VELOCITY)
323 super(PulsatingLamp, self).__init__(**kw)
326 result = super(PulsatingLamp, self).serialize()
327 result["pulse_velocity"] = self.pulse_velocity
328 result["intensity_range"] = self.intensity_range
329 result["intensity_velocity"] = self.intensity_velocity
332 def _update_range(self, value, velocity, value_range):
334 if value < value_range[0]:
335 value = value_range[0]
337 elif value > value_range[1]:
338 value = value_range[1]
340 return value, velocity
343 self.ray_manager.max_radius, self.pulse_velocity = self._update_range(
344 self.ray_manager.max_radius, self.pulse_velocity, self.pulse_range)
345 self.intensity, self.intensity_velocity = self._update_range(
346 self.intensity, self.intensity_velocity, self.intensity_range)
349 class SpotLight(BaseLight):
351 FITTING_IMG = "spotlight.png"
353 def __init__(self, **kw):
354 self.angular_velocity = kw.pop("angular_velocity", None)
355 super(SpotLight, self).__init__(**kw)
358 result = super(SpotLight, self).serialize()
359 result["angular_velocity"] = self.angular_velocity
362 def fitting_image(self):
363 fitting_image = super(SpotLight, self).fitting_image()
364 rot_fitting_image = pygame.transform.rotozoom(
365 fitting_image, self.ray_manager.direction - 90, 1)
367 rot_rect = fitting_image.get_rect().copy()
368 rot_rect.center = rot_fitting_image.get_rect().center
369 rot_fitting_image = rot_fitting_image.subsurface(rot_rect).copy()
371 return rot_fitting_image
374 if self.angular_velocity:
375 self.ray_manager.direction -= self.angular_velocity
376 self.ray_manager.update_shapes()