Skip to content

Geometry

The geometry pipeline from raw meshes to the output mesh, in three modules, and the volume of a site (sites.py), which the local web service turns into the maximum volume:

  1. Surface sampling (surface_sampling.py): discretizes test-surface faces into evenly spaced points with outward-facing normals, using grid_step and a coplanarity tolerance; also computes the edge_taper weights. Used by preprocessing.
  2. Voxelization (voxelization.py): converts the max-volume mesh into a dense cubic boolean grid at the configured voxel_size. Used by preprocessing.
  3. Meshing (meshing.py): removes voxel clusters smaller than min_voxels and converts the carved voxel mask back into a triangle mesh, either as cubic voxel faces or via SDF smoothing + marching cubes + Taubin polishing. Used by exporting.

Surface sampling

urbansolarcarver.surface_sampling

UrbanSolarCarver: test-surface sampling

Samples the test surfaces into the points and normals that rays start from, and the analysis-mesh quads that show one face per sample point. Used by preprocessing.

Pipeline entry point

sample_surface(insolation_mesh, settings) discretize_surface_with_normals with the preprocessing settings; raises when no sample points are produced.

Public API

sample_planar_surface(mesh, sample_step=1.0, include_boundary=True, edge_taper=0.0) Sample one planar connected component on a regular grid. Returns points, normals, analysis-mesh quads (vertices + faces), and edge-taper weights.

discretize_surface_with_normals(mesh, sample_step=1.0, coplanarity_tol_deg=5.0, edge_taper=0.0) Split the mesh into connected components, sample each planar one, and return points, normals, an AnalysisMesh, weights, and taper statistics.

AnalysisMesh Quad mesh with one face per sample point; serialised to analysis_mesh.json.

Internal helpers

plane_frame(surface_normal) Orthonormal in-plane basis for planar sampling.

_mesh_boundary_loops(mesh), _sample_boundary_edges(polygon, ...) Boundary extraction and extra samples along boundary edges.

Data types and units
  • Points and normals: np.ndarray, shape (N, 3), world units.

SkippedSurfaces(surface_count=0, surfaces=list()) dataclass

What the sampling left out: how many surfaces it saw, and for each one skipped the reason ("degenerate", "non-planar" or "no samples") and its triangles ((T, 3, 3) array).

AnalysisMesh(vertices, faces, face_normals=None)

One quad per sample point: the patch of test surface each point stands for.

Written to analysis_mesh.json by preprocessing, for visualising sampling density or per-point results.

Attributes:

Name Type Description
vertices (V, 3) float64 array of quad corners
faces (N, 4) int32 array of quad vertex indices, one quad per sample point
face_normals (N, 3) float32 array of outward unit normals, or None

to_dict()

Serialise to a plain dict (vertices + faces as nested lists).

sample_surface(insolation_mesh, settings, skipped_surfaces=None)

Sample quasi-planar patches to produce point/normal sets for carving.

Parameters:

Name Type Description Default
insolation_mesh Trimesh

Test surfaces; each connected component should be one flat panel.

required
settings PreprocessingSettings

Supplies grid_step (sample spacing) and edge_taper.

required

Returns:

Name Type Description
sample_points (ndarray(N, 3), float32)
sample_normals (ndarray(N, 3), float32)
analysis_mesh AnalysisMesh or None

The analysis mesh whose face centroids are the sample points.

sample_weights ndarray(N)

Edge-taper design weights in [0, 1] (all ones when settings.edge_taper is 0).

taper_stats list of dict

Per-component taper statistics (empty when edge_taper is 0).

Raises:

Type Description
InputError

If no points are sampled from the insolation surface.

plane_frame(surface_normal)

Return two orthonormal vectors spanning the plane orthogonal to surface_normal.

Parameters:

Name Type Description Default
surface_normal (3,) array_like

Plane normal (need not be unit length).

required

Returns:

Type Description
axis_u, axis_v : (3,) np.ndarray

Unit vectors with cross(axis_u, axis_v) equal to the unit normal, so (axis_u, axis_v, normal) is a right-handed frame.

