home · contact · privacy
Only send to client whether map starts indented, not whole offset.
[plomrogue2-experiments] / new / plomrogue / mapping.py
1 from plomrogue.errors import ArgError
2 import collections
3
4
5
6 class YX(collections.namedtuple('YX', ('y', 'x'))):
7
8     def __add__(self, other):
9         return YX(self.y + other.y, self.x + other.x)
10
11     def __sub__(self, other):
12         return YX(self.y - other.y, self.x - other.x)
13
14     def __str__(self):
15         return 'Y:%s,X:%s' % (self.y, self.x)
16
17
18
19 class Map:
20
21     def __init__(self, size=YX(0, 0), init_char = '?', start_indented=True):
22         self.size = size
23         self.terrain = init_char*self.size_i
24         self.start_indented = start_indented
25
26     def __getitem__(self, yx):
27         return self.terrain[self.get_position_index(yx)]
28
29     def __setitem__(self, yx, c):
30         pos_i = self.get_position_index(yx)
31         if type(c) == str:
32             self.terrain = self.terrain[:pos_i] + c + self.terrain[pos_i + 1:]
33         else:
34             self.terrain[pos_i] = c
35
36     def __iter__(self):
37         """Iterate over YX position coordinates."""
38         for y in range(self.size.y):
39             for x in range(self.size.x):
40                 yield YX(y, x)
41
42     @property
43     def size_i(self):
44         return self.size.y * self.size.x
45
46     def set_line(self, y, line):
47         height_map = self.size.y
48         width_map = self.size.x
49         if y >= height_map:
50             raise ArgError('too large row number %s' % y)
51         width_line = len(line)
52         if width_line > width_map:
53             raise ArgError('too large map line width %s' % width_line)
54         self.terrain = self.terrain[:y * width_map] + line +\
55                        self.terrain[(y + 1) * width_map:]
56
57     def get_position_index(self, yx):
58         return yx.y * self.size.x + yx.x
59
60     def lines(self):
61         width = self.size.x
62         for y in range(self.size.y):
63             yield (y, self.terrain[y * width:(y + 1) * width])
64
65
66
67 class MapGeometry():
68
69     def get_directions(self):
70         directions = []
71         for name in dir(self):
72             if name[:5] == 'move_':
73                 directions += [name[5:]]
74         return directions
75
76     def get_neighbors(self, pos, map_size, start_indented=True):
77         neighbors = {}
78         if not hasattr(self, 'neighbors_to'):
79             self.neighbors_to = {}
80         if not map_size in self.neighbors_to:
81             self.neighbors_to[map_size] = {}
82         if not start_indented in self.neighbors_to[map_size]:
83             self.neighbors_to[map_size][start_indented] = {}
84         if pos in self.neighbors_to[map_size][start_indented]:
85             return self.neighbors_to[map_size][start_indented][pos]
86         for direction in self.get_directions():
87             neighbors[direction] = self.move(pos, direction, map_size,
88                                              start_indented)
89         self.neighbors_to[map_size][start_indented][pos] = neighbors
90         return neighbors
91
92     def undouble_coordinate(self, maps_size, coordinate):
93         y = maps_size.y * coordinate[0].y + coordinate[1].y
94         x = maps_size.x * coordinate[0].x + coordinate[1].x
95         return YX(y, x)
96
97     def get_view_offset(self, maps_size, center, radius):
98         yx_to_origin = self.undouble_coordinate(maps_size, center)
99         return yx_to_origin - YX(radius, radius)
100
101     def pos_in_view(self, pos, offset, maps_size):
102         return self.undouble_coordinate(maps_size, pos) - offset
103
104     def get_view(self, maps_size, get_map, radius, view_offset):
105         m = Map(size=YX(radius*2+1, radius*2+1),
106                 start_indented=(view_offset.y % 2 == 0))
107         for pos in m:
108             seen_pos = self.correct_double_coordinate(maps_size, (0,0),
109                                                       pos + view_offset)
110             seen_map = get_map(seen_pos[0], False)
111             if seen_map is None:
112                 seen_map = Map(size=maps_size)
113             m[pos] = seen_map[seen_pos[1]]
114         return m
115
116     def correct_double_coordinate(self, map_size, big_yx, little_yx):
117
118         def adapt_axis(axis):
119             maps_crossed = little_yx[axis] // map_size[axis]
120             new_big = big_yx[axis] + maps_crossed
121             new_little = little_yx[axis] % map_size[axis]
122             return new_big, new_little
123
124         new_big_y, new_little_y = adapt_axis(0)
125         new_big_x, new_little_x = adapt_axis(1)
126         return YX(new_big_y, new_big_x), YX(new_little_y, new_little_x)
127
128     def move(self, start_pos, direction, map_size, start_indented=True):
129         mover = getattr(self, 'move_' + direction)
130         big_yx, little_yx = start_pos
131         uncorrected_target = mover(little_yx, start_indented)
132         return self.correct_double_coordinate(map_size, big_yx,
133                                               uncorrected_target)
134
135
136
137 class MapGeometryWithLeftRightMoves(MapGeometry):
138
139     def move_LEFT(self, start_pos, _):
140         return YX(start_pos.y, start_pos.x - 1)
141
142     def move_RIGHT(self, start_pos, _):
143         return YX(start_pos.y, start_pos.x + 1)
144
145
146
147 class MapGeometrySquare(MapGeometryWithLeftRightMoves):
148
149     def move_UP(self, start_pos, _):
150         return YX(start_pos.y - 1, start_pos.x)
151
152     def move_DOWN(self, start_pos, _):
153         return YX(start_pos.y + 1, start_pos.x)
154
155
156
157 class MapGeometryHex(MapGeometryWithLeftRightMoves):
158
159     def __init__(self, *args, **kwargs):
160         super().__init__(*args, **kwargs)
161         self.fov_map_type = FovMapHex
162
163     def move_UPLEFT(self, start_pos, start_indented):
164         if start_pos.y % 2 == start_indented:
165             return YX(start_pos.y - 1, start_pos.x - 1)
166         else:
167             return YX(start_pos.y - 1, start_pos.x)
168
169     def move_UPRIGHT(self, start_pos, start_indented):
170         if start_pos.y % 2 == start_indented:
171             return YX(start_pos.y - 1, start_pos.x)
172         else:
173             return YX(start_pos.y - 1, start_pos.x + 1)
174
175     def move_DOWNLEFT(self, start_pos, start_indented):
176         if start_pos.y % 2 == start_indented:
177              return YX(start_pos.y + 1, start_pos.x - 1)
178         else:
179                return YX(start_pos.y + 1, start_pos.x)
180
181     def move_DOWNRIGHT(self, start_pos, start_indented):
182         if start_pos.y % 2 == start_indented:
183             return YX(start_pos.y + 1, start_pos.x)
184         else:
185             return YX(start_pos.y + 1, start_pos.x + 1)
186
187
188
189 class FovMap(Map):
190
191     def __init__(self, source_map, center):
192         self.source_map = source_map
193         self.size = self.source_map.size
194         self.fov_radius = (self.size.y / 2) - 0.5
195         self.start_indented = source_map.start_indented
196         self.terrain = '?' * self.size_i
197         self[center] = '.'
198         self.shadow_cones = []
199         self.circle_out(center, self.shadow_process_hex)
200
201     def shadow_process_hex(self, yx, distance_to_center, dir_i, dir_progress):
202         # Possible optimization: If no shadow_cones yet and self[yx] == '.',
203         # skip all.
204         CIRCLE = 360  # Since we'll float anyways, number is actually arbitrary.
205
206         def correct_arm(arm):
207             if arm < 0:
208                 arm += CIRCLE
209             return arm
210
211         def in_shadow_cone(new_cone):
212             for old_cone in self.shadow_cones:
213                 if old_cone[0] >= new_cone[0] and \
214                     new_cone[1] >= old_cone[1]:
215                     #print('DEBUG shadowed by:', old_cone)
216                     return True
217                 # We might want to also shade hexes whose middle arm is inside a
218                 # shadow cone for a darker FOV. Note that we then could not for
219                 # optimization purposes rely anymore on the assumption that a
220                 # shaded hex cannot add growth to existing shadow cones.
221             return False
222
223         def merge_cone(new_cone):
224             import math
225             for old_cone in self.shadow_cones:
226                 if new_cone[0] > old_cone[0] and \
227                     (new_cone[1] < old_cone[0] or
228                      math.isclose(new_cone[1], old_cone[0])):
229                     #print('DEBUG merging to', old_cone)
230                     old_cone[0] = new_cone[0]
231                     #print('DEBUG merged cone:', old_cone)
232                     return True
233                 if new_cone[1] < old_cone[1] and \
234                     (new_cone[0] > old_cone[1] or
235                      math.isclose(new_cone[0], old_cone[1])):
236                     #print('DEBUG merging to', old_cone)
237                     old_cone[1] = new_cone[1]
238                     #print('DEBUG merged cone:', old_cone)
239                     return True
240             return False
241
242         def eval_cone(cone):
243             #print('DEBUG CONE', cone, '(', step_size, distance_to_center, number_steps, ')')
244             if in_shadow_cone(cone):
245                 return
246             self[yx] = '.'
247             if self.source_map[yx] != '.':
248                 #print('DEBUG throws shadow', cone)
249                 unmerged = True
250                 while merge_cone(cone):
251                     unmerged = False
252                 if unmerged:
253                     self.shadow_cones += [cone]
254
255         #print('DEBUG', yx)
256         step_size = (CIRCLE/len(self.circle_out_directions)) / distance_to_center
257         number_steps = dir_i * distance_to_center + dir_progress
258         left_arm = correct_arm(-(step_size/2) - step_size*number_steps)
259         right_arm = correct_arm(left_arm - step_size)
260         # Optimization potential: left cone could be derived from previous
261         # right cone. Better even: Precalculate all cones.
262         if right_arm > left_arm:
263             eval_cone([left_arm, 0])
264             eval_cone([CIRCLE, right_arm])
265         else:
266             eval_cone([left_arm, right_arm])
267
268     def basic_circle_out_move(self, pos, direction):
269         """Move position pos into direction. Return whether still in map."""
270         mover = getattr(self.geometry, 'move_' + direction)
271         pos = mover(pos, self.start_indented)
272         if pos.y < 0 or pos.x < 0 or \
273             pos.y >= self.size.y or pos.x >= self.size.x:
274             return pos, False
275         return pos, True
276
277     def circle_out(self, yx, f):
278         # Optimization potential: Precalculate movement positions. (How to check
279         # circle_in_map then?)
280         # Optimization potential: Precalculate what hexes are shaded by what hex
281         # and skip evaluation of already shaded hexes. (This only works if hex
282         # shading implies they completely lie in existing shades; otherwise we
283         # would lose shade growth through hexes at shade borders.)
284
285         # TODO: Start circling only in earliest obstacle distance.
286         # TODO: get rid of circle_in_map logic
287         circle_in_map = True
288         distance = 1
289         yx = YX(yx.y, yx.x)
290         #print('DEBUG CIRCLE_OUT', yx)
291         while circle_in_map:
292             if distance > self.fov_radius:
293                 break
294             circle_in_map = False
295             yx, _ = self.basic_circle_out_move(yx, 'RIGHT')
296             for dir_i in range(len(self.circle_out_directions)):
297                 for dir_progress in range(distance):
298                     direction = self.circle_out_directions[dir_i]
299                     yx, test = self.circle_out_move(yx, direction)
300                     if test:
301                         f(yx, distance, dir_i, dir_progress)
302                         circle_in_map = True
303             distance += 1
304
305
306
307 class FovMapHex(FovMap):
308     circle_out_directions = ('DOWNLEFT', 'LEFT', 'UPLEFT',
309                              'UPRIGHT', 'RIGHT', 'DOWNRIGHT')
310
311     def __init__(self, *args, **kwargs):
312         self.geometry = MapGeometryHex()
313         super().__init__(*args, **kwargs)
314
315     def circle_out_move(self, yx, direction):
316         return self.basic_circle_out_move(yx, direction)
317
318
319
320 class FovMapSquare(FovMap):
321     circle_out_directions = (('DOWN', 'LEFT'), ('LEFT', 'UP'),
322                              ('UP', 'RIGHT'), ('RIGHT', 'DOWN'))
323
324     def __init__(self, *args, **kwargs):
325         self.geometry = MapGeometrySquare()
326         super().__init__(*args, **kwargs)
327
328     def circle_out_move(self, yx, direction):
329         self.basic_circle_out_move(yx, direction[0])
330         return self.basic_circle_out_move(yx, direction[1])
331