home · contact · privacy
Only calculate DijkstraMap until reachable targets.
[plomrogue2] / plomrogue / mapping.py
index e0a59d8e225f56af79b0b516bb7f6e366de164a4..707111263d884b21508ba536fc02b95e2af66677 100644 (file)
@@ -20,74 +20,146 @@ class MapGeometry():
 
     def __init__(self, size):
         self.size = size
+        self.neighbors_i = {}
+        self.directions = self.get_directions()
 
     def get_directions(self):
         directions = []
+        prefix = 'move__'
         for name in dir(self):
-            if name[:5] == 'move_':
-                directions += [name[5:]]
+            if name[:len(prefix)] == prefix:
+                directions += [name[len(prefix):]]
         return directions
 
-    def get_neighbors(self, pos):
+    def get_neighbors_yxyx(self, yxyx):
         neighbors = {}
-        for direction in self.get_directions():
-            neighbors[direction] = self.move(pos, direction)
+        for direction in self.directions:
+            neighbors[direction] = self.move_yxyx(yxyx, direction)
         return neighbors
 
-    def move(self, start_pos, direction):
-        mover = getattr(self, 'move_' + direction)
-        target = mover(start_pos)
+    def get_neighbors_yx(self, pos):
+        neighbors = {}
+        for direction in self.directions:
+            neighbors[direction] = self.move_yx(pos, direction)
+        return neighbors
+
+    def get_neighbors_i(self, i):
+        if i in self.neighbors_i:
+            return self.neighbors_i[i]
+        pos = YX(i // self.size.x, i % self.size.x)
+        neighbors_pos = self.get_neighbors_yx(pos)
+        neighbors_i = {}
+        for direction in neighbors_pos:
+            pos = neighbors_pos[direction]
+            if pos is None:
+                neighbors_i[direction] = None
+            else:
+                neighbors_i[direction] = pos.y * self.size.x + pos.x
+        self.neighbors_i[i] = neighbors_i
+        return self.neighbors_i[i]
+
+    def move_yx(self, start_yx, direction, check=True):
+        mover = getattr(self, 'move__' + direction)
+        target = mover(start_yx)
+        # TODO refactor with SourcedMap.inside?
         if target.y < 0 or target.x < 0 or \
-                target.y >= self.size.y or target.x >= self.size.x:
+           target.y >= self.size.y or target.x >= self.size.x:
             return None
         return target
 
+    def move_yxyx(self, start_yxyx, direction):
+        mover = getattr(self, 'move__' + direction)
+        start_yx = self.undouble_yxyx(*start_yxyx)
+        target_yx = mover(start_yx)
+        return self.double_yx(target_yx)
+
+    def double_yx(self, absolute_yx):
+        big_y = absolute_yx.y // self.size.y
+        little_y = absolute_yx.y % self.size.y
+        big_x = absolute_yx.x // self.size.x
+        little_x = absolute_yx.x % self.size.x
+        return YX(big_y, big_x), YX(little_y, little_x)
+
+    def undouble_yxyx(self, big_yx, little_yx):
+        y = big_yx.y * self.size.y + little_yx.y
+        x = big_yx.x * self.size.x + little_yx.x
+        return YX(y, x)
+
+    def basic_circle_out_move(self, position, direction):
+        mover = getattr(self, 'move__' + direction)
+        return mover(position)
+
 
 
 class MapGeometryWithLeftRightMoves(MapGeometry):
 
-    def move_LEFT(self, start_pos):
+    def move__LEFT(self, start_pos):
         return YX(start_pos.y, start_pos.x - 1)
 
-    def move_RIGHT(self, start_pos):
+    def move__RIGHT(self, start_pos):
         return YX(start_pos.y, start_pos.x + 1)
 
 
 
 class MapGeometrySquare(MapGeometryWithLeftRightMoves):
+    circle_out_directions = (('DOWN', 'LEFT'), ('LEFT', 'UP'),
+                             ('UP', 'RIGHT'), ('RIGHT', 'DOWN'))
+
+    def circle_out_move(self, yx, direction):
+        yx = self.basic_circle_out_move(yx, direction[0])
+        return self.basic_circle_out_move(yx, direction[1])
+
+    def define_segment(self, source_center, radius):
+        source_center = self.undouble_yxyx(*source_center)
+        size = YX(2 * radius + 1, 2 * radius + 1)
+        offset = YX(source_center.y - radius, source_center.x - radius)
+        center = YX(radius, radius)
+        return size, offset, center
 
-    def move_UP(self, start_pos):
+    def move__UP(self, start_pos):
         return YX(start_pos.y - 1, start_pos.x)
 
-    def move_DOWN(self, start_pos):
+    def move__DOWN(self, start_pos):
         return YX(start_pos.y + 1, start_pos.x)
 
 
-
 class MapGeometryHex(MapGeometryWithLeftRightMoves):
+    circle_out_directions = ('DOWNLEFT', 'LEFT', 'UPLEFT',
+                             'UPRIGHT', 'RIGHT', 'DOWNRIGHT')
+
+    def circle_out_move(self, yx, direction):
+        return self.basic_circle_out_move(yx, direction)
 
-    def move_UPLEFT(self, start_pos):
+    def define_segment(self, source_center, radius):
+        source_center = self.undouble_yxyx(*source_center)
+        indent = 1 if (source_center.y % 2) else 0
+        size = YX(2 * radius + 1 + indent, 2 * radius + 1)
+        offset = YX(source_center.y - radius - indent, source_center.x - radius)
+        center = YX(radius + indent, radius)
+        return size, offset, center
+
+    def move__UPLEFT(self, start_pos):
         start_indented = start_pos.y % 2
         if start_indented:
             return YX(start_pos.y - 1, start_pos.x)
         else:
             return YX(start_pos.y - 1, start_pos.x - 1)
 
-    def move_UPRIGHT(self, start_pos):
+    def move__UPRIGHT(self, start_pos):
         start_indented = start_pos.y % 2
         if start_indented:
             return YX(start_pos.y - 1, start_pos.x + 1)
         else:
             return YX(start_pos.y - 1, start_pos.x)
 
-    def move_DOWNLEFT(self, start_pos):
+    def move__DOWNLEFT(self, start_pos):
         start_indented = start_pos.y % 2
         if start_indented:
             return YX(start_pos.y + 1, start_pos.x)
         else:
             return YX(start_pos.y + 1, start_pos.x - 1)
 
-    def move_DOWNRIGHT(self, start_pos):
+    def move__DOWNRIGHT(self, start_pos):
         start_indented = start_pos.y % 2
         if start_indented:
             return YX(start_pos.y + 1, start_pos.x + 1)
@@ -98,9 +170,9 @@ class MapGeometryHex(MapGeometryWithLeftRightMoves):
 
 class Map():
 
-    def __init__(self, map_size):
-        self.size = map_size
-        self.terrain = '.' * self.size_i
+    def __init__(self, map_geometry):
+        self.geometry = map_geometry
+        self.terrain = '.' * self.size_i  # TODO: use Game.get_flatland()?
 
     def __getitem__(self, yx):
         return self.terrain[self.get_position_index(yx)]
@@ -112,25 +184,233 @@ class Map():
         else:
             self.terrain[pos_i] = c
 
+    def __iter__(self):
+        """Iterate over YX position coordinates."""
+        for y in range(self.geometry.size.y):
+            for x in range(self.geometry.size.x):
+                yield YX(y, x)
+
     @property
     def size_i(self):
-        return self.size.y * self.size.x
+        return self.geometry.size.y * self.geometry.size.x
 
     def set_line(self, y, line):
-        height_map = self.size.y
-        width_map = self.size.x
+        height_map = self.geometry.size.y
+        width_map = self.geometry.size.x
         if y >= height_map:
             raise ArgError('too large row number %s' % y)
         width_line = len(line)
         if width_line != width_map:
             raise ArgError('map line width %s unequal map width %s' % (width_line, width_map))
         self.terrain = self.terrain[:y * width_map] + line +\
-                       self.terrain[(y + 1) * width_map:]
+            self.terrain[(y + 1) * width_map:]
 
     def get_position_index(self, yx):
-        return yx.y * self.size.x + yx.x
+        return yx.y * self.geometry.size.x + yx.x
 
     def lines(self):
-        width = self.size.x
-        for y in range(self.size.y):
+        width = self.geometry.size.x
+        for y in range(self.geometry.size.y):
             yield (y, self.terrain[y * width:(y + 1) * width])
+
+
+
+class SourcedMap(Map):
+
+    def __init__(self, block_chars, obstacle_positions, source_maps,
+                 source_center, radius, get_map):
+        self.block_chars = block_chars
+        self.radius = radius
+        example_map = get_map(YX(0, 0))
+        self.source_geometry = example_map.geometry
+        size, self.offset, self.center = \
+            self.source_geometry.define_segment(source_center, radius)
+        self.geometry = self.source_geometry.__class__(size)
+        self.source_map_segment = ''
+        for yx in self:
+            big_yx, little_yx = self.source_yxyx(yx)
+            get_map(big_yx)
+            if (big_yx, little_yx) in obstacle_positions:
+                self.source_map_segment += self.block_chars[0]
+            else:
+                self.source_map_segment += source_maps[big_yx][little_yx]
+
+    def source_yxyx(self, yx):
+        absolute_yx = yx + self.offset
+        big_yx, little_yx = self.source_geometry.double_yx(absolute_yx)
+        return big_yx, little_yx
+
+    def target_yx(self, big_yx, little_yx, check=False):
+        target_yx = self.source_geometry.undouble_yxyx(big_yx, little_yx) - self.offset
+        if check and not self.inside(target_yx):
+            return False
+        return target_yx
+
+    def inside(self, yx):
+        if yx.y < 0 or yx.x < 0 or \
+           yx.y >= self.geometry.size.y or yx.x >= self.geometry.size.x:
+            return False
+        return True
+
+
+
+class DijkstraMap(SourcedMap):
+
+    def __init__(self, potential_targets, *args, **kwargs):
+        # TODO: check potential optimizations:
+        # - somehow ignore tiles that have the lowest possible value (we can
+        #   compare with a precalculated map for given starting position)
+        # - check if Python offers more efficient data structures to use here
+        super().__init__(*args, **kwargs)
+        self.terrain = [255] * self.size_i
+        self[self.center] = 0
+        targets = []
+        for target_yxyx in potential_targets:
+            target = self.target_yx(*target_yxyx)
+            if target == self.center:
+                continue
+            if self.inside(target):
+                targets += [target]
+
+        def work_tile(position_i):
+            shrunk_test = False
+            if self.source_map_segment[position_i] in self.block_chars:
+                return shrunk_test
+            neighbors = self.geometry.get_neighbors_i(position_i)
+            for direction in [d for d in neighbors if neighbors[d]]:
+                j = neighbors[direction]
+                if self.terrain[j] < self.terrain[position_i] - 1:
+                    self.terrain[position_i] = self.terrain[j] + 1
+                    shrunk_test = True
+            return shrunk_test
+
+        # TODO: refactor with FovMap.circle_out()
+        shrunk = True
+        while shrunk and len(targets) > 0:
+            shrunk = False
+            yx = self.center
+            distance = 1
+            while distance <= self.radius and len(targets) > 0:
+                yx = self.geometry.basic_circle_out_move(yx, 'RIGHT')
+                for dir_i in range(len(self.geometry.circle_out_directions)):
+                    for dir_progress in range(distance):
+                        direction = self.geometry.circle_out_directions[dir_i]
+                        yx = self.geometry.circle_out_move(yx, direction)
+                        position_i = self.get_position_index(yx)
+                        cur_shrunk = work_tile(position_i)
+                        if cur_shrunk and yx in targets:
+                            targets.remove(yx)
+                        shrunk = shrunk or cur_shrunk
+                distance += 1
+        # print('DEBUG Dijkstra')
+        # line_to_print = []
+        # x = 0
+        # for n in self.terrain:
+        #     line_to_print += ['%3s' % n]
+        #     x += 1
+        #     if x >= self.geometry.size.x:
+        #         x = 0
+        #         print(' '.join(line_to_print))
+        #         line_to_print = []
+
+
+
+class FovMap(SourcedMap):
+    # TODO: player visibility asymmetrical (A can see B when B can't see A):
+    # does this make sense, or not?
+
+    def __init__(self, *args, **kwargs):
+        super().__init__(*args, **kwargs)
+        self.terrain = '?' * self.size_i
+        self[self.center] = '.'
+        self.shadow_cones = []
+        #self.circle_out(self.center, self.shadow_process)
+
+    def init_terrain(self):
+        # we outsource this to allow multiprocessing some stab at it,
+        # and return it since multiprocessing does not modify its
+        # processing sources
+        self.circle_out(self.center, self.shadow_process)
+        return self
+
+    def throws_shadow(self, yx):
+        return self.source_map_segment[self.get_position_index(yx)]\
+            in self.block_chars
+
+    def shadow_process(self, yx, distance_to_center, dir_i, dir_progress):
+        # Possible optimization: If no shadow_cones yet and self[yx] == '.',
+        # skip all.
+        CIRCLE = 360  # Since we'll float anyways, number is actually arbitrary.
+
+        def correct_arm(arm):
+            if arm > CIRCLE:
+                arm -= CIRCLE
+            return arm
+
+        def in_shadow_cone(new_cone):
+            for old_cone in self.shadow_cones:
+                if old_cone[0] <= new_cone[0] and \
+                   new_cone[1] <= old_cone[1]:
+                    return True
+                # We might want to also shade tiles whose middle arm is inside a
+                # shadow cone for a darker FOV. Note that we then could not for
+                # optimization purposes rely anymore on the assumption that a
+                # shaded tile cannot add growth to existing shadow cones.
+            return False
+
+        def merge_cone(new_cone):
+            import math
+            for old_cone in self.shadow_cones:
+                if new_cone[0] < old_cone[0] and \
+                    (new_cone[1] > old_cone[0] or
+                     math.isclose(new_cone[1], old_cone[0])):
+                    old_cone[0] = new_cone[0]
+                    return True
+                if new_cone[1] > old_cone[1] and \
+                    (new_cone[0] < old_cone[1] or
+                     math.isclose(new_cone[0], old_cone[1])):
+                    old_cone[1] = new_cone[1]
+                    return True
+            return False
+
+        def eval_cone(cone):
+            if in_shadow_cone(cone):
+                return
+            self[yx] = '.'
+            if self.throws_shadow(yx):
+                unmerged = True
+                while merge_cone(cone):
+                    unmerged = False
+                if unmerged:
+                    self.shadow_cones += [cone]
+
+        step_size = (CIRCLE / len(self.geometry.circle_out_directions))\
+            / distance_to_center
+        number_steps = dir_i * distance_to_center + dir_progress
+        left_arm = correct_arm(step_size / 2 + step_size * number_steps)
+        right_arm = correct_arm(left_arm + step_size)
+
+        # Optimization potential: left cone could be derived from previous
+        # right cone. Better even: Precalculate all cones.
+        if right_arm < left_arm:
+            eval_cone([left_arm, CIRCLE])
+            eval_cone([0, right_arm])
+        else:
+            eval_cone([left_arm, right_arm])
+
+    def circle_out(self, yx, f):
+        # Optimization potential: Precalculate movement positions.
+        # Optimization potential: Precalculate what tiles are shaded by what tile
+        # and skip evaluation of already shaded tile. (This only works if tiles
+        # shading implies they completely lie in existing shades; otherwise we
+        # would lose shade growth through tiles at shade borders.)
+        distance = 1
+        yx = YX(yx.y, yx.x)
+        while distance <= self.radius:
+            yx = self.geometry.basic_circle_out_move(yx, 'RIGHT')
+            for dir_i in range(len(self.geometry.circle_out_directions)):
+                for dir_progress in range(distance):
+                    direction = self.geometry.circle_out_directions[dir_i]
+                    yx = self.geometry.circle_out_move(yx, direction)
+                    f(yx, distance, dir_i, dir_progress)
+            distance += 1