Use pulsating lamp images.
[tabakrolletjie.git] / tabakrolletjie / lights.py
index 2590e310bc3247680ce13eef5f2bea7b1fdc7964..cda60022a5d5aa227d7a9401ad119ca31ff2ba67 100644 (file)
@@ -1,13 +1,23 @@
 """ May it be a light for you in dark places, when all other lights go out.
 """
 
+import math
+
 import pymunk
 import pymunk.pygame_util
+import pygame.display
 import pygame.draw
+import pygame.locals as pgl
+import pygame.rect
+import pygame.transform
 
 from .constants import (
-    SCREEN_SIZE, LIGHT_CATEGORY, FITTINGS_CATEGORY)
-from .utils import debug_timer
+    LIGHT_CATEGORY, FITTINGS_CATEGORY, OBSTACLE_CATEGORY, TURNIP_CATEGORY,
+    COLOURS)
+from .rays import RayPolyManager
+from .utils import DetailedTimer
+from .loader import loader
+from .transforms import ColourWedges
 
 LIGHT_FILTER = pymunk.ShapeFilter(
     mask=pymunk.ShapeFilter.ALL_MASKS ^ (
@@ -19,129 +29,359 @@ FITTINGS_FILTER = pymunk.ShapeFilter(
         LIGHT_CATEGORY | FITTINGS_CATEGORY),
     categories=FITTINGS_CATEGORY)
 
+# Just match lights, nothing else
+LIT_BY_FILTER = pymunk.ShapeFilter(mask=LIGHT_CATEGORY)
+SPACE_FOR_LIGHT_FILTER = pymunk.ShapeFilter(
+    mask=FITTINGS_CATEGORY | OBSTACLE_CATEGORY | TURNIP_CATEGORY)
+
+
+def check_space_for_light(space, pos, max_distance):
+    point_info = space.point_query_nearest(
+        pos, max_distance, SPACE_FOR_LIGHT_FILTER)
+    if point_info is not None:
+        return True
+    return False
+
+
+class LightManager(object):
+    """ Manages a set of lights. """
+
+    def __init__(self, space, gamestate):
+        self._space = space
+        self._battery_dead = False
+        self._lights = [
+            BaseLight.load(cfg) for cfg in gamestate.station["lights"]]
+        for light in self._lights:
+            light.add(self._space)
+
+    def add_light(self, cfg):
+        light = BaseLight.load(cfg)
+        self._lights.append(light)
+        light.add(self._space)
+
+    def remove_light(self, light):
+        self._lights.remove(light)
+        light.remove(self._space)
+
+    def battery_dead(self):
+        self._battery_dead = True
+        for light in self._lights:
+            light.off()
+
+    def serialize_lights(self):
+        result = []
+        for light in self._lights:
+            result.append(light.serialize())
+        return result
 
-def screen_rays(pos):
-    """ An iterable that returns ordered rays from pos to the edge of the
-        screen, starting with the edge point (0, 0) and continuing clockwise
-        in pymunk coordinates.
-    """
-    w, h = SCREEN_SIZE
-    left, right, bottom, top = 0, w, 0, h
-    step = 1
-    for y in range(0, h, step):
-        yield pymunk.Vec2d(left, y)
-    for x in range(0, w, step):
-        yield pymunk.Vec2d(x, top)
-    for y in range(top, -1, -step):
-        yield pymunk.Vec2d(right, y)
-    for x in range(right, -1, -step):
-        yield pymunk.Vec2d(x, bottom)
-
-
-@debug_timer("lights.calculate_ray_polys")
-def calculate_ray_polys(space, body, position):
-    position = pymunk.Vec2d(position)
-    vertices = [position]
-    ray_polys = []
-    for ray in screen_rays(position):
-        info = space.segment_query_first(position, ray, 1, LIGHT_FILTER)
-        point = ray if info is None else info.point
-        vertices.append(point)
-        if len(vertices) > 3:
-            trial_poly = pymunk.Poly(None, vertices)
-            trial_poly.update(pymunk.Transform.identity())
-            query_prev = trial_poly.point_query(vertices[-2])
-            query_pos = trial_poly.point_query(position)
-            if query_prev.distance < -0.01 or query_pos.distance < -0.01:
-                new_poly = pymunk.Poly(body, vertices[:-1])
-                vertices = [position, vertices[-1]]
-                ray_polys.append(new_poly)
-            else:
-                vertices = trial_poly.get_vertices() + [point]
-    if len(vertices) > 2:
-        ray_polys.append(pymunk.Poly(body, vertices))
-    return ray_polys
+    def toggle_nearest(self, *args, **kw):
+        if self._battery_dead:
+            return
+        light = self.nearest(*args, **kw)
+        if light:
+            light.toggle()
+
+    def nearest(self, pos, surfpos=False, max_distance=1.0):
+        if surfpos:
+            surface = pygame.display.get_surface()
+            pos = pymunk.pygame_util.from_pygame(pos, surface)
+        point_info = self._space.point_query_nearest(
+            pos, max_distance, pymunk.ShapeFilter(mask=FITTINGS_CATEGORY))
+        if point_info is not None:
+            return point_info.shape.body.light
+        return None
+
+    def lit_by(self, pos, surfpos=False, max_distance=0.0):
+        if surfpos:
+            surface = pygame.display.get_surface()
+            pos = pymunk.pygame_util.from_pygame(pos, surface)
+        point_info_list = self._space.point_query(
+            pos, max_distance, LIT_BY_FILTER)
+        lights = [p.shape.body.light for p in point_info_list]
+        return [
+            light for light in lights
+            if light.on and light.ray_manager.reaches(pos)
+        ]
+
+    def light_query(self, shape):
+        """Query the lights by shape"""
+        old_filter = shape.filter
+        # We need to restrict matches to only the lights
+        shape.filter = LIT_BY_FILTER
+        shape_info_list = self._space.shape_query(shape)
+        shape.filter = old_filter
+        lights = [p.shape.body.light for p in shape_info_list]
+        return [
+            light for light in lights
+            if light.on and light.ray_manager.reaches(shape.body.position)
+        ]
+
+    def total_power_usage(self):
+        return sum(light.power_usage() for light in self._lights)
+
+    def render_light(self, surface):
+        for light in self._lights:
+            light.render_light(surface)
+
+    def render_fittings(self, surface):
+        for light in self._lights:
+            light.render_fitting(surface)
+
+    def tick(self):
+        for light in self._lights:
+            light.tick()
+
+
+def light_fitting_by_type(light_type):
+    """ Render a light fitting image for a light type. """
+    return BaseLight.find_cls(light_type).FITTING_IMG
 
 
 class BaseLight(object):
     """ Common light functionality. """
 
-    COLOURS = {
-        "red": (255, 0, 0),
-        "green": (0, 255, 0),
-        "blue": (0, 255, 255),
-        "yellow": (255, 255, 0),
-        "white": (255, 255, 255),
-    }
-
-    def __init__(self, colour, position):
-        self.colour = colour
-        self.position = pymunk.Vec2d(position)
-        self.on = True
+    # defaults
+    RAY_MANAGER = RayPolyManager
+    FITTING_IMG = None
+    FITTING_RADIUS = 24.0
+
+    # cached surfaces
+    _surface_cache = {}
+
+    def __init__(
+            self, colours, position, intensity=1.0, radius_limits=None,
+            direction=None, spread=None, on=True, start_colour=None,
+            bounding_radius=None):
+        self.colour_cycle = colours
+        self.colour_pos = 0
+        self.colour = colours[0]
+        if start_colour and start_colour in colours:
+            self.colour_pos = colours.index(start_colour)
+            self.colour = start_colour
+        self.on = on
+        if not on and len(colours) > 1:
+            self.colour_pos = -1
+        self.intensity = intensity
         self.body = pymunk.Body(0, 0, pymunk.body.Body.STATIC)
-        self.fitting = pymunk.Circle(self.body, 10.0, self.position)
         self.body.light = self
+        self.ray_manager = self.RAY_MANAGER(
+            self.body, position, ray_filter=LIGHT_FILTER,
+            radius_limits=radius_limits, direction=direction, spread=spread,
+            bounding_radius=bounding_radius)
+        self.fitting = pymunk.Circle(
+            self.body, self.FITTING_RADIUS, self.ray_manager.position)
+        self.fitting.filter = FITTINGS_FILTER
+        self._fitting_image = None
+        self._colour_mult_image = None
+
+    def serialize(self):
+        result = self.ray_manager.serialize()
+        result.update({
+            "type": self.__class__.__name__.lower(),
+            "colours": self.colour_cycle,
+            "position": self.position,
+            "intensity": self.intensity,
+            "on": self.on,
+            "start_colour": self.colour,
+        })
+        return result
+
+    @property
+    def position(self):
+        return self.ray_manager.position
 
     @classmethod
     def load(cls, config):
         kw = config.copy()
         light_type = kw.pop("type")
+        light_class = cls.find_cls(light_type)
+        return light_class(**kw)
+
+    @classmethod
+    def find_cls(cls, light_type):
         [light_class] = [
             c for c in cls.__subclasses__()
             if c.__name__.lower() == light_type]
-        return light_class(**kw)
+        return light_class
 
     def add(self, space):
         if self.body.space is not None:
             space.remove(self.body, *self.body.shapes)
-        shapes = self.shapes_for_ray_polys(
-            calculate_ray_polys(space, self.body, self.position))
-        for shape in shapes:
-            shape.filter = LIGHT_FILTER
-        self.fitting.filter = FITTINGS_FILTER
-        space.add(self.body, self.fitting, *shapes)
+        space.add(self.body, self.fitting)
+        self.ray_manager.set_space(space)
+        self.ray_manager.update_shapes()
 
-    def shapes_for_ray_polys(self, ray_polys):
-        return ray_polys
+    def remove(self, space):
+        if self.body.space is not None:
+            space.remove(self.body, *self.body.shapes)
 
-    def toggle(self):
-        self.on = not self.on
+    def _cached_surface(self, name, surface):
+        surf = self._surface_cache.get(name)
+        if surf is None:
+            surf = self._surface_cache[name] = pygame.surface.Surface(
+                surface.get_size(), pgl.SWSURFACE
+            ).convert_alpha()
+        return surf
+
+    def light_colour(self):
+        light_colour = COLOURS[self.colour]
+        intensity = int(255 * self.intensity)
+        return light_colour + (intensity,)
 
     def render_light(self, surface):
         if not self.on:
             return
-        subsurface = surface.copy()
-        light_colour = self.COLOURS[self.colour]
-        for shape in self.body.shapes:
-            if shape is self.fitting:
-                continue
-            pygame_poly = [
-                pymunk.pygame_util.to_pygame(v, surface) for v in
-                shape.get_vertices()]
-            pygame.draw.polygon(
-                subsurface, light_colour, pygame_poly, 0)
-            pygame.draw.aalines(
-                subsurface, light_colour, True, pygame_poly, 1)
-        subsurface.set_alpha(50)
-        surface.blit(subsurface, (0, 0), None)
 
-    def render_fittings(self, surface):
+        dt = DetailedTimer("render_light")
+        dt.start()
+
+        max_radius = self.ray_manager.max_radius
+        min_radius = self.ray_manager.min_radius
+        dest_rect = self.ray_manager.pygame_rect(surface)
+
+        white, black = (255, 255, 255, 255), (0, 0, 0, 0)
+        light_colour = self.light_colour()
+
+        radius_mask = self._cached_surface('radius_mask', surface)
+        radius_mask.set_clip(dest_rect)
+        ray_mask = self._cached_surface('ray_mask', surface)
+        ray_mask.set_clip(dest_rect)
+
+        ray_mask.fill(black)
+        for pygame_poly in self.ray_manager.pygame_polys(surface):
+            pygame.draw.polygon(ray_mask, white, pygame_poly, 0)
+            pygame.draw.polygon(ray_mask, white, pygame_poly, 1)
+        dt.lap("ray mask rendered")
+
+        radius_mask.fill(black)
+        centre = self.ray_manager.pygame_position(surface)
+        pygame.draw.circle(
+            radius_mask, light_colour, centre, int(max_radius), 0)
         pygame.draw.circle(
-            surface, (255, 255, 0),
-            pymunk.pygame_util.to_pygame(self.fitting.offset, surface),
-            int(self.fitting.radius))
+            radius_mask, black, centre, int(min_radius), 0)
+        dt.lap("radius mask rendered")
 
