diff --git a/README.md b/README.md index 5b23563..d89fdf7 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ BIMO hosts the Python engine inside Revit, so users do not need a separate local | [Import image to active view](documentation/import_image_to_active_view.md) | Documentation | IronPython | Writes model and optionally copies a file | | [Create Toposolid from model lines](modeling/create_toposolid_from_model_lines.md) | Modeling | IronPython | Writes model | | [Create model-line contour from linked STL slice](modeling/create_model_line_contour_from_linked_stl_slice.md) | Modeling | IronPython | Writes model and optionally reads local assemblies | +| [Create Floors from shape-edited roofs](modeling/create_floors_from_roofs.md) | Modeling | IronPython | Writes model; dry run by default | | [Calculate selected lines length](miscellaneous/calculate_selected_lines_length_mm.md) | Miscellaneous | IronPython | Read-only | | [Calculate element volume](miscellaneous/calculate_element_volume.md) | Miscellaneous | IronPython | Read-only | | [Delete BIMO preview rays](miscellaneous/Delete_BIMO_PreviewRays_DirectShapes.md) | Miscellaneous | IronPython | Deletes elements | diff --git a/catalog.json b/catalog.json index b95d381..26a1bc5 100644 --- a/catalog.json +++ b/catalog.json @@ -222,6 +222,56 @@ "stl" ] }, + { + "id": "modeling.create-floors-from-roofs", + "name": "Create Floors from shape-edited roofs", + "summary": "Creates validated Floors with roof layers, shape elevations and vertical openings while retaining source roofs and annotations.", + "category": "modeling", + "path": "modeling/create_floors_from_roofs.py", + "documentation": "modeling/create_floors_from_roofs.md", + "engine": "ironpython", + "revit": { + "minimum": 2024, + "tested": [] + }, + "risk": "write", + "requiresActiveDocument": true, + "selection": { + "required": false, + "description": "Select supported shape-edited Basic FootPrintRoofs, or provide an explicit comma-separated roof ID list in IN[1]. Mixed or empty selections are rejected." + }, + "inputs": [ + { + "index": 0, + "name": "dry_run", + "type": "boolean-string", + "required": false, + "default": "true", + "description": "Create and validate trial Floors, then roll back everything. Set false to retain the new Floors." + }, + { + "index": 1, + "name": "roof_ids", + "type": "string", + "required": false, + "default": "", + "description": "Comma-separated positive roof IDs in the active document; overrides selection. Empty uses current selection." + } + ], + "output": { + "format": "object", + "description": "Dry-run state, Floor count, source/target IDs, opening mapping, geometry measurements, point corrections and warnings. Trial IDs are not persistent." + }, + "tags": [ + "roof", + "floor", + "conversion", + "slab-shape", + "slope", + "opening", + "selection" + ] + }, { "id": "miscellaneous.calculate-selected-lines-length-mm", "name": "Calculate selected lines length in millimetres", diff --git a/docs/decisions/0002-roof-to-floor-conversion.md b/docs/decisions/0002-roof-to-floor-conversion.md new file mode 100644 index 0000000..8774c61 --- /dev/null +++ b/docs/decisions/0002-roof-to-floor-conversion.md @@ -0,0 +1,76 @@ +# 0002 — Roof-to-Floor geometry conversion + +- Status: Accepted for the current draft +- Date: 2026-09-14 +- Related issue: [#6](https://github.com/BIMO-Tools/Revit-Python-Scripts/issues/6) +- Implementation: [create_floors_from_roofs.py](../../modeling/create_floors_from_roofs.py) +- User guide: [Create Floors from roofs](../../modeling/create_floors_from_roofs.md) + +## Goal and invariants + +Reuse a conversion developed through BIMO MCP to create native editable Floors +from shape-edited Basic Roofs. Preserve the existing surface, compound layers, +levels, inner sketch contours and vertical hosted openings. Require explicit +selection or IDs, retain originals and annotations, and roll back the entire +batch if an API operation or geometry check fails. + +## Evidence from the original Revit 2024 prototype + +The prototype created 16 Floors from 16 Basic FootPrintRoofs of one RoofType with +a 152.4 mm constant structural layer. Six hosted Opening Cuts were recreated; +one additional opening was an inner sketch loop. The largest Opening Cut had +75 straight boundary curves. The source included boundary/edge vertices and +both user-drawn and automatic creases. + +A removal trial revealed 45 dependent Spot Slopes, 186 automatic sketch +dimensions and one alignment constraint. That trial was rolled back. Final +creation kept every source and annotation; the user subsequently removed the +sources manually. The reusable script deliberately has no deletion mode. + +## Evaluated approaches and decisions + +| Approach | Evidence | Decision | +| --- | --- | --- | +| Recreate sketch, shape points, non-boundary creases and hosted openings | Reproduced the prototype geometry as native Floors | Retained; copy automatic creases as explicit split lines to constrain triangulation | +| Boolean symmetric difference of source and result | Revit failed on the complex trimmed main roof | Not the acceptance check; do not infer equivalence from boolean failure | +| Raw mesh vertices and triangle points | Apparent deviations around 0.009 mm despite matching volumes and areas; coordinates far from origin lose mesh precision | Use exact edge samples and project triangle interior points onto analytical source faces | +| Preserve all stored subelement heights literally | A nearly coplanar quadrilateral differed by about 0.02 mm after reconstruction; its stored points did not lie on the source's actual planar face | Match the actual single top-face plane with a bounded, reported correction | +| Implicitly delete original hosts after successful conversion | Would also delete 45 user annotations and an alignment | Retain all sources; deletion is a separate user decision | + +The single-plane correction adjusted one prototype's stored height by at most +0.0312993 mm. After correction and precise sampling, maximum sampled surface +distance across all 16 pairs was approximately `5.2e-11 mm`. The affected roof's +relative volume difference was `2.1026e-7`; the other pairs were around floating +point precision. The volume and area acceptance tolerance is `1e-6` relative +with an absolute `1e-6` native-unit floor. Surface tolerance remains 0.01 mm. +These checks are measured practical acceptance criteria, not a mathematical +proof of identical solids. + +## API details and retained behaviour + +- For the exercised shape-edited roofs, the sketch/base is below the original + flat top by the compound thickness. Floor level offset includes that thickness. +- Get the FootPrintRoof sketch through its dependent `Sketch`; the Revit 2024 + FootPrintRoof does not expose the Floor-style `SketchId` property. +- Create missing shape points on the initially flat Floor top. Draw split lines, + then set vertex offsets relative to the initial top elevation. +- `Document.NewOpening(host, curves, False)` cuts vertically. `True` means + perpendicular to the host face, not vertical. +- The BIMO IronPython execution used here did not provide the `traceback` standard + library module. The catalog script uses ordinary re-raising after rollback so + BIMO captures the real exception and reports failure. +- The generalized script derives floor types per source RoofType and uses + explicit selection/IN, replacing all prototype-specific document names and IDs. + +## Validation boundary and remaining cases + +The measurements above describe the original live prototype. The exact generalized +catalog file needs its own runtime validation; record those results separately +in the PR and only then list a tested Revit version in the catalog. + +The script excludes curved faces/boundaries, variable layers, extruded and curtain +roofs, non-shape-edited slopes, shaft openings and hosted-family conversion. +Multiple RoofTypes, additional constant layers, phases, and other Revit versions +need dedicated fixtures. Samples do not exhaust every point on a face, and merged +multi-solid geometry can still encounter Revit boolean-union failures; such a +failure aborts instead of bypassing validation. diff --git a/docs/decisions/README.md b/docs/decisions/README.md index fb6309c..96c2c7f 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -18,3 +18,4 @@ Update an existing record when its accepted decision is refined. If a decision i | 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 | +| [0002 — Roof-to-Floor conversion](0002-roof-to-floor-conversion.md) | Accepted for the current draft | Native Floors preserving roof shape and openings | diff --git a/modeling/create_floors_from_roofs.md b/modeling/create_floors_from_roofs.md new file mode 100644 index 0000000..56bc1f5 --- /dev/null +++ b/modeling/create_floors_from_roofs.md @@ -0,0 +1,122 @@ +# Create Floors from shape-edited roofs + +Creates one native architectural `Floor` for each explicitly selected Basic Roof, +with its layers, elevation, shape points, split lines, sketch holes and hosted +vertical openings. Source roofs and their annotations are retained. + +## Compatibility and scope + +- BIMO engine: **IronPython**; minimum Revit API version: **2024**. +- Active editable project required, with no transaction already open. +- Exact catalog-script Revit testing: pending; see the pull request for current results. +- Only `FootPrintRoof` elements with enabled slab-shape editing, straight sketch + and opening boundaries, planar solid faces, and no variable-thickness layer. +- Requires at least one architectural `FloorType` in the project. + +The script does not convert extruded/curtain roofs, sloped roof sketches without +shape editing, curved boundaries, variable-layer roofs, shaft openings, or other +hosted families. Later Revit versions are not validated. + +## Inputs + +BIMO passes optional positional inputs as strings. + +| Index | Name | Type | Default | Meaning | +| --- | --- | --- | --- | --- | +| `IN[0]` | `dry_run` | boolean-string | `true` | `true` creates and checks trial elements, then rolls everything back; `false` keeps the new Floors. | +| `IN[1]` | `roof_ids` | string | empty | Comma-separated positive roof IDs in the active document. Empty uses the current selection. | + +Every selected or specified element must be a supported roof. Invalid IDs and +mixed selections fail before model changes. An explicit ID list overrides the +selection. Empty input does **not** collect every roof in the project. + +## Run through BIMO + +1. Select the roofs to convert, or provide their IDs in `IN[1]`. +2. Choose **IronPython**, leave the inline Script field empty and point Script + file at `create_floors_from_roofs.py`. +3. Run with `IN[0] = "true"`. Check the returned geometry report and warnings. +4. Run with `IN[0] = "false"` to retain the new Floors. +5. Inspect the results before manually removing any source roofs. Deleting a + roof can also delete dimensions, spot slopes, alignments and hosted elements. + +The same source works through the approved BIMO MCP Python execution operation. +No local Python installation or third-party geometry package is required in Revit. + +## Model changes and other side effects + +- Creates one Floor per source roof and one new FloorType per distinct RoofType + per run. Copies the compound structure, including layer materials and thicknesses. +- Derives the new type from the lowest-ID architectural FloorType. Uncopied type + properties retain that template's values. Existing types are never modified; + a numeric suffix resolves name collisions. +- Keeps the roof's base level. Sets the Floor offset to the roof base offset plus + the compound-structure thickness, then transfers shape elevations. +- Copies instance comments, mark, creation phase and demolition phase when set + and writable. Other instance/type/shared parameters, worksets, design options, + joins, attachments, hosted families, constraints and view overrides are not copied. +- Recreates curve-based hosted openings as **vertical** Floor openings and + preserves inner sketch loops. Perpendicular openings are not a supported input; + geometric mismatch causes rollback. +- Preserves both user-drawn and automatic non-boundary creases as explicit Floor + split lines, which may change the later editing behaviour of automatic folds. +- Never deletes or modifies source roofs or their dependent annotations, and does + not rehost spot slopes. Source and converted geometry overlap until the user + removes or otherwise manages the sources. +- Does not save, synchronize or close the project, change selection or views, + read/write files, access the network or show its own modal prompts. +- Warnings are collected in `OUT`; errors roll back the entire batch and propagate + to BIMO. A committed run is grouped into one Revit Undo operation. +- Repeating a committed run creates additional Floors and types. It is not an + update or duplicate-detection command. + +## Geometry validation + +The script compares bidirectional surface samples, solid volumes and total face +areas, including opening surfaces. It checks again after transaction commit and +before accepting the transaction group. Surface sampling is a practical check, +not a proof of exact solid equivalence. + +- Maximum sampled surface distance: **0.01 mm**. +- Maximum volume difference: the greater of `1e-6 ft3` or `1e-6` of source volume. +- Maximum area difference: the greater of `1e-6 ft2` or `1e-6` of source surface area. +- Shape-point matching tolerance: `1e-6 ft`. + +For a single planar top face, stored shape points may differ slightly from the +actual Revit surface. The script projects their heights onto that plane, reports +the adjustment, and rejects adjustments over **0.1 mm**. It preserves the existing +surface geometry rather than insisting on those inconsistent stored heights. + +See [the algorithm decision record](../docs/decisions/0002-roof-to-floor-conversion.md) +for the reason for these checks and prototype measurements. + +## Output + +`OUT` is an object with `dry_run`, `floor_count`, `created_ids_are_persistent`, +`source_roofs_retained`, `warnings` and a per-roof `report` containing: + +- source roof and new Floor IDs, plus source/target opening IDs; +- shape-vertex and explicit split-line counts; +- sampled surface distance and sample count; +- source/result volumes in cubic feet and their difference; +- source/result surface areas in square feet; +- vertex matching error and stored-point adjustment in millimetres. + +In a dry run, `floor_count` means successfully validated trial Floors. Their IDs +and opening IDs are **not persistent** after rollback. Failures are execution +errors, never successful results containing `ok: false`. + +## Manual Revit test scenario + +Use a separate test copy containing several shape-edited polygonal roofs, an inner +sketch hole, vertical Opening Cuts crossing the outer boundary, edge points and +split lines. Include a nearly coplanar quadrilateral and spot-slope annotations. + +1. Record counts of Floors, FloorTypes, roofs, openings and spot dimensions. +2. Run dry mode and confirm every count is unchanged. +3. Run commit mode and confirm one Floor per roof, one type per RoofType, and the + expected new opening count; original roofs and annotations must remain. +4. Inspect top/bottom geometry, slope direction, thickness, materials and openings. +5. Test empty/mixed selection and missing IDs; expect an error with no new elements. +6. Exercise multiple RoofTypes and a deliberately unsupported input. Additional + layers, phase transfer and failure-processor error rollback require separate cases. diff --git a/modeling/create_floors_from_roofs.py b/modeling/create_floors_from_roofs.py new file mode 100644 index 0000000..a5ed25a --- /dev/null +++ b/modeling/create_floors_from_roofs.py @@ -0,0 +1,364 @@ +"""Create validated Floors from selected shape-edited Basic Roofs. + +BIMO IronPython: IN[0] = dry_run (default "true"), IN[1] = optional +comma-separated roof IDs. Sources and annotations are always retained. +""" + +import clr + +clr.AddReference("RevitAPI") +from Autodesk.Revit.DB import ( + BooleanOperationsType, BooleanOperationsUtils, BuiltInParameter, + CurveArray, CurveLoop, Element, ElementClassFilter, ElementId, + FailureProcessingResult, FailureSeverity, FilteredElementCollector, + Floor, FloorType, FootPrintRoof, IFailuresPreprocessor, Level, Line, + Opening, Options, PlanarFace, Sketch, Solid, StorageType, + Transaction, TransactionGroup, TransactionStatus, ViewDetailLevel, XYZ, +) +from System.Collections.Generic import List + + +MM_PER_FOOT = 304.8 +VERTEX_TOLERANCE = 1e-6 +SURFACE_TOLERANCE = 0.01 / MM_PER_FOOT +PLANAR_CORRECTION_LIMIT = 0.1 / MM_PER_FOOT +RELATIVE_QUANTITY_TOLERANCE = 1e-6 + + +def element_id(element): + return element.Id.Value + + +def element_name(element): + return Element.Name.GetValue(element) + + +def input_text(index, default=""): + if index >= len(IN) or IN[index] is None: + return default + value = str(IN[index]).strip() + return value if value else default + + +def read_inputs(doc): + if len(IN) > 2: + raise ValueError("Expected at most IN[0] and IN[1].") + flag = input_text(0, "true").lower() + if flag not in ("true", "false"): + raise ValueError("IN[0] must be true or false.") + explicit_ids = input_text(1) + if explicit_ids: + numbers = [int(value.strip()) for value in explicit_ids.split(",")] + if any(value <= 0 for value in numbers): + raise ValueError("IN[1] must contain positive element IDs.") + ids = [ElementId(value) for value in sorted(set(numbers))] + else: + ids = list(__uidoc__.Selection.GetElementIds()) + if not ids: + raise ValueError("Select Basic Roofs or provide their IDs in IN[1].") + roofs = [doc.GetElement(value) for value in ids] + if any(roof is None or not isinstance(roof, FootPrintRoof) for roof in roofs): + raise ValueError("Every selected/provided element must be a Basic FootPrintRoof.") + return flag == "true", sorted(roofs, key=element_id) + + +def get_sketch(doc, element): + ids = element.GetDependentElements(ElementClassFilter(clr.GetClrType(Sketch))) + sketches = [doc.GetElement(value) for value in ids] + if len(sketches) != 1: + raise ValueError("Expected one sketch for roof {0}.".format(element_id(element))) + return sketches[0] + + +def solids(element): + options = Options() + options.DetailLevel = ViewDetailLevel.Fine + result = [geometry for geometry in element.get_Geometry(options) + if isinstance(geometry, Solid) and geometry.Volume > 1e-9] + if not result: + raise ValueError("No solid for element {0}.".format(element_id(element))) + return result + + +def merged_solid(element): + geometry = solids(element) + result = geometry[0] + for solid in geometry[1:]: + result = BooleanOperationsUtils.ExecuteBooleanOperation( + result, solid, BooleanOperationsType.Union) + return result + + +def surface_samples(solid): + # Revit mesh vertices lose precision far from the origin. Use exact edges + # and project triangle interior samples onto their source analytical planes. + points = {} + + def add(point): + key = (round(point.X, 9), round(point.Y, 9), round(point.Z, 9)) + points[key] = point + + for edge in solid.Edges: + curve = edge.AsCurve() + for parameter in (0.0, 0.25, 0.5, 0.75, 1.0): + add(curve.Evaluate(parameter, True)) + for face in solid.Faces: + if not isinstance(face, PlanarFace): + raise ValueError("Only planar solid faces are supported.") + mesh = face.Triangulate() + for index in range(mesh.NumTriangles): + triangle = mesh.get_Triangle(index) + center = sum([triangle.get_Vertex(i) for i in range(3)], XYZ.Zero) / 3.0 + projection = face.Project(center) + if projection is not None: + add(projection.XYZPoint) + if not points: + raise ValueError("No surface samples available.") + return list(points.values()) + + +def distance_to_solid(point, solid): + best = float("inf") + for face in solid.Faces: + projection = face.Project(point) + if projection is not None: + best = min(best, projection.Distance) + if best < 1e-9: + return best + for edge in solid.Edges: + curve = edge.AsCurve() + best = min(best, point.DistanceTo(curve.GetEndPoint(0)), + point.DistanceTo(curve.GetEndPoint(1))) + projection = curve.Project(point) + low, high = sorted([curve.GetEndParameter(0), curve.GetEndParameter(1)]) + if projection is not None and low - 1e-9 <= projection.Parameter <= high + 1e-9: + best = min(best, projection.Distance) + return best + + +def vertex_at(editor, point): + for vertex in editor.SlabShapeVertices: + location = vertex.Position + if (abs(location.X - point.X) < VERTEX_TOLERANCE + and abs(location.Y - point.Y) < VERTEX_TOLERANCE): + return vertex + raise ValueError("Cannot find a matching slab-shape vertex.") + + +def copy_parameter(source, target, parameter_id): + original = source.get_Parameter(parameter_id) + replacement = target.get_Parameter(parameter_id) + if not original or not replacement or not original.HasValue or replacement.IsReadOnly: + return + if original.StorageType == StorageType.String: + replacement.Set(original.AsString() or "") + elif original.StorageType == StorageType.ElementId: + replacement.Set(original.AsElementId()) + elif original.StorageType == StorageType.Integer: + replacement.Set(original.AsInteger()) + elif original.StorageType == StorageType.Double: + replacement.Set(original.AsDouble()) + + +def prepare_roof(doc, roof, openings): + roof_type = doc.GetElement(roof.GetTypeId()) + structure = roof_type.GetCompoundStructure() + editor = roof.SlabShapeEditor + if structure is None or structure.VariableLayerIndex != -1 or structure.IsVerticallyCompound: + raise ValueError("Only homogeneous roofs without variable layers are supported.") + if structure.GetWidth() <= 0 or editor is None or not editor.IsEnabled: + raise ValueError("Each roof must have thickness and enabled shape editing.") + if not isinstance(doc.GetElement(roof.LevelId), Level): + raise ValueError("Roof has no valid base level.") + points = [vertex.Position for vertex in editor.SlabShapeVertices] + if not points: + raise ValueError("Roof has no slab-shape vertices.") + sketch = get_sketch(doc, roof) + profiles = List[CurveLoop]() + for curves in sketch.Profile: + loop = CurveLoop() + for curve in curves: + if not isinstance(curve, Line): + raise ValueError("Only straight sketch boundaries are supported.") + loop.Append(curve.Clone()) + profiles.Add(loop) + hosted_openings = [opening for opening in openings + if opening.Host is not None and opening.Host.Id == roof.Id] + for opening in hosted_openings: + if opening.IsRectBoundary or any(not isinstance(c, Line) for c in opening.BoundaryCurves): + raise ValueError("Only curve-based openings with straight edges are supported.") + source = merged_solid(roof) + samples = surface_samples(source) + top_faces = [face for face in source.Faces if face.FaceNormal.Z > 0.1] + adjustment = 0.0 + if len(top_faces) == 1: + # Near-coplanar shape points may differ from the face Revit actually built. + # Match that face, with a bounded and reported correction, never a roof ID. + face = top_faces[0] + normal, origin = face.FaceNormal, face.Origin + adjusted = [XYZ(p.X, p.Y, origin.Z - ( + normal.X * (p.X - origin.X) + normal.Y * (p.Y - origin.Y)) / normal.Z) + for p in points] + adjustment = max(abs(a.Z - b.Z) for a, b in zip(points, adjusted)) + if adjustment > PLANAR_CORRECTION_LIMIT: + raise ValueError("Stored shape points differ from the actual plane by over 0.1 mm.") + points = adjusted + edges = [(crease.EndPoints[0].Position, crease.EndPoints[1].Position) + for crease in editor.SlabShapeCreases if str(crease.CreaseType) != "Boundary"] + return {"roof": roof, "type": roof_type, "structure": structure, + "points": points, "profiles": profiles, "edges": edges, + "openings": hosted_openings, "solid": source, "samples": samples, + "adjustment": adjustment} + + +def new_floor_type(doc, template, source_type, structure, used_names): + base_name = "BIMO - Roof to Floor - {0}".format(element_name(source_type)) + candidate, suffix = base_name, 2 + while candidate in used_names: + candidate = "{0} ({1})".format(base_name, suffix) + suffix += 1 + result = template.Duplicate(candidate) + result.SetCompoundStructure(structure) + used_names.add(candidate) + return result + + +class CaptureFailures(IFailuresPreprocessor): + def __init__(self): + self.messages = [] + + def PreprocessFailures(self, accessor): + has_error = False + for failure in accessor.GetFailureMessages(): + self.messages.append(failure.GetDescriptionText()) + if failure.GetSeverity() == FailureSeverity.Warning: + accessor.DeleteWarning(failure) + else: + has_error = True + if has_error: + return FailureProcessingResult.ProceedWithRollBack + return FailureProcessingResult.Continue + + +def create_floor(doc, source, floor_type): + roof, points = source["roof"], source["points"] + floor = Floor.Create(doc, source["profiles"], floor_type.Id, roof.LevelId) + offset = (roof.get_Parameter(BuiltInParameter.ROOF_LEVEL_OFFSET_PARAM).AsDouble() + + source["structure"].GetWidth()) + floor.get_Parameter(BuiltInParameter.FLOOR_HEIGHTABOVELEVEL_PARAM).Set(offset) + for parameter in (BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS, + BuiltInParameter.ALL_MODEL_MARK, + BuiltInParameter.PHASE_CREATED, BuiltInParameter.PHASE_DEMOLISHED): + copy_parameter(roof, floor, parameter) + doc.Regenerate() + editor = floor.SlabShapeEditor + editor.Enable() + doc.Regenerate() + base_z = list(editor.SlabShapeVertices)[0].Position.Z + for point in points: + found = any(abs(v.Position.X - point.X) < VERTEX_TOLERANCE + and abs(v.Position.Y - point.Y) < VERTEX_TOLERANCE + for v in editor.SlabShapeVertices) + if not found and editor.DrawPoint(XYZ(point.X, point.Y, base_z)) is None: + raise ValueError("Cannot add a roof vertex to the Floor.") + for start, end in source["edges"]: + editor.DrawSplitLine(vertex_at(editor, start), vertex_at(editor, end)) + for point in points: + editor.ModifySubElement(vertex_at(editor, point), point.Z - base_z) + doc.Regenerate() + vertex_error = max(abs(vertex_at(editor, p).Position.Z - p.Z) for p in points) + if vertex_error > VERTEX_TOLERANCE: + raise ValueError("Slab-shape vertex elevations do not match.") + opening_map = [] + for opening in source["openings"]: + curves = CurveArray() + for curve in opening.BoundaryCurves: + curves.Append(curve.Clone()) + # False means vertical, not perpendicular to the sloping face. + created = doc.Create.NewOpening(floor, curves, False) + opening_map.append({"source": element_id(opening), "target": element_id(created)}) + doc.Regenerate() + return floor, opening_map, vertex_error + + +def verify_floor(source, floor, opening_map, vertex_error): + original, result = source["solid"], merged_solid(floor) + original_samples, result_samples = source["samples"], surface_samples(result) + distance = max(max(distance_to_solid(p, result) for p in original_samples), + max(distance_to_solid(p, original) for p in result_samples)) + original_area = sum(face.Area for face in original.Faces) + result_area = sum(face.Area for face in result.Faces) + volume_difference = abs(original.Volume - result.Volume) + area_difference = abs(original_area - result_area) + if (distance > SURFACE_TOLERANCE + or volume_difference > max(1e-6, original.Volume * RELATIVE_QUANTITY_TOLERANCE) + or area_difference > max(1e-6, original_area * RELATIVE_QUANTITY_TOLERANCE)): + raise ValueError("Geometry validation failed for roof {0}: surface {1} mm, " + "volume difference {2} ft3, area difference {3} ft2.".format( + element_id(source["roof"]), distance * MM_PER_FOOT, + volume_difference, area_difference)) + return {"roof_id": element_id(source["roof"]), "floor_id": element_id(floor), + "openings": opening_map, "shape_vertices": len(source["points"]), + "split_lines": len(source["edges"]), "surface_distance_mm": distance * MM_PER_FOOT, + "surface_samples": len(original_samples) + len(result_samples), + "source_volume_ft3": original.Volume, "floor_volume_ft3": result.Volume, + "volume_difference_ft3": volume_difference, + "source_surface_ft2": original_area, "floor_surface_ft2": result_area, + "vertex_error_mm": vertex_error * MM_PER_FOOT, + "stored_point_adjustment_mm": source["adjustment"] * MM_PER_FOOT} + + +def main(): + doc = __doc__ + if doc is None or doc.IsFamilyDocument or doc.IsReadOnly or doc.IsModifiable: + raise ValueError("An editable project with no active transaction is required.") + dry_run, roofs = read_inputs(doc) + openings = list(FilteredElementCollector(doc).OfClass(Opening)) + sources = [prepare_roof(doc, roof, openings) for roof in roofs] + floor_types = list(FilteredElementCollector(doc).OfClass(FloorType)) + templates = sorted([ft for ft in floor_types if not ft.IsFoundationSlab], key=element_id) + if not templates: + raise ValueError("The project must contain an architectural FloorType.") + used_names = set(element_name(ft) for ft in floor_types) + derived_types, report = {}, [] + failures = CaptureFailures() + group = TransactionGroup(doc, "BIMO: Create Floors from roofs") + group.Start() + transaction = None + try: + transaction = Transaction(doc, "Create and validate Floors and openings") + transaction.Start() + options = transaction.GetFailureHandlingOptions() + options.SetFailuresPreprocessor(failures) + options.SetClearAfterRollback(True) + transaction.SetFailureHandlingOptions(options) + for source in sources: + type_id = element_id(source["type"]) + if type_id not in derived_types: + derived_types[type_id] = new_floor_type( + doc, templates[0], source["type"], source["structure"], used_names) + floor, opening_map, vertex_error = create_floor(doc, source, derived_types[type_id]) + report.append(verify_floor(source, floor, opening_map, vertex_error)) + if transaction.Commit() != TransactionStatus.Committed: + raise RuntimeError("Revit rolled back creation: {0}".format(failures.messages)) + transaction = None + # Commit processing can change geometry: verify again before assimilating. + for source, item in zip(sources, report): + verify_floor(source, doc.GetElement(ElementId(item["floor_id"])), + item["openings"], item["vertex_error_mm"] / MM_PER_FOOT) + if dry_run: + group.RollBack() + elif group.Assimilate() != TransactionStatus.Committed: + raise RuntimeError("Could not commit the conversion transaction group.") + return {"dry_run": dry_run, "floor_count": len(report), + "created_ids_are_persistent": not dry_run, + "source_roofs_retained": True, "report": report, "warnings": failures.messages} + except: + if transaction is not None and transaction.GetStatus() == TransactionStatus.Started: + transaction.RollBack() + if group.GetStatus() == TransactionStatus.Started: + group.RollBack() + raise + + +OUT = main()