Raises:

Type Description
ValueError

If surface_normal has near-zero length.

Notes
  • The normal is normalized internally.
  • The reference axis is X, or Y when the normal is within about 26 deg of X, so the cross product never degenerates.
  • The result depends only on the normal, so panels with the same normal get the same frame (up to the sign of axis_u when the normal is negated).
  • Used by sample_planar_surface to build a local 2D sampling frame.

sample_planar_surface(mesh, sample_step=1.0, include_boundary=True, edge_taper=0.0)

Sample points on a regular grid over one planar submesh.

Parameters:

Name Type Description Default
mesh Trimesh

Single planar connected component (convex or not, with or without holes).

required
sample_step float

Spacing of the sampling grid in world units.

1.0
include_boundary bool

If True, keep grid points that fall on the polygon boundary; otherwise drop them. Extra points seeded along the boundary edges (_sample_boundary_edges) are added in both cases.

True
edge_taper float

Design-constraint taper distance (world units). When > 0, each sample gets a weight ramping linearly from 0 at the component outline (exterior and holes) to 1 at edge_taper from it.

0.0

Returns:

Name Type Description
points (N, 3) float64 np.ndarray

Sample locations in world coordinates.

normals (N, 3) np.ndarray

Unit normal, the same for every point, oriented to agree with the area-weighted normal of the mesh faces.

quad_verts (4N, 3) float64 np.ndarray

Corner positions of one analysis-mesh quad per sample point.

quad_faces (N, 4) int32 np.ndarray

Vertex indices of each quad (indices into quad_verts).

weights (N,) float32 np.ndarray

Edge-taper design weights in [0, 1]; all ones when edge_taper == 0.