+        ray_mask.blit(radius_mask, dest_rect, dest_rect, pgl.BLEND_RGBA_MULT)
+        dt.lap("blitted radius mask to ray mask")
 
-class SpotLight(BaseLight):
-    def __init__(
-            self, colour="white", position=None, direction=90.0, spread=45.0):
-        super(SpotLight, self).__init__(colour, position)
-        self.direction = direction
-        self.spread = spread
-        self.i = 0
+        surface.blit(ray_mask, dest_rect, dest_rect)
+        dt.lap("blitted surface")
+        dt.end()
+
+    def fitting_image(self):
+        if self._fitting_image is None:
+            self._fitting_image = loader.load_image(
+                "48", self.FITTING_IMG,
+                transform=ColourWedges(colours=self.colour_cycle))
+        return self._fitting_image
+
+    def invalidate_fitting_image(self):
+        self._fitting_image = None
+
+    def render_fitting(self, surface):
+        rx, ry = self.ray_manager.pygame_position(surface)
+        surface.blit(self.fitting_image(), (rx - 24, ry - 24), None, 0)
+
+    def power_usage(self):
+        if not self.on:
+            return 0.0
+        area = math.pi * (self.ray_manager.max_radius ** 2)  # radius
+        area = area * (self.ray_manager.spread / (2 * math.pi))  # spread
+        return 5 * area * self.intensity / 6400  # 80x80 unit area
+
+    def base_damage(self):
+        return 10 * self.intensity
+
+    def off(self):
+        self.on = False
+
+    def toggle(self):
+        self.colour_pos += 1
+        if self.colour_pos >= len(self.colour_cycle):
+            self.colour = self.colour_cycle[0]
+            self.colour_pos = -1
+            self.on = False
+        else:
+            self.colour = self.colour_cycle[self.colour_pos]
+            self.on = True
+
+    def tick(self):
+        pass
 
 
 class Lamp(BaseLight):
