forked from tenth10th/wfc-zelda-outpainting
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwfc_model.py
193 lines (156 loc) · 5.75 KB
/
wfc_model.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
from __future__ import annotations
from collections import defaultdict
from dataclasses import dataclass, field
from enum import Enum, auto
from random import Random
from typing import Iterable, MutableMapping, NewType, TypeVar
class Direction(Enum):
north = auto()
east = auto()
south = auto()
west = auto()
TileId = NewType("TileId", int)
@dataclass
class TileChance:
chance: int
@dataclass
class PossibleNeighbors:
"""
A L{PossibleNeighbors} represents the possible neighbors of the tile
identified by C{id}, in each direction.
"""
id: TileId
possibilities: MutableMapping[
Direction, MutableMapping[TileId, TileChance]
] = field(
default_factory=lambda: defaultdict(lambda: defaultdict(lambda: TileChance(0)))
)
compass = (
(Direction.north, (0, 1)),
(Direction.east, (1, 0)),
(Direction.south, (0, -1)),
(Direction.west, (-1, 0)),
)
def in_bounds(targetx: int, targety: int, w: int, h: int) -> bool:
return (targetx >= 0) and (targetx < w) and (targety >= 0) and (targety < h)
T = TypeVar("T")
def adjacents(
x: int, y: int, w: int, h: int, grid: list[list[T]]
) -> Iterable[tuple[Direction, T]]:
for direction, (deltax, deltay) in compass:
targetx = x + deltax
targety = y + deltay
if in_bounds(targetx, targety, w, h):
yield (direction, grid[targety][targetx])
def weighted_choice(r: Random, x: Iterable[tuple[T, int]]) -> T:
return r.choices(
[each for each, weight in x], weights=[weight for each, weight in x]
)[0]
@dataclass
class GeneratingTile:
remaining: set[TileId] | None = None
# None means 'all tiles are valid'
def observe(
self,
r: Random,
x: int,
y: int,
w: int,
h: int,
in_progress: GeneratingMap,
trained: TrainedSet,
) -> TileId:
if self.remaining is None:
self.remaining = set(trained.neighbors.keys())
if len(self.remaining) == 1:
return next(iter(self.remaining))
probabilities = {each: trained.toplevel[each].chance for each in self.remaining}
for direction, other_generating_tile in adjacents(x, y, w, h, in_progress):
reversed = {
Direction.north: Direction.south,
Direction.east: Direction.west,
Direction.south: Direction.north,
Direction.west: Direction.east,
}[direction]
options_for_other_tile = other_generating_tile.remaining or set(
trained.neighbors.keys()
)
unseen = set(probabilities.keys())
for other_tile_option in options_for_other_tile:
for possible_tile, possible_chance in (
trained.neighbors[other_tile_option].possibilities[reversed].items()
):
if possible_tile in probabilities:
probabilities[possible_tile] += possible_chance.chance
if possible_tile in unseen:
unseen.remove(possible_tile)
for still_unseen in unseen:
del probabilities[still_unseen]
if not probabilities:
return TileId(99)
chosen = weighted_choice(r, probabilities.items())
self.remaining = set([chosen])
trained.toplevel[chosen].chance -= 1
for direction, other_generating_tile in adjacents(x, y, w, h, in_progress):
other_generating_tile.remaining = (
other_generating_tile.remaining
if other_generating_tile.remaining is not None
else set(trained.neighbors.keys())
) & set(trained.neighbors[chosen].possibilities[direction])
return chosen
GeneratingMap = list[list[GeneratingTile]]
GeneratedMap = list[list[TileId]]
@dataclass
class TrainedSet:
neighbors: MutableMapping[TileId, PossibleNeighbors]
toplevel: MutableMapping[TileId, TileChance]
class IdToTileMap(defaultdict):
def __missing__(self, key: TileId) -> PossibleNeighbors:
result = self[key] = PossibleNeighbors(key)
return result
def train_on_map(training: list[list[TileId]]) -> TrainedSet:
assert training, "training data"
width = len(training[0])
height = len(training)
id_to_tile: defaultdict[TileId, PossibleNeighbors] = IdToTileMap()
toplevel: defaultdict[TileId, TileChance] = defaultdict(lambda: TileChance(0))
for y, row in enumerate(training):
assert len(row) == width, "uniform widths required"
for x, cell in enumerate(row):
for direction, adjacent in adjacents(x, y, width, height, training):
toplevel[cell].chance += 1
id_to_tile[cell].possibilities[direction][adjacent].chance += 1
return TrainedSet(id_to_tile, toplevel)
@dataclass
class MapGenerator:
width: int
height: int
output: GeneratedMap
trained: TrainedSet
progress: GeneratingMap
ungenerated: list[tuple[int, int]]
random: Random
@classmethod
def new(
cls,
random: Random,
output: GeneratedMap,
trained: TrainedSet,
progress: GeneratingMap,
) -> MapGenerator:
width = len(output[0])
height = len(output)
ungenerated = [
(x, height - (y + 1)) for y in range(height) for x in range(width)
]
random.shuffle(ungenerated)
return MapGenerator(
width, height, output, trained, progress, ungenerated, random
)
def step(self) -> None:
if not self.ungenerated:
return
x, y = self.ungenerated.pop()
self.output[y][x] = self.progress[y][x].observe(
self.random, x, y, self.width, self.height, self.progress, self.trained
)