"""
Build the 150 m tile grid for the City3D-MultiGen reconstruction pipeline.
Role in the pipeline:
This script turns a coarse tile-index footprint into the fine, regularly
spaced grid of 150 m x 150 m tiles that drives the rest of the pipeline.
Each generated tile later defines the geographic extent used to crop the
source city point cloud and to fetch aligned satellite/semantic maps.
Input:
A KML tile-index file (default "Tile_Index.kml") whose polygons describe
the WGS84 (lon/lat) coverage area of the source city data.
Outputs:
- output_grids.kml: a colorized KML visualization of the generated tiles.
- output_grids.json: the machine-readable grid consumed downstream. It
stores grid_size_m, grid_spacing_m, input_polygons, total_grids, and a
"grids" list where each entry has id, row, col, and both UTM and WGS84
corner coordinates (utm_nw/utm_se, wgs84_nw/wgs84_se).
Key steps:
Parse the KML polygons, pick a UTM zone from the data centroid, project the
polygons into metric UTM coordinates, tile the bounding box on a fixed
pitch, keep tiles whose center falls inside a footprint polygon, then
project the tile corners back to WGS84 for output.
Coordinate-system handling:
All distances/sizes are computed in metric UTM (zone chosen automatically
from the centroid via EPSG:326xx/327xx). pyproj Transformers (always_xy)
convert between EPSG:4326 (WGS84 lon/lat) and the chosen UTM CRS.
"""
import json
import math
from xml.etree import ElementTree as ET
from pyproj import Transformer, CRS
from typing import List, Tuple
GRID_SIZE = 150
GRID_SPACING = -130 # 150 m tile - 130 m overlap = 20 m center spacing (paper setting)
def parse_kml_polygons(kml_path: str) -> List[List[Tuple[float, float]]]:
tree = ET.parse(kml_path)
root = tree.getroot()
polygons = []
for elem in root.iter():
if elem.tag.endswith('coordinates'):
coords_text = elem.text
if coords_text:
coords = []
for line in coords_text.strip().split():
parts = line.split(',')
if len(parts) >= 2:
lon, lat = float(parts[0]), float(parts[1])
coords.append((lon, lat))
if coords:
polygons.append(coords)
print(f"Parsed {len(polygons)} polygons from KML")
return polygons
def get_utm_zone(lon: float, lat: float) -> str:
zone = int((lon + 180) / 6) + 1
hemisphere = 'north' if lat >= 0 else 'south'
return f"EPSG:326{zone:02d}" if hemisphere == 'north' else f"EPSG:327{zone:02d}"
def point_in_polygon(point: Tuple[float, float], polygon: List[Tuple[float, float]]) -> bool:
x, y = point
n = len(polygon)
inside = False
p1x, p1y = polygon[0]
for i in range(1, n + 1):
p2x, p2y = polygon[i % n]
if y > min(p1y, p2y):
if y <= max(p1y, p2y):
if x <= max(p1x, p2x):
if p1y != p2y:
xinters = (y - p1y) * (p2x - p1x) / (p2y - p1y) + p1x
if p1x == p2x or x <= xinters:
inside = not inside
p1x, p1y = p2x, p2y
return inside
def generate_grid(polygons_wgs84: List[List[Tuple[float, float]]],
grid_size: float,
spacing: float) -> List[dict]:
all_points = [p for poly in polygons_wgs84 for p in poly]
center_lon = sum(p[0] for p in all_points) / len(all_points)
center_lat = sum(p[1] for p in all_points) / len(all_points)
utm_crs = get_utm_zone(center_lon, center_lat)
print(f"Using coordinate system: {utm_crs}")
transformer_to_utm = Transformer.from_crs("EPSG:4326", utm_crs, always_xy=True)
transformer_to_wgs = Transformer.from_crs(utm_crs, "EPSG:4326", always_xy=True)
polygons_utm = []
for poly_wgs in polygons_wgs84:
poly_utm = [transformer_to_utm.transform(lon, lat) for lon, lat in poly_wgs]
polygons_utm.append(poly_utm)
all_utm_points = [p for poly in polygons_utm for p in poly]
min_x = min(p[0] for p in all_utm_points)
max_x = max(p[0] for p in all_utm_points)
min_y = min(p[1] for p in all_utm_points)
max_y = max(p[1] for p in all_utm_points)
print(f"Overall boundary in UTM: X=[{min_x:.2f}, {max_x:.2f}], Y=[{min_y:.2f}, {max_y:.2f}]")
print(f"Area size: {max_x-min_x:.2f}m x {max_y-min_y:.2f}m")
grids = []
grid_id = 0
total_candidates = 0
y = min_y
row = 0
while y < max_y:
x = min_x
col = 0
while x < max_x:
total_candidates += 1
center_x = x + grid_size / 2
center_y = y + grid_size / 2
center_utm = (center_x, center_y)
is_inside = False
for poly_utm in polygons_utm:
if point_in_polygon(center_utm, poly_utm):
is_inside = True
break
if is_inside:
nw_utm = (x, y + grid_size)
ne_utm = (x + grid_size, y + grid_size)
se_utm = (x + grid_size, y)
sw_utm = (x, y)
nw_wgs = transformer_to_wgs.transform(*nw_utm)
ne_wgs = transformer_to_wgs.transform(*ne_utm)
se_wgs = transformer_to_wgs.transform(*se_utm)
sw_wgs = transformer_to_wgs.transform(*sw_utm)
color_index = (row + col) % 2
grids.append({
'id': grid_id,
'row': row,
'col': col,
'color_index': color_index,
'utm': {
'nw': nw_utm,
'ne': ne_utm,
'se': se_utm,
'sw': sw_utm
},
'wgs84': {
'nw': nw_wgs,
'ne': ne_wgs,
'se': se_wgs,
'sw': sw_wgs
}
})
grid_id += 1
x += grid_size + spacing
col += 1
y += grid_size + spacing
row += 1
print(f"Generated {len(grids)} grids from {total_candidates} candidates")
return grids
def create_kml(grids: List[dict], output_path: str):
kml_header = '''
Grid Output
'''
kml_footer = '''
'''
with open(output_path, 'w', encoding='utf-8') as f:
f.write(kml_header)
for grid in grids:
wgs = grid['wgs84']
color_id = f"color{grid['color_index']}"
f.write(f'''
Grid_{grid['id']}
#{color_id}
{wgs['nw'][0]},{wgs['nw'][1]},0
{wgs['ne'][0]},{wgs['ne'][1]},0
{wgs['se'][0]},{wgs['se'][1]},0
{wgs['sw'][0]},{wgs['sw'][1]},0
{wgs['nw'][0]},{wgs['nw'][1]},0
''')
f.write(kml_footer)
print(f"KML file saved to: {output_path}")
def create_json(grids: List[dict], output_path: str, input_polygon_count: int = 1):
output_data = {
'grid_size_m': GRID_SIZE,
'grid_spacing_m': GRID_SPACING,
'input_polygons': input_polygon_count,
'total_grids': len(grids),
'grids': [
{
'id': g['id'],
'row': g['row'],
'col': g['col'],
'utm_nw': g['utm']['nw'],
'utm_se': g['utm']['se'],
'wgs84_nw': g['wgs84']['nw'],
'wgs84_se': g['wgs84']['se']
}
for g in grids
]
}
with open(output_path, 'w', encoding='utf-8') as f:
json.dump(output_data, f, indent=2, ensure_ascii=False)
print(f"JSON file saved to: {output_path}")
def main(input_kml: str, output_kml: str, output_json: str):
print(f"Reading input KML: {input_kml}")
print(f"Grid size: {GRID_SIZE}m, Spacing: {GRID_SPACING}m")
print("-" * 60)
polygons = parse_kml_polygons(input_kml)
if not polygons:
raise ValueError("No polygons found in input KML")
grids = generate_grid(polygons, GRID_SIZE, GRID_SPACING)
create_kml(grids, output_kml)
create_json(grids, output_json, len(polygons))
print("-" * 60)
print("Grid generation completed successfully!")
if __name__ == "__main__":
INPUT_KML = "Tile_Index.kml"
OUTPUT_KML = "output_grids.kml"
OUTPUT_JSON = "output_grids.json"
main(INPUT_KML, OUTPUT_KML, OUTPUT_JSON)