Notes
  • Builds a local 2D grid in the plane (see plane_frame) and rasterizes the polygon footprint to select in-polygon grid sites.
  • If no grid site falls inside the polygon, one point guaranteed to lie inside it (Shapely's representative_point) is used as the single sample.
  • Used by discretize_surface_with_normals for planar-only sampling.

skip_reasons(triangles, surface_of_face, surface_count, coplanarity_tol_deg=5.0)

Per surface of a test surface file, why a run would leave it out before sampling it: "degenerate" (no area), "non-planar", or None; the sampling's own rule (_flatness_of_surfaces). "no samples" depends on the grid step and is known only when sampling. Inspect calls this.

discretize_surface_with_normals(mesh, sample_step=1.0, coplanarity_tol_deg=5.0, edge_taper=0.0, skipped_surfaces=None)

Sample the nearly planar connected components of a mesh and return point/normal pairs.

Each connected component whose faces all lie within coplanarity_tol_deg of the component's area-weighted mean normal, or stay within 0.1 mm of its plane, is sampled with sample_planar_surface; other components are skipped with a UserWarning. The quad analysis mesh has one face per sample point, suitable for per-face colouring (e.g. "LB Spatial Heatmap" in Grasshopper/Rhino).

Parameters:

Name Type Description Default
mesh Trimesh

Input triangle mesh (test surface).

required
sample_step float

Sampling grid spacing in world units.

1.0
coplanarity_tol_deg float

Maximum face-normal deviation (degrees) to consider a component planar.

5.0
edge_taper float

Design-constraint taper distance (meters): sample weights ramp from 0 at each component's outline to 1 at edge_taper inward. Distances are measured in the component's plane, which the coplanarity check guarantees exists.

0.0
skipped_surfaces SkippedSurfaces or None

Filled with the surfaces seen and the ones skipped, when given.

None

Returns:

Name Type Description
points (N, 3) float32 np.ndarray

Sample points (centroids of the analysis-mesh quads).

normals (N, 3) float32 np.ndarray

Outward-facing normals at each sample point.

analysis_mesh AnalysisMesh or None

Combined quad analysis mesh, or None if no points were sampled.

weights (N,) float32 np.ndarray

Edge-taper design weights in [0, 1]; all ones when edge_taper == 0.

taper_stats list of dict

Per-component taper statistics (empty when edge_taper == 0). Components that never reach full weight (narrower than ~2× the taper) also emit a UserWarning, so the user knows that geometry is partly or wholly excluded from the protected program.

Voxelization

urbansolarcarver.voxelization

UrbanSolarCarver: voxelization

Rasterizes the maximum volume into a padded cubic occupancy grid. Used by preprocessing.

Pipeline entry point

voxelize(envelope_mesh, settings, device=None) voxelize_mesh with the preprocessing settings; raises on an empty grid.

Public API

voxelize_mesh(mesh, voxel_size=1.0, margin_frac=0.2, device=None) Rasterize a watertight mesh into a padded cubic occupancy grid. The result is cached in the active CarverSession under a key made of the mesh arrays, voxel size, margin and device (_voxelize_cache_key).

voxelize_solid_warp(vertices, faces, grid_origin, voxel_size, resolution, device) The Warp parity voxelizer voxelize_mesh uses (kernel in warp_kernels); None when Warp cannot run on the device.

Data types and units
  • Voxel grids: torch.Tensor, shape (D, D, D), uint8/bool, 1 = inside.
  • voxel_size is in world units.

voxelize(envelope_mesh, settings, device=None)

Rasterize the envelope into a padded cubic voxel grid.

Parameters:

Name Type Description Default
envelope_mesh Trimesh
required
settings PreprocessingSettings

Supplies voxel_size and margin_frac.

required
device device or None

Device for the returned grid; None picks CUDA when available.

None

Returns:

Name Type Description
voxel_grid (Tensor(D, D, D), uint8)

1 indicates inside/filled.

grid_origin ndarray(3)

World-space min corner for index (0,0,0).

grid_extent float

Physical cube size (meters).

grid_resolution int

Number of voxels per side (D).

Raises:

Type Description
InputError

If voxelization returns an empty grid.

voxelize_mesh(mesh, voxel_size=1.0, margin_frac=0.2, device=None)

Rasterize a watertight mesh into a padded binary voxel grid.

Parameters:

Name Type Description Default
mesh Trimesh
required
voxel_size float

Edge length of one voxel in world units.

1.0
margin_frac float

Padding on each side as a fraction of the longest side of the mesh's axis-aligned bounding box.

0.2
device device or None

Device for the returned tensor and for the Warp voxelizer; None picks CUDA when available, else CPU.

None

Returns:

Name Type Description
voxels (D, D, D) uint8 torch.Tensor

1 where inside/filled, 0 otherwise.

origin (3,) np.ndarray

World-space min corner of the grid.

grid_extent float

Side length of the cubic domain in world units (D * voxel_size).

resolution int

Number of voxels per side (D).

Raises:

Type Description
ValueError

If voxel_size <= 0, margin_frac < 0, or the grid would have more than grid_planning.MAX_GRID_VOXELS voxels (checked before anything is allocated).

RuntimeError

If the Warp voxelizer fails (for example out of memory), or the trimesh voxelization fails.

Notes
  • Uses the Warp parity voxelizer (voxelize_solid_warp below, on CUDA or the Warp CPU device); only when Warp cannot run on device does it use trimesh voxelization plus fill. Sealed interior cavities are then filled with scipy's binary_fill_holes.
  • The grid is axis-aligned, cubic, and centred on the mesh bounding box.
  • Results are cached per session (see _voxelize_cache_key).

voxelize_solid_warp(vertices, faces, grid_origin, voxel_size, resolution, device, *, centre_only=False, span_min=None, span_max=None)

Solid-voxelize a triangle mesh by parity ray casting along x, y and z against a Warp BVH (bounding volume hierarchy).

A voxel is occupied when at least 2 of the 3 axis parity tests find its centre inside (a majority vote, so one axis confused by a small hole or a grazing ray does not decide the result; trimesh's orthographic fill uses the same idea), or when the mesh surface passes through it. Runs on CUDA or the Warp CPU device; voxelization.py uses trimesh's slower rasterize-and-fill only when this returns None, and lets anything it raises propagate.

With centre_only the surface-through rule is left out: a voxel is occupied only when its centre is inside (the context rule). span_min and span_max (same frame as grid_origin) move the start and end of the per-axis rays out to them where they lie beyond the grid, so a mesh larger than the grid keeps a correct parity inside it; votes are still written only for cells of the grid. The defaults give the maximum volume's voxelization unchanged.

Returns:

Type Description
ndarray | None

(resolution, resolution, resolution) bool occupancy array, or None when the Warp backend is unavailable on device.

Raises:

Type Description
ValueError

If the mesh has no vertices or no faces.

Meshing

urbansolarcarver.meshing

UrbanSolarCarver: meshing

Cleans the carved occupancy grid and turns it into the output mesh. Used by exporting.

Overview

Two meshing modes are supported:

1) Cubic (apply_smoothing == False) - Clean the binary grid: drop small connected components, then drop occupied voxels with fewer than 2 occupied neighbours in their 3×3×3 neighbourhood. - Triangulate with the shared-vertex cubic mesher (_cubic_mesh_from_occupancy).

2) Smoothed SDF (apply_smoothing == True) - Convert occupancy to a signed distance field (SDF) in voxel units. - Light Gaussian blur, then edge-preserving Perona–Malik diffusion; the result is kept only within 2 voxels of the zero level. - Pick an iso value that preserves the original inside volume. - Extract a surface with marching cubes (scikit-image). - Optionally run a short Taubin polish (0 to 6 iterations) after cleanup.

