Map: name the street where you can see it, not where it begins

Street names got rarer the further you zoomed in, which is backwards.
A line label anchored to the midpoint of the feature as the *tile* drew
it -- a fixed geographic point, not a point in your view -- and the
tighter the view, the less likely that point was still on screen. Of the
265 named streets in the Montréal fixture, 37 anchors landed on a 53x26
canvas at zoom 14 and 6 at zoom 16, of which 2 survived collision.

The line is now clipped to the canvas first and the label goes on the
longest piece that survives, so the anchor is always somewhere you are
actually looking. Clipping rather than testing the endpoints matters:
at high zoom a street often crosses the whole view with both of its ends
outside it, and that is exactly the street you most want named. The
next-longest pieces are kept as alternates and tried in turn when the
first spot is already taken, so a street whose middle sits under a node
marker still gets named further along. A feature with nothing on screen
queues nothing at all.

That made a second bug visible: OpenStreetMap splits a long street into
several named features, and once each one anchored to its own visible
stretch, René-Lévesque was drawn twice on one screen. A name is now drawn
once per frame -- on a terminal's worth of columns the second copy only
ever takes space from a street that has none.

Zoom 16 goes 2 -> 6 street names at 53x26 and 2 -> 8 at 72x24; zoom 15
goes 10 -> 13. Waterway labels take the same path and improve with it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jean-Pierre MartineauandClaude Opus 5 committed 2026-08-08 02:10:38 -04:00
1 parent 71e979eadb
commit fd312db8b9
2 files changed
+191 -9

No files matched your search

