-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtile_render.py
More file actions
228 lines (184 loc) · 8.15 KB
/
tile_render.py
File metadata and controls
228 lines (184 loc) · 8.15 KB
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
"""
SVG rendering for Truchet tiles.
"""
from libtile import (TileInstance, TileType, Point,
compute_segments, edge_point_world,
TilingGraph)
from libgeom import centroid
from libsvg import SVG, Group, Path, Polygon, Semicircle, Line
def render_tile_outline(vertices: list[Point]) -> Polygon:
"""Render a tile's polygon outline (white fill, thin gray stroke)."""
return Polygon(list(vertices)).stroke("#ccc", 0.5).fill("white")
def render_tile_segments(tile: TileInstance, vertices: list[Point],
palette: list[str], stroke_width: float = 3.0,
ep_radius: float = 3.0, tick_length: float = 5.0) -> Group:
"""Render a tile's colored segments and edge point markers.
Returns Group containing:
- Colored polylines for each segment
- Inward-facing semicircles at edge points with tick lines
"""
g = Group()
# 1. Colored segments
segs = compute_segments(tile, vertices)
for seg in segs:
p = Path()
p.move_to(*seg.points[0])
for pt in seg.points[1:]:
p.line_to(*pt)
p.stroke(palette[seg.color], stroke_width)
g.add(p)
# 2. Inward-facing semicircles at edge points
tt = tile.tile_type
cx, cy = centroid(vertices)
for edge_idx, pts in enumerate(tt.edge_points):
for t in pts:
wp = edge_point_world(vertices, edge_idx, t)
dx = cx - wp[0]
dy = cy - wp[1]
mag = (dx**2 + dy**2)**0.5
if mag > 0:
ndx, ndy = dx / mag, dy / mag
else:
ndx, ndy = 0, 1
g.add(Semicircle(wp[0], wp[1], ep_radius, ndx, ndy)
.stroke("#333", 1).fill("none"))
g.add(Line(wp[0], wp[1],
wp[0] + ndx * tick_length,
wp[1] + ndy * tick_length)
.stroke("#333", 0.75))
return g
def render_tiling(graph: TilingGraph, group_colors: dict[int, int],
palette: list[str], stroke_width: float = 3.0,
svg: SVG | None = None) -> SVG | None:
"""Render all tiles using solver-assigned group colors.
Two-pass rendering: outlines first, then segments on top.
Args:
graph: TilingGraph with placed tiles
group_colors: mapping from canonical group ID → color index
palette: list of color strings
stroke_width: width of segment strokes
svg: optional SVG to render into; if None, elements are not added
"""
uf = graph.uf
# Pass 1: outlines
for placement in graph.tiles:
if svg:
svg.add(render_tile_outline(placement.vertices))
# Pass 2: segments
for placement in graph.tiles:
seg_colors = [group_colors[uf.find(gid)] for gid in placement.segment_group_ids]
tile_inst = TileInstance(placement.tile_type, seg_colors)
if svg:
svg.add(render_tile_segments(tile_inst, placement.vertices, palette, stroke_width))
return svg
def greedy_color(adjacency: list[tuple[int, int]], nodes: set[int]) -> dict[int, int]:
"""Greedy graph coloring. Returns node → color index."""
neighbors: dict[int, set[int]] = {n: set() for n in nodes}
for a, b in adjacency:
neighbors[a].add(b)
neighbors[b].add(a)
coloring: dict[int, int] = {}
for node in sorted(nodes):
used = {coloring[nb] for nb in neighbors[node] if nb in coloring}
c = 0
while c in used:
c += 1
coloring[node] = c
return coloring
if __name__ == "__main__":
from libtile import (TileType, TileInstance,
oct_tile_type, corner_tri_tile_type,
enriched_square_tile_type)
from libgeom import equilateral_triangle, rect, octagon_in_square
palette = ["#2980b9", "#e74c3c", "#27ae60"]
# --- Single tile examples (top row) ---
# 1. Triangle with irregular points: edge 0 has 2 points, edges 1-2 have 1
tri_type = TileType("tri-irreg", 3, [[0.3, 0.7], [0.5], [0.5]])
tri_inst = TileInstance(tri_type, [0, 1, 0, 1])
tri_verts = list(equilateral_triangle(cx=130, base_y=260, side=180))
# 2. Square with 2 points per edge (8 segments, 3 colors)
sq_type = TileType.uniform("sq-2pt", 4, [0.33, 0.67])
sq_inst = TileInstance(sq_type, [0, 1, 2, 0, 1, 2, 0, 1])
sq_verts = list(rect(260, 60, 180, 180))
svg = SVG(500, 300, "0 0 500 300")
# Pass 1: outlines
svg.add(render_tile_outline(tri_verts))
svg.add(render_tile_outline(sq_verts))
# Pass 2: segments
svg.add(render_tile_segments(tri_inst, tri_verts, palette))
svg.add(render_tile_segments(sq_inst, sq_verts, palette))
with open("examples/tile_test.svg", "w") as f:
f.write(str(svg))
print("Wrote examples/tile_test.svg")
# --- Tessellation example (graph-based) ---
# Build 4x4 grid via TilingGraph, auto-color with greedy coloring.
grid_type = TileType.uniform("sq", 4, [0.5])
rows, cols = 4, 4
side = 100
margin = 30
graph = TilingGraph()
for r in range(rows):
for c in range(cols):
x = margin + c * side
y = margin + r * side
graph.place_tile(grid_type, list(rect(x, y, side, side)))
adj = graph.group_adjacency()
groups = graph.canonical_groups()
print(f"Constraint graph: {len(groups)} groups, {len(adj)} adjacency edges")
coloring = greedy_color(adj, groups)
n_colors = max(coloring.values()) + 1 if coloring else 0
print(f"Greedy coloring used {n_colors} colors")
canvas = 2 * margin + cols * side
tess_svg = SVG(canvas, canvas, f"0 0 {canvas} {canvas}")
render_tiling(graph, coloring, palette, svg=tess_svg)
with open("examples/tile_tessellation.svg", "w") as f:
f.write(str(tess_svg))
print("Wrote examples/tile_tessellation.svg")
# --- Octagon + Square tiling demo (3x3 grid, center = composite) ---
oct_side = 100 # side length of each grid cell
oct_margin = 30
# Tile types
oct_type = oct_tile_type()
tri_type = corner_tri_tile_type()
plain_sq_type = TileType.uniform("sq", 4, [0.5])
oct_graph = TilingGraph()
s = oct_side
# Grid positions: row 0=top, col 0=left; center cell is (1,1)
# Place 4 corner plain squares
for (gr, gc) in [(0, 0), (0, 2), (2, 0), (2, 2)]:
x = oct_margin + gc * s
y = oct_margin + gr * s
oct_graph.place_tile(plain_sq_type, list(rect(x, y, s, s)))
# Place 4 enriched squares (edges facing center)
# Top center (row 0, col 1): enriched edge 2 (bottom)
x, y = oct_margin + 1 * s, oct_margin + 0 * s
oct_graph.place_tile(enriched_square_tile_type(2), list(rect(x, y, s, s)))
# Bottom center (row 2, col 1): enriched edge 0 (top)
x, y = oct_margin + 1 * s, oct_margin + 2 * s
oct_graph.place_tile(enriched_square_tile_type(0), list(rect(x, y, s, s)))
# Left center (row 1, col 0): enriched edge 1 (right)
x, y = oct_margin + 0 * s, oct_margin + 1 * s
oct_graph.place_tile(enriched_square_tile_type(1), list(rect(x, y, s, s)))
# Right center (row 1, col 2): enriched edge 3 (left)
x, y = oct_margin + 2 * s, oct_margin + 1 * s
oct_graph.place_tile(enriched_square_tile_type(3), list(rect(x, y, s, s)))
# Center cell: octagon + 4 corner triangles
cx0 = oct_margin + 1 * s
cy0 = oct_margin + 1 * s
oct_v = list(octagon_in_square(cx0, cy0, s))
tl = (cx0, cy0)
tr = (cx0 + s, cy0)
br = (cx0 + s, cy0 + s)
bl = (cx0, cy0 + s)
oct_graph.place_tile(oct_type, oct_v)
oct_graph.place_tile(tri_type, [tl, oct_v[0], oct_v[7]])
oct_graph.place_tile(tri_type, [tr, oct_v[2], oct_v[1]])
oct_graph.place_tile(tri_type, [br, oct_v[4], oct_v[3]])
oct_graph.place_tile(tri_type, [bl, oct_v[6], oct_v[5]])
# Graph stats (rendering blocked by transitive merge — needs segment fix)
oct_adj = oct_graph.group_adjacency()
oct_groups = oct_graph.canonical_groups()
print(f"\nOctagon tiling: {len(oct_groups)} groups, {len(oct_adj)} adjacency edges")
oct_coloring = greedy_color(oct_adj, oct_groups)
oct_n_colors = max(oct_coloring.values()) + 1 if oct_coloring else 0
print(f"Greedy coloring used {oct_n_colors} colors")