-    def __init__(self, colour="white", position=None, radius=100.0):
-        super(Lamp, self).__init__(colour, position)
-        self.radius = radius
+
+    FITTING_IMG = "lamp.png"
+
+
+class PulsatingLamp(BaseLight):
+
+    FITTING_IMG = "pulsatinglamp.png"
+    DEFAULT_PULSE_RANGE = (20, 100)
+    DEFAULT_PULSE_VELOCITY = 2
+    DEFAULT_INTENSITY_RANGE = (0.0, 0.9)
+    DEFAULT_INTENSITY_VELOCITY = 0.1
+
+    def __init__(self, **kw):
+        self.pulse_range = kw.pop("pulse_range", self.DEFAULT_PULSE_RANGE)
+        self.pulse_velocity = kw.pop(
+            "pulse_velocity", self.DEFAULT_PULSE_VELOCITY)
+        self.intensity_range = kw.pop(
+            "intensity_range", self.DEFAULT_INTENSITY_RANGE)
+        self.intensity_velocity = kw.pop(
+            "intensity_velocity", self.DEFAULT_INTENSITY_VELOCITY)
+        super(PulsatingLamp, self).__init__(
+            bounding_radius=self.pulse_range[1], **kw)
+
+    def serialize(self):
+        result = super(PulsatingLamp, self).serialize()
+        result["pulse_velocity"] = self.pulse_velocity
+        result["intensity_range"] = self.intensity_range
+        result["intensity_velocity"] = self.intensity_velocity
+        return result
+
+    def _update_range(self, value, velocity, value_range):
+        value += velocity
+        if value < value_range[0]:
+            value = value_range[0]
+            velocity = -velocity
+        elif value > value_range[1]:
+            value = value_range[1]
+            velocity = -velocity
+        return value, velocity
+
+    def tick(self):
+        self.ray_manager.max_radius, self.pulse_velocity = self._update_range(
+            self.ray_manager.max_radius, self.pulse_velocity, self.pulse_range)
+        self.intensity, self.intensity_velocity = self._update_range(
+            self.intensity, self.intensity_velocity, self.intensity_range)
+
+
+class SpotLight(BaseLight):
+
+    FITTING_IMG = "spotlight.png"
+
+    def __init__(self, **kw):
+        self.angular_velocity = kw.pop("angular_velocity", None)
+        super(SpotLight, self).__init__(**kw)
+
+    def serialize(self):
+        result = super(SpotLight, self).serialize()
+        result["angular_velocity"] = self.angular_velocity
+        return result
+
+    def fitting_image(self):
+        fitting_image = super(SpotLight, self).fitting_image()
+        rot_fitting_image = pygame.transform.rotozoom(
+            fitting_image, self.ray_manager.direction - 90, 1)
+
+        rot_rect = fitting_image.get_rect().copy()
+        rot_rect.center = rot_fitting_image.get_rect().center
+        rot_fitting_image = rot_fitting_image.subsurface(rot_rect).copy()
+
+        return rot_fitting_image
+
+    def tick(self):
+        if self.angular_velocity:
+            self.ray_manager.direction -= self.angular_velocity
+            self.ray_manager.update_shapes()