Pipeline entry point

finalize_mesh(carved_grid, grid_origin, settings, voxel_size) Clean the carved grid and mesh it with the cubic or smoothed path.

Public API

prune_voxels(voxels, min_voxels) Remove 26-connected components smaller than min_voxels.

prune_voxels_morph(voxels, min_voxels) Cleanup for the cubic path: component prune, then the neighbour-count filter described above. Only removes voxels; no erosion or closing.

mesh_from_voxels(voxels, min_corner, voxel_size) Build a blocky mesh from the binary grid. Returns an unprocessed Trimesh.

mesh_from_voxels_smoothed(voxels, min_corner, voxel_size) Build a smooth mesh by contouring a smoothed SDF with marching cubes. Uses a volume-matched iso to avoid systematic thinning.

cleanup_mesh(mesh, min_face_count=100, light=False) Fix winding/normals (unless light), weld vertices, drop small fragments.

polish_mesh_taubin(mesh, iters=2) Optional Taubin polish after the SDF + marching cubes path, at most 6 iterations.

Internal helpers

_cubic_mesh_from_occupancy(voxels, min_corner, voxel_size) Vertex and face arrays for the cubic mesher.

_voxel_presmooth(field_bool) SDF build + Gaussian + narrow-band Perona–Malik diffusion.

_pm_anisotropic_diffuse(sdf, iters, k, tau) Edge-preserving diffusion stepper used by _voxel_presmooth.

_volume_matched_threshold(sdf, target_inside_voxels) Iso selection that matches the original inside count.

_median_edge_length(m) Median of unique edge lengths; used to normalize the Taubin polish.

Data types and units
  • Voxel grids: torch.Tensor, shape (D, D, D), uint8/bool, 1 = inside.
  • Meshes: trimesh.Trimesh in world coordinates.
  • voxel_size is in world units and is passed to marching cubes as the grid spacing.
Notes
  • The cubic path gives a blocky "voxel look" that is stable between runs. It applies no erosion, so thin volumes are kept.
  • The smoothed path operates in SDF space, not on the triangle mesh. This removes terracing while keeping the overall form.
  • The Taubin step is short and optional. Heavy smoothing belongs in SDF space, not on the mesh.

finalize_mesh(carved_grid, grid_origin, settings, voxel_size)

Convert carved voxels to a mesh and clean results.

Behavior

• If apply_smoothing is False: prune_voxels_morph (small-component prune + neighbour-count filter), cubic meshing, then cleanup_mesh in light mode. • If apply_smoothing is True: prune_voxels (small-component prune), SDF presmooth + marching cubes, vertex weld, then cleanup_mesh (light mode when the welded mesh is watertight), then polish_mesh_taubin with settings.smooth_iters (0 to 6).

