From c6b2253b6fa88f30cdbf61088a1c6a9d8c09aa32 Mon Sep 17 00:00:00 2001 From: Oleg Date: Fri, 28 Aug 2026 01:45:59 +0300 Subject: [PATCH 1/2] feat(modeling): polygonize linked STL slice contour --- catalog.json | 15 +- ...odel_line_contour_from_linked_stl_slice.md | 69 ++-- ...odel_line_contour_from_linked_stl_slice.py | 319 ++++++++++++------ 3 files changed, 281 insertions(+), 122 deletions(-) diff --git a/catalog.json b/catalog.json index 4559109..b95d381 100644 --- a/catalog.json +++ b/catalog.json @@ -126,7 +126,7 @@ { "id": "modeling.create-model-line-contour-from-linked-stl-slice", "name": "Create model-line contour from linked STL slice", - "summary": "Slices one selected linked STL mesh and creates the largest NetTopologySuite concave hull as a closed model-line contour.", + "summary": "Polygonizes a selected linked STL slice, heals small gaps between mesh fragments, and creates the largest exterior shell as model lines.", "category": "modeling", "path": "modeling/create_model_line_contour_from_linked_stl_slice.py", "documentation": "modeling/create_model_line_contour_from_linked_stl_slice.md", @@ -160,19 +160,19 @@ }, { "index": 2, - "name": "point_snap_mm", + "name": "endpoint_snap_mm", "type": "number-string", "required": false, "default": "25", - "description": "XY grid used to merge nearby intersection points, in millimetres." + "description": "XY grid used to snap section-segment endpoints, in millimetres." }, { "index": 3, - "name": "maximum_hull_edge_mm", + "name": "gap_healing_mm", "type": "number-string", "required": false, - "default": "2500", - "description": "Maximum edge length used by the concave-hull algorithm, in millimetres." + "default": "250", + "description": "Buffer distance used to close gaps between polygonized STL fragments, in millimetres; zero disables healing." }, { "index": 4, @@ -212,12 +212,13 @@ "description": "Source, slice, geometry-processing, contour-area, model-line, sketch-plane, and line-style details." }, "tags": [ - "concave-hull", "contour", + "gap-healing", "import-instance", "mesh", "model-curves", "nettopologysuite", + "polygonization", "stl" ] }, diff --git a/modeling/create_model_line_contour_from_linked_stl_slice.md b/modeling/create_model_line_contour_from_linked_stl_slice.md index 838b5b2..a9834ee 100644 --- a/modeling/create_model_line_contour_from_linked_stl_slice.md +++ b/modeling/create_model_line_contour_from_linked_stl_slice.md @@ -1,8 +1,8 @@ # Create model-line contour from linked STL slice -Creates one closed exterior contour as Revit model lines by intersecting a selected linked STL mesh with a horizontal plane and calculating a NetTopologySuite concave hull from the intersection points. +Creates one closed exterior contour as Revit model lines by intersecting a selected linked STL mesh with a horizontal plane. The script preserves the triangle-section segments, polygonizes the resulting linework, heals small gaps between separate STL solids, and keeps the largest exterior shell. -The initial defaults preserve the prototype scenario: level `L3`, a slice `1500` mm above the level, `25` mm point snapping, a `2500` mm maximum hull edge, and `50` mm contour simplification. +The defaults preserve the validated prototype scenario: level `L3`, a slice `1500` mm above the level, `25` mm endpoint snapping, `250` mm polygon gap healing, and `50` mm topology-preserving simplification. ## Compatibility @@ -13,7 +13,7 @@ The initial defaults preserve the prototype scenario: level `L3`, a slice `1500` - File-system reads: optional local .NET assembly paths supplied through `IN[6]` - Tested Revit versions: not yet recorded for this exact catalog script -The prototype from which this draft was generalized ran successfully in Revit 2024. The generalized repository file still requires a separate manual test before Revit 2024 can be listed as tested. +The polygonization and gap-healing prototype from which this draft was generalized ran successfully in Revit 2024. The generalized repository file still requires a separate manual test before Revit 2024 can be listed as tested. ## Before running @@ -27,7 +27,7 @@ The script reads all mesh geometry exposed by the selected linked import. It doe ## NetTopologySuite dependency -The concave hull is calculated with `NetTopologySuite` 2.6.0. If the assemblies are already loaded in the Revit process, leave `IN[6]` empty. Otherwise pass a semicolon-separated list of full local DLL paths in dependency order, with `NetTopologySuite.dll` last. +Segment noding, polygonization, buffering, and simplification use `NetTopologySuite` 2.6.0. If the assemblies are already loaded in the Revit process, leave `IN[6]` empty. Otherwise pass a semicolon-separated list of full local DLL paths in dependency order, with `NetTopologySuite.dll` last. The prototype used these assemblies: @@ -47,14 +47,14 @@ BIMO passes `IN` values as strings. All inputs are positional. | --- | --- | --- | | `IN[0]` | Exact Revit level name | `L3` | | `IN[1]` | Slice offset above the level, in millimetres | `1500` | -| `IN[2]` | XY grid used to merge nearby intersection points, in millimetres | `25` | -| `IN[3]` | Maximum edge length used by the concave-hull algorithm, in millimetres | `2500` | -| `IN[4]` | Topology-preserving contour simplification tolerance, in millimetres | `50` | -| `IN[5]` | Minimum accepted contour area, in square metres | `10` | +| `IN[2]` | XY grid used to snap segment endpoints, in millimetres; must be greater than zero | `25` | +| `IN[3]` | Buffer distance used to close gaps between polygonized STL fragments, in millimetres; `0` disables healing | `250` | +| `IN[4]` | Topology-preserving contour simplification tolerance, in millimetres; `0` disables simplification | `50` | +| `IN[5]` | Minimum accepted exterior-shell area, in square metres | `10` | | `IN[6]` | Semicolon-separated full paths to required .NET assemblies, in load order | Empty when already loaded | | `IN[7]` | Model-line style name | `BIMO_STL_Contour` | -When a slice produces more than 100,000 raw points, the script raises the effective point snap to at least `50` mm. It stops if the slice exceeds 2,000,000 raw points. +The script stops if the slice exceeds 2,000,000 raw segments. ## Processing @@ -62,18 +62,34 @@ The script: 1. resolves the exact named `Level` and places the section plane at `Level.ProjectElevation + IN[1]`; 2. recursively reads mesh geometry from the selected linked `ImportInstance` in project coordinates; -3. intersects each mesh triangle with the horizontal plane; -4. snaps and deduplicates the resulting XY points; -5. calculates a NetTopologySuite concave hull with holes disabled; -6. applies topology-preserving simplification; -7. keeps the largest polygon whose area meets `IN[5]`; -8. validates the contour before opening a Revit transaction; +3. intersects every mesh triangle with the horizontal plane and keeps the real section segments; +4. snaps segment endpoints to the `IN[2]` grid, discards collapsed segments, and removes duplicates; +5. uses NetTopologySuite to node and dissolve the linework, then polygonizes every closed ring; +6. combines nearby polygon fragments by buffering outward and inward by `IN[3]`; +7. keeps the polygon with the largest exterior shell and applies topology-preserving simplification using `IN[4]`; +8. checks the final exterior-shell area against `IN[5]` before opening a Revit transaction; 9. creates a line subcategory when needed, one horizontal `SketchPlane`, and the closed model-line contour; 10. rolls the transaction back if any model creation step fails. +## Tuning contour accuracy + +`IN[3]` and `IN[4]` affect different parts of the result: + +- Reduce `IN[4]` to `25`, `10`, or `0` to retain more of the healed shell and determine whether a local discrepancy comes from simplification. +- Reduce `IN[3]` when the contour bridges intended recesses or rounds exterior corners too strongly. Increase it only when the polygonized STL remains split into separate building fragments. +- Keep `IN[2]` small enough to preserve wall location. Increasing endpoint snap can close noisy linework but also moves every sliced endpoint to a coarser grid. + +The gap-healing operation uses the default NetTopologySuite buffer joins. Consequently, some corner rounding can be introduced by `IN[3]` even when simplification is disabled. Tune simplification first, then gap healing, so the source of a discrepancy remains clear. + ## Output -On success, `OUT` is a dictionary containing the source element ID, level and slice elevation, mesh and triangle counts, raw and snapped point counts, effective parameters, contour area, created model-line IDs, sketch-plane ID, and line-style information. +On success, `OUT` is a dictionary containing: + +- source, level, and slice elevation; +- mesh, triangle, raw-segment, collapsed-segment, duplicate-segment, and unique-segment counts; +- noded line component and polygonizer diagnostics (`polygon_count`, `dangle_count`, `cut_edge_count`, and `invalid_ring_count`); +- gap-healing and simplification parameters plus healed and final exterior-shell areas; +- created model-line IDs, sketch-plane ID, and line-style information. Validation, dependency-loading, geometry, and Revit API failures reach BIMO as execution errors. @@ -81,7 +97,7 @@ Validation, dependency-loading, geometry, and Revit API failures reach BIMO as e The script creates: -- a model-line subcategory named by `IN[7]` when it does not already exist; a new subcategory is colored magenta; +- a model-line subcategory named by `IN[7]` when it does not already exist; a new subcategory is colored cyan; - one `SketchPlane` at the section elevation; - one closed chain of model curves assigned to that line style. @@ -89,13 +105,25 @@ No existing model elements are intentionally edited or deleted. Undo the single ## Limitations -- Only the largest exterior polygon is created. Courtyards, holes, and smaller detached contours are omitted. -- The concave hull is inferred from points, not reconstructed from connected triangle-intersection segments. Its shape depends strongly on point snap, maximum edge length, and simplification tolerance. +- Only the largest exterior shell is created. Courtyards, holes, and smaller detached contours are omitted. +- Gap healing can join close but intentionally separate geometry, fill narrow recesses, and round corners. Its default is model-dependent, not a universal building tolerance. - Coplanar mesh triangles are ignored to avoid filling horizontal mesh faces. - The source must be a selected linked `ImportInstance`; unloaded links and other element types are not supported. - Very large STL meshes can take tens of seconds or longer to process because every triangle is inspected. - NetTopologySuite and all required assemblies must be compatible with the selected IronPython host. +## Prototype validation + +The current approach was exercised in Revit 2024 on the `L3 + 1500 mm` slice shown during development: + +- 49 meshes and 7,264,272 triangles were inspected; +- 12,275 raw section segments became 9,861 unique snapped segments; +- polygonization produced 997 valid polygons, 13 dangles, no cut edges, and no invalid rings; +- `250` mm gap healing produced one exterior shell of approximately 572.873 m2; +- `50` mm simplification produced an exterior shell of approximately 573.418 m2 and 179 model lines. + +These figures document the prototype run, not a successful run of the exact generalized repository file. + ## Manual Revit test 1. Open a disposable Revit 2024 or newer project containing level `L3` and a linked building STL. @@ -103,4 +131,5 @@ No existing model elements are intentionally edited or deleted. Undo the single 3. Supply the local NetTopologySuite assembly paths in `IN[6]` when they are not already loaded. 4. Run with the defaults and verify that model lines are created at `L3 + 1500 mm`. 5. Inspect the contour against the mesh in plan and 3D, confirm it is closed, and review omitted courtyards or detached portions. -6. Undo the transaction and confirm that the created lines, sketch plane, and newly created style are removed together. +6. Repeat with `IN[4] = 0` and compare the suspect locations to isolate simplification effects. +7. Undo each transaction and confirm that the created lines, sketch plane, and newly created style are removed together. diff --git a/modeling/create_model_line_contour_from_linked_stl_slice.py b/modeling/create_model_line_contour_from_linked_stl_slice.py index ccac57e..b900998 100644 --- a/modeling/create_model_line_contour_from_linked_stl_slice.py +++ b/modeling/create_model_line_contour_from_linked_stl_slice.py @@ -1,12 +1,12 @@ -"""Create a model-line concave hull from a horizontal slice of a linked STL mesh. +"""Create a model-line exterior contour from a horizontal linked-STL slice. BIMO Run Python contract: - Engine: IronPython - Selection: exactly one linked ImportInstance containing mesh geometry - IN[0]: exact level name (optional, default: L3) - IN[1]: slice offset above the level in millimetres (optional, default: 1500) -- IN[2]: XY point snap in millimetres (optional, default: 25) -- IN[3]: concave-hull maximum edge length in millimetres (optional, default: 2500) +- IN[2]: XY endpoint snap in millimetres (optional, default: 25) +- IN[3]: polygon gap-healing distance in millimetres (optional, default: 250) - IN[4]: contour simplification tolerance in millimetres (optional, default: 50) - IN[5]: minimum accepted contour area in square metres (optional, default: 10) - IN[6]: semicolon-separated .NET assembly paths (optional if NTS is loaded) @@ -38,9 +38,7 @@ MILLIMETRES_PER_FOOT = 304.8 SQUARE_METRES_PER_SQUARE_FOOT = 0.09290304 -MAXIMUM_RAW_SLICE_POINTS = 2000000 -ADAPTIVE_SNAP_POINT_COUNT = 100000 -ADAPTIVE_SNAP_MM = 50.0 +MAXIMUM_RAW_SLICE_SEGMENTS = 2000000 def _input(index, default_value=None): @@ -72,11 +70,23 @@ def _number(value, input_name, minimum=None, minimum_inclusive=False): def _import_nettopologysuite_types(): - from NetTopologySuite.Algorithm.Hull import ConcaveHull - from NetTopologySuite.Geometries import Coordinate, GeometryFactory + from NetTopologySuite.Geometries import ( + Coordinate, + Geometry, + GeometryFactory, + LineString, + ) + from NetTopologySuite.Operation.Polygonize import Polygonizer from NetTopologySuite.Simplify import TopologyPreservingSimplifier - return Coordinate, GeometryFactory, ConcaveHull, TopologyPreservingSimplifier + return ( + Coordinate, + Geometry, + GeometryFactory, + LineString, + Polygonizer, + TopologyPreservingSimplifier, + ) def _load_nettopologysuite(assembly_paths_value): @@ -137,7 +147,7 @@ def _resolve_level(doc, requested_name): def _selected_linked_import_instance(doc): - selected_ids = list(__selection__.GetElementIds()) + selected_ids = list(__uidoc__.Selection.GetElementIds()) if len(selected_ids) != 1: raise ValueError( "Select exactly one linked STL ImportInstance before running the script." @@ -196,9 +206,7 @@ def _triangle_slice_segment(triangle, slice_z, tolerance_feet): if abs(start_distance) <= tolerance_feet and abs(end_distance) <= tolerance_feet: continue if abs(start_distance) <= tolerance_feet: - _append_unique_point( - intersections, (start.X, start.Y), tolerance_feet - ) + _append_unique_point(intersections, (start.X, start.Y), tolerance_feet) continue if abs(end_distance) <= tolerance_feet: _append_unique_point(intersections, (end.X, end.Y), tolerance_feet) @@ -235,9 +243,8 @@ def _triangle_slice_segment(triangle, slice_z, tolerance_feet): def _slice_meshes(meshes, slice_z, tolerance_feet): - points = [] + segments = [] triangle_count = 0 - intersected_triangle_count = 0 for mesh in meshes: triangle_count += mesh.NumTriangles @@ -248,83 +255,179 @@ def _slice_meshes(meshes, slice_z, tolerance_feet): if segment is None: continue - intersected_triangle_count += 1 - points.extend(segment) - if len(points) > MAXIMUM_RAW_SLICE_POINTS: + segments.append(segment) + if len(segments) > MAXIMUM_RAW_SLICE_SEGMENTS: raise ValueError( - "The slice exceeded the {0}-point safety limit.".format( - MAXIMUM_RAW_SLICE_POINTS + "The slice exceeded the {0}-segment safety limit.".format( + MAXIMUM_RAW_SLICE_SEGMENTS ) ) - if len(points) < 3: + if not segments: raise ValueError( "The selected mesh does not intersect the requested horizontal plane." ) - return points, triangle_count, intersected_triangle_count + return segments, triangle_count + + +def _snap_and_deduplicate_segments(segments, snap_feet): + unique_segments = {} + collapsed_segment_count = 0 + duplicate_segment_count = 0 + + for start, end in segments: + start_key = ( + int(round(start[0] / snap_feet)), + int(round(start[1] / snap_feet)), + ) + end_key = ( + int(round(end[0] / snap_feet)), + int(round(end[1] / snap_feet)), + ) + if start_key == end_key: + collapsed_segment_count += 1 + continue + if end_key < start_key: + start_key, end_key = end_key, start_key + segment_key = start_key, end_key + if segment_key in unique_segments: + duplicate_segment_count += 1 + continue -def _snap_points(points, snap_feet): - snapped = {} - for x_coordinate, y_coordinate in points: - key = ( - int(round(x_coordinate / snap_feet)), - int(round(y_coordinate / snap_feet)), + unique_segments[segment_key] = ( + (start_key[0] * snap_feet, start_key[1] * snap_feet), + (end_key[0] * snap_feet, end_key[1] * snap_feet), ) - snapped[key] = (key[0] * snap_feet, key[1] * snap_feet) - return [snapped[key] for key in sorted(snapped.keys())] + if not unique_segments: + raise ValueError("Endpoint snapping left no usable slice segments.") + + return ( + [unique_segments[key] for key in sorted(unique_segments.keys())], + collapsed_segment_count, + duplicate_segment_count, + ) + +def _polygon_members(geometry): + if geometry is None or geometry.IsEmpty: + return [] + geometry_type = str(geometry.GeometryType) + if geometry_type == "Polygon": + return [geometry] + if geometry_type not in ("MultiPolygon", "GeometryCollection"): + return [] -def _largest_polygon(geometry, minimum_area_square_feet): polygons = [] for geometry_index in range(geometry.NumGeometries): - candidate = geometry.GetGeometryN(geometry_index) - if str(candidate.GeometryType) == "Polygon": - if candidate.Area >= minimum_area_square_feet: - polygons.append(candidate) - + polygons.extend(_polygon_members(geometry.GetGeometryN(geometry_index))) + return polygons + + +def _ring_area_square_feet(ring): + coordinates = ring.Coordinates + origin = coordinates[0] + twice_signed_area = 0.0 + for index in range(len(coordinates) - 1): + start = coordinates[index] + end = coordinates[index + 1] + start_x = start.X - origin.X + start_y = start.Y - origin.Y + end_x = end.X - origin.X + end_y = end.Y - origin.Y + twice_signed_area += start_x * end_y - end_x * start_y + return abs(twice_signed_area) * 0.5 + + +def _largest_exterior_polygon(geometry, stage_name): + polygons = _polygon_members(geometry) if not polygons: - raise ValueError( - "The concave hull produced no polygon at least {0:.3f} m2 in area.".format( - minimum_area_square_feet * SQUARE_METRES_PER_SQUARE_FOOT - ) - ) + raise ValueError("{0} produced no polygon.".format(stage_name)) - return max(polygons, key=lambda polygon: polygon.Area) + return ( + max(polygons, key=lambda polygon: _ring_area_square_feet(polygon.ExteriorRing)), + len(polygons), + ) def _build_contour( - points, + segments, coordinate_type, + geometry_type, geometry_factory_type, - concave_hull_type, + line_string_type, + polygonizer_type, simplifier_type, - maximum_edge_feet, + gap_healing_feet, simplify_feet, - minimum_area_square_feet, ): - coordinates = [coordinate_type(point[0], point[1]) for point in points] geometry_factory = geometry_factory_type() - multi_point = geometry_factory.CreateMultiPointFromCoords( - Array[coordinate_type](coordinates) + line_strings = [] + for start, end in segments: + coordinates = Array[coordinate_type]( + [ + coordinate_type(start[0], start[1]), + coordinate_type(end[0], end[1]), + ] + ) + line_strings.append(geometry_factory.CreateLineString(coordinates)) + + multi_line = geometry_factory.CreateMultiLineString( + Array[line_string_type](line_strings) ) + noded_lines = multi_line.Union() - hull_builder = concave_hull_type(multi_point) - hull_builder.MaximumEdgeLength = maximum_edge_feet - hull_builder.HolesAllowed = False - hull = hull_builder.GetHull() + polygonizer = polygonizer_type(False) + polygonizer.Add(noded_lines) + polygons = list(polygonizer.GetPolygons()) + dangle_count = len(list(polygonizer.GetDangles())) + cut_edge_count = len(list(polygonizer.GetCutEdges())) + invalid_ring_count = len(list(polygonizer.GetInvalidRingLines())) - if hull is None or hull.IsEmpty: + if not polygons: raise ValueError( - "NetTopologySuite could not create a concave hull from the slice points." + "Polygonization produced no polygons (dangles: {0}, cut edges: {1}, " + "invalid rings: {2}).".format( + dangle_count, cut_edge_count, invalid_ring_count + ) + ) + + polygon_collection = geometry_factory.CreateGeometryCollection( + Array[geometry_type](polygons) + ) + healed_geometry = polygon_collection + if gap_healing_feet > 0: + healed_geometry = healed_geometry.Buffer(gap_healing_feet).Buffer( + -gap_healing_feet ) + healed_polygon, healed_polygon_count = _largest_exterior_polygon( + healed_geometry, "Gap healing" + ) + healed_shell_area_square_feet = _ring_area_square_feet( + healed_polygon.ExteriorRing + ) + + final_geometry = healed_polygon if simplify_feet > 0: - hull = simplifier_type.Simplify(hull, simplify_feet) + final_geometry = simplifier_type.Simplify(healed_polygon, simplify_feet) + final_polygon, final_polygon_count = _largest_exterior_polygon( + final_geometry, "Simplification" + ) - return _largest_polygon(hull, minimum_area_square_feet) + diagnostics = { + "noded_component_count": noded_lines.NumGeometries, + "polygon_count": len(polygons), + "dangle_count": dangle_count, + "cut_edge_count": cut_edge_count, + "invalid_ring_count": invalid_ring_count, + "healed_polygon_count": healed_polygon_count, + "healed_shell_area_square_feet": healed_shell_area_square_feet, + "final_polygon_count": final_polygon_count, + } + return final_polygon, diagnostics def _clean_ring_coordinates(coordinates, minimum_segment_length): @@ -342,17 +445,18 @@ def _clean_ring_coordinates(coordinates, minimum_segment_length): if distance_squared >= minimum_segment_length ** 2: points.append(point) - if len(points) > 1: + while len(points) > 1: first = points[0] last = points[-1] - if ( - (first[0] - last[0]) ** 2 + (first[1] - last[1]) ** 2 - < minimum_segment_length ** 2 - ): - points.pop() + closing_distance_squared = (first[0] - last[0]) ** 2 + ( + first[1] - last[1] + ) ** 2 + if closing_distance_squared >= minimum_segment_length ** 2: + break + points.pop() if len(points) < 3: - raise ValueError("The simplified contour contains fewer than three vertices.") + raise ValueError("The final contour contains fewer than three vertices.") return points @@ -364,12 +468,12 @@ def _line_subcategory(doc, style_name): return subcategory, False subcategory = doc.Settings.Categories.NewSubcategory(lines_category, style_name) - subcategory.LineColor = Color(255, 0, 255) + subcategory.LineColor = Color(0, 200, 255) return subcategory, True def _create_model_lines(doc, contour_points, slice_z, style_name): - transaction = Transaction(doc, "Create linked STL slice concave hull contour") + transaction = Transaction(doc, "Create linked STL polygonized slice contour") started = False try: transaction.Start() @@ -412,9 +516,9 @@ def _create_contour(): raise ValueError("IN[0] level name must not be empty.") slice_offset_mm = _number(_input(1, 1500.0), "IN[1] slice offset") - requested_snap_mm = _number(_input(2, 25.0), "IN[2] XY point snap", 0.0) - maximum_edge_mm = _number( - _input(3, 2500.0), "IN[3] maximum hull edge", 0.0 + endpoint_snap_mm = _number(_input(2, 25.0), "IN[2] XY endpoint snap", 0.0) + gap_healing_mm = _number( + _input(3, 250.0), "IN[3] polygon gap healing", 0.0, True ) simplify_mm = _number( _input(4, 50.0), "IN[4] simplification tolerance", 0.0, True @@ -429,13 +533,16 @@ def _create_contour(): ( coordinate_type, + geometry_type, geometry_factory_type, - concave_hull_type, + line_string_type, + polygonizer_type, simplifier_type, ) = _load_nettopologysuite(assembly_paths) - level = _resolve_level(__doc__, requested_level_name) - linked_import = _selected_linked_import_instance(__doc__) + doc = __uidoc__.Document + level = _resolve_level(doc, requested_level_name) + linked_import = _selected_linked_import_instance(doc) slice_z = level.ProjectElevation + slice_offset_mm / MILLIMETRES_PER_FOOT options = Options() @@ -450,40 +557,52 @@ def _create_contour(): raise ValueError("The selected linked import contains no mesh geometry.") intersection_tolerance_feet = 0.01 / MILLIMETRES_PER_FOOT - raw_points, triangle_count, intersected_triangle_count = _slice_meshes( + raw_segments, triangle_count = _slice_meshes( meshes, slice_z, intersection_tolerance_feet ) - effective_snap_mm = requested_snap_mm - if len(raw_points) > ADAPTIVE_SNAP_POINT_COUNT: - effective_snap_mm = max(requested_snap_mm, ADAPTIVE_SNAP_MM) - effective_snap_feet = effective_snap_mm / MILLIMETRES_PER_FOOT - snapped_points = _snap_points(raw_points, effective_snap_feet) - if len(snapped_points) < 3: - raise ValueError("Point snapping left fewer than three unique slice points.") + endpoint_snap_feet = endpoint_snap_mm / MILLIMETRES_PER_FOOT + ( + unique_segments, + collapsed_segment_count, + duplicate_segment_count, + ) = _snap_and_deduplicate_segments(raw_segments, endpoint_snap_feet) - maximum_edge_feet = maximum_edge_mm / MILLIMETRES_PER_FOOT + gap_healing_feet = gap_healing_mm / MILLIMETRES_PER_FOOT simplify_feet = simplify_mm / MILLIMETRES_PER_FOOT - minimum_area_square_feet = minimum_area_m2 / SQUARE_METRES_PER_SQUARE_FOOT - contour_polygon = _build_contour( - snapped_points, + contour_polygon, diagnostics = _build_contour( + unique_segments, coordinate_type, + geometry_type, geometry_factory_type, - concave_hull_type, + line_string_type, + polygonizer_type, simplifier_type, - maximum_edge_feet, + gap_healing_feet, simplify_feet, - minimum_area_square_feet, ) + final_shell_area_square_feet = _ring_area_square_feet( + contour_polygon.ExteriorRing + ) + minimum_area_square_feet = minimum_area_m2 / SQUARE_METRES_PER_SQUARE_FOOT + if final_shell_area_square_feet < minimum_area_square_feet: + raise ValueError( + "The largest exterior contour is {0:.3f} m2, below the IN[5] " + "minimum of {1:.3f} m2.".format( + final_shell_area_square_feet * SQUARE_METRES_PER_SQUARE_FOOT, + minimum_area_m2, + ) + ) + minimum_segment_length = max( - __doc__.Application.ShortCurveTolerance, 0.1 / MILLIMETRES_PER_FOOT + doc.Application.ShortCurveTolerance, 0.1 / MILLIMETRES_PER_FOOT ) contour_points = _clean_ring_coordinates( contour_polygon.ExteriorRing.Coordinates, minimum_segment_length ) model_line_ids, sketch_plane_id, style_created = _create_model_lines( - __doc__, contour_points, slice_z, style_name + doc, contour_points, slice_z, style_name ) return { @@ -493,13 +612,23 @@ def _create_contour(): "slice_elevation_mm": slice_z * MILLIMETRES_PER_FOOT, "mesh_count": len(meshes), "triangle_count": triangle_count, - "intersected_triangle_count": intersected_triangle_count, - "raw_slice_point_count": len(raw_points), - "hull_point_count": len(snapped_points), - "effective_snap_mm": effective_snap_mm, - "maximum_edge_mm": maximum_edge_mm, + "raw_segment_count": len(raw_segments), + "collapsed_segment_count": collapsed_segment_count, + "duplicate_segment_count": duplicate_segment_count, + "unique_segment_count": len(unique_segments), + "endpoint_snap_mm": endpoint_snap_mm, + "noded_component_count": diagnostics["noded_component_count"], + "polygon_count": diagnostics["polygon_count"], + "dangle_count": diagnostics["dangle_count"], + "cut_edge_count": diagnostics["cut_edge_count"], + "invalid_ring_count": diagnostics["invalid_ring_count"], + "gap_healing_mm": gap_healing_mm, + "healed_polygon_count": diagnostics["healed_polygon_count"], + "healed_shell_area_m2": diagnostics["healed_shell_area_square_feet"] + * SQUARE_METRES_PER_SQUARE_FOOT, "simplify_mm": simplify_mm, - "contour_area_m2": contour_polygon.Area + "final_polygon_count": diagnostics["final_polygon_count"], + "final_shell_area_m2": final_shell_area_square_feet * SQUARE_METRES_PER_SQUARE_FOOT, "model_line_count": len(model_line_ids), "model_line_ids": model_line_ids, From decf582077ae866063f84da17cc974fc3e5fd979 Mon Sep 17 00:00:00 2001 From: Oleg Date: Fri, 28 Aug 2026 01:57:52 +0300 Subject: [PATCH 2/2] docs(modeling): record STL contour decisions --- AGENTS.md | 12 +- README.md | 1 + .../0001-linked-stl-slice-contour.md | 135 ++++++++++++++++++ docs/decisions/README.md | 20 +++ ...odel_line_contour_from_linked_stl_slice.md | 12 +- 5 files changed, 170 insertions(+), 10 deletions(-) create mode 100644 docs/decisions/0001-linked-stl-slice-contour.md create mode 100644 docs/decisions/README.md diff --git a/AGENTS.md b/AGENTS.md index ed4a014..883566d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,8 +6,9 @@ This repository is a reviewed catalog of reusable Revit scripts for BIMO Run Pyt 1. Read [`README.md`](README.md) and [`CONTRIBUTING.md`](CONTRIBUTING.md) completely. 2. Inspect [`catalog.json`](catalog.json), the paired documentation for similar scripts, and [`schemas/catalog.schema.json`](schemas/catalog.schema.json). -3. Keep one focused user outcome per pull request. Do not add speculative frameworks or unrelated cleanup. -4. Work on a branch and open a draft pull request. Do not push script changes directly to `main`. +3. Read applicable long-lived context under [`docs/decisions`](docs/decisions/README.md) before changing a non-obvious algorithm or its defaults. +4. Keep one focused user outcome per pull request. Do not add speculative frameworks or unrelated cleanup. +5. Work on a branch and open a draft pull request. Do not push script changes directly to `main`. ## Adding a script @@ -19,6 +20,13 @@ This repository is a reviewed catalog of reusable Revit scripts for BIMO Run Pyt - Keep existing script paths stable because saved BIMO presets may reference them. - Never claim a Revit version is tested unless the exact repository script was run successfully in that version. Record partial or manual validation honestly in the pull request. +## Recording decisions + +- Store durable algorithm and architecture context under [`docs/decisions`](docs/decisions/README.md). +- Record the problem, invariants, evaluated alternatives, measured evidence, accepted decision, limitations, and remaining work. Do not store chat transcripts or unfiltered reasoning. +- Link decision records to the related issue, pull request, implementation, and user guide. Update or supersede the relevant record when later evidence changes the decision. +- Keep user-facing execution instructions in the paired script documentation and keep this file as a concise routing entry point. + ## Required validation Run: diff --git a/README.md b/README.md index bb1fc6e..5b23563 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,7 @@ The authoritative machine-readable index is [`catalog.json`](catalog.json). Its ```text catalog.json Machine-readable script index schemas/catalog.schema.json Catalog JSON Schema +docs/decisions/ Durable algorithm and architecture decisions documentation/ View documentation and image scripts modeling/ Model-creation and editing scripts miscellaneous/ General-purpose scripts diff --git a/docs/decisions/0001-linked-stl-slice-contour.md b/docs/decisions/0001-linked-stl-slice-contour.md new file mode 100644 index 0000000..755c43a --- /dev/null +++ b/docs/decisions/0001-linked-stl-slice-contour.md @@ -0,0 +1,135 @@ +# 0001 — Linked STL slice contour extraction + +- Status: Accepted for the current draft +- Date: 2026-08-28 +- Related issue: [#4](https://github.com/BIMO-Tools/Revit-Python-Scripts/issues/4) +- Related pull request: [#5](https://github.com/BIMO-Tools/Revit-Python-Scripts/pull/5) +- Implementation: [`modeling/create_model_line_contour_from_linked_stl_slice.py`](../../modeling/create_model_line_contour_from_linked_stl_slice.py) +- User guide: [`modeling/create_model_line_contour_from_linked_stl_slice.md`](../../modeling/create_model_line_contour_from_linked_stl_slice.md) + +## Context and goal + +The source is an exported building model linked into Revit as an STL `ImportInstance`. For a requested Revit `Level`, the script must create a closed exterior contour as horizontal model lines at `Level.ProjectElevation + 1500 mm` by default. + +The STL is not one watertight building solid. Walls, columns, facade components, and other parts can be represented by separate meshes or solids. A horizontal cut therefore contains both the building exterior and many disconnected interior rings. + +## Invariants and current public contract + +- The source is exactly one selected linked `ImportInstance` containing mesh geometry. +- Revit `Level` elements define storey elevations; the section offset is configurable and defaults to `1500 mm`. +- Mesh coordinates must be read in project coordinates. +- Existing model elements and the source link are not intentionally modified or deleted. +- Geometry processing completes before the Revit transaction starts. +- One transaction creates the line subcategory when absent, one `SketchPlane`, and the model-line chain; failures roll it back. +- The current output is only the largest exterior shell. Holes, courtyards, and detached contours are intentionally omitted. +- Existing script and documentation paths stay stable because saved BIMO presets may reference them. + +## Approaches evaluated + +| Approach | Observed behavior | Decision | +| --- | --- | --- | +| Convex hull | Cannot preserve facade recesses or a concave building footprint. | Rejected conceptually. | +| Point-based NetTopologySuite concave hull | Produced one compact contour, but inferred edges from points rather than preserving triangle-section segments. It bridged or simplified facade conditions too aggressively. | Rejected as the primary algorithm. | +| Segment polygonization without healing | Preserved real section connectivity, but separate STL solids remained separate. The prototype produced 997 polygons; the largest direct shell was only about `27.953 m²`. | Accepted as the geometric basis, insufficient alone. | +| Segment polygonization plus morphological closing | Preserved section segments, then joined nearby polygon fragments into a building-scale exterior shell. | Accepted for the current draft. | + +## Accepted pipeline + +1. Resolve the exact named Revit `Level`. +2. Place a horizontal plane at the level project elevation plus the requested offset. +3. Recursively read every `Mesh` from the selected linked import using instance geometry. +4. Intersect every mesh triangle with the horizontal plane and retain the resulting XY segment. +5. Snap both segment endpoints to a configurable grid. +6. Remove collapsed and direction-independent duplicate segments. +7. Build NetTopologySuite `LineString` objects and call the geometry instance `Union()` to node and dissolve the network. +8. Run `Polygonizer(False)` and collect its polygons and diagnostics. +9. Build a polygon collection and apply `Buffer(+gap).Buffer(-gap)` to close bounded gaps between separate STL components. +10. Select the polygon with the largest exterior-ring area. +11. Apply `TopologyPreservingSimplifier` when its tolerance is greater than zero. +12. Validate area and Revit short-curve constraints, then create the closed model-line chain. + +This is a hybrid contour-extraction approach. Polygonization provides topology from the actual section segments; morphological closing compensates for the source STL being split into nearby solids. + +## Prototype evidence + +The accepted approach was exercised through BIMO MCP in Revit 2024 on the development building model at `L3 + 1500 mm`. + +### Section and polygonization + +| Measurement | Result | +| --- | ---: | +| Meshes | 49 | +| Triangles inspected | 7,264,272 | +| Raw section segments | 12,275 | +| Segments collapsed by `25 mm` snapping | 1,976 | +| Duplicate segments removed | 438 | +| Unique snapped segments | 9,861 | +| Noded line components | 9,925 | +| Valid polygons | 997 | +| Dangles | 13 | +| Cut edges | 0 | +| Invalid rings | 0 | +| Largest polygon before healing | approximately `27.953 m²` | + +### Gap-healing sweep + +The same polygon collection was buffered outward and inward by each distance. + +| Healing distance | Largest exterior-shell area | Exterior vertices | +| ---: | ---: | ---: | +| `250 mm` | `572.873 m²` | 1,229 | +| `500 mm` | `574.097 m²` | 959 | +| `750 mm` | `575.454 m²` | 750 | +| `1000 mm` | `576.870 m²` | 618 | +| `1500 mm` | `580.061 m²` | 462 | + +`250 mm` was selected because it was the smallest tested distance that produced one building-scale shell. Larger distances changed the area more and progressively removed detail. + +With `50 mm` topology-preserving simplification, the `250 mm` healed shell changed from approximately `572.873 m²` to `573.418 m²` and was created as 179 model lines. The complete prototype run took approximately 58.9 seconds. + +For comparison, the earlier point-based concave-hull prototype created 46 model lines with an area of approximately `590.55 m²` in 25.8 seconds. Its lower complexity and larger area were signs that it was generalizing across facade detail rather than reconstructing the section network. + +The exact generalized repository script has not yet been run as-is. These measurements validate the underlying algorithm and parameter choice, not the complete catalog file or every supported input path. Keep `revit.tested` empty until the repository file itself passes the documented manual test. + +## Parameter interpretation and calibration order + +| Input | Current default | Effect | +| --- | ---: | --- | +| `endpoint_snap_mm` | `25` | Moves endpoints to an XY grid before noding. A larger value can close noisy connections but also shifts wall locations. | +| `gap_healing_mm` | `250` | Joins nearby polygon fragments. A larger value can bridge intended recesses and close narrow passages. `0` disables the operation. | +| `simplification_tolerance_mm` | `50` | Reduces vertices after healing while preserving topology. A larger value removes more facade detail. `0` disables the operation. | + +When investigating a local mismatch: + +1. Keep endpoint snapping and gap healing unchanged. +2. Compare simplification values `50`, `25`, `10`, and `0 mm`. +3. If the mismatch remains at `0`, reduce gap healing and verify whether the result still forms one building-scale shell. +4. Change endpoint snapping last, because it changes the input network rather than only the final shell. + +This order separates three different error sources instead of tuning several parameters simultaneously. + +## Known geometric effects and limitations + +- Default NetTopologySuite buffer joins can round exterior corners even when simplification is disabled. +- Morphological closing can fill real narrow recesses or join intentionally separate objects. +- The largest shell is selected by exterior-ring area; polygon holes are not emitted as model lines. +- Coplanar triangles are ignored to avoid filling horizontal mesh faces. +- Runtime is dominated by the full mesh-triangle scan. +- The chosen `250 mm` healing distance is evidence from one building model, not a universal architectural tolerance. +- The source STL is not stored in this repository, so the numeric prototype results are not yet an automated regression fixture. + +## IronPython and API implementation notes + +- Use `__uidoc__.Document` for the active document. A module docstring occupies Python's `__doc__` name and can hide a host-provided global with the same name. +- Call the parameterless geometry instance method `multi_line.Union()`. Calling static unary-union overloads from IronPython caused overload ambiguity during the prototype. +- NetTopologySuite coordinates and Revit geometry use Revit internal feet in the implementation. Convert millimetre inputs before geometry processing and square feet before reporting square metres. +- Construct typed .NET arrays for NetTopologySuite factory calls, including `Array[LineString]` and `Array[Geometry]`. +- Do not open a Revit transaction until slicing, polygonization, healing, simplification, area checks, and short-curve cleanup have succeeded. + +## Remaining work + +- Run the exact repository script in a disposable Revit 2024 model and record the result. +- Compare `simplification_tolerance_mm` values `0`, `10`, `25`, and `50` at the visually discrepant facade locations. +- Evaluate a mitre-join buffer or a graph-based gap-bridging strategy if corner rounding remains material. +- Decide whether courtyards, holes, and detached building parts should become explicit outputs. +- Add a distributable synthetic mesh fixture and automated geometry regression tests when the script moves beyond the current draft stage. diff --git a/docs/decisions/README.md b/docs/decisions/README.md new file mode 100644 index 0000000..fb6309c --- /dev/null +++ b/docs/decisions/README.md @@ -0,0 +1,20 @@ +# Decision records + +This directory stores durable context for non-obvious script behavior and architecture. Decision records help future maintainers and agents continue work without reconstructing earlier experiments. + +Record conclusions and reproducible evidence, not chat transcripts or unfiltered reasoning. A useful record contains: + +- the user outcome and invariants; +- approaches evaluated and why they were accepted or rejected; +- measured evidence, test conditions, and confidence level; +- the accepted pipeline and parameter meanings; +- known limitations, implementation traps, and remaining experiments; +- links to the related issue, pull request, script, and user guide. + +Update an existing record when its accepted decision is refined. If a decision is replaced, mark the old record as superseded and link to the replacement instead of erasing the historical evidence. + +## Index + +| Record | Status | Scope | +| --- | --- | --- | +| [0001 — Linked STL slice contour extraction](0001-linked-stl-slice-contour.md) | Accepted for the current draft | Exterior model-line contour from a horizontal linked-STL section | diff --git a/modeling/create_model_line_contour_from_linked_stl_slice.md b/modeling/create_model_line_contour_from_linked_stl_slice.md index a9834ee..632f05f 100644 --- a/modeling/create_model_line_contour_from_linked_stl_slice.md +++ b/modeling/create_model_line_contour_from_linked_stl_slice.md @@ -4,6 +4,8 @@ Creates one closed exterior contour as Revit model lines by intersecting a selec The defaults preserve the validated prototype scenario: level `L3`, a slice `1500` mm above the level, `25` mm endpoint snapping, `250` mm polygon gap healing, and `50` mm topology-preserving simplification. +The alternatives, parameter sweep, measured evidence, implementation traps, and remaining experiments are maintained in [decision record 0001](../docs/decisions/0001-linked-stl-slice-contour.md). + ## Compatibility - BIMO engine: `IronPython` @@ -114,15 +116,9 @@ No existing model elements are intentionally edited or deleted. Undo the single ## Prototype validation -The current approach was exercised in Revit 2024 on the `L3 + 1500 mm` slice shown during development: - -- 49 meshes and 7,264,272 triangles were inspected; -- 12,275 raw section segments became 9,861 unique snapped segments; -- polygonization produced 997 valid polygons, 13 dangles, no cut edges, and no invalid rings; -- `250` mm gap healing produced one exterior shell of approximately 572.873 m2; -- `50` mm simplification produced an exterior shell of approximately 573.418 m2 and 179 model lines. +The current approach was exercised in Revit 2024 on the development building model at `L3 + 1500 mm`. The complete measurements, comparison with the earlier concave hull, gap-healing sweep, confidence boundary, and calibration order are recorded in [decision record 0001](../docs/decisions/0001-linked-stl-slice-contour.md). -These figures document the prototype run, not a successful run of the exact generalized repository file. +Those measurements document the prototype run, not a successful run of the exact generalized repository file. ## Manual Revit test