+84 -9
View File
@@ -139,7 +139,13 @@ DRAWN_LAYERS: frozenset[str] = frozenset(
@dataclass(slots=True)
class _Label:
"""A pending label placement candidate."""
"""A pending label placement candidate.
Attributes:
alts: Further anchors to try, in order, when the preferred one is already taken.
A line feature offers these along the stretch of itself that is on screen, so
a street whose middle is under a node marker still gets named further along.
"""
rank: int
x: float
@@ -148,6 +154,7 @@ class _Label:
color: RGB
bold: bool
min_zoom: int = 0
alts: tuple[tuple[float, float], ...] = ()
@dataclass(slots=True)
@@ -192,14 +199,21 @@ def render_map(
_draw_nodes(canvas, viewport, markers, find=find)
# Then place basemap labels by importance, honouring the zoom gate and collisions.
# OpenStreetMap splits a long street into several named features, so one name can
# arrive many times over; on a terminal's worth of columns the second copy is only
# ever taking space from a street that has none, so a name is drawn once per frame.
placed = 0
named: set[str] = set()
for label in sorted(frame.labels, key=lambda l: l.rank):
if placed >= max_labels:
break
if viewport.zoom < label.min_zoom:
if viewport.zoom < label.min_zoom or label.text in named:
continue
if canvas.place_label(label.x, label.y, label.text, label.color, bold=label.bold):
placed += 1
for ax, ay in ((label.x, label.y), *label.alts):
if canvas.place_label(ax, ay, label.text, label.color, bold=label.bold):
placed += 1
named.add(label.text)
break
return canvas.to_ansi_lines()
@@ -315,6 +329,36 @@ def _draw_tile(frame: _Frame, layers: list[Layer], z: int, x: int, y: int) -> No
frame.labels.append(_Label(rank, dx, dy, feat.name, mark_rgb(color), bold, 8))
def _clip_to_canvas(
x0: float, y0: float, x1: float, y1: float, w: float, h: float
) -> Optional[tuple[float, float, float, float]]:
"""Trim a segment to the ``0..w`` by ``0..h`` canvas (Liang-Barsky).
Returns:
The part of the segment inside the canvas, or ``None`` if none of it is. A street
that crosses the view with both of its endpoints beyond the edges still yields the
stretch you can see, which is the whole point of clipping rather than testing the
endpoints.
"""
dx, dy = x1 - x0, y1 - y0
t0, t1 = 0.0, 1.0
for p, q in ((-dx, x0), (dx, w - x0), (-dy, y0), (dy, h - y0)):
if p == 0:
if q < 0:
return None # parallel to this edge and wholly outside it
continue
t = q / p
if p < 0:
if t > t1:
return None
t0 = max(t0, t)
else:
if t < t0:
return None
t1 = min(t1, t)
return (x0 + t0 * dx, y0 + t0 * dy, x0 + t1 * dx, y0 + t1 * dy)
def _add_line_label(
frame: _Frame,
rings: list[list[tuple[int, int]]],
@@ -327,12 +371,43 @@ def _add_line_label(
*,
min_zoom: int = 0,
) -> None:
"""Queue a label at the midpoint of a line feature's longest part."""
longest = max(rings, key=len)
lx, ly = longest[len(longest) // 2]
dx, dy = frame.viewport.feature_to_dot(x, y, z, extent, lx, ly)
"""Queue a label on the longest stretch of a line feature that is actually on screen.
Anchoring to the feature's own midpoint — the middle of the street as the *tile* drew
it — pins the label to a fixed geographic point rather than to your view, and the
tighter you zoom the less likely that point is to still be on screen. It made street
names get rarer the further in you went: of 265 named streets in a central Montréal
tile, 37 anchors landed on a 53x26 canvas at zoom 14 and only 6 at zoom 16.
So the line is clipped to the canvas first and the label goes on the longest piece
that survives, with the next-longest pieces kept as alternates for when that spot is
already spoken for. Nothing is queued for a feature that is wholly off screen.
"""
vp = frame.viewport
w, h = float(vp.dot_w), float(vp.dot_h)
pieces: list[tuple[float, float, float]] = [] # (length, mid x, mid y)
for ring in rings:
if len(ring) < 2:
continue
prev = vp.feature_to_dot(x, y, z, extent, *ring[0])
for point in ring[1:]:
cur = vp.feature_to_dot(x, y, z, extent, *point)
visible = _clip_to_canvas(prev[0], prev[1], cur[0], cur[1], w, h)
prev = cur
if visible is None:
continue
ax, ay, bx, by = visible
pieces.append((math.hypot(bx - ax, by - ay), (ax + bx) / 2, (ay + by) / 2))
if not pieces:
return
pieces.sort(key=lambda p: -p[0])
color, bold, rank = style
frame.labels.append(_Label(rank, dx, dy, text, mark_rgb(color), bold, min_zoom))
frame.labels.append(
_Label(
rank, pieces[0][1], pieces[0][2], text, mark_rgb(color), bold, min_zoom,
alts=tuple((px, py) for _, px, py in pieces[1:4]),
)
)
def _marker_style(marker: MapMarker) -> tuple[str, str]:
+107
View File
@@ -287,6 +287,113 @@ def test_render_map_prioritises_repeater_glyph() -> None:
assert "▲" in out and "●" not in out
def _street_labels_placed(cols: int, rows: int, zoom: int) -> int:
"""How many street names actually reach the canvas at this size and zoom."""
from meshterm.ui.map_render import DRAWN_LAYERS, _draw_tile, _Frame
from meshterm.ui.mapcanvas import MapCanvas
layers = decode_tile(_FIXTURE.read_bytes(), layers=DRAWN_LAYERS)
vp = Viewport(45.5019, -73.5674, zoom, cols * 2, (rows - 4) * 4)
canvas = MapCanvas(vp.dot_w // 2, vp.dot_h // 4)
frame = _Frame(canvas=canvas, viewport=vp)
_draw_tile(frame, layers, 14, 4843, 5861)
placed = 0
for label in sorted(frame.labels, key=lambda l: l.rank):
if vp.zoom < label.min_zoom:
continue
for ax, ay in ((label.x, label.y), *label.alts):
if canvas.place_label(ax, ay, label.text, label.color, bold=label.bold):
placed += label.min_zoom == 15 # the street-label gate identifies them
break
return placed
def test_street_labels_get_denser_as_you_zoom_in() -> None:
"""Zooming toward a street must not make its name less likely to appear.
Anchoring a label to the feature's own midpoint pinned it to a fixed geographic
point, so the tighter the view the less often that point was still on screen — the
fixture's 265 named streets yielded 2 labels at zoom 16 and 10 at zoom 15.
"""
assert _street_labels_placed(53, 26, 16) >= 5
assert _street_labels_placed(53, 26, 15) >= 10
# A wider terminal sees more of the same ground, so it may name more -- never fewer.
assert _street_labels_placed(72, 24, 16) >= _street_labels_placed(53, 26, 16)
def _tile_local_of_view_centre(vp: Viewport, tz: int, tx: int, ty: int, extent: int = 4096):
"""The tile-local point that lands in the middle of this viewport (inverts feature_to_dot)."""
from meshterm.core.geo import TILE_PX
ox, oy = vp.origin_world
scale = 2.0 ** (vp.zoom - tz)
lx = extent * ((vp.dot_w / 2 + ox) / (TILE_PX * scale) - tx)
ly = extent * ((vp.dot_h / 2 + oy) / (TILE_PX * scale) - ty)
return lx, ly
def test_street_name_is_drawn_only_once() -> None:
"""OSM splits a long street into several features; the map names it once."""
from meshterm.ui.map_render import DRAWN_LAYERS, MapMarker, render_map
layers = decode_tile(_FIXTURE.read_bytes(), layers=DRAWN_LAYERS)
vp = Viewport(45.5019, -73.5674, 16, 53 * 2, 22 * 4)
out = _plain(render_map(vp, {(14, 4843, 5861): layers},
[MapMarker("YUL", 45.5040, -73.5700, is_repeater=True)]))
# René-Lévesque arrives as several segments and used to be drawn twice on one screen.
assert out.count("René-Lévesque") <= 1, "a street was named more than once"
def test_line_label_anchors_on_the_visible_stretch() -> None:
"""A street crossing the view is named even with both its endpoints off screen."""
from meshterm.ui.map_render import _Frame, _add_line_label
from meshterm.ui.mapcanvas import MapCanvas
vp = Viewport(45.5019, -73.5674, 14, 120, 80)
frame = _Frame(canvas=MapCanvas(60, 20), viewport=vp)
_, cy = _tile_local_of_view_centre(vp, 14, 4843, 5861)
# A line spanning the whole tile at the view's latitude: its own midpoint is far away,
# but it crosses the canvas, so the clip must find it.
_add_line_label(frame, [[(0, cy), (4096, cy)]], 4096, 14, 4843, 5861, "Rue Long",
("#9aa0aa", False, 7))
assert len(frame.labels) == 1
label = frame.labels[0]
assert 0 <= label.x <= vp.dot_w and 0 <= label.y <= vp.dot_h
def test_line_label_off_screen_is_not_queued() -> None:
"""A feature with nothing on screen costs no label slot at all."""
from meshterm.ui.map_render import _Frame, _add_line_label
from meshterm.ui.mapcanvas import MapCanvas
vp = Viewport(45.5019, -73.5674, 16, 120, 80)
frame = _Frame(canvas=MapCanvas(60, 20), viewport=vp)
# A short line in the far corner of the tile, well outside a zoom-16 window.
_add_line_label(frame, [[(0, 0), (8, 8)]], 4096, 14, 4843, 5861, "Nowhere",
("#9aa0aa", False, 7))
assert frame.labels == []
def test_line_label_offers_alternates_along_the_visible_run() -> None:
"""A crowded first choice falls back further along the street rather than vanishing."""
from meshterm.ui.map_render import _Frame, _add_line_label
from meshterm.ui.mapcanvas import MapCanvas
vp = Viewport(45.5019, -73.5674, 14, 120, 80)
frame = _Frame(canvas=MapCanvas(60, 20), viewport=vp)
cx, cy = _tile_local_of_view_centre(vp, 14, 4843, 5861)
# A zig-zag across the view gives several visible pieces to choose between.
ring = [(cx - 120 + i * 40, cy - 40 + (i % 2) * 80) for i in range(8)]
_add_line_label(frame, [ring], 4096, 14, 4843, 5861, "Rue Zig", ("#9aa0aa", False, 7))
assert frame.labels and frame.labels[0].alts, "no fallback anchors offered"
assert all(a != (frame.labels[0].x, frame.labels[0].y) for a in frame.labels[0].alts)
def test_render_map_drops_crowded_labels_favouring_repeaters() -> None:
"""When labels can't all fit, the repeater's wins and a crowded node's is dropped."""
from meshterm.ui.map_render import MapMarker, render_map