Parameters:

Name Type Description Default
carved_grid Tensor(D, D, D)

Binary occupancy after carving.

required
grid_origin ndarray(3)

World-space min corner for index (0,0,0).

required
settings ExportingSettings

Supplies apply_smoothing, min_voxels, min_face_count and smooth_iters.

required
voxel_size float

Edge length of a voxel in meters; it belongs to the preprocessing run that built the grid, so it is not part of the exporting settings.

required

Returns:

Name Type Description
cleaned_voxels Tensor(D, D, D)

Post-pruned (and possibly morphologically cleaned) occupancy.

initial_mesh Trimesh

Mesh directly from the selected meshing path (pre-cleanup copy).

final_mesh Trimesh

Cleaned mesh, Taubin-polished on the smoothed path when smooth_iters > 0.

prune_voxels(voxels, min_voxels)

Remove connected components smaller than min_voxels (26-connectivity).

Parameters:

Name Type Description Default
voxels (D, D, D) uint8/bool torch.Tensor
required
min_voxels int

Size threshold; components with fewer voxels are removed.

required

Returns:

Name Type Description
cleaned (D, D, D) uint8 torch.Tensor

Binary occupancy on the same device as voxels.

Notes
  • Used on the smoothed path (apply_smoothing=True) prior to SDF smoothing.

prune_voxels_morph(voxels, min_voxels)

Light cleanup for the cubic (unsmoothed) path.

Steps
  1. Remove connected components (26-connectivity) with fewer than min_voxels voxels.
  2. Remove occupied voxels whose 3×3×3 neighbourhood (including the voxel itself) holds fewer than 3 occupied voxels, i.e. voxels with 0 or 1 occupied neighbours. This drops isolated specks and one-voxel spurs.

Only removes voxels, never adds them: adding would undo carving.

Parameters:

Name Type Description Default
voxels (D, D, D) uint8/bool torch.Tensor
required
min_voxels int

Size threshold; components with fewer voxels are removed.

required

Returns:

Name Type Description
cleaned (D, D, D) uint8 torch.Tensor

Binary occupancy on the same device as voxels.

polish_mesh_taubin(mesh, iters=2)

Apply a short Taubin smoothing pass to remove small ripples.

Parameters:

Name Type Description Default
mesh Trimesh

Modified in place.

required
iters int

Number of trimesh Taubin steps, capped at 6. trimesh alternates steps (even steps shrink, odd steps inflate), so even values give complete shrink/inflate pairs. If 0 or less, the mesh is returned unchanged.

2

Returns:

Name Type Description
mesh Trimesh

The same object, smoothed, with degenerate faces removed.

Notes
  • Uses fixed parameters λ = 0.28 and ν = 0.31 (trimesh's sign convention; μ = −0.31 in Taubin's notation).
  • Vertices are centred and scaled to unit median edge length during smoothing, then restored.
  • Intended only after the SDF + marching cubes path. Keep the iteration count small to avoid shape drift.

mesh_from_voxels(voxels, min_corner, voxel_size)

Construct a blocky (cubic) mesh from a binary occupancy grid.

Parameters:

Name Type Description Default
voxels (D, D, D) uint8/bool torch.Tensor
required
min_corner (3,) array_like

World-space origin of the grid (maps index [0,0,0] to this point).

required
voxel_size float

Size of one voxel in world units.

required

Returns:

Name Type Description
mesh Trimesh

Unprocessed triangle mesh (process=False). Call cleanup_mesh next.

See Also

mesh_from_voxels_smoothed

mesh_from_voxels_smoothed(voxels, min_corner, voxel_size)

Construct a smooth mesh by contouring a smoothed SDF with marching cubes.

Parameters:

Name Type Description Default
voxels (D, D, D) uint8/bool torch.Tensor

Binary occupancy (1 = inside).

required
min_corner (3,) array_like

World-space grid origin.

required
voxel_size float

World units per voxel (passed as spacing to marching cubes).

required

Returns:

Name Type Description
mesh Trimesh

Unprocessed triangle mesh (process=False) in world coordinates; an empty Trimesh if the grid is empty or the field is constant.

Notes
  • Internally calls _voxel_presmooth and chooses an iso-value via _volume_matched_threshold to preserve volume.
  • Marching cubes runs directly on the continuous SDF so the surface interpolates smoothly between voxel centers. (trimesh's matrix_to_marching_cubes(threshold=...) would binarize the field first, throwing the smoothing away.)

cleanup_mesh(mesh, min_face_count=100, light=False)

Repair and prune small fragments from a mesh.

Parameters:

Name Type Description Default
mesh Trimesh

Modified in place.

required
min_face_count int

Fragments with fewer faces than this are discarded.

100
light bool

If True, skip the repair steps (fix_winding, fix_normals, fix_inversion, fill_holes, merge_vertices). Use for meshes that already have shared vertices and consistent outward winding: the cubic mesher's output and watertight marching-cubes output. Roughly 10x faster on large meshes.

False

Returns:

Name Type Description
mesh Trimesh

Concatenation of the components with at least min_face_count faces. If no component is that large, only the largest one is returned and a UserWarning is issued.

Sites

A site is a closed outline whose vertices carry the ground's elevation, and a height. Its volume stands on the ground inside the outline (linear along the edges, harmonic inside) and has a flat top at its lowest vertex plus its height; see A site as the input.

urbansolarcarver.sites

Sites: closed outlines on the ground, each raised to its own height, as the maximum volume.

A site is a closed outline whose vertices carry the elevation of the ground, in the coordinates of the other input files, and a height. Its volume is the closed mesh of - the ground inside the outline (the bottom): linear along each edge between its two vertices, and inside the harmonic function of those boundary values, the shape a stretched membrane takes on the outline, never above the highest or below the lowest vertex; - a flat top at the site's lowest elevation plus its height; - the walls from the boundary ground up to the top.

A site may have holes (design/site-holes.md): closed outlines strictly inside its outline, whose vertices carry the ground's elevation too. The volume leaves them out from the ground to the top: the ground's boundary follows every ring, and walls go up every ring.

The service joins the volumes of a project's sites into the maximum volume file the engine carves, so carving needs nothing new.

ring_points(points)

A ring's vertices as an (n, 3) array, without a repeated last point or consecutive repeats.

outline_points(site)

The site's outline vertices as an (n, 3) array, without a repeated last point or consecutive repeats.

hole_points(site)

Each hole's vertices as an (n, 3) array, cleaned as the outline's.

all_points(site)

Every vertex of the site, the outline's then the holes'.

site_polygon(site)

The site in plan: its outline with its holes.

site_rise(site)

How much higher the site's highest vertex is than its lowest, the holes' vertices included.

check_site(site)

The plain reasons the site cannot make a volume; empty when it can.

ground_spacing(site, spacing)

The spacing of the ground's points: spacing, finer on a small site, coarser on a site so large it would need too many.

site_ground(site, spacing)

The ground inside the outline and outside the holes: (vertices (n, 3), triangles (m, 3) counter-clockwise from above, boundary flags (n,)).

The site is triangulated (shapely's constrained Delaunay) and the triangles divided until no edge is longer than the ground spacing; the boundary vertices (on the outline or a hole) take the ground along the edges, the others the harmonic function of those values.

site_volume(site, spacing)

The site's closed volume (a trimesh): the ground below, a flat top at the lowest vertex plus the height, walls between, up the outline and every hole.

site_base_volume(site, base, bottom)

The prism of the site's outline from bottom up to its lowest vertex plus base (a trimesh): the volume a base height keeps.

bottom is below every site's ground, so the prism holds every voxel of the site up to the base level; the voxels below the ground are not part of the maximum volume, so the prism needs no ground. ValueError when the outline is refused, base is not more than 0 or bottom is not below the base level.

sites_volume(sites, spacing)

The volumes of all the sites joined into one mesh, as several maximum volume files are joined.