Compare commits

..

44 Commits

Author SHA1 Message Date
Bruno Postle 680f29f284 Add missing standard library includes for self-sufficient headers
Fixes builds with newer GCC/libstdc++ that no longer provide <cstdint>,
<cstring>, <cfloat>, <memory>, <algorithm> etc. transitively. Also
disambiguates visit<> calls in taxonomy.h with the full namespace and
casts the character value in IfcCharacterDecoder to uint32_t to silence
ambiguous overload warnings.
2026-06-04 22:23:19 +01:00
Ryan Schultz f158ae7377 Fix crash in update_bim_tool_props when selected type isn't a valid ifc_class
props.ifc_class is an EnumProperty whose items list only the element/space
types present in the model. Assigning element_type.is_a() crashed with
`enum "<class>" not found` when the selected element's type wasn't a member
(e.g. a raw IfcTypeProduct, or a stale item list mid-rebuild), aborting the
post-commit refresh.

Wrap the assignment in the same try/except TypeError guard already used for
the sibling relating_type_id assignments (added in 233cc344fa).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-02 08:44:21 +02:00
Bruno Perdigão 5dde402f8b Optimize 2D projection in ray_cast_by_proximity_2d 2026-06-01 22:27:58 -03:00
Bruno Perdigão 1daee04d9c Early-terminate solid raycasts in non-xray mode 2026-06-01 22:18:13 -03:00
Bruno Perdigão 0d7c378db5 Lazy BVH tree construction in SnapObj 2026-06-01 20:47:27 -03:00
falken10vdl 1c128a2d6a Add has_underside_connection method to Model class and update wall regeneration logic 2026-06-01 07:44:49 -05:00
Ryan Schultz 36372627db Fix validate_type corruption; remove debug prints
When validate_type selected a preferred_item from remaining_items
(e.g. the sole IfcBooleanResult in a representation), it left that
item in the list. The subsequent Items filter removed every item,
leaving Items=[] and causing guess_type to return
"MappedRepresentation" — silently corrupting the representation.

Also removes temporary debug print statements added during
investigation of the wall-to-slab extension workflow.

Generated with the assistance of an AI coding tool.
2026-06-01 07:44:49 -05:00
Ryan Schultz a9b6f02f02 Fix duplicate booleans in extend_walls_to_underside
Re-running the operator on the same wall/slab pair created
additional IfcPolygonalFaceSet booleans each time. Now each
wall's existing booleans are removed before re-clipping, and
previously connected slabs are merged with the new selection
so no earlier clips are silently discarded.

Generated with the assistance of an AI coding tool.
2026-06-01 07:44:49 -05:00
Ryan Schultz 9e7d97e298 Regenerate connected walls when recalculating a slab
When Shift+G is pressed on a LAYER3 element, any LAYER2 walls
connected via IfcRelConnectsElements(TOP) are now re-clipped
to the slab's updated geometry after recalculate_slab runs.

Generated with the assistance of an AI coding tool.
2026-06-01 07:44:49 -05:00
Ryan Schultz 187b8e7167 Add extend/regenerate walls to multiple undersides
extend_walls_to_underside now accepts multiple slab/roof
objects in a single operation — all selected non-LAYER2 IFC
elements are treated as clip targets, all LAYER2 elements as
walls. Placement sync is done once upfront; each wall is then
clipped against every selected slab before reloading.

Also adds bim.regenerate_wall_to_underside (Shift+G): after
moving a slab, re-clips connected walls using the existing
IfcRelConnectsElements(TOP) relationship. Old booleans are
removed via remove_representation_item before re-clipping.

Generated with the assistance of an AI coding tool.
2026-06-01 07:44:49 -05:00
Ryan Schultz 08e33fe572 Closes #7943: Add regenerate_wall_to_underside operator
When extend_walls_to_underside is applied to a wall and the
roof/slab is later moved, pressing Shift+G now re-clips the
wall to the slab's new position.

The IFC relationship created by connect_wall_to_slab
(IfcRelConnectsElements, Description="TOP") is used to look
up which slabs a wall is clipped to. On regeneration, the
existing manual booleans (IfcPolygonalFaceSet operands) are
cleanly removed via remove_representation_item, then
clip_wall_to_slab is re-applied for each connected slab.

Shift+G on a LAYER2 wall that has a TOP connection now calls
bim.regenerate_wall_to_underside; walls without a connection
continue to call bim.recalculate_wall as before.

Generated with the assistance of an AI coding tool.
2026-06-01 07:44:49 -05:00
Ryan Schultz e142b9d7b4 Fix extend_walls_to_underside ridge artifact
When the operator was called twice on the same wall for a
ridge roof, the two IfcPolygonalFaceSet clip solids shared
an exact ridge edge (kissing-solid). OCCT produced spurious
extra vertices at the coincident boundary.

Fix by building the clip solid from a rectangle on the slope
plane that extends slightly past the face edge (1 project
unit margin) rather than the exact face footprint. Adjacent
slope solids now volumetrically overlap at the ridge instead
of sharing a boundary face, which OCCT handles correctly.

Generated with the assistance of an AI coding tool.
2026-06-01 07:44:49 -05:00
falken10vdl 431cf435ef Fix assign_container in spatial.py (#8079)
ifc.get_object(element) can return None for IFC elements that aren't loaded as Blender objects (e.g., decomposed sub-elements). 
The loop now skips those instead of passing None into collector.assign().

Cheers!
2026-06-01 07:02:28 -05:00
Tiago Azevedo a433f56337 Fix sign of temporary offset restore in sweep_along_curve
The temporary-offset workaround (#7408, commit bd57cc8735) subtracts the
directrix centroid (`mean`) from the curve points before building the
sweep near the origin, then must add it back to restore the original
location. The restore negated the sign — `Move(-mean)` instead of
`Move(+mean)` — placing the swept solid at -mean (mirrored through the
origin) rather than its true position.

Only triggers for polyline directrixes (`is_polyhedron()`) whose centroid
is more than 100 m from the origin (`mean.norm() > 1e2`), so models
centered near the origin are unaffected. Models that keep absolute site
coordinates (e.g. many Revit/ODA IFC exports) render affected swept
solids — reinforcing bars, pipes — at a mirrored phantom location far
from the rest of the model.
2026-06-01 11:42:39 +02:00
Gorgious56 a3f92eb427 Merge pull request #8133 from Gorgious56/bonsai/parametric-framework-features
Bonsai/parametric framework features
2026-06-01 09:20:51 +02:00
Gorgious56 453e6dc1cc Add behaviour-contract tests for PR4 surfaces
Three test files covering PR4's new surfaces — preview registry,
wall-gizmo poll behaviour, fillet operator registration. Every test
walks the live registry or class hierarchy instead of hard-coding
preview keys, operator names, or helper function names, so adding a
new preview / wall gizmo group / fillet operator exercises the same
invariants without test edits.

test_preview_base.py (6 tests):
* RegistryContract: every PREVIEW_CANCEL_OPS entry resolves to a
  callable cancel operator on bpy.ops.bim.
* GetPreviewPropsTolerance: get_preview_props returns None for
  contexts without a scene (regression guard for the SimpleNamespace
  bug fixed in commit ee63137c6).
* ActivationCycle (registry-driven loop): any_preview_active toggles
  with each registered preview's is_active flag;
  discard_pending_previews clears every active flag across every
  registered preview.
* SaveOnDiscardWired: locates the bim.save_project operator
  dynamically and verifies its execute path references the discard
  helper by its actual __name__.

test_wall_gizmo_poll_gate.py (4 tests):
* WallGizmoGroupsHideDuringPreview: walks the wall module for
  bpy.types.GizmoGroup subclasses (skips preview-owner exceptions
  whose bl_idname contains 'preview'), mocks any_preview_active to
  True, and asserts every discovered gizmo's poll returns False.
* BaseParametricGizmoPollHidesDuringPreview: mirrors the test for
  the cross-feature parametric framework base class.

test_fillet_operators.py (3 tests):
* FilletOperatorsRegistered: at-least-four-ops + every-discovered-op-
  is-callable. Catches accidental deregistration.
* EnableRejectsIneligibleSelection: poll returns False without a
  selection so the operator is greyed-out in menus.

State-clearing tests via bpy.ops.bim.cancel_wall_fillet_preview() are
deliberately omitted — the operator early-returns when context.screen
is unattached and prior tests in the model lane can leave the screen
in that state, making the dispatch path inherently flaky. Live testing
covers the behaviour.

Net: 13 tests pass cleanly in both single-file and full model lane.

Generated with the assistance of an AI coding tool.
2026-06-01 08:35:26 +02:00
Bruno Perdigão 728026d3f0 Remove debug print 2026-05-31 22:30:56 -03:00
Bruno Perdigão 3f270df11e Add more no headless test for snap 2026-05-31 22:26:16 -03:00
Bruno Perdigão 792a0c7da1 Merge tests into a single file 2026-05-31 22:26:16 -03:00
Bruno Perdigão 5856d29fbe Add test files and scripts 2026-05-31 22:26:16 -03:00
Bruno Perdigão cd482a7874 Initial implementation of tests for modal operators 2026-05-31 22:26:16 -03:00
Gorgious56 f6e95c8e8e Bonsai Makefile - pin deepdiff<9.1
deepdiff 9.1.0 added cachebox<6,>=5.2 as a direct runtime dep.
cachebox 5.2.3 only publishes macOS x86_64 wheels for macosx_10_12+,
incompatible with the macos py311 build's --platform macosx_10_10_x86_64.
The daily build's linux-wheel safeguard fires when the resulting
cachebox-*-manylinux_*.whl leaks into the macOS / windows wheels folder
(builds run on ubuntu-latest and cross-build via pip download --platform).

Pin deepdiff to <9.1 (resolves to 9.0.0, no cachebox transitive dep) as
the minimal hotfix. Long-term cleanup: bump the macos py311 platform tag
from 10_10 to 10_13 (matching py312/py313) and re-flag this line with the
standard \$(PYPI_PLATFORM) --only-binary=:all: pattern used by brickschema
and python-socketio.

Partly generated with the assistance of an AI coding tool.
2026-05-31 21:33:28 +02:00
Gorgious56 ee63137c6c Discard previews on IFC save + harden preview-active gate
Save-path:
* SaveProject._execute (project/operator.py) now calls
  preview_base.discard_pending_previews(context.scene) right after
  tool.Parametric.commit_pending_edits(). Previews are session-
  transient — discard rather than commit. Sibling gizmo polls gate
  on each preview's is_active flag; a stuck flag persisted through
  the save would silently hide them on reload. Mirrors the pattern
  already in gizmos-8088.

Preview-active gate hardening:
* preview_base.get_preview_props tolerates contexts without a
  ``scene`` attribute. Pre-existing tests use SimpleNamespace mocks
  for the context; the previous getattr(context.scene, ...) raised
  AttributeError before the inner default kicked in.

Test update:
* test_wall_header_refresh.test_geom_generation_invalidates_wall_geom_cache
  patches tool.Wall.read_geometry instead of the now-deleted local
  wall._read_wall_geometry (commit 7e5e7b8d6 migrated the call site).

Generated with the assistance of an AI coding tool.
2026-05-31 19:10:48 +02:00
Ryan Schultz c83b4eb69f Restore pre-aggregate selection on exit; deselect on unsupported profile
When override_mode_set_edit encounters an unsupported profile (Couldn't
import profile), deselect the object so Tab continues to cycle cleanly.

Also restores the selection that existed before entering aggregate mode
when finally tabbing out, via save/restore_previous_selection().
2026-05-31 07:41:03 -05:00
Ryan Schultz 5eef433abf Deselect geometry after exiting item mode in aggregate context
Following the pattern from 586f9be077, deselect the active object after
exiting item mode so Tab continues to cycle cleanly. Also deselects
parametric LAYER1/LAYER2 items that cannot be edited directly, avoiding
the need to manually deselect before Tab-cycling out of aggregate mode.
2026-05-31 07:25:58 -05:00
Gorgious56 7e5e7b8d6a Drop wall.py local read_geometry + validate dupes + relax gates
Two cohesive cleanups in one commit.

A. Migrate wall.py to PR3-absorbed tool methods (fixes bug 4: pen icon
missing on fillet corner walls):

PR3 shipped tool.Wall.read_geometry + tool.Wall.validate_for_parametric_edit
but wall.py kept local duplicates predating that work. The local
_read_wall_geometry guards on tool.Blender.Modifier.is_wall (LAYER2-only)
while the tool method guards on tool.Parametric.is_path_connectable_wall
(LAYER2 OR fillet corner). Consequence: _get_wall_geom_cached → local
_read_wall_geometry returned None for every fillet corner →
GizmoWallFilletReedit.position_gizmos hit `if geom is None: hide` →
pen icon was unreachable for every fillet corner the user created.

Three _read_wall_geometry callers migrated to tool.Wall.read_geometry
(_read_wall_state_into_props, _get_wall_geom_cached,
GizmoWallJoinIntersection.position_gizmos). Two
_validate_wall_for_parametric_edit callers migrated to
tool.Wall.validate_for_parametric_edit (_maybe_resync_wall_props_from_ifc,
EnableEditingWall._execute). Local helpers deleted; docstring references
updated.

B. Drop over-restrictive gizmo gates (fixes bug 1: join icons missing
when walls intersect away from endpoints):

GizmoWallJoinIntersection.position_gizmos no longer hides itself when
the projected intersection lands further than MAX_DISTANCE_TO_ENDPOINT_
FACTOR (0.75 wall lengths) from any endpoint. The remaining
PARALLEL_DOT_THRESHOLD (cos 2°) gate via project_axis_intersection
returns None for near-parallel walls and is the only correctness bound;
distance from endpoints is a UI concern, not a geometric one.

GizmoWallFilletReedit.poll drops the has_a / has_b ConnectedFrom +
ConnectedTo guard — the IsFilletCorner pset is the authoritative signal.
EnableWallFilletPreviewFromCorner.execute already separately validates
both neighbour connections and reports a user-facing error if either
side is disconnected.

Generated with the assistance of an AI coding tool.
2026-05-31 12:15:39 +02:00
Gorgious56 788d4fe8e8 Hide sister gizmos during preview + ESC cancels + DRY wall polls
Three live-session regressions surfaced after the fillet feature
landed.

Sister gizmos competed with the active preview:
* preview_base.any_preview_active(context): new helper iterates the
  PREVIEW_CANCEL_OPS registry and returns True if any preview is open.
  Future previews registered there automatically gate sister gizmos.
* BaseParametricGizmoGroup.poll (gizmos.py): short-circuits on
  any_preview_active so every parametric gizmo (door/window/stair/
  roof/railing/wall edition) hides during ANY preview.
* The 4 wall gizmo groups with explicit polls (GizmoWallAddOpening,
  GizmoWallExtendVertically, GizmoWallJoinIntersection,
  GizmoWallUnjoinSingle) + GizmoWallFilletReedit gain the same gate.

DRY: extract _wall_gizmo_poll_gate(context):
* 5 wall gizmo polls each duplicated the 2 pre-flight checks
  (viewport-gizmos enabled + no preview active). The helper centralises
  them — each poll becomes a single short-circuit line followed by its
  per-feature selection inspection.

ESC cancels the active preview:
* try_cancel_active_preview already existed in preview_base since PR3
  but had no caller. Hooked into OverrideEscape.execute (geometry/
  operator.py) as a new elif branch — same keymap that already cancels
  pen gizmo edit mode + item mode + edit mode + aggregate mode. Order
  in the branch chain matters: try preview cancel before falling back
  to try_canceling_editing_modifier_parameters_or_path so the in-
  flight preview wins over a stale modifier-edit cancel attempt.

Generated with the assistance of an AI coding tool.
2026-05-31 10:38:30 +02:00
Ryan Schultz a1c2aecf1b Add select_similar to type attribute panels
In BIM_PT_type_attributes and BIM_PT_object_attributes (when
the active object is a type), attribute value buttons now use
"type.<Attr>" as the selector key so the operator finds
matching occurrences via their relating type rather than the
occurrence's own (often unset) attributes.

Generated with the assistance of an AI coding tool.
2026-05-30 21:53:13 -05:00
Ryan Schultz d501970352 Add clipboard copy to SelectSimilarContainer operator
After selecting objects in the same container, copy a `location="Name"`
filter query to the clipboard and report it — consistent with the same
behaviour in SelectSimilarType, SelectSimilarAggregate, SelectIfcClass,
and SelectSimilarMaterial.

Generated with the assistance of an AI coding tool.
2026-05-30 17:41:50 -05:00
Ryan Schultz fd96e6a4d2 Fix #8128: Fix filter_elements skipping groups after a zero-result facet_list
When a `+`-separated filter group returns no results, `FacetTransformer.facet_list`
was skipping the reset of `has_additive_facet_in_current_list` because the reset
was inside the `if self.elements:` guard. The stale flag caused the next group's
`add_default_elements()` to bail out early, leaving its element set empty and
silently dropping every subsequent group from the result.

Move the flag reset outside the guard so it always fires regardless of whether
the group produced any results.
2026-05-30 16:28:14 -05:00
Ryan Schultz 3dd3a0d70c Closes #8127: Add imperial location display to Placement panel
In the Placement panel, show Location and Rotation X/Y/Z
each on their own row beneath a header label. When the IFC
file uses imperial units, display a read-only feet-and-inches
label alongside each Location input field.

Generated with the assistance of an AI coding tool.
2026-05-30 14:08:53 -05:00
Ryan Schultz 2e5995176a Format stair lengths using IFC length unit
Display general and calculated stair parameters (Width,
Height, Tread Run, Tread Rise, Length, etc.) formatted
to the IFC file's configured length unit rather than
raw numeric values.

Generated with the assistance of an AI coding tool.
2026-05-30 12:03:50 -05:00
Gorgious56 2114c1d5d0 Add wall-fillet feature: operators, gizmos, decorator
End-to-end fillet flow on top of the helpers + recreate_wall hook
(landed in the previous commit). Users select two LAYER2 walls, click
the fillet entry icon, drag the live radius widget, and validate to
replace the corner with a curved LAYER2 corner wall (banana body).

Operators (5):
* EnableWallFilletPreview: 2-wall selection → validates LAYER2 +
  straight axis + zero-slope + intersect-or-joined state → seeds the
  preview props with a default radius computed from the shorter
  available leg.
* FinishWallFilletPreview: dispatches CreateWallFillet with the tuned
  radius; clears preview state on FINISHED, preserves it on failure so
  the user can re-tune without re-selecting.
* CancelWallFilletPreview: clears preview state, no IFC mutation.
* EnableWallFilletPreviewFromCorner: pen-icon re-edit on an existing
  fillet corner — pre-fills the preview from the corner's BBIM_Wall
  pset + walks the inverse graph to recover wall A and wall B.
* CreateWallFillet: deletes any prior corner + A↔B path connection,
  shortens A and B to the tangent points, instantiates a corner wall
  from A's type, unassigns the swept-layer material/type (the explicit
  banana body MUST own its geometry), assigns the dominant material,
  rebuilds the body, sets a straight 2-point chord axis, stores
  BBIM_Wall.IsFilletCorner+FilletRadius, reconnects A and B to the
  corner with NOTDEFINED on the corner's side.

Gizmo groups (2 new + entry icon on existing):
* GizmoWallFilletPreview: visible while a preview is active. Bundles
  a radius_dim widget at the arc apex, a trim_dim widget along wall A
  expressing the same DOF via the leg setback distance
  (trim = |radius| * tan(sweep/2)), and validate / cancel icons
  anchored above the apex in screen-up.
* GizmoWallFilletReedit: pen-icon entry on an existing fillet corner
  wall (single-selection, BBIM_Wall.IsFilletCorner set, both neighbour
  connections present). Mutually exclusive with an active preview.
* GizmoWallJoinIntersection now stacks a fillet entry icon
  (VIEW3D_GT_fillet → bim.enable_wall_fillet_preview) above the
  existing join/unjoin icon in the joined and intersect state branches.

Property + decorator infrastructure:
* prop.py: BIMWallFilletPreviewProperties (Scene-level draft) +
  BIMPreviewProperties umbrella with only the wall_fillet pointer.
  The umbrella is the seam preview_base.py (landed in PR3) already
  reads via getattr(scene, "BIMPreviewProperties", None).
* decorator.py: _stroke_lines_alpha helper + WallFilletPreviewDecorator.
  Polls is_active; renders leg projections + arc + arc-center
  construction lines from tool.Wall.compute_wall_fillet_geometry.
* __init__.py: registers operators + gizmo groups + property groups +
  wires Scene.BIMPreviewProperties.
* handler.py: WallFilletPreviewDecorator.install/uninstall in
  _install_decorators — always installed, self-polls on is_active.

Drive-by: extract gizmo.get_screen_up(billboard_rot) helper —
the local +Y of a billboard rotation is the camera's screen-up world
direction. Replaces 4 inline `billboard_rot @ Vector((0.0, 1.0, 0.0))`
sites added across the fillet feature's gizmo groups.

Generated with the assistance of an AI coding tool.
2026-05-30 13:04:49 +02:00
carlopav 3f680f5c21 IfcCostSchedule PDF export with typst: fix bugs
Fixed a bug when a summary cost has no sum applied.
Added Currency in table header.
Cleanup.
Added guards for end summary.
2026-05-29 18:38:16 +02:00
Gorgious56 97e8deb069 Cache opening previews + dissolve fill
DecorationsHandler now caches dissolved edges (mesh-keyed), world-space
draw payload, and GPUBatch objects with per-object epoch invalidation —
moving one wall doesn't wipe 50 opening caches. Object-mode dissolve
removes triangulation noise; 2-pass depth-test split dims occluded lines
instead of hiding them. Edit-mode behavior unchanged.

Also: disable viewport shadows for IfcFeatureElementSubtraction objects,
and wire DecorationsHandler.uninstall() into the model module's
unregister() so the new persistent handlers don't leak on addon disable.

Generated with the assistance of an AI coding tool.
2026-05-29 12:16:49 +02:00
Gorgious56 49348908e6 Add wall-fillet helper functions + recreate_wall hook
Eleven module-level helpers in wall.py that the upcoming wall-fillet
operators + gizmo groups depend on. Each is self-contained or
references only helpers earlier in the file; the operators and
gizmos themselves land in follow-up commits.

* _wall_fillet_props / _wall_fillet_preview_active /
  _wall_fillet_preview_walls: thin read-side accessors over the
  BIMPreviewProperties.wall_fillet pointer (added with the
  operators commit). Safe today: get_preview_props returns None
  until the pointer is attached.
* _walls_have_zero_slope_for_fillet: validates that input walls
  are vertical (x_angle ~ 0); slanted-extrusion fillets require
  swept-along-curve geometry the banana profile builder doesn't
  support.
* _build_curved_corner_body_representation: builds the banana
  (annular sector) IfcExtrudedAreaSolid as a polyline-tessellated
  IfcIndexedPolyCurve.
* _apply_fillet_corner_geometry: positions the corner wall at
  tangent_a and rebuilds its body. Shared by the creation operator
  and the regenerate path.
* _resolve_two_walls: pulls (active, other) from a 2-wall
  selection, validates both as LAYER2 + straight-axis + not-already-
  a-fillet-corner.
* _pick_dominant_wall_material: returns the thickest layer's
  material from an element's IfcMaterialLayerSet / Usage.
* regenerate_fillet_corner_wall: re-runs the geometry build from
  BBIM_Wall.FilletRadius + current neighbour layer parameters.
  Called by tool.Model.recreate_wall when the IsFilletCorner pset
  is set; the FIXME(PR4) placeholder in recreate_wall is dropped.
* _wall_fillet_gizmo_x_matrix: 4x4 placement matrix with local +X
  aligned to a world-space direction; used by the fillet preview
  gizmo group.

Centralises the IsFilletCorner pset read as
tool.Parametric.is_fillet_corner_wall — replaces 3 inline
get_pset(element, "BBIM_Wall", "IsFilletCorner") sites
(tool.Model.recreate_wall, tool.Model.recalculate_walls,
tool.Parametric.is_path_connectable_wall) plus the new
_resolve_two_walls call.

Generated with the assistance of an AI coding tool.
2026-05-28 16:42:42 +02:00
Gorgious56 c250b2c1a7 Gate parametric-edit array gizmo until integration completes
The framework's parametric-edit icon row currently binds an array
icon to bim.add_array_from_feature_edit, but the supporting per-
feature add-array flow and gizmo positioning haven't fully landed.
Showing the icon today lets the user click it and trigger a half-
wired flow.

Force the icon hidden inside the props.is_editing branch of
BaseParametricGizmoGroup.update_editing_gizmos. The else-branch
(not editing) already hides it, so this just mirrors that behavior
during edit mode. Drop this gate when array integration completes
to re-enable the icon position + visibility plumbing.

Generated with the assistance of an AI coding tool.
2026-05-28 15:30:46 +02:00
Gorgious56 6874d52100 Add cursor-aware extend-arrow flip on wall edit gizmos
The extend-X / extend-Z icons in GizmoWallEdition's cursor row are
billboarded toward the camera; without orientation polish they
always point in the same screen-space direction regardless of which
wall endpoint the click will move (or whether the cursor sits above
or below the wall top). New helper mirrors the icon's local-X (extend-X)
or local-Y (extend-Z) axis so each arrow points toward the end it
will move:

* Extend-X: walk wall midpoint to figure out which endpoint stays
  fixed (cursor past midpoint → ATSTART stays; cursor before midpoint
  → ATEND stays). Project the fixed endpoint into screen-space and
  flip the arrow when the gizmo's anchor sits on the same side.
* Extend-Z: flip when the cursor is below the wall top (within
  EXTEND_FLIP_EPSILON tolerance).

Called once per resolved cursor gizmo from
``GizmoWallEdition._update_cursor_gizmos``, after the gizmo's
``matrix_basis`` is set by ``gizmo.billboarded_at``. Reuses
``gizmo.should_flip_extend_arrow`` + ``EXTEND_FLIP_MIRROR_X/Y`` +
``EXTEND_FLIP_EPSILON`` already on tool.

Generated with the assistance of an AI coding tool.
2026-05-28 15:14:51 +02:00
Gorgious56 6c21e2b6f4 Add single-wall unjoin operator + gizmo group
GizmoWallJoinIntersection's unjoin only fires when exactly two walls
are selected and surfaces one icon at their shared corner — useless
when the wall has 3+ joins and the user wants to disconnect just one.

* UnjoinWallPathConnection: surgical counterpart to UnjoinWalls.
  Disconnects the active wall from a single partner wall identified
  by IFC GlobalId (invariant under Blender-object renames + file
  save/reload + undo). Walks both inverse arrays of the active wall
  for the specific IfcRelConnectsPathElements joining the pair —
  matches DumbWallJoiner.split's pattern and avoids disconnect_path's
  direction-sensitivity. Resyncs both walls' draft props after the
  recreate_wall pass.
* GizmoWallUnjoinSingle: activates on exactly-one selected
  LAYER2 wall. Preallocates a pool of 16 unjoin icons (Blender forbids
  gizmo allocation outside setup(); ATSTART + ATEND + ATPATH rels are
  rarely more than a handful). Per-frame, iterates _iter_path_connections,
  positions one billboarded icon at each join via
  tool.Wall.path_connection_location_world, and hides the rest. Each
  visible icon's bound operator carries the partner GlobalId, so a
  click removes only that one rel.
* model/__init__.py: register both classes alphabetically.

Mutually exclusive with GizmoWallJoinIntersection via poll() — that
group requires len(selected) == 2; this one requires 1.

Generated with the assistance of an AI coding tool.
2026-05-28 15:05:23 +02:00
Gorgious56 70845e4dd4 Add wall path-connection inverse-walk helpers
The single-wall unjoin gizmo needs to enumerate every
IfcRelConnectsPathElements a wall participates in, regardless of which
side of the rel the wall was authored on, and place an icon at each
join's physical location. Two helpers carry that work:

_path_connection_location_world wraps core.compute_path_connection_location
at the Vector boundary. _iter_path_connections walks ConnectedTo +
ConnectedFrom, normalises orientation to (other, self_ct, other_ct),
and filters non-wall partners + None refs so per-frame gizmo positioning
survives malformed IFC.

Generated with the assistance of an AI coding tool.
2026-05-28 14:23:35 +02:00
Gorgious56 d7b5ac1453 Add wall draft-resync helper + wire 6 mutation operators
After a one-shot wall IFC mutation (unjoin / split / merge / extend /
join-at-corner …) the always-visible gizmos on the OTHER side of the
join can be left reading stale ``BIMWallProperties`` — the IFC
geometry moved but the draft props that drive the gizmo handles still
point at the pre-mutation numbers, so a subsequent edit-mode enter
shows the wall at its old length / position.

* New ``_maybe_resync_wall_props_from_ifc(obj)``: re-primes a single
  wall's draft props from current IFC, with guards for non-walls,
  non-parametric walls, and walls in an active draft session (the
  draft is then the source of truth, not IFC). Must run from an
  operator ``_execute`` — ID writes from gizmo refresh raise.
* New ``_resync_walls_after_mutation(objs)``: iterates the above
  across a selection.
* Six existing mutation operators gain a resync call after their
  ``core.*`` / ``DumbWallJoiner`` mutation completes:
  UnjoinWalls, ExtendWallsToUnderside, ExtendWallsToWall, SplitWall,
  MergeWall, JoinWallsIntersection. MergeWall resyncs only the
  surviving wall — the active wall is the deletion target.

Generated with the assistance of an AI coding tool.
2026-05-28 14:06:11 +02:00
Gorgious56 1961cd905e Fix parametric framework live-session regressions
Bundle of bugs surfaced when exercising the new gizmo framework
end-to-end in a live Blender session after the
bim/module/drawing/gizmos.py refactor + TypeAccessor/CycleType/PickType
mixins landed.

Register / annotation resolution
* parametric_lifecycle.py: hoist `entity_instance` import out of
  TYPE_CHECKING so typing.get_type_hints resolves the
  Callable[[entity_instance], bool] annotation at operator registration
  (CycleDoorType, CycleWindowType, CycleStairType failed with NameError).
  Clarify the INTERFACE return contract on the picker entry-point so
  readers see why the gizmo step stays off the undo stack.

Framework callable contracts
* model/wall.py, door.py, window.py, stair.py: migrate `props_getter`
  and `element_checker` from bl_idname strings to bound classmethods
  on tool.Model / tool.Parametric. BaseParametricGizmoGroup.get_props
  expects a callable; the string form raised TypeError on first
  gizmo poll.
* model/door.py, model/stair.py: drop the dead `prop_path=` operator
  kwarg from create_arc_gizmo / create_icon_gizmo call sites. The
  framework helper blindly setattrs every kwarg onto the operator's
  OperatorProperties, but ToggleDoorSwing / ToggleStairProperty don't
  declare prop_path — the setattr raised mid-setup_element_specific_gizmos,
  so self.gizmo_door_type / self.lock_gizmo never got assigned and
  every subsequent draw_prepare tornadoed AttributeError. Nothing
  reads op.prop_path anywhere; the kwarg was dead data.

Dispatcher operators
* model/array.py: add EnableEditingParametric (the framework pen-icon
  dispatcher that routes to a per-feature edit operator by bl_idname
  string) and AddArrayFromFeatureEdit (binds the framework's array
  icon to bim.add_array on the current parametric draft).
* model/__init__.py: register both new operators.

Per-frame robustness
* drawing/gizmos.py: guard BaseParametricGizmoGroup.draw_prepare with
  is_setup_complete() — matches the existing guard in refresh() and
  in BaseSchematicGizmoGroup.draw_prepare(). Defense-in-depth: when
  any subclass's setup raises mid-way, draw_prepare now no-ops cleanly
  instead of per-frame AttributeError-tornadoing on whatever attribute
  the failed setup phase was meant to populate.
* model/decorator.py: guard ProfileDecorator.__call__ against
  context.active_object is None. The decorator is a per-frame
  viewport draw handler; deselecting or deleting the active object
  while it's installed crashed on obj.mode access. Treat None the
  same as "no longer in edit mode" — uninstall + fire the exit
  callback if present.
* geometry/data.py: ViewportData.load() populates `data` before
  flipping `is_loaded`, so a raise from cls.mode() no longer leaves
  the class flag-set but data-empty for subsequent reads.

Generated with the assistance of an AI coding tool.
2026-05-28 13:48:15 +02:00
Gorgious56 f1cf757ba2 Refactor bim/module/drawing/gizmos — framework + icon infra
Three concerns bundled into one cohesive refactor of gizmos.py
(splitting them surgically requires intermediate commits with
duplicate same-named classes that Python can't parse):

1. Framework primitives — StaticTrisGizmoMixin + TexturedQuadGizmoMixin
   replace the older TrisGizmoMixin. New module-level helpers:
   _get_static_tris_shader / _get_static_tris_batch / clear_static_
   tris_cache for cached GPU batch reuse, _draw_outline_and_body for
   the shared outline-then-body render path, draw_tris_with_outline
   as the public wrapper. billboarded_at(world_pos, billboard_rot,
   scale) is the canonical billboard-matrix helper; should_flip_extend_
   arrow encapsulates the view-aware mirror decision for extend
   gizmos; get_warning_color_from_prefs reads the user's warning
   color.

2. Config classes — BaseValueGizmoConfig (shared visibility + dimension-
   text contract), CountGizmoConfig (array N indicator),
   DimensionGizmoConfig (length / height / depth labels), IconActionConfig
   (icon-only gizmos that invoke an operator on click). DimensionRenderer
   draws the actual numeric label using BLF.

3. Icon classes — each rewritten on StaticTrisGizmoMixin so they share
   the cached GPU batch + outline-then-body render path:
   GizmoLockOpen / GizmoLockClosed (replacing the single-state
   GizmoLock), GizmoArc, GizmoFillet, GizmoWallCornerIcon,
   GizmoWallTeeIcon, GizmoPen / GizmoValidate / GizmoCancel (the
   parametric-edit triad), GizmoPlus / GizmoMinus / GizmoTrash,
   GizmoArrayParent / GizmoArrayAll / GizmoArrayLayerIndicator (array
   context indicators with a small digit-rendering helper for the "xN"
   count label), GizmoMerge / GizmoSplit / GizmoUnjoin (wall-join
   icons), and GizmoMenu (textured-quad icon-action menu trigger).

The legacy TrisGizmoMixin, GizmoLock, and DimensionDrawConfig are
removed; downstream callers in subsequent PR4 commits swap to the
new mixin and config classes when their feature operators land.

CycleTypeMixin / PickTypeMixin / TypeAccessorBase live in
bim.parametric_lifecycle (previous commit). The three mixins are
re-exported from gizmos.py here so feature-module access via
``gizmo.<MixinName>`` keeps working until PR5 cleanup drops the
re-exports.

bim/module/drawing/__init__.py is updated in the same commit to
register the 11 new gizmo classes (GizmoLockOpen / GizmoLockClosed /
GizmoFillet / GizmoWallCornerIcon / GizmoWallTeeIcon / GizmoTrash /
GizmoArrayParent / GizmoArrayAll / GizmoArrayLayerIndicator /
GizmoUnjoin / GizmoMenu) — without that, the new classes exist in
gizmos.py but aren't usable as bpy gizmo types.

Generated with the assistance of an AI coding tool.
2026-05-27 23:56:28 +02:00
Gorgious56 b039e12623 Add TypeAccessorBase + CycleTypeMixin + PickTypeMixin
Three operator mixins for type-selection ops on parametric features
(door type-cycle, window type-pick, stair type-cycle, railing
type-pick, roof type-cycle, etc.). Each shares the same contract:

* ``element_checker`` validates the active object is the expected
  IFC type
* ``props_getter`` resolves the BIM<Name>Properties group
* ``type_literal`` is the Literal type whose args drive the enum
* ``type_attr`` is the PropertyGroup field to read/write
* ``skip_element_check=True`` bypasses element validation (for
  operators that target a non-IFC context)

CycleTypeMixin shift-click reverses direction (forward by default).
PickTypeMixin opens a popup menu and routes the picked value
through execute() so F6 redo / EXEC_DEFAULT reach the apply path.
The PickType modal-handler dance waits for LEFTMOUSE release before
opening the menu when invoked mid-click (e.g. from a gizmo's
target_set_operator) so Blender's drag-through-pick gesture doesn't
commit an accidental item.

Ships standalone — the next commit's gizmos.py framework refactor
re-exports these names from bonsai.bim.parametric_lifecycle so
gizmo modules can spell ``gizmo.CycleTypeMixin`` / ``gizmo.PickTypeMixin``.
Concrete operator subclasses land in subsequent PR4 commits per
feature (door / window / stair / railing / roof).

Generated with the assistance of an AI coding tool.
2026-05-27 23:06:42 +02:00
65 changed files with 8684 additions and 848 deletions
+9 -1
View File
@@ -192,7 +192,11 @@ endif
# Provides networkx graph analysis for project dependency calculations
cd build && . env/$(VENV_ACTIVATE) && $(PIP) download networkx --dest=./wheels
# Required by IFCDiff
cd build && . env/$(VENV_ACTIVATE) && $(PIP) download deepdiff --dest=./wheels
# Pinned <9.1: deepdiff 9.1.0 adds cachebox<6,>=5.2 which only ships macOS x86_64
# wheels for macosx_10_12+ and is incompatible with our macos py311 --platform
# macosx_10_10_x86_64 target. Revisit once the macos py311 platform tag is bumped
# to 10_13 (matching py312/py313).
cd build && . env/$(VENV_ACTIVATE) && $(PIP) download "deepdiff<9.1" --dest=./wheels
# Required by IFCCSV and ifcopenshell.util.selector
cd build && . env/$(VENV_ACTIVATE) && $(PIP) download lark --dest=./wheels
# Required by IFC4D
@@ -356,6 +360,10 @@ else
pytest test/tool/test_$(MODULE).py --maxfail=1
endif
.PHONY: test-modal
test-modal:
blender --enable-event-simulate --python test/modal/test_modal.py --window-maximized
# Reregistering test is not added to the standard test suite because during unregister
# Blender removes all Bonsai dependencies breaking dev-environment symlinks.
.PHONY: test-reregister
+14 -1
View File
@@ -46,6 +46,7 @@ from bonsai.bim.module.model.decorator import (
BoundingBoxDecorator,
SlabDirectionDecorator,
WallAxisDecorator,
WallFilletPreviewDecorator,
)
from bonsai.bim.module.model.preview_base import discard_pending_previews
from bonsai.bim.module.nest.decorator import NestDecorator
@@ -150,7 +151,14 @@ def update_bim_tool_props():
return
if is_bim_tool:
props.ifc_class = element_type.is_a()
try:
props.ifc_class = element_type.is_a()
except TypeError:
# ifc_class only lists element/space types present in the model, so an
# unsupported type (e.g. a raw IfcTypeProduct) or a stale item list mid-
# rebuild raises `enum "<class>" not found`. Skip rather than crash the
# handler — it re-fires on the next selection and the panel resyncs.
pass
# Only assign when the target enum is the one that lists this type — otherwise
# we hit `enum "<id>" not found in (...)` if the user selects an element of a
@@ -462,6 +470,7 @@ def _install_viewport_overlays() -> None:
NestDecorator.uninstall()
WallAxisDecorator.uninstall()
SlabDirectionDecorator.uninstall()
WallFilletPreviewDecorator.uninstall()
uninstall_decorator_cache_handlers()
try:
if georeference_props.should_visualise:
@@ -476,6 +485,10 @@ def _install_viewport_overlays() -> None:
SlabDirectionDecorator.install(bpy.context)
if model_props.show_bounding_box:
BoundingBoxDecorator.install(bpy.context)
# Always-installed: draw() self-polls on Scene.BIMPreviewProperties.
# wall_fillet.is_active, so installation has no cost when no preview
# is open. No corresponding addon-preference toggle.
WallFilletPreviewDecorator.install(bpy.context)
finally:
install_decorator_cache_handlers()
@@ -139,6 +139,7 @@ class BIMAggregateProperties(PropertyGroup):
previous_editing_aggregate: PointerProperty(name="Editing Aggregate", type=bpy.types.Object)
editing_objects: CollectionProperty(type=Objects)
not_editing_objects: CollectionProperty(type=Objects)
previously_selected_objects: CollectionProperty(type=Objects)
aggregate_decorator: BoolProperty(
name="Display Aggregate",
default=False,
@@ -155,5 +156,6 @@ class BIMAggregateProperties(PropertyGroup):
previous_editing_aggregate: Union[bpy.types.Object, None]
editing_objects: bpy.types.bpy_prop_collection_idprop[Objects]
not_editing_objects: bpy.types.bpy_prop_collection_idprop[Objects]
previously_selected_objects: bpy.types.bpy_prop_collection_idprop[Objects]
aggregate_decorator: bool
previous_state: bool
+3 -1
View File
@@ -48,12 +48,14 @@ def draw_ui(context: bpy.types.Context, layout: bpy.types.UILayout, attributes)
row = layout.row()
op = row.operator("bim.enable_editing_attributes", icon="GREASEPENCIL", text="Edit")
element = tool.Ifc.get_entity(obj)
key_prefix = "type." if (element and element.is_a("IfcTypeObject")) else ""
for attribute in attributes:
row = layout.row(align=True)
row.label(text=attribute["name"])
value = bonsai.bim.helper.get_display_value(attribute["value"])
op = row.operator("bim.select_similar", text=value, icon="NONE", emboss=False)
op.key = attribute["name"]
op.key = key_prefix + attribute["name"]
# TODO: reimplement, see #1222
# if "IfcSite/" in context.active_object.name or "IfcBuilding/" in context.active_object.name:
@@ -138,15 +138,24 @@ classes = (
gizmos.GizmoArrow2D,
gizmos.GizmoCone,
gizmos.GizmoDimension,
gizmos.GizmoLock,
gizmos.GizmoLockOpen,
gizmos.GizmoLockClosed,
gizmos.GizmoArc,
gizmos.GizmoFillet,
gizmos.GizmoWallCornerIcon,
gizmos.GizmoWallTeeIcon,
gizmos.GizmoPen,
gizmos.GizmoValidate,
gizmos.GizmoCancel,
gizmos.GizmoPlus,
gizmos.GizmoMinus,
gizmos.GizmoTrash,
gizmos.GizmoArrayParent,
gizmos.GizmoArrayAll,
gizmos.GizmoArrayLayerIndicator,
gizmos.GizmoMerge,
gizmos.GizmoSplit,
gizmos.GizmoUnjoin,
gizmos.GizmoExtend,
gizmos.GizmoExtendVertical,
gizmos.GizmoOffsetExterior,
@@ -154,6 +163,7 @@ classes = (
gizmos.GizmoOffsetInterior,
gizmos.GizmoAddOpening,
gizmos.GizmoCycle,
gizmos.GizmoMenu,
# Drawing-specific gizmos
gizmos.UglyDotGizmo,
gizmos.ExtrusionGuidesGizmo,
File diff suppressed because it is too large Load Diff
@@ -44,8 +44,12 @@ class ViewportData:
@classmethod
def load(cls):
cls.is_loaded = True
# Populate data BEFORE flipping is_loaded so a raising ``mode()``
# call doesn't leave the class half-loaded (flag set, dict empty).
# Subsequent items-callback invocations skip load() on a True flag
# and would hit ``cls.data["mode"]`` → KeyError.
cls.data = {"mode": cls.mode()}
cls.is_loaded = True
@classmethod
def mode(cls) -> tool.Blender.BLENDER_ENUM_ITEMS:
@@ -60,6 +60,7 @@ import bonsai.core.root
import bonsai.core.spatial
import bonsai.tool as tool
from bonsai.bim.ifc import IfcStore
from bonsai.bim.module.model import preview_base
from bonsai.bim.module.model.decorator import ProfileDecorator
if TYPE_CHECKING:
@@ -2228,6 +2229,8 @@ class OverrideEscape(bpy.types.Operator):
bpy.ops.bim.hide_all_openings()
elif tool.Aggregate.get_aggregate_props().in_aggregate_mode:
bpy.ops.bim.disable_aggregate_mode()
elif preview_base.try_cancel_active_preview(context):
pass
elif active_object := context.active_object:
if tool.Blender.Modifier.try_canceling_editing_modifier_parameters_or_path(active_object):
pass
@@ -2269,6 +2272,8 @@ class OverrideModeSetEdit(bpy.types.Operator, tool.Ifc.Operator):
gprops = tool.Geometry.get_geometry_props()
if gprops.representation_obj:
tool.Geometry.disable_item_mode()
if active_obj := bpy.context.active_object:
active_obj.select_set(False)
else:
bonsai.core.aggregate.exit_aggregate_mode(tool.Aggregate)
return {"FINISHED"}
@@ -2355,6 +2360,7 @@ class OverrideModeSetEdit(bpy.types.Operator, tool.Ifc.Operator):
and usage in ("LAYER1", "LAYER2")
):
self.report({"INFO"}, f"Parametric {usage} elements cannot be edited directly")
obj.select_set(False)
elif item.is_a("IfcSweptAreaSolid"):
tool.Geometry.sync_item_positions()
res = tool.Model.import_profile((profile := item.SweptArea), obj=obj)
@@ -2363,6 +2369,7 @@ class OverrideModeSetEdit(bpy.types.Operator, tool.Ifc.Operator):
{"INFO"},
f"Couldn't import profile, editing it directly is not yet supported. Failing profile: {profile}.",
)
obj.select_set(False)
return
tool.Ifc.link(item, obj.data)
self.enable_edit_mode(context)
+25 -2
View File
@@ -19,6 +19,7 @@
import bpy
from bpy.types import Menu, Panel, UIList
import ifcopenshell.util.unit
import bonsai.bim
import bonsai.tool as tool
from bonsai.bim.helper import prop_with_search
@@ -483,10 +484,32 @@ class BIM_PT_placement(Panel):
row.label(text="No Object Placement Found")
return
is_imperial = False
if tool.Ifc.get():
length_unit = ifcopenshell.util.unit.get_project_unit(tool.Ifc.get(), "LENGTHUNIT")
if length_unit and length_unit.Name != "METRE":
is_imperial = True
row = self.layout.row()
row.prop(context.active_object, "location", text="Location")
row.label(text="Location:")
if is_imperial:
loc = context.active_object.location
for i, (axis, comp) in enumerate(zip("XYZ", (loc.x, loc.y, loc.z))):
split = self.layout.split(factor=0.6)
split.prop(context.active_object, "location", index=i, text=axis)
sub = split.row()
sub.enabled = False
sub.alignment = "LEFT"
sub.label(text=tool.Unit.format_distance(comp))
else:
for i, axis in enumerate("XYZ"):
self.layout.prop(context.active_object, "location", index=i, text=axis)
row = self.layout.row()
row.prop(context.active_object, "rotation_euler", text="Rotation")
row.label(text="Rotation:")
for i, axis in enumerate("XYZ"):
self.layout.prop(context.active_object, "rotation_euler", index=i, text=axis)
if props.blender_offset_type != "NONE":
row = self.layout.row(align=True)
@@ -61,6 +61,8 @@ classes = (
array.Input3DCursorXArray,
array.Input3DCursorYArray,
array.Input3DCursorZArray,
array.EnableEditingParametric,
array.AddArrayFromFeatureEdit,
product.AddDefaultType,
product.AddEmptyType,
product.AddOccurrence,
@@ -83,6 +85,7 @@ classes = (
wall.EnableEditingWall,
wall.ExtendWallHeightToCursor,
wall.ExtendWallsToUnderside,
wall.RegenerateWallToUnderside,
wall.ExtendWallsToWall,
wall.ExtendWallsToPolylinePoint,
wall.ExtendWallToCursor,
@@ -91,7 +94,10 @@ classes = (
wall.GizmoWallAddOpening,
wall.GizmoWallEdition,
wall.GizmoWallExtendVertically,
wall.GizmoWallFilletPreview,
wall.GizmoWallFilletReedit,
wall.GizmoWallJoinIntersection,
wall.GizmoWallUnjoinSingle,
wall.JoinWallsIntersection,
wall.MergeWall,
wall.OffsetWalls,
@@ -100,7 +106,13 @@ classes = (
wall.SplitWall,
wall.SplitWallAtCursor,
wall.ToggleWallOpenings,
wall.UnjoinWallPathConnection,
wall.UnjoinWalls,
wall.EnableWallFilletPreview,
wall.FinishWallFilletPreview,
wall.CancelWallFilletPreview,
wall.EnableWallFilletPreviewFromCorner,
wall.CreateWallFillet,
opening.AddBoolean,
opening.CloneOpening,
opening.EditOpenings,
@@ -161,6 +173,8 @@ classes = (
prop.BIMWallProperties,
prop.BIMPolylineProperties,
prop.BIMExternalParametricGeometryProperties,
prop.BIMWallFilletPreviewProperties,
prop.BIMPreviewProperties,
ui.BIM_PT_array,
ui.BIM_PT_stair,
ui.BIM_PT_wall,
@@ -291,6 +305,7 @@ def register():
bpy.types.Object.BIMExternalParametricGeometryProperties = bpy.props.PointerProperty(
type=prop.BIMExternalParametricGeometryProperties
)
bpy.types.Scene.BIMPreviewProperties = bpy.props.PointerProperty(type=prop.BIMPreviewProperties)
bpy.types.VIEW3D_MT_add.prepend(ui.add_menu)
bpy.app.handlers.load_post.append(handler.load_post)
@@ -299,6 +314,12 @@ def register():
def unregister():
# DecorationsHandler is installed lazily by bim.show_openings; tear it down
# (along with its persistent depsgraph / undo / redo / load cache handlers)
# before the rest of unregister so those handlers can't fire against
# half-unloaded module state.
opening.DecorationsHandler.uninstall()
if not bpy.app.background:
for tool_data in reversed(tools):
bpy.utils.unregister_tool(tool_data.tool)
@@ -309,6 +330,7 @@ def unregister():
del bpy.types.Object.BIMSverchokProperties
tool.Parametric.unregister_object_properties()
del bpy.types.Object.BIMExternalParametricGeometryProperties
del bpy.types.Scene.BIMPreviewProperties
bpy.app.handlers.load_post.remove(handler.load_post)
bpy.types.VIEW3D_MT_add.remove(ui.add_menu)
+126
View File
@@ -379,3 +379,129 @@ class Input3DCursorZArray(bpy.types.Operator):
else:
props.z = cursor.location.z - obj.location.z
return {"FINISHED"}
class EnableEditingParametric(bpy.types.Operator):
"""Pen-icon dispatcher: fires the gizmo group's per-feature edit operator.
Bound to every parametric gizmo group's pen icon. The gizmo group's own
``enable_editing_operator`` (``bim.enable_editing_door``, ``_wall``, )
is passed as ``feature_enable_op`` at setup time and invoked here. The
indirection lets one gizmo class serve all features without per-feature
subclasses."""
bl_idname = "bim.enable_editing_parametric"
bl_label = "Enable Editing"
bl_description = "Edit this object's parameters"
bl_options = {"REGISTER", "UNDO"}
feature_enable_op: bpy.props.StringProperty(
default="",
description="Operator bl_idname to invoke (e.g., 'bim.enable_editing_door').",
)
def execute(self, context):
# Malformed ``feature_enable_op`` (missing dot) would otherwise crash
# the unpack with ValueError; treat the same as the empty-string case.
parts = self.feature_enable_op.split(".", 1)
if len(parts) != 2:
return {"CANCELLED"}
domain, opname = parts
return getattr(getattr(bpy.ops, domain), opname)("INVOKE_DEFAULT")
class AddArrayFromFeatureEdit(bpy.types.Operator, tool.Ifc.Operator):
"""Commit any in-progress feature edit and add an array with
gizmo-friendly defaults (count=2, offset = bbox extent along the axis).
Modifier-aware: plain click X, Shift Y, Ctrl Z. Callers can pass
``axis="X"`` via EXEC_DEFAULT to bypass the modifier read.
All three chained operators (feature finish + add_array + enable_editing)
run inside one transaction for a single undo step."""
bl_idname = "bim.add_array_from_feature_edit"
bl_label = "Add Array"
bl_description = (
"Click: add an array along X.\n" "Shift+Click: add an array along Y.\n" "Ctrl+Click: add an array along Z"
)
bl_options = {"REGISTER", "UNDO"}
axis: bpy.props.EnumProperty(
name="Offset Axis",
items=[
("X", "X", "Offset along the object's X axis (bbox X extent)"),
("Y", "Y", "Offset along the object's Y axis (bbox Y extent)"),
("Z", "Z", "Offset along the object's Z axis (bbox Z extent)"),
],
default="X",
)
# Minimum offset to use when the object's bbox extent is tiny — prevents
# the second instance from visually overlapping the parent on small
# annotations / openings (0.3m ≈ a clearly-separated next-instance distance).
MIN_DEFAULT_OFFSET = 0.3
def invoke(self, context, event):
# Modifier-aware axis pick: X by default, Shift → Y, Ctrl → Z.
if event.shift:
self.axis = "Y"
elif event.ctrl:
self.axis = "Z"
else:
self.axis = "X"
return self.execute(context)
def _execute(self, context):
obj = context.active_object
if obj is None:
return {"CANCELLED"}
# Commit any in-progress parametric edit lifecycle on this object first — the
# user expects "Add Array" to also finalise whatever they were editing
# so they don't lose their draft changes.
editing = tool.Parametric.is_object_editing(obj, skip_name="array")
if editing is not None:
finish_op_name = editing.finish_op.removeprefix("bim.")
getattr(bpy.ops.bim, finish_op_name)("INVOKE_DEFAULT")
# Bounding-box derived offset along the chosen axis, converted from
# Blender SI (meters) to IFC project units (which is what
# ``BBIM_Array.Data`` stores; the regenerator multiplies by
# unit_scale on the way out).
axis_idx = "XYZ".index(self.axis)
if obj.bound_box:
bbox_extent_si = max(c[axis_idx] for c in obj.bound_box) - min(c[axis_idx] for c in obj.bound_box)
else:
bbox_extent_si = 1.0
bbox_extent_si = max(bbox_extent_si, self.MIN_DEFAULT_OFFSET)
si_conversion = ifcopenshell.util.unit.calculate_unit_scale(tool.Ifc.get())
offset_project = bbox_extent_si / si_conversion if si_conversion else bbox_extent_si
add_kwargs = {"count": 2, "x": 0.0, "y": 0.0, "z": 0.0}
add_kwargs[self.axis.lower()] = offset_project
result = bpy.ops.bim.add_array(**add_kwargs)
if result != {"FINISHED"}:
return result
# Restore selection to just the parent. ``regenerate_array`` calls
# ``tool.Geometry.duplicate_ifc_objects`` which leaves the newly-created
# child selected alongside the parent. The edit-lifecycle gizmos poll on a
# single-selected parent, so with both selected the gizmos wouldn't
# surface and "ARRAY → enter edit" would feel broken.
tool.Blender.select_and_activate_single_object(context, active_object=obj)
# Chain straight into array edit for the newly-added layer (always the
# last entry in the pset's Data list, by AddArray's append semantics).
# The user's expectation after clicking ARRAY is "I want to tweak this
# array now" — entering edit mode immediately collapses the 2-click
# discover-then-edit flow into one.
element = tool.Ifc.get_entity(obj)
if element is None:
return {"FINISHED"}
data_text = ifcopenshell.util.element.get_pset(element, "BBIM_Array", "Data")
if not data_text:
return {"FINISHED"}
try:
layers = json.loads(data_text)
except (ValueError, TypeError):
return {"FINISHED"}
if not layers:
return {"FINISHED"}
bpy.ops.bim.enable_editing_array("INVOKE_DEFAULT", item=len(layers) - 1)
return {"FINISHED"}
+149 -1
View File
@@ -108,7 +108,7 @@ class ProfileDecorator:
obj = context.active_object
if obj.mode != "EDIT":
if obj is None or obj.mode != "EDIT":
if exit_edit_mode_callback:
ProfileDecorator.uninstall()
exit_edit_mode_callback()
@@ -2029,3 +2029,151 @@ class BoundingBoxDecorator:
else:
co1.y += y_overlap / 2 + min_spacing
co2.y -= y_overlap / 2 + min_spacing
def _stroke_lines_alpha(
context: bpy.types.Context,
segments: list[tuple[tuple[float, float, float], tuple[float, float, float]]],
color_rgb: tuple[float, float, float],
line_width: float,
line_alpha: float,
) -> None:
"""Render ``segments`` (a list of ``(start, end)`` tuples) as one
anti-aliased LINES batch in world space. Early-returns when
``context.region`` is unavailable (e.g. when called from a
``_RestrictContext``)."""
if not segments:
return
verts: list[tuple[float, float, float]] = []
indices: list[tuple[int, int]] = []
for start, end in segments:
base = len(verts)
verts.append(tuple(start))
verts.append(tuple(end))
indices.append((base, base + 1))
if not tool.Blender.validate_shader_batch_data(verts, indices):
return
region = getattr(context, "region", None)
if region is None:
return
shader = gpu.shader.from_builtin("POLYLINE_UNIFORM_COLOR")
shader.bind()
shader.uniform_float("viewportSize", (region.width, region.height))
shader.uniform_float("lineWidth", line_width)
shader.uniform_float("color", (*color_rgb, line_alpha))
batch = batch_for_shader(shader, "LINES", {"pos": verts}, indices=indices)
gpu.state.blend_set("ALPHA")
batch.draw(shader)
gpu.state.blend_set("NONE")
class WallFilletPreviewDecorator(tool.Blender.ViewportDecorator):
"""GPU preview lines for the wall-fillet flow.
Polls on ``scene.BIMPreviewProperties.wall_fillet.is_active`` and renders
the leg projections + arc + radial construction lines returned by
``tool.Wall.compute_wall_fillet_geometry``. The two leg lines show how
each wall will be shortened to its tangent point; the arc approximates
the rounded corner; the two construction lines (arc center to each
tangent point) visually pin the radius.
Installed once per Blender session from ``bim/handler.py:load_post``
and uninstalled in ``bim/module/model/__init__.py:unregister``."""
LINE_WIDTH_LEG = 1.5
LINE_WIDTH_ARC = 2.5
LINE_WIDTH_CONSTRUCTION = 1.0
LINE_ALPHA = 0.7
CONSTRUCTION_ALPHA = 0.4
def draw(self, context: bpy.types.Context) -> None:
scene = context.scene
preview_props = getattr(scene, "BIMPreviewProperties", None)
props = preview_props.wall_fillet if preview_props is not None else None
if props is None or not props.is_active:
return
ifc_file = tool.Ifc.get()
if ifc_file is None:
return
try:
wall_a = ifc_file.by_id(props.wall_a_id)
wall_b = ifc_file.by_id(props.wall_b_id)
except Exception:
return
wall_a_obj = tool.Ifc.get_object(wall_a) if wall_a else None
wall_b_obj = tool.Ifc.get_object(wall_b) if wall_b else None
if wall_a_obj is None or wall_b_obj is None:
return
geom = tool.Wall.compute_wall_fillet_geometry(wall_a_obj, wall_b_obj, props.radius)
if geom is None:
return
prefs = tool.Blender.get_addon_preferences()
warning_color = tuple(prefs.decorator_color_error[:3])
if not geom["valid"]:
# Degenerate geometry paints red: invalid_radius shows legs+arc
# past the wall ends; invalid_axes shows the parallel/collinear
# axes.
if geom.get("invalid_radius"):
tangent_a = geom.get("tangent_a")
tangent_b = geom.get("tangent_b")
ref_a = tool.Wall.get_world_reference_line(wall_a_obj)
ref_b = tool.Wall.get_world_reference_line(wall_b_obj)
if tangent_a is not None and tangent_b is not None and ref_a is not None and ref_b is not None:
far_a = self._far_endpoint(ref_a, geom["intersection"])
far_b = self._far_endpoint(ref_b, geom["intersection"])
legs = [
(tuple(far_a), tuple(tangent_a)),
(tuple(far_b), tuple(tangent_b)),
]
_stroke_lines_alpha(context, legs, warning_color, self.LINE_WIDTH_LEG, self.LINE_ALPHA)
arc = geom.get("arc") or []
if len(arc) >= 2:
arc_segments = [(tuple(arc[i]), tuple(arc[i + 1])) for i in range(len(arc) - 1)]
_stroke_lines_alpha(context, arc_segments, warning_color, self.LINE_WIDTH_ARC, self.LINE_ALPHA)
elif geom.get("invalid_axes"):
axes = geom["invalid_axes"]
segments = [(tuple(a), tuple(b)) for a, b in axes]
_stroke_lines_alpha(context, segments, warning_color, self.LINE_WIDTH_ARC, self.LINE_ALPHA)
return
leg_color = tuple(prefs.decorations_colour[:3])
arc_color = tuple(prefs.decorator_color_selected[:3])
# Resolved against the IFC reference line, not mesh bounds, so trimmed
# walls and openings don't shift the leg endpoints.
ref_a = tool.Wall.get_world_reference_line(wall_a_obj)
ref_b = tool.Wall.get_world_reference_line(wall_b_obj)
if ref_a is not None and ref_b is not None and geom["intersection"] is not None:
far_a = self._far_endpoint(ref_a, geom["intersection"])
far_b = self._far_endpoint(ref_b, geom["intersection"])
legs = [
(tuple(far_a), tuple(geom["tangent_a"])),
(tuple(far_b), tuple(geom["tangent_b"])),
]
_stroke_lines_alpha(context, legs, leg_color, self.LINE_WIDTH_LEG, self.LINE_ALPHA)
arc = geom["arc"]
if len(arc) >= 2:
arc_segments = [(tuple(arc[i]), tuple(arc[i + 1])) for i in range(len(arc) - 1)]
_stroke_lines_alpha(context, arc_segments, arc_color, self.LINE_WIDTH_ARC, self.LINE_ALPHA)
# Dim construction lines from arc_center to each tangent point so
# the radius reads as concrete during drag.
arc_center = geom.get("arc_center")
if arc_center is not None:
construction = [
(tuple(arc_center), tuple(geom["tangent_a"])),
(tuple(arc_center), tuple(geom["tangent_b"])),
]
_stroke_lines_alpha(context, construction, arc_color, self.LINE_WIDTH_CONSTRUCTION, self.CONSTRUCTION_ALPHA)
@staticmethod
def _far_endpoint(reference_line, intersection):
"""Endpoint of ``reference_line`` furthest from ``intersection``."""
p1, p2 = reference_line
d1 = (p1.x - intersection[0]) ** 2 + (p1.y - intersection[1]) ** 2 + (p1.z - intersection[2]) ** 2
d2 = (p2.x - intersection[0]) ** 2 + (p2.y - intersection[1]) ** 2 + (p2.z - intersection[2]) ** 2
return p2 if d2 >= d1 else p1
+3 -5
View File
@@ -707,8 +707,8 @@ class CycleDoorType(bpy.types.Operator, tool.Ifc.Operator, gizmo.CycleTypeMixin)
bl_label = "Cycle Door Type"
bl_options = {"REGISTER", "UNDO"}
element_checker = "is_door"
props_getter = "get_door_props"
element_checker = tool.Parametric.is_door
props_getter = tool.Model.get_door_props
type_literal = tool.Model.DoorType
type_attr = "door_type"
@@ -835,7 +835,7 @@ class GizmoDoorEdition(bpy.types.GizmoGroup, gizmo.BaseParametricGizmoGroup):
),
]
props_getter = "get_door_props"
props_getter = tool.Model.get_door_props
gizmo_pref_name = "door"
@classmethod
@@ -866,13 +866,11 @@ class GizmoDoorEdition(bpy.types.GizmoGroup, gizmo.BaseParametricGizmoGroup):
self.gizmo_door_type = self.create_arc_gizmo(
special_color,
"bim.toggle_door_swing",
prop_path="BIMDoorProperties.door_type",
flip_geometry=False,
)
self.gizmo_flip_arc = self.create_arc_gizmo(
inactive_color,
"bim.toggle_door_swing",
prop_path="BIMDoorProperties.door_type",
flip_geometry=True,
flip_local_axes="XY",
)
+227 -23
View File
@@ -41,8 +41,187 @@ from mathutils import Matrix, Vector
import bonsai.core.geometry
import bonsai.tool as tool
from bonsai.bim import decorator_cache
from bonsai.bim.module.drawing.decoration import DecoratorData
# Multi-entry cache for the opening preview's dissolved-edges fallback.
# Single-entry wouldn't fit: the draw handler iterates every active opening
# per frame, each with its own mesh. Bumped wholesale on the shared
# decorator-cache token (depsgraph / undo / redo / load), one slot per
# (mesh.session_uid, angle_limit). Outlier vs. the per-object caches below —
# consulted only on world-draw-data miss, so the global wipe rarely fires in
# steady state and the simpler invalidation is enough.
_dissolved_edges_cache: dict[
tuple[int, float],
tuple[list[Vector], list[tuple[int, int]]],
] = {}
_dissolved_edges_cache_token: int = -1
def _get_cached_dissolved_edges(
mesh: bpy.types.Mesh,
angle_limit: float = radians(1.0),
) -> tuple[list[Vector], list[tuple[int, int]]]:
global _dissolved_edges_cache_token
token = decorator_cache.get_decorator_cache_token()
if token != _dissolved_edges_cache_token:
_dissolved_edges_cache.clear()
_dissolved_edges_cache_token = token
key = (mesh.session_uid, angle_limit)
cached = _dissolved_edges_cache.get(key)
if cached is not None:
return cached
result = tool.Geometry.get_dissolved_edges(mesh, angle_limit=angle_limit)
_dissolved_edges_cache[key] = result
return result
# Per-object epoch: bumped only when this specific object's transform or geometry
# updates land in the depsgraph delta. Invalidation work scales with the number
# of changed objects, not total scene size — moving one object leaves every
# other entry valid. Bumped by the depsgraph handler below; cleared on
# undo/redo/load alongside the cache dicts.
_object_epochs: dict[int, int] = {}
@bpy.app.handlers.persistent
def _bump_object_epochs_for_decoration(*args) -> None:
# depsgraph_update_post is called as (scene, depsgraph) in 4.x but the
# *args signature follows decorator_cache's defensive idiom.
depsgraph = args[1] if len(args) >= 2 else None
if depsgraph is None or not hasattr(depsgraph, "updates"):
return
for u in depsgraph.updates:
if not isinstance(u.id, bpy.types.Object):
continue
if not (u.is_updated_geometry or u.is_updated_transform):
continue
# u.id is the evaluated COW copy; the cache keys are written from the
# original Object (read by the draw handler), and session_uid can
# differ across the COW boundary. Resolve to the original before keying.
original = getattr(u.id, "original", u.id)
if original is None:
continue
uid = original.session_uid
_object_epochs[uid] = _object_epochs.get(uid, 0) + 1
@bpy.app.handlers.persistent
def _clear_decoration_caches_globally(*args) -> None:
# Undo/redo/load: depsgraph deltas can't be trusted to describe the
# transition, so wipe every per-object cache state.
_object_epochs.clear()
_world_draw_data_cache.clear()
_batch_cache.clear()
def _decoration_invalidation_hooks() -> tuple:
return (
bpy.app.handlers.undo_post,
bpy.app.handlers.redo_post,
bpy.app.handlers.load_post,
)
def install_decoration_cache_handlers() -> None:
if _bump_object_epochs_for_decoration not in bpy.app.handlers.depsgraph_update_post:
bpy.app.handlers.depsgraph_update_post.append(_bump_object_epochs_for_decoration)
for hook in _decoration_invalidation_hooks():
if _clear_decoration_caches_globally not in hook:
hook.append(_clear_decoration_caches_globally)
def uninstall_decoration_cache_handlers() -> None:
try:
bpy.app.handlers.depsgraph_update_post.remove(_bump_object_epochs_for_decoration)
except ValueError:
pass
for hook in _decoration_invalidation_hooks():
try:
hook.remove(_clear_decoration_caches_globally)
except ValueError:
pass
# Per-object world-space draw payload: line_verts (dissolved or ios_edges-filtered),
# verts (full mesh, indexed by loop_triangles), edges_indices, tris. Entries are
# (epoch, payload) tuples; lookup compares epoch to _object_epochs[uid], so a
# stale entry for an object that didn't change since the last build still hits.
_world_draw_data_cache: dict[
int,
tuple[
int,
tuple[
list[tuple[float, float, float]],
list[tuple[float, float, float]],
list[tuple[int, int]],
list[tuple[int, ...]],
],
],
] = {}
def _get_cached_world_draw_data(
obj: bpy.types.Object,
) -> tuple[
list[tuple[float, float, float]],
list[tuple[float, float, float]],
list[tuple[int, int]],
list[tuple[int, ...]],
]:
uid = obj.session_uid
epoch = _object_epochs.get(uid, 0)
entry = _world_draw_data_cache.get(uid)
if entry is not None and entry[0] == epoch:
return entry[1]
mw = obj.matrix_world
verts = [tuple(mw @ v.co) for v in obj.data.vertices]
obj.data.calc_loop_triangles()
tris = [tuple(t.vertices) for t in obj.data.loop_triangles]
ios_edges_attribute = obj.data.attributes.get("ios_edges")
if ios_edges_attribute:
# Loader-curated edges: read the attribute aligned with bm.edges order.
bm = bmesh.new()
bm.from_mesh(obj.data)
edges_indices = [
tuple(v.index for v in e.verts) for i, e in enumerate(bm.edges) if ios_edges_attribute.data[i].value
]
bm.free()
line_verts = verts
else:
dissolved, edges_indices = _get_cached_dissolved_edges(obj.data)
line_verts = [tuple(mw @ v) for v in dissolved]
result = (line_verts, verts, edges_indices, tris)
_world_draw_data_cache[uid] = (epoch, result)
return result
# GPUBatch cache: skip per-frame batch_for_shader. Entries are (epoch, batch);
# lookup compares epoch to _object_epochs[uid] so other objects' batches stay
# alive when one object's depsgraph delta bumps only its own epoch. The cached
# batches reference GPU-side buffers tied to Blender's built-in shaders, which
# are themselves cached by name (gpu.shader.from_builtin returns the same
# handle each call), so they stay drawable across frames.
_batch_cache: dict[tuple[int, str], tuple[int, "gpu.types.GPUBatch"]] = {}
def _get_cached_batch_or_none(cache_key: tuple[int, str]) -> "gpu.types.GPUBatch | None":
uid = cache_key[0]
epoch = _object_epochs.get(uid, 0)
entry = _batch_cache.get(cache_key)
if entry is not None and entry[0] == epoch:
return entry[1]
return None
def _store_batch_in_cache(cache_key: tuple[int, str], batch: "gpu.types.GPUBatch") -> None:
uid = cache_key[0]
epoch = _object_epochs.get(uid, 0)
_batch_cache[cache_key] = (epoch, batch)
class FilledOpeningGenerator:
def generate(
@@ -941,7 +1120,6 @@ class SelectBoolean(Operator):
return {"FINISHED"}
# TODO: merge with ProfileDecorator?
class DecorationsHandler:
installed = None
@@ -951,6 +1129,7 @@ class DecorationsHandler:
cls.uninstall()
handler = cls()
cls.installed = SpaceView3D.draw_handler_add(handler, (context,), "WINDOW", "POST_VIEW")
install_decoration_cache_handlers()
@classmethod
def uninstall(cls):
@@ -959,15 +1138,46 @@ class DecorationsHandler:
except ValueError:
pass
cls.installed = None
uninstall_decoration_cache_handlers()
def draw_batch(self, shader_type, content_pos, color, indices=None):
def _get_or_build_batch(self, shader, shader_type, content_pos, indices=None, cache_key=None):
if cache_key is not None:
cached = _get_cached_batch_or_none(cache_key)
if cached is not None:
return cached
if not tool.Blender.validate_shader_batch_data(content_pos, indices):
return
shader = self.line_shader if shader_type == "LINES" else self.shader
return None
batch = batch_for_shader(shader, shader_type, {"pos": content_pos}, indices=indices)
if cache_key is not None:
_store_batch_in_cache(cache_key, batch)
return batch
def draw_batch(self, shader_type, content_pos, color, indices=None, cache_key=None):
shader = self.line_shader if shader_type == "LINES" else self.shader
batch = self._get_or_build_batch(shader, shader_type, content_pos, indices, cache_key=cache_key)
if batch is None:
return
shader.uniform_float("color", color)
batch.draw(shader)
def _draw_lines_with_occlusion(self, verts, color, edges_indices, occluded_alpha: float = 0.25, cache_key=None):
# One batch, two draws: front pass at full color, occluded pass at
# `occluded_alpha`. Save/restore depth_test matches the pattern in
# bim/module/structural/decorator.py so callers' state survives.
batch = self._get_or_build_batch(self.line_shader, "LINES", verts, edges_indices, cache_key=cache_key)
if batch is None:
return
original_depth_test = gpu.state.depth_test_get()
gpu.state.depth_test_set("LESS_EQUAL")
self.line_shader.uniform_float("color", color)
batch.draw(self.line_shader)
gpu.state.depth_test_set("GREATER")
dimmed = list(color)
dimmed[3] = occluded_alpha
self.line_shader.uniform_float("color", dimmed)
batch.draw(self.line_shader)
gpu.state.depth_test_set(original_depth_test)
def __call__(self, context):
props = tool.Model.get_model_props()
if not props.openings:
@@ -1039,23 +1249,20 @@ class DecorationsHandler:
self.draw_batch("LINES", verts, selected_elements_color, selected_edges)
self.draw_batch("POINTS", unselected_vertices, unselected_elements_color)
self.draw_batch("POINTS", selected_vertices, selected_elements_color)
obj.data.calc_loop_triangles()
tris = [tuple(t.vertices) for t in obj.data.loop_triangles]
self.draw_batch("TRIS", verts, transparent_color(special_elements_color), tris)
else:
bm = bmesh.new()
bm.from_mesh(obj.data)
verts = [tuple(obj.matrix_world @ v.co) for v in bm.verts]
if ios_edges_attribute := obj.data.attributes.get("ios_edges"):
edges = [e for i, e in enumerate(bm.edges) if ios_edges_attribute.data[i].value]
else:
edges = bm.edges
edges_indices = [tuple([v.index for v in e.verts]) for e in edges]
line_verts, verts, edges_indices, tris = _get_cached_world_draw_data(obj)
color = selected_elements_color if obj in context.selected_objects else special_elements_color
self.draw_batch("LINES", verts, color, edges_indices)
obj.data.calc_loop_triangles()
tris = [tuple(t.vertices) for t in obj.data.loop_triangles]
self.draw_batch("TRIS", verts, transparent_color(special_elements_color), tris)
self._draw_lines_with_occlusion(line_verts, color, edges_indices, cache_key=(obj.session_uid, "lines"))
self.draw_batch(
"TRIS",
verts,
transparent_color(special_elements_color),
tris,
cache_key=(obj.session_uid, "tris"),
)
if "HalfSpaceSolid" in obj.name:
# Arrow shape
@@ -1069,7 +1276,4 @@ class DecorationsHandler:
]
edges = [(0, 1), (1, 2), (1, 3), (1, 4), (1, 5)]
color = selected_elements_color if obj in context.selected_objects else special_elements_color
self.draw_batch("LINES", verts, color, edges)
if obj.mode != "EDIT":
bm.free()
self._draw_lines_with_occlusion(verts, color, edges, cache_key=(obj.session_uid, "arrow"))
@@ -75,6 +75,7 @@ class PolylineOperator:
self.is_typing = False
self.snap_angle = None
self.snapping_points = []
self.unit_scale = 1.0
self.instructions = {
"Cycle Input": {"icons": True, "keys": ["EVENT_TAB"]},
"Distance Input": {"icons": True, "keys": ["EVENT_D"]},
@@ -60,8 +60,12 @@ def get_preview_props(context: bpy.types.Context, attr: str):
Returns ``None`` if the umbrella isn't attached yet — true briefly
during addon register and during plug-out, so polls / draw callbacks
must defend against ``None`` rather than assuming the prop is always
available."""
preview = getattr(context.scene, "BIMPreviewProperties", None)
available. Also tolerates contexts without a ``scene`` attribute
(test mocks built from ``SimpleNamespace``)."""
scene = getattr(context, "scene", None)
if scene is None:
return None
preview = getattr(scene, "BIMPreviewProperties", None)
return getattr(preview, attr, None) if preview is not None else None
@@ -74,6 +78,17 @@ def is_preview_active(context: bpy.types.Context, attr: str) -> bool:
return bool(props is not None and props.is_active)
def any_preview_active(context: bpy.types.Context) -> bool:
"""``True`` if any registered preview is currently open. Sister gizmo
polls call this to hide themselves uniformly during ANY preview, so a
new preview registered in ``PREVIEW_CANCEL_OPS`` automatically gates
every parametric gizmo without each one growing a specific check."""
for attr, _op_name in PREVIEW_CANCEL_OPS:
if is_preview_active(context, attr):
return True
return False
# --- Lazy closure factories --------------------------------------------------
#
# Used by preview gizmo groups when wiring ``BIM_GT_gizmo_dimension``'s
@@ -1902,3 +1902,65 @@ class BIMExternalParametricGeometryProperties(bpy.types.PropertyGroup):
geometry_source: Literal["GEONODES", "IFCSVERCHOK"]
geo_nodes: Union[bpy.types.GeometryNodeTree, None]
sverchok_nodes: Union[sverchok.node_tree.SverchCustomTree, None]
class BIMWallFilletPreviewProperties(PropertyGroup):
"""Scene-level pending state for the wall-fillet preview flow.
Scene-level because the fillet spans two walls and commits a third
(corner) wall between them. ``SKIP_SAVE`` fields throughout."""
is_active: bpy.props.BoolProperty(
default=False,
options={"SKIP_SAVE"},
description="True while the wall-fillet preview flow is active.",
)
wall_a_id: bpy.props.IntProperty(
default=0,
options={"SKIP_SAVE"},
description=(
"IFC element id of the active wall — the corner wall inherits its "
"material layer set, height, x_angle, and type."
),
)
wall_b_id: bpy.props.IntProperty(
default=0,
options={"SKIP_SAVE"},
description="IFC element id of the other selected wall.",
)
radius: bpy.props.FloatProperty(
name="Radius",
default=0.5,
soft_min=-10.0,
soft_max=10.0,
subtype="DISTANCE",
unit="LENGTH",
options={"SKIP_SAVE"},
description="Radius of the circular arc connecting the two walls.",
)
editing_corner_id: bpy.props.IntProperty(
default=0,
options={"SKIP_SAVE"},
description=(
"IFC element id of an existing fillet corner being re-edited "
"(non-zero only on the pen-icon re-edit flow). The create "
"operator deletes this corner + its connections before recreating "
"with the new radius."
),
)
if TYPE_CHECKING:
is_active: bool
wall_a_id: int
wall_b_id: int
radius: float
editing_corner_id: int
class BIMPreviewProperties(PropertyGroup):
"""Umbrella for parametric-edit preview drafts attached to ``Scene``."""
wall_fillet: bpy.props.PointerProperty(type=BIMWallFilletPreviewProperties)
if TYPE_CHECKING:
wall_fillet: BIMWallFilletPreviewProperties
+2 -4
View File
@@ -430,7 +430,7 @@ class CycleStairType(bpy.types.Operator, gizmo.CycleTypeMixin):
bl_label = "Cycle Stair Type"
bl_options = {"REGISTER", "UNDO"}
props_getter = "get_stair_props"
props_getter = tool.Model.get_stair_props
type_literal = tool.Model.StairType
type_attr = "stair_type"
skip_element_check = True
@@ -580,7 +580,7 @@ class GizmoStairEdition(bpy.types.GizmoGroup, gizmo.BaseParametricGizmoGroup):
]
# Metadata-driven dispatch for props and preferences
props_getter = "get_stair_props"
props_getter = tool.Model.get_stair_props
gizmo_pref_name = "stair"
@classmethod
@@ -593,14 +593,12 @@ class GizmoStairEdition(bpy.types.GizmoGroup, gizmo.BaseParametricGizmoGroup):
"VIEW3D_GT_lock",
self.COLOR_BLUE,
"bim.toggle_stair_property",
prop_path="BIMStairProperties.total_length_lock",
property_name="total_length_lock",
)
self.tread_lock_gizmo = self.create_icon_gizmo(
"VIEW3D_GT_lock",
(1.0, 1.0, 1.0),
"bim.toggle_stair_property",
prop_path="BIMStairProperties.custom_tread_lock",
property_name="custom_tread_lock",
)
self.plus_gizmo = self.create_icon_gizmo(
+15 -3
View File
@@ -24,6 +24,7 @@ from typing import TYPE_CHECKING, Any
import bpy
from bpy.types import Panel
import ifcopenshell.util.unit
import bonsai.bim
import bonsai.tool as tool
from bonsai.bim.helper import prop_with_search
@@ -303,6 +304,8 @@ class BIM_PT_stair(bpy.types.Panel):
row = self.layout.row(align=True)
row.label(text="Stair parameters", icon="IPO_CONSTANT")
si_conversion = ifcopenshell.util.unit.calculate_unit_scale(tool.Ifc.get())
if props.is_editing:
calculated_params = tool.Model.get_active_stair_calculated_params()
row = self.layout.row(align=True)
@@ -322,16 +325,25 @@ class BIM_PT_stair(bpy.types.Panel):
row.label(text=f"{prop_name}:")
row = self.layout.row(align=True)
for prop_value_item in prop_value:
row.label(text=str(prop_value_item))
if isinstance(prop_value_item, float):
row.label(text=tool.Unit.format_distance(prop_value_item * si_conversion))
else:
row.label(text=str(prop_value_item))
else:
row.label(text=prop_name)
row.label(text=str(prop_value))
if isinstance(prop_value, float):
row.label(text=tool.Unit.format_distance(prop_value * si_conversion))
else:
row.label(text=str(prop_value))
# calculated properties
for prop_name, prop_value in calculated_params.items():
row = self.layout.row(align=True)
row.label(text=prop_name)
row.label(text=str(prop_value))
if isinstance(prop_value, float):
row.label(text=tool.Unit.format_distance(prop_value * si_conversion))
else:
row.label(text=str(prop_value))
else:
row = self.layout.row()
row.label(text="No Stair Found")
File diff suppressed because it is too large Load Diff
+3 -3
View File
@@ -558,8 +558,8 @@ class CycleWindowType(bpy.types.Operator, tool.Ifc.Operator, gizmo.CycleTypeMixi
bl_label = "Cycle Window Type"
bl_options = {"REGISTER", "UNDO"}
element_checker = "is_window"
props_getter = "get_window_props"
element_checker = tool.Parametric.is_window
props_getter = tool.Model.get_window_props
type_literal = tool.Model.WindowType
type_attr = "window_type"
@@ -745,7 +745,7 @@ class GizmoWindowEdition(bpy.types.GizmoGroup, gizmo.BaseParametricGizmoGroup):
DimensionGizmoConfig(attr_name="lining_offset", axis=(0, 1, 0), min_value=-10.0),
]
props_getter = "get_window_props"
props_getter = tool.Model.get_window_props
gizmo_pref_name = "window"
@classmethod
@@ -1294,9 +1294,15 @@ class Hotkey(bpy.types.Operator, tool.Ifc.Operator):
bpy.ops.bim.generate_space()
return
if self.active_material_usage == "LAYER2":
bpy.ops.bim.recalculate_wall()
if element and tool.Model.has_underside_connection(element):
bpy.ops.bim.regenerate_wall_to_underside()
else:
bpy.ops.bim.recalculate_wall()
elif self.active_material_usage == "LAYER3":
bpy.ops.bim.recalculate_slab()
wall_objs = tool.Model.get_connected_wall_objs(element)
if wall_objs:
core.regenerate_wall_to_underside(tool.Ifc, tool.Geometry, tool.Model, wall_objs)
elif tool.System.get_ports(element):
bpy.ops.bim.regenerate_distribution_element()
elif self.active_material_usage == "PROFILE":
@@ -63,6 +63,7 @@ import bonsai.core.project as core
import bonsai.tool as tool
from bonsai.bim import export_ifc, import_ifc
from bonsai.bim.ifc import IfcStore
from bonsai.bim.module.model import preview_base
from bonsai.bim.module.model.decorator import FaceAreaDecorator, PolylineDecorator
from bonsai.bim.module.model.polyline import PolylineOperator
from bonsai.bim.module.project.data import LinksData, ProjectLibraryData
@@ -1936,6 +1937,10 @@ class ExportIFC(bpy.types.Operator, ExportHelper):
def _execute(self, context):
committed, failed_commits = tool.Parametric.commit_pending_edits()
# Previews are session-transient — discard rather than commit. Sibling
# gizmo polls gate on each preview's is_active flag, and a stuck flag
# persisted through the save would silently hide them on reload.
preview_base.discard_pending_previews(context.scene)
# Suffix is appended to the IFC save-success report below so the auto-commit
# info isn't immediately overwritten by the success message in Blender's
# status bar (only the latest self.report({"INFO"}, ...) sticks).
@@ -302,6 +302,15 @@ class SelectSimilarContainer(bpy.types.Operator):
is_recursive=self.is_recursive,
)
self.is_recursive = True # <-- forcibly reset
element = tool.Ifc.get_entity(context.active_object)
if element:
container = tool.Spatial.get_container(element)
if container:
result = f'location="{container.Name}"'
bpy.context.window_manager.clipboard = result
self.report({"INFO"}, f"({result}) was copied to the clipboard.")
return {"FINISHED"}
+2 -1
View File
@@ -151,7 +151,8 @@ class BIM_PT_type_attributes(Panel):
row = layout.row(align=True)
row.label(text=attribute["name"])
value = get_display_value(attribute["value"])
row.label(text=value)
op = row.operator("bim.select_similar", text=value, icon="NONE", emboss=False)
op.key = "type." + attribute["name"]
def add_object_button(self, context):
+153 -4
View File
@@ -71,18 +71,16 @@ from __future__ import annotations
import json
from collections.abc import Callable
from typing import TYPE_CHECKING, ClassVar
from typing import ClassVar, get_args
import bpy
import ifcopenshell.util.element
from bpy.app.handlers import persistent
from ifcopenshell import entity_instance
import bonsai.core.geometry
import bonsai.tool as tool
if TYPE_CHECKING:
from ifcopenshell import entity_instance
class ParametricEditMixinBase:
"""Common scaffolding for parametric edit-lifecycle mixins.
@@ -379,6 +377,157 @@ class PathPreservingEditMixin(ParametricEditMixinBase):
return {"FINISHED"}
# --- Type-selection mixins (Cycle / Pick) ------------------------------------
class TypeAccessorBase:
"""Shared contract for operators that resolve and write a Literal type
attribute on a Bonsai PropertyGroup.
Subclasses define ``element_checker``, ``props_getter``, ``type_literal``,
``type_attr``; ``skip_element_check`` bypasses element validation. Concrete
subclasses (``CycleTypeMixin``, ``PickTypeMixin``) add the interaction
shape on top.
Test doubles must be set on the operator instance the predicates are
bound at class-definition time, so patching the underlying tool module
has no effect."""
element_checker: Callable[[entity_instance], bool]
props_getter: Callable[[bpy.types.Object], bpy.types.PropertyGroup]
type_literal: type
type_attr: str
skip_element_check: bool = False
def _resolve_target(self, context: bpy.types.Context) -> bpy.types.Object | None:
"""Return the active object iff it passes ``element_checker`` (or the
check is skipped). ``None`` signals the operator should bail with
``{'CANCELLED'}``."""
obj = context.active_object
if not obj:
return None
if not self.skip_element_check:
element = tool.Ifc.get_entity(obj)
if not element or not self.element_checker(element):
return None
return obj
class CycleTypeMixin(TypeAccessorBase):
"""Operator mixin that cycles through ``type_literal``'s values.
Shift-click reverses direction."""
reverse: bpy.props.BoolProperty(name="Reverse", default=False, options={"HIDDEN", "SKIP_SAVE"})
def invoke(self, context: bpy.types.Context, event: bpy.types.Event) -> set[str]:
self.reverse = event.shift
return self.execute(context)
def _cycle_type(self, context: bpy.types.Context) -> set[str]:
obj = self._resolve_target(context)
if obj is None:
return {"CANCELLED"}
props = self.props_getter(obj)
types = get_args(self.type_literal)
current = getattr(props, self.type_attr)
idx = types.index(current) if current in types else 0
direction = -1 if self.reverse else 1
setattr(props, self.type_attr, types[(idx + direction) % len(types)])
return {"FINISHED"}
class PickTypeMixin(TypeAccessorBase):
"""Operator mixin that opens a popup menu listing ``type_literal``'s values.
Empty ``value`` ``invoke`` opens the popup; non-empty the user picked
an item and ``_pick_type`` applies it.
When invoked mid-click (e.g. from a gizmo's ``target_set_operator``), the
menu opens only after the originating ``LEFTMOUSE`` releases. Otherwise
the still-pressed click flows straight into Blender's drag-through-pick
gesture and the menu commits whichever item the cursor drifts over on
release. Other invocation paths (command-palette / F3, EXEC_DEFAULT, F6
redo) bypass the wait and open the menu immediately.
The ``value`` StringProperty is declared on this mixin but registered via
the concrete Operator subclass's MRO scan — do not instantiate the mixin
standalone."""
# Carries the picked value through invoke→execute; empty default
# distinguishes "open popup" from "apply".
value: bpy.props.StringProperty(default="", options={"HIDDEN", "SKIP_SAVE"})
def invoke(self, context: bpy.types.Context, event: bpy.types.Event) -> set[str]:
"""Open the picker menu, or apply a value that was preset by a
menu-item click.
Routing through ``execute()`` keeps subclass IFC-transaction wrapping
in the loop and means F6 redo / ``EXEC_DEFAULT`` reach the apply path."""
if self.value:
return self.execute(context)
if self._resolve_target(context) is None:
return {"CANCELLED"}
if event.value == "PRESS":
context.window_manager.modal_handler_add(self)
return {"RUNNING_MODAL"}
return self._open_picker(context)
def modal(self, context: bpy.types.Context, event: bpy.types.Event) -> set[str]:
if event.type == "LEFTMOUSE" and event.value == "RELEASE":
self._open_picker(context)
# INTERFACE does not remove a modal handler; only FINISHED /
# CANCELLED do.
return {"CANCELLED"}
if event.type in {"RIGHTMOUSE", "ESC"}:
return {"CANCELLED"}
return {"RUNNING_MODAL"}
def _open_picker(self, context: bpy.types.Context) -> set[str]:
bl_idname = self.bl_idname
values = list(get_args(self.type_literal))
def draw(menu_self, _menu_context):
layout = menu_self.layout
for v in values:
op = layout.operator(bl_idname, text=v)
op.value = v
context.window_manager.popup_menu(draw, title=self.bl_label, icon="MENU_PANEL")
# The type change is a two-step interaction: this invocation just OPENS
# the menu (no state change yet); a SECOND invocation fires when the
# user clicks a menu item — that one writes ``props.<type_attr>`` and
# returns FINISHED. By returning INTERFACE here (and not FINISHED), the
# menu-open step is excluded from Blender's undo stack so the user
# gets exactly ONE undo entry per type change. If we returned FINISHED
# here too, the stack would gain a no-op "opened the menu" entry that
# Ctrl+Z would dismiss before reverting the actual type change —
# confusing UX where the first Ctrl+Z appears to do nothing.
return {"INTERFACE"}
def _pick_type(self, context: bpy.types.Context) -> set[str]:
if not self.value:
# No-op rather than re-open the menu, so command-palette misuse
# doesn't infinite-loop.
return {"CANCELLED"}
obj = self._resolve_target(context)
if obj is None:
return {"CANCELLED"}
if self.value not in get_args(self.type_literal):
self.report({"WARNING"}, f"Unknown {self.type_attr}: {self.value!r}")
return {"CANCELLED"}
props = self.props_getter(obj)
setattr(props, self.type_attr, self.value)
return {"FINISHED"}
# --- Undo-resync registry ----------------------------------------------------
#
# Per-type regenerators called from ``resync_parametric_drafts_after_undo``
+3
View File
@@ -93,6 +93,8 @@ def enter_aggregate_mode(
aggregator: type[tool.Aggregate],
obj: bpy.types.Object,
):
if not aggregator.get_aggregate_props().in_aggregate_mode:
aggregator.save_previous_selection()
aggregator.update_previous_aggregate_mode_state()
if aggregator.get_higher_aggregate():
aggregator.disable_aggregate_mode()
@@ -107,6 +109,7 @@ def exit_aggregate_mode(aggregator: type[tool.Aggregate]):
aggregator.enable_aggregate_mode(new_obj)
else:
aggregator.disable_aggregate_mode()
aggregator.restore_previous_selection()
class IncompatibleAggregateError(Exception):
+57 -7
View File
@@ -161,23 +161,73 @@ def align_objects(
model.align_objects(reference_obj, objs, align_type)
def regenerate_wall_to_underside(
ifc: type[tool.Ifc],
geometry: type[tool.Geometry],
model: type[tool.Model],
wall_objs: list[bpy.types.Object],
) -> None:
"""Re-clip walls to their connected underside objects after the slab has moved."""
clipped_objs = []
for obj in wall_objs:
wall = ifc.get_entity(obj)
slab_objs = model.get_connected_slab_objs(wall)
if not slab_objs:
continue
if ifc.is_moved(obj):
geometry.run_edit_object_placement(obj=obj)
# Sync each slab's Blender mesh to its current IFC representation before
# reading face geometry, so a changed profile is picked up correctly.
model.reload_body_representation(slab_objs)
model.remove_wall_to_underside_booleans(wall)
for slab_obj in slab_objs:
clip = model.get_slab_clipping_bmesh(slab_obj)
if clip:
model.clip_wall_to_slab(wall, clip)
clipped_objs.append(obj)
if clipped_objs:
model.reload_body_representation(clipped_objs)
def extend_wall_to_slab(
ifc: type[tool.Ifc],
geometry: type[tool.Geometry],
model: type[tool.Model],
slab_obj: bpy.types.Object,
slab_objs: list[bpy.types.Object],
wall_objs: list[bpy.types.Object],
) -> None:
if not (clip := model.get_slab_clipping_bmesh(slab_obj)):
return # Nothing to clip?
slab = ifc.get_entity(slab_obj)
# If any wall is currently in item mode, exit it before modifying the
# representation. Leaving stale item objects around causes delete_ifc_item
# to later remove the extrusion (or other pre-boolean items) from inside
# the boolean chain, corrupting the IFC model.
geom_props = geometry.get_geometry_props()
if geom_props.representation_obj in wall_objs:
geometry.disable_item_mode()
clipped_walls = []
for obj in wall_objs:
if ifc.is_moved(obj):
geometry.run_edit_object_placement(obj=obj)
wall = ifc.get_entity(obj)
model.clip_wall_to_slab(wall, clip)
model.connect_wall_to_slab(wall, slab)
model.reload_body_representation(wall_objs)
# Merge previously connected slabs with newly requested ones so that
# re-running the operator never produces duplicate booleans and never
# silently discards clips that were applied in an earlier call.
existing = model.get_connected_slab_objs(wall)
seen = {id(s) for s in existing}
all_slab_objs = list(existing) + [s for s in slab_objs if id(s) not in seen]
# Remove stale booleans once, then re-clip against the full set.
model.remove_wall_to_underside_booleans(wall)
did_clip = False
for slab_obj in all_slab_objs:
clip = model.get_slab_clipping_bmesh(slab_obj)
if not clip:
continue
model.clip_wall_to_slab(wall, clip)
model.connect_wall_to_slab(wall, ifc.get_entity(slab_obj))
did_clip = True
if did_clip:
clipped_walls.append(obj)
if clipped_walls:
model.reload_body_representation(clipped_walls)
class RequireTwoWallsError(Exception):
+2 -1
View File
@@ -67,7 +67,8 @@ def assign_container(
if products := [e for e in root_elements if spatial.can_contain(container, root_element)]:
ifc.run("spatial.assign_container", products=products, relating_structure=container)
for element in all_elements:
collector.assign(ifc.get_object(element))
if obj := ifc.get_object(element):
collector.assign(obj)
def enable_editing_container(spatial: type[tool.Spatial], obj: bpy.types.Object) -> None:
+4
View File
@@ -681,6 +681,9 @@ class Model:
def export_profile(cls, obj, position=None): pass
def generate_occurrence_name(cls, element_type, ifc_class): pass
def get_extrusion(cls, representation): pass
def get_connected_slab_objs(cls, wall): pass
def get_connected_wall_objs(cls, slab): pass
def has_underside_connection(cls, element): pass
def get_manual_booleans(cls, element): pass
def get_material_layer_parameters(cls, element): pass
def get_slab_clipping_bmesh(cls, obj): pass
@@ -696,6 +699,7 @@ class Model:
def regenerate_profile(cls, obj): pass
def regenerate_slab(cls, obj): pass
def reload_body_representation(cls, obj_or_objects): pass
def remove_wall_to_underside_booleans(cls, wall): pass
def replace_object_ifc_representation(cls, ifc_file, ifc_context, obj, new_representation): pass
+21
View File
@@ -205,6 +205,27 @@ class Aggregate(bonsai.core.tool.Aggregate):
props.in_aggregate_mode = True
return {"FINISHED"}
@classmethod
def save_previous_selection(cls) -> None:
props = cls.get_aggregate_props()
props.previously_selected_objects.clear()
for obj in bpy.context.selected_objects:
entry = props.previously_selected_objects.add()
entry.obj = obj
@classmethod
def restore_previous_selection(cls) -> None:
props = cls.get_aggregate_props()
for obj in bpy.context.selected_objects:
obj.select_set(False)
for entry in props.previously_selected_objects:
if entry.obj:
try:
entry.obj.select_set(True)
except Exception:
pass
props.previously_selected_objects.clear()
@classmethod
def disable_aggregate_mode(cls):
context = bpy.context
+1
View File
@@ -135,6 +135,7 @@ class Collector(bonsai.core.tool.Collector):
if element.is_a("IfcFeatureElementSubtraction"):
obj.display_type = "WIRE"
obj.display.show_shadows = False
@classmethod
def _create_project_child_collection(cls, name: str) -> bpy.types.Collection:
+42 -6
View File
@@ -257,7 +257,13 @@ class Geometry(bonsai.core.tool.Geometry):
break
mesh = obj.data
assert isinstance(mesh, bpy.types.Mesh)
item = tool.Ifc.get().by_id(tool.Geometry.get_mesh_props(mesh).ifc_definition_id)
item_id = tool.Geometry.get_mesh_props(mesh).ifc_definition_id
try:
item = tool.Ifc.get().by_id(item_id)
except RuntimeError:
# Entity already deleted (e.g. removed as part of a sibling boolean collapse).
bpy.data.objects.remove(obj)
return
rep_obj = props.representation_obj
assert (rep_obj := props.representation_obj) and (rep_element := tool.Ifc.get_entity(rep_obj))
cls.remove_representation_item(item, rep_element)
@@ -421,6 +427,29 @@ class Geometry(bonsai.core.tool.Geometry):
bm.free()
del mesh["ios_edges"]
@classmethod
def get_dissolved_edges(
cls,
mesh: bpy.types.Mesh,
angle_limit: float = radians(1.0),
) -> tuple[list[Vector], list[tuple[int, int]]]:
# Read-only on `mesh`: builds a throwaway bmesh, dissolves coplanar
# edges while preserving material seams, returns wire-overlay data.
bm = bmesh.new()
bm.from_mesh(mesh)
bmesh.ops.dissolve_limit(
bm,
angle_limit=angle_limit,
verts=bm.verts,
edges=bm.edges,
delimit={"MATERIAL"},
)
bm.verts.index_update()
verts = [v.co.copy() for v in bm.verts]
edges = [(e.verts[0].index, e.verts[1].index) for e in bm.edges]
bm.free()
return verts, edges
@classmethod
def apply_item_ids_as_vertex_groups(cls, obj: bpy.types.Object) -> None:
"""Save mesh-object item_ids as vertex groups in format 'ios_item_id_xxxx'.
@@ -1134,11 +1163,16 @@ class Geometry(bonsai.core.tool.Geometry):
@classmethod
def get_representation_item(cls, obj: bpy.types.Object) -> Union[ifcopenshell.entity_instance, None]:
data = obj.data
if (
isinstance(data, Geometry.TYPES_WITH_MESH_PROPERTIES)
and (ifc_id := tool.Geometry.get_mesh_props(data).ifc_definition_id)
and ((item := tool.Ifc.get().by_id(ifc_id)).is_a("IfcRepresentationItem"))
):
if not isinstance(data, Geometry.TYPES_WITH_MESH_PROPERTIES):
return None
ifc_id = tool.Geometry.get_mesh_props(data).ifc_definition_id
if not ifc_id:
return None
try:
item = tool.Ifc.get().by_id(ifc_id)
except RuntimeError:
return None
if item.is_a("IfcRepresentationItem"):
return item
return None
@@ -1312,6 +1346,8 @@ class Geometry(bonsai.core.tool.Geometry):
cls, representation: ifcopenshell.entity_instance
) -> ifcopenshell.entity_instance:
if representation.RepresentationType == "MappedRepresentation":
if not representation.Items:
return representation
return cls.resolve_mapped_representation(representation.Items[0].MappingSource.MappedRepresentation)
return representation
+123 -20
View File
@@ -351,6 +351,8 @@ class Model(bonsai.core.tool.Model):
@classmethod
def get_extrusion(cls, representation: ifcopenshell.entity_instance) -> Union[ifcopenshell.entity_instance, None]:
"""Return first found IfcExtrudedAreaSolid"""
if not representation.Items:
return None
item = representation.Items[0]
while True:
if item.is_a("IfcExtrudedAreaSolid"):
@@ -843,6 +845,57 @@ class Model(bonsai.core.tool.Model):
items.append(item.FirstOperand)
return booleans
@classmethod
def get_connected_slab_objs(cls, wall: ifcopenshell.entity_instance) -> list[bpy.types.Object]:
"""Return Blender objects for slabs connected to wall via IfcRelConnectsElements(TOP)."""
result = []
for rel in wall.ConnectedFrom:
if rel.is_a("IfcRelConnectsElements") and rel.Description == "TOP":
slab_obj = tool.Ifc.get_object(rel.RelatingElement)
if slab_obj:
result.append(slab_obj)
return result
@classmethod
def get_connected_wall_objs(cls, slab: ifcopenshell.entity_instance) -> list[bpy.types.Object]:
"""Return Blender objects for LAYER2 walls connected to slab via IfcRelConnectsElements(TOP)."""
result = []
for rel in slab.ConnectedTo:
if rel.is_a("IfcRelConnectsElements") and rel.Description == "TOP":
wall_obj = tool.Ifc.get_object(rel.RelatedElement)
if wall_obj:
result.append(wall_obj)
return result
@classmethod
def has_underside_connection(cls, element: ifcopenshell.entity_instance) -> bool:
"""Return True if element has an IfcRelConnectsElements(TOP) relationship."""
return any(rel.is_a("IfcRelConnectsElements") and rel.Description == "TOP" for rel in element.ConnectedFrom)
@classmethod
def remove_wall_to_underside_booleans(cls, wall: ifcopenshell.entity_instance) -> None:
"""Remove all IfcBooleanResult items previously added by extend_walls_to_underside."""
manual_booleans = cls.get_manual_booleans(wall)
if not manual_booleans:
return
ifc_file = tool.Ifc.get()
for b in manual_booleans:
sec = b.SecondOperand
if sec is None:
# The IfcPolygonalFaceSet was already deleted externally. Splice the
# orphaned IfcBooleanResult out of the chain so the representation stays valid.
parents = list(ifc_file.get_inverse(b))
for parent in parents:
if parent.is_a("IfcBooleanResult") and parent.FirstOperand == b:
parent.FirstOperand = b.FirstOperand
elif parent.is_a("IfcShapeRepresentation"):
new_items = tuple((set(parent.Items) - {b}) | {b.FirstOperand})
parent.Items = new_items
cls.unmark_manual_booleans(wall, [b.id()])
ifc_file.remove(b)
elif sec.is_a("IfcTessellatedFaceSet"):
tool.Geometry.remove_representation_item(sec, wall)
@classmethod
def get_manual_booleans(
cls, element: ifcopenshell.entity_instance, representation: Optional[ifcopenshell.entity_instance] = None
@@ -855,7 +908,8 @@ class Model(bonsai.core.tool.Model):
representation = tool.Geometry.get_body_representation(element)
if not representation:
return []
booleans = [b for b in cls.get_booleans(element, representation) if b.id() in boolean_ids]
all_chain_booleans = cls.get_booleans(element, representation)
booleans = [b for b in all_chain_booleans if b.id() in boolean_ids]
return booleans
@classmethod
@@ -2557,12 +2611,15 @@ class Model(bonsai.core.tool.Model):
clipping_bm = bmesh.new()
vertex_map = {}
kept = 0
for face in bm.faces:
face.normal_update()
normal = face.normal.to_4d()
normal.w = 0
if (obj.matrix_world @ normal).z >= -0.5:
world_normal_z = (obj.matrix_world @ normal).z
if world_normal_z >= -0.5:
continue
kept += 1
new_verts = []
for vert in face.verts:
if not (new_vert := vertex_map.get(vert.index, None)):
@@ -2575,6 +2632,7 @@ class Model(bonsai.core.tool.Model):
return
bmesh.ops.recalc_face_normals(clipping_bm, faces=clipping_bm.faces)
clipping_bm.faces.ensure_lookup_table()
return clipping_bm # clipping_bm is in project units
@classmethod
@@ -2588,17 +2646,53 @@ class Model(bonsai.core.tool.Model):
min_z = min(zs)
max_z = max(zs)
operand = None
if (z := max_z - min_z) and not np.isclose(z, 0.0):
builder = ifcopenshell.util.shape_builder.ShapeBuilder(tool.Ifc.get())
ifc_file = tool.Ifc.get()
builder = ifcopenshell.util.shape_builder.ShapeBuilder(ifc_file)
result = bmesh.ops.extrude_face_region(bm, geom=bm.faces)
extruded_verts = [elem for elem in result["geom"] if isinstance(elem, bmesh.types.BMVert)]
bmesh.ops.translate(bm, verts=extruded_verts, vec=(0, 0, z))
# Build one IfcPolygonalFaceSet clip solid per clipping face.
# Each solid uses a rectangle on the slope plane rather than the exact face
# footprint. The original approach (exact footprint) caused a kissing-solid /
# boundary-coincidence bug when the operator is called twice for a ridge roof: the
# two slope solids share an exact ridge edge, and OCCT produces spurious extra
# vertices. Extending each solid slightly past the ridge (by margin) creates a
# volumetric overlap instead of a kissing boundary — OCCT handles overlapping
# DIFFERENCE operands correctly.
margin = 1.0 # project units past the face edge — enough to ensure overlap at ridge
operands = []
for face in bm.faces:
face.normal_update()
normal = Vector(face.normal).normalized()
verts = [v.co for v in bm.verts]
faces = [[v.index for v in p.verts] for p in bm.faces]
operand = builder.mesh(verts, faces)
# Orthonormal basis spanning the slope plane.
ref = Vector((0, 0, 1)) if abs(normal.z) < 0.9 else Vector((1, 0, 0))
tangent1 = normal.cross(ref).normalized()
tangent2 = normal.cross(tangent1).normalized()
centroid = sum((v.co for v in face.verts), Vector()) / len(face.verts)
# Tight bounding rectangle in slope-plane coords, plus a small margin.
t1_coords = [(v.co - centroid).dot(tangent1) for v in face.verts]
t2_coords = [(v.co - centroid).dot(tangent2) for v in face.verts]
half1 = max(abs(c) for c in t1_coords) + margin
half2 = max(abs(c) for c in t2_coords) + margin
# Rectangle on the slope plane, extruded upward in wall-local Z.
clip_bm = bmesh.new()
v0 = clip_bm.verts.new(centroid + half1 * tangent1 + half2 * tangent2)
v1 = clip_bm.verts.new(centroid - half1 * tangent1 + half2 * tangent2)
v2 = clip_bm.verts.new(centroid - half1 * tangent1 - half2 * tangent2)
v3 = clip_bm.verts.new(centroid + half1 * tangent1 - half2 * tangent2)
bottom_face = clip_bm.faces.new([v0, v1, v2, v3])
result = bmesh.ops.extrude_face_region(clip_bm, geom=[bottom_face])
top_verts = [e for e in result["geom"] if isinstance(e, bmesh.types.BMVert)]
bmesh.ops.translate(clip_bm, verts=top_verts, vec=Vector((0, 0, max_z - min_z)))
clip_bm.verts.ensure_lookup_table()
clip_verts = [v.co for v in clip_bm.verts]
clip_faces = [[v.index for v in f.verts] for f in clip_bm.faces]
operand = builder.mesh(clip_verts, clip_faces)
clip_bm.free()
operands.append(operand)
for extrusion in ifcopenshell.util.shape.get_base_extrusions(wall) or []:
if extrusion.Position:
@@ -2615,10 +2709,9 @@ class Model(bonsai.core.tool.Model):
extrusion.Depth = max_z / direction[2]
if operand:
booleans = ifcopenshell.api.geometry.add_boolean(
tool.Ifc.get(), first_item=extrusion, second_items=[operand]
)
if operands:
body_repr = ifcopenshell.util.representation.get_representation(wall, "Model", "Body", "MODEL_VIEW")
booleans = ifcopenshell.api.geometry.add_boolean(ifc_file, first_item=extrusion, second_items=operands)
tool.Model.mark_manual_booleans(wall, booleans)
@classmethod
@@ -2871,10 +2964,20 @@ class Model(bonsai.core.tool.Model):
@classmethod
def recreate_wall(cls, element: ifcopenshell.entity_instance, obj: bpy.types.Object) -> None:
# FIXME(PR4): the fillet-corner branch lands with PR4's
# `regenerate_fillet_corner_wall` (bim/module/model/wall.py). On v0.8.0
# the function doesn't exist; falling through to the straight-extrusion
# path preserves v0.8.0 behaviour for fillet walls until PR4 ships.
# Curved fillet-corner walls own a hand-built banana body that
# ``regenerate_wall_representation`` would flatten — it reads the axis
# as a 2-point reference line and builds a straight extrusion. Rebuild
# the curve in place instead: ``regenerate_fillet_corner_wall`` keeps
# radius + placement from the pset / current ``ObjectPlacement`` while
# picking up new thickness / height from the wall type, which is what
# we want when a type-property edit triggered this call.
if tool.Parametric.is_fillet_corner_wall(element):
# Lazy import: ``tool.Model`` loads before ``bim/module/model`` at
# addon enable; a module-level import would cycle.
from bonsai.bim.module.model.wall import regenerate_fillet_corner_wall
regenerate_fillet_corner_wall(element, obj)
return
rep = ifcopenshell.api.geometry.regenerate_wall_representation(tool.Ifc.get(), element)
bonsai.core.geometry.switch_representation(
tool.Ifc,
@@ -2909,7 +3012,7 @@ class Model(bonsai.core.tool.Model):
if not wall:
continue
is_layer2_usage = tool.Model.get_usage_type(element) == "LAYER2"
is_fillet_corner = bool(ifcopenshell.util.element.get_pset(element, "BBIM_Wall", "IsFilletCorner"))
is_fillet_corner = tool.Parametric.is_fillet_corner_wall(element)
if not (is_layer2_usage or is_fillet_corner):
continue
if is_layer2_usage:
+7
View File
@@ -487,6 +487,13 @@ class Parametric(bonsai.core.tool.Parametric):
return False
if tool.Model.get_usage_type(element) == "LAYER2":
return True
return cls.is_fillet_corner_wall(element)
@classmethod
def is_fillet_corner_wall(cls, element: entity_instance) -> bool:
"""``True`` if the wall carries the ``BBIM_Wall.IsFilletCorner`` flag,
marking it as a curved corner whose banana body is hand-built rather
than regenerated from the wall's axis + layer set."""
import ifcopenshell.util.element
return bool(ifcopenshell.util.element.get_pset(element, "BBIM_Wall", "IsFilletCorner"))
+145 -58
View File
@@ -373,26 +373,42 @@ class Raycast(bonsai.core.tool.Raycast):
except:
loc = Vector((0, 0, 0))
verts_2d = [
view3d_utils.location_3d_to_region_2d(region, rv3d, v) for v in snap_obj.verts_3d
] # Numpy version is worst in performance
snap_obj._ensure_bvh()
intersected = snap_obj.raycast_boxes(
context, event, snap_obj.root, intersected=[], rays=(ray_origin, ray_direction)
)
# Collect edges from intersected BVH boxes
edges = []
for it in intersected:
edges.extend(it.edges)
edges = set(edges)
# Build only the vertices indices that belong to these edges
verts_idx: set[int] = set()
for e in edges:
ev = snap_obj.obj.data.edges[e].vertices
verts_idx.add(ev[0])
verts_idx.add(ev[1])
# Lazily project only the needed vertices to 2D screen space
verts_2d: dict[int, Vector] = {}
for idx in verts_idx:
v2d = view3d_utils.location_3d_to_region_2d(
region, rv3d, snap_obj.verts_3d[idx]
)
if v2d is not None:
verts_2d[idx] = v2d
edge_verts = {}
for e in edges:
verts_idx = tuple(snap_obj.obj.data.edges[e].vertices)
verts = snap_obj.obj.data.vertices
v1 = snap_obj.obj.matrix_world @ verts[verts_idx[0]].co
v1_2d = verts_2d[verts_idx[0]]
v2 = snap_obj.obj.matrix_world @ verts[verts_idx[1]].co
v2_2d = verts_2d[verts_idx[1]]
verts_idx = snap_obj.obj.data.edges[e].vertices
v1 = snap_obj.verts_3d[verts_idx[0]]
v2 = snap_obj.verts_3d[verts_idx[1]]
v1_2d = verts_2d.get(verts_idx[0])
v2_2d = verts_2d.get(verts_idx[1])
if (v1_2d is None) ^ (v2_2d is None):
point, _ = cls.intersect_edge_region_border(region, context.space_data, rv3d, v1, v2)
if v1_2d is None:
@@ -404,10 +420,16 @@ class Raycast(bonsai.core.tool.Raycast):
snap_threshold = 10.0
for i, point in enumerate(verts_2d):
if not point:
continue
distance = (Vector(mouse_pos) - point).length
# Check all vertices for proximity to mouse position.
# Re-use the 2D projections already computed for edge endpoints.
for i, v3d in enumerate(snap_obj.verts_3d):
if i in verts_2d:
v2d = verts_2d[i]
else:
v2d = view3d_utils.location_3d_to_region_2d(region, rv3d, v3d)
if v2d is None:
continue
distance = (Vector(mouse_pos) - v2d).length
if distance <= snap_threshold:
snap_point = {
"object": snap_obj.obj,
@@ -799,6 +821,30 @@ class Raycast(bonsai.core.tool.Raycast):
else:
return None, None, None
@classmethod
def process_wireframe_snap_obj(
cls,
context: bpy.types.Context,
event: bpy.types.Event,
snap_obj,
ray_origin: Vector,
closest_snaps: list,
):
snap_points = tool.Raycast.ray_cast_by_proximity_2d(context, event, snap_obj)
hit_obj = None
hit = None
if snap_points:
closest_length_squared = float("inf")
for point in snap_points:
point["group"] = "Wireframe"
closest_snaps.append(point)
length = (point["point"] - ray_origin).length_squared
if length < closest_length_squared:
closest_length_squared = length
hit = point["point"]
hit_obj = point["object"]
return hit_obj, hit
@classmethod
def ray_cast_and_get_closest_to_camera_snaps(
cls,
@@ -813,35 +859,45 @@ class Raycast(bonsai.core.tool.Raycast):
ray_origin, ray_target, ray_direction = cls.get_viewport_ray_data(context, event)
space = context.space_data
xray_mode = (space.shading.type == "SOLID" and space.shading.show_xray) or (
space.shading.type == "WIREFRAME" and space.shading.show_xray_wireframe
)
closest_snaps = []
hit = None
for snap_obj in objs_to_raycast:
if snap_obj.obj.type in {"EMPTY", "CURVE"} or (
hasattr(snap_obj.obj.data, "polygons") and len(snap_obj.obj.data.polygons) == 0
):
# For wireframe objects we have to test all the snaps to see which is closer
snap_points = tool.Raycast.ray_cast_by_proximity_2d(context, event, snap_obj)
closest_wf_hit = None
closest_wf_length_squared = 1.0
closest_wf_point = None
if snap_points:
for point in snap_points:
point["group"] = "Wireframe"
closest_snaps.append(point)
length = (point["point"] - ray_origin).length_squared
if closest_wf_hit is None or length < closest_wf_length_squared:
closest_wf_length_squared = length
closest_wf_hit = point["point"]
closest_wf_point = point
if not xray_mode and objs_to_raycast:
# Non-xray - only the closest solid object's Face snap is kept by
# the caller (detect_snapping_points). Process solids in distance
# order and stop at the first hit to minimise raycasts.
wireframe_objs = []
solid_objs = []
for snap_obj in objs_to_raycast:
if snap_obj.obj.type in {"EMPTY", "CURVE"} or (
hasattr(snap_obj.obj.data, "polygons") and len(snap_obj.obj.data.polygons) == 0
):
wireframe_objs.append(snap_obj)
else:
solid_objs.append(snap_obj)
if closest_wf_point:
hit_obj = closest_wf_point["object"]
hit = closest_wf_point["point"]
face_index = None
# Rough distance - object origin to ray origin
solid_objs.sort(key=lambda so: (so.obj.matrix_world.translation - ray_origin).length_squared)
else:
# Solid objects
# Process wireframe objects first (all of them, always collected)
for snap_obj in wireframe_objs:
hit_obj, hit = cls.process_wireframe_snap_obj(
context, event, snap_obj, ray_origin, closest_snaps
)
if hit is not None:
length_squared = (hit - ray_origin).length_squared
if closest_obj is None or length_squared < closest_length_squared:
closest_length_squared = length_squared
closest_obj = hit_obj
closest_hit = hit
closest_face_index = None
# Process solid objects in distance order, stop at first hit
for snap_obj in solid_objs:
hit_obj, hit, face_index = cls.cast_rays_to_single_object(context, event, snap_obj.obj)
if hit:
@@ -855,14 +911,47 @@ class Raycast(bonsai.core.tool.Raycast):
}
closest_snaps.append(snap_point)
# Here we test which is closer, including wireframe and solid objects
if hit is not None:
length_squared = (hit - ray_origin).length_squared
if closest_obj is None or length_squared < closest_length_squared:
closest_length_squared = length_squared
closest_obj = hit_obj
closest_hit = hit
closest_face_index = face_index
length_squared = (hit - ray_origin).length_squared
if closest_obj is None or length_squared < closest_length_squared:
closest_length_squared = length_squared
closest_obj = hit_obj
closest_hit = hit
closest_face_index = face_index
break
else:
# Xray mode - process all objects (all snaps are kept by the caller)
for snap_obj in objs_to_raycast:
if snap_obj.obj.type in {"EMPTY", "CURVE"} or (
hasattr(snap_obj.obj.data, "polygons") and len(snap_obj.obj.data.polygons) == 0
):
hit_obj, hit = cls.process_wireframe_snap_obj(
context, event, snap_obj, ray_origin, closest_snaps
)
face_index = None
else:
# Solid objects
hit_obj, hit, face_index = cls.cast_rays_to_single_object(context, event, snap_obj.obj)
if hit:
snap_point = {
"point": hit,
"type": "Face",
"group": "Object",
"object": hit_obj,
"face_index": face_index,
"distance": 9, # High value so it has low priority
}
closest_snaps.append(snap_point)
if hit is not None:
length_squared = (hit - ray_origin).length_squared
if closest_obj is None or length_squared < closest_length_squared:
closest_length_squared = length_squared
closest_obj = hit_obj
closest_hit = hit
closest_face_index = face_index
# Label snaps from the closest object
if closest_obj is not None:
@@ -888,15 +977,6 @@ class Raycast(bonsai.core.tool.Raycast):
def create_snap_obj(cls, obj):
if obj.data is None or not isinstance(obj.data, bpy.types.Mesh):
return None
# Evict cached entries whose Blender object has since been freed.
valid = []
for s in cls.snap_objs:
try:
_ = s.obj.name
valid.append(s)
except ReferenceError:
pass
cls.snap_objs[:] = valid
for i, snap_obj in enumerate(cls.snap_objs):
if obj.name == snap_obj.obj.name:
# Handle objects modified while a modal operator is active.
@@ -945,12 +1025,19 @@ class SnapObj:
def __init__(self, obj: bpy.types.Object):
self.__class__.all.append(self)
self.obj = obj
self.root = self._create_root_node()
self.root.edges = [e.index for e in obj.data.edges]
self.split_box(self.root, 0)
self.root = None
self._bvh_built = False
self.verts_3d = [obj.matrix_world @ v.co for v in obj.data.vertices]
self.snap_points = []
def _ensure_bvh(self):
if self._bvh_built:
return
self.root = self._create_root_node()
self.root.edges = [e.index for e in self.obj.data.edges]
self.split_box(self.root, 0)
self._bvh_built = True
def __clear_all__():
for instance in SnapObj.all:
del instance
@@ -0,0 +1,96 @@
# Bonsai - OpenBIM Blender Add-on
# Copyright (C) 2026
#
# This file is part of Bonsai.
#
# Bonsai is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Bonsai is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Bonsai. If not, see <http://www.gnu.org/licenses/>.
#
# This file was generated with the assistance of an AI coding tool.
"""Behaviour contracts for the wall-fillet operator chain.
Each fillet operator's geometry path requires real Blender + IFC fixtures
(walls with IfcMaterialLayerSetUsage, neighbour rels, etc.). End-to-end
fillet round-trips belong in the bim feature suite (model.feature) where
that scaffolding already exists. This file pins the surface-level invariants
that don't depend on the geometry path:
* the lifecycle operators are registered under their conventional bl_idnames,
* the enable poll rejects ineligible selections.
State-clearing tests via ``bpy.ops.bim.cancel_wall_fillet_preview()`` were
removed because the dispatch is flaky in full-suite ordering the operator
early-returns when ``context.screen`` is unattached and prior tests can leave
the screen in that state. The behaviour is covered by the user-visible live
test loop instead."""
import types
import bpy
import pytest
pytestmark = pytest.mark.model
@pytest.fixture(autouse=True)
def _require_real_bpy():
if not isinstance(bpy, types.ModuleType) or hasattr(bpy, "_mock_name"):
pytest.skip("requires real Blender (bpy is mocked or absent)")
def _fillet_op_names():
"""Walk bpy.ops.bim for operators whose name contains ``wall_fillet`` —
avoids hard-coding the five lifecycle bl_idnames so adding / renaming
one updates discovery automatically. Each name maps to a callable
operator."""
return sorted(name for name in dir(bpy.ops.bim) if "wall_fillet" in name)
class TestFilletOperatorsRegistered:
"""Catches accidental deregistration of any fillet lifecycle operator —
drops in the classes tuple of bim/module/model/__init__.py would otherwise
leave the gizmo group's target_set_operator binding pointing at a missing
op and crash the first time a user clicked the icon."""
def test_at_least_the_expected_lifecycle_set_is_registered(self):
names = _fillet_op_names()
# The lifecycle has enable + finish + cancel as a minimum; a healthy
# build also includes the from-corner re-edit entry and the create
# operator the finish dispatches to. The test asserts at least four —
# below that the feature can't function — without enumerating each
# by name, so the test stays meaningful if one is renamed or merged.
assert len(names) >= 4, (
f"Only {len(names)} fillet operators found on bpy.ops.bim: {names}. "
"The fillet lifecycle needs enable + finish + cancel + create at "
"minimum; check bim/module/model/__init__.py classes tuple."
)
def test_every_discovered_fillet_op_is_callable(self):
for name in _fillet_op_names():
op = getattr(bpy.ops.bim, name)
assert callable(op), f"bpy.ops.bim.{name} is not callable — registration broke?"
class TestEnableRejectsIneligibleSelection:
"""The preview enable operator requires a specific 2-wall selection
(LAYER2 walls with straight axes). With no selection at all, poll
must return False so the operator is greyed-out in menus instead of
crashing on dispatch."""
def test_enable_poll_returns_false_with_no_selection(self):
# Deselect everything in the default scene; no IfcWall is present
# in a fresh bpy_extras context anyway, so poll() must short-circuit.
bpy.ops.object.select_all(action="DESELECT")
bpy.context.view_layer.update()
assert bpy.ops.bim.enable_wall_fillet_preview.poll() is False
@@ -0,0 +1,521 @@
# Bonsai - OpenBIM Blender Add-on
# Copyright (C) 2026
#
# This file is part of Bonsai.
#
# Bonsai is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Bonsai is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Bonsai. If not, see <http://www.gnu.org/licenses/>.
#
# This file was generated with the assistance of an AI coding tool.
"""Tests for tool.Geometry.get_dissolved_edges and the opening-decoration cache
layers. The dissolve helper's contract:
- Read-only on the input mesh.
- Returns (verts_local, edge_indices) indexed into the dissolved bmesh.
- Material seams survive (delimit=MATERIAL).
- Default angle threshold is 1°."""
from math import radians
import bmesh
import bpy
import pytest
from mathutils import Matrix, Vector
import bonsai.tool as tool
from bonsai.bim import decorator_cache
from bonsai.bim.module.model import opening as opening_module
pytestmark = pytest.mark.model
@pytest.fixture(autouse=True)
def _reset_decoration_caches():
# Tests share module-global state (dissolve cache + token, world-draw-data
# cache, batch cache, per-object epochs). Reset every layer so a previous
# test can't poison hit/miss assertions.
decorator_cache.reset_for_test()
opening_module._dissolved_edges_cache.clear()
opening_module._dissolved_edges_cache_token = -1
opening_module._world_draw_data_cache.clear()
opening_module._batch_cache.clear()
opening_module._object_epochs.clear()
yield
decorator_cache.reset_for_test()
opening_module._dissolved_edges_cache.clear()
opening_module._world_draw_data_cache.clear()
opening_module._batch_cache.clear()
opening_module._object_epochs.clear()
def _make_mesh(name: str, verts: list[tuple[float, float, float]], faces: list[tuple[int, ...]]) -> bpy.types.Mesh:
mesh = bpy.data.meshes.new(name)
mesh.from_pydata(verts, [], faces)
mesh.update()
return mesh
def _edge_count(mesh: bpy.types.Mesh) -> int:
bm = bmesh.new()
bm.from_mesh(mesh)
n = len(bm.edges)
bm.free()
return n
def test_collapses_coplanar_diagonal_on_triangulated_quad():
# Triangulated unit quad in the XY plane: 4 verts, 2 tris share a diagonal.
# Raw bmesh has 5 edges (4 quad sides + 1 diagonal). Dissolve must drop the
# diagonal because both triangles are perfectly coplanar.
mesh = _make_mesh(
"quad_tri",
verts=[(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)],
faces=[(0, 1, 2), (0, 2, 3)],
)
assert _edge_count(mesh) == 5
verts, edges = tool.Geometry.get_dissolved_edges(mesh)
assert len(verts) == 4
assert len(edges) == 4
# Every returned edge index must point into the returned verts list.
for a, b in edges:
assert 0 <= a < len(verts)
assert 0 <= b < len(verts)
assert a != b
def test_preserves_real_edges_on_cube():
# Default cube has 8 verts / 12 edges / 6 quad faces. There are no coplanar
# internal splits to dissolve, so the helper must return the cube intact.
mesh = bpy.data.meshes.new("cube")
bm = bmesh.new()
bmesh.ops.create_cube(bm, size=1.0)
bm.to_mesh(mesh)
bm.free()
verts, edges = tool.Geometry.get_dissolved_edges(mesh)
assert len(verts) == 8
assert len(edges) == 12
def test_preserves_material_seam_on_coplanar_split():
# Two coplanar triangles sharing an edge but each with a different
# material_index. delimit=MATERIAL must keep the shared edge alive.
mesh = _make_mesh(
"split_mat",
verts=[(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)],
faces=[(0, 1, 2), (0, 2, 3)],
)
mat_a = bpy.data.materials.new("mat_a")
mat_b = bpy.data.materials.new("mat_b")
mesh.materials.append(mat_a)
mesh.materials.append(mat_b)
mesh.polygons[0].material_index = 0
mesh.polygons[1].material_index = 1
mesh.update()
verts, edges = tool.Geometry.get_dissolved_edges(mesh)
# The 4 perimeter edges plus the shared diagonal: 5 total survive.
assert len(verts) == 4
assert len(edges) == 5
bpy.data.materials.remove(mat_a)
bpy.data.materials.remove(mat_b)
def test_does_not_mutate_input_mesh():
# The helper must be read-only: viewport draw handlers call it every frame
# and any obj.data mutation would race the depsgraph and trigger redraws.
mesh = _make_mesh(
"ro_quad",
verts=[(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)],
faces=[(0, 1, 2), (0, 2, 3)],
)
edges_before = _edge_count(mesh)
verts_before = len(mesh.vertices)
tool.Geometry.get_dissolved_edges(mesh)
assert _edge_count(mesh) == edges_before
assert len(mesh.vertices) == verts_before
def test_accepts_explicit_angle_limit():
# Smoke: the angle_limit kwarg must be honored end-to-end (not silently
# ignored). With a near-zero threshold, even sub-degree coplanar splits
# survive; with a generous threshold, they collapse.
mesh = _make_mesh(
"quad_tri",
verts=[(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)],
faces=[(0, 1, 2), (0, 2, 3)],
)
_, edges_zero = tool.Geometry.get_dissolved_edges(mesh, angle_limit=0.0)
_, edges_default = tool.Geometry.get_dissolved_edges(mesh)
assert len(edges_zero) > len(edges_default), "angle_limit=0 must preserve more edges than the default 1° dissolve"
def test_cache_serves_identical_object_on_repeat_call():
# Without caching, the helper rebuilds verts/edges every viewport redraw.
# Identity (`is`) — not equality — proves the second call hit the cache
# rather than recomputing identical content.
mesh = _make_mesh(
"cached",
verts=[(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)],
faces=[(0, 1, 2), (0, 2, 3)],
)
first = opening_module._get_cached_dissolved_edges(mesh)
second = opening_module._get_cached_dissolved_edges(mesh)
assert first is second
def test_cache_invalidates_on_decorator_token_bump():
# depsgraph_update_post / undo / redo / load all bump the shared decorator
# token; this cache must clear when the token changes so a downstream
# depsgraph edit (mesh content changed) is reflected on the next call.
mesh = _make_mesh(
"bumped",
verts=[(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)],
faces=[(0, 1, 2), (0, 2, 3)],
)
first = opening_module._get_cached_dissolved_edges(mesh)
decorator_cache._DECORATOR_CACHE_TOKEN += 1
second = opening_module._get_cached_dissolved_edges(mesh)
assert first is not second, "token bump must invalidate the cache entry"
assert len(first[0]) == len(second[0])
assert len(first[1]) == len(second[1])
def test_cache_partitions_entries_by_mesh_identity():
# Two distinct meshes share the same epoch; both must coexist in the cache
# so multi-opening frames don't thrash.
mesh_a = _make_mesh(
"a",
verts=[(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)],
faces=[(0, 1, 2), (0, 2, 3)],
)
mesh_b = _make_mesh(
"b",
verts=[(0, 0, 0), (2, 0, 0), (2, 2, 0), (0, 2, 0)],
faces=[(0, 1, 2), (0, 2, 3)],
)
a_first = opening_module._get_cached_dissolved_edges(mesh_a)
b_first = opening_module._get_cached_dissolved_edges(mesh_b)
a_second = opening_module._get_cached_dissolved_edges(mesh_a)
assert a_first is a_second, "mesh_a entry must survive an interleaved mesh_b call"
assert a_first is not b_first
def test_cache_partitions_entries_by_angle_limit():
# Same mesh, different angle_limit → different cached results. Hardens
# against a future caller introducing a per-opening threshold override.
mesh = _make_mesh(
"partitioned",
verts=[(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)],
faces=[(0, 1, 2), (0, 2, 3)],
)
tight = opening_module._get_cached_dissolved_edges(mesh, angle_limit=0.0)
loose = opening_module._get_cached_dissolved_edges(mesh, angle_limit=radians(1.0))
tight_again = opening_module._get_cached_dissolved_edges(mesh, angle_limit=0.0)
assert tight is tight_again
assert tight is not loose
# --- world-data cache (_get_cached_world_draw_data) ---------------------------
def _make_object(name: str, mesh: bpy.types.Mesh) -> bpy.types.Object:
obj = bpy.data.objects.new(name, mesh)
bpy.context.scene.collection.objects.link(obj)
return obj
def _make_triangulated_quad_obj(name: str) -> bpy.types.Object:
mesh = _make_mesh(
name,
verts=[(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)],
faces=[(0, 1, 2), (0, 2, 3)],
)
return _make_object(name, mesh)
def test_world_data_cache_returns_four_tuple_with_expected_shapes():
obj = _make_triangulated_quad_obj("shape")
line_verts, verts, edges_indices, tris = opening_module._get_cached_world_draw_data(obj)
assert len(verts) == 4 # full mesh vert count
assert len(line_verts) == 4 # dissolved (diagonal collapsed → 4 surviving verts)
assert len(edges_indices) == 4 # quad outline, no diagonal
assert len(tris) == 2 # two triangles
assert all(len(t) == 3 for t in tris)
def test_world_data_cache_hit_returns_identical_tuple_on_repeat_call():
obj = _make_triangulated_quad_obj("hit")
first = opening_module._get_cached_world_draw_data(obj)
second = opening_module._get_cached_world_draw_data(obj)
assert first is second
def test_world_data_cache_invalidates_on_object_epoch_bump():
# depsgraph_update_post bumps per-object epochs (one per Object whose
# transform or geometry changed). After bumping this object's epoch the
# next lookup must miss and recompute.
obj = _make_triangulated_quad_obj("bumped")
first = opening_module._get_cached_world_draw_data(obj)
opening_module._object_epochs[obj.session_uid] = opening_module._object_epochs.get(obj.session_uid, 0) + 1
second = opening_module._get_cached_world_draw_data(obj)
assert first is not second
def test_world_data_cache_partitions_entries_by_object_identity():
a = _make_triangulated_quad_obj("a")
b = _make_triangulated_quad_obj("b")
a_first = opening_module._get_cached_world_draw_data(a)
b_first = opening_module._get_cached_world_draw_data(b)
a_second = opening_module._get_cached_world_draw_data(a)
assert a_first is a_second
assert a_first is not b_first
def test_world_data_cache_reflects_new_matrix_after_epoch_bump():
# The cache stores world-space verts. A transform without an epoch bump
# would serve stale coordinates — but transform updates bump the object's
# epoch via the depsgraph handler, so after bump + recompute the new
# matrix must be reflected.
obj = _make_triangulated_quad_obj("moved")
before = opening_module._get_cached_world_draw_data(obj)
obj.matrix_world = obj.matrix_world @ Matrix.Translation((5.0, 0.0, 0.0))
opening_module._object_epochs[obj.session_uid] = opening_module._object_epochs.get(obj.session_uid, 0) + 1
after = opening_module._get_cached_world_draw_data(obj)
# Each vert in `after` is 5 units shifted on X relative to `before`.
for a_co, b_co in zip(after[1], before[1]):
assert a_co[0] - b_co[0] == pytest.approx(5.0)
assert a_co[1] == pytest.approx(b_co[1])
assert a_co[2] == pytest.approx(b_co[2])
def test_world_data_cache_ios_edges_path_returns_curated_edges():
# When the mesh has an ios_edges attribute, line_verts must equal the full
# verts (no dissolve), and edges_indices must include only entries where
# the attribute is True.
obj = _make_triangulated_quad_obj("curated")
attr = obj.data.attributes.new(name="ios_edges", type="BOOLEAN", domain="EDGE")
# 5 edges total (quad + diagonal). Mark only the 4 quad sides as real.
bm = bmesh.new()
bm.from_mesh(obj.data)
real_edges_count = 0
for i, edge in enumerate(bm.edges):
is_diagonal = (
abs(edge.verts[0].co[0] - edge.verts[1].co[0]) > 0 and abs(edge.verts[0].co[1] - edge.verts[1].co[1]) > 0
)
attr.data[i].value = not is_diagonal
if not is_diagonal:
real_edges_count += 1
bm.free()
obj.data.update()
line_verts, verts, edges_indices, _ = opening_module._get_cached_world_draw_data(obj)
assert line_verts is verts, "ios_edges path must reuse the full-verts list as line_verts"
assert len(edges_indices) == real_edges_count
def test_world_data_cache_dissolve_path_drops_diagonal():
# Without ios_edges, the cache falls through to dissolve. The 5th edge
# (diagonal) must be gone from edges_indices.
obj = _make_triangulated_quad_obj("dissolved")
line_verts, verts, edges_indices, _ = opening_module._get_cached_world_draw_data(obj)
assert len(edges_indices) == 4
assert len(line_verts) == 4
assert len(verts) == 4
# --- batch cache (_get_cached_batch_or_none / _store_batch_in_cache) ---------
def test_batch_cache_returns_none_on_cold_lookup():
assert opening_module._get_cached_batch_or_none((123, "lines")) is None
def test_batch_cache_returns_stored_batch_on_hit():
# Sentinel stands in for a GPUBatch — the cache treats it opaquely, so
# this test pins lookup/store correctness without needing a real shader.
sentinel = object()
opening_module._store_batch_in_cache((42, "lines"), sentinel)
assert opening_module._get_cached_batch_or_none((42, "lines")) is sentinel
def test_batch_cache_invalidates_on_object_epoch_bump():
sentinel = object()
opening_module._store_batch_in_cache((42, "lines"), sentinel)
opening_module._object_epochs[42] = opening_module._object_epochs.get(42, 0) + 1
assert opening_module._get_cached_batch_or_none((42, "lines")) is None
def test_batch_cache_partitions_entries_by_kind():
# Same object, different batch kinds (LINES vs TRIS vs arrow) coexist —
# required so the same opening's three batches don't evict each other.
lines_batch = object()
tris_batch = object()
opening_module._store_batch_in_cache((42, "lines"), lines_batch)
opening_module._store_batch_in_cache((42, "tris"), tris_batch)
assert opening_module._get_cached_batch_or_none((42, "lines")) is lines_batch
assert opening_module._get_cached_batch_or_none((42, "tris")) is tris_batch
def test_batch_cache_partitions_entries_by_object_uid():
a_batch = object()
b_batch = object()
opening_module._store_batch_in_cache((1, "lines"), a_batch)
opening_module._store_batch_in_cache((2, "lines"), b_batch)
assert opening_module._get_cached_batch_or_none((1, "lines")) is a_batch
assert opening_module._get_cached_batch_or_none((2, "lines")) is b_batch
# --- per-object epoch invalidation (granularity contract) --------------------
def test_world_data_cache_per_object_epoch_invalidates_only_target():
# Core contract for the granular-invalidation feature: bumping one object's
# epoch must not evict another object's cached payload. This is what makes
# dragging a single object in a 50-opening scene affordable.
a = _make_triangulated_quad_obj("granular_a")
b = _make_triangulated_quad_obj("granular_b")
a_first = opening_module._get_cached_world_draw_data(a)
b_first = opening_module._get_cached_world_draw_data(b)
opening_module._object_epochs[a.session_uid] = opening_module._object_epochs.get(a.session_uid, 0) + 1
a_second = opening_module._get_cached_world_draw_data(a)
b_second = opening_module._get_cached_world_draw_data(b)
assert a_first is not a_second, "a's epoch bump must invalidate a's entry"
assert b_first is b_second, "a's epoch bump must NOT touch b's entry"
def test_batch_cache_per_object_epoch_invalidates_only_target():
a_lines = object()
b_lines = object()
opening_module._store_batch_in_cache((1, "lines"), a_lines)
opening_module._store_batch_in_cache((2, "lines"), b_lines)
opening_module._object_epochs[1] = opening_module._object_epochs.get(1, 0) + 1
assert opening_module._get_cached_batch_or_none((1, "lines")) is None
assert opening_module._get_cached_batch_or_none((2, "lines")) is b_lines
def test_global_clear_handler_wipes_everything():
# undo/redo/load can't be modeled as per-object deltas — the global handler
# must wipe every layer (epochs + both caches) so we can never serve state
# that pre-dates the undo/load.
a = _make_triangulated_quad_obj("wipe_a")
opening_module._get_cached_world_draw_data(a)
opening_module._store_batch_in_cache((a.session_uid, "lines"), object())
assert a.session_uid in opening_module._world_draw_data_cache
assert (a.session_uid, "lines") in opening_module._batch_cache
opening_module._clear_decoration_caches_globally()
assert opening_module._world_draw_data_cache == {}
assert opening_module._batch_cache == {}
assert opening_module._object_epochs == {}
class _FakeDepsgraphUpdate:
def __init__(self, id_, transform: bool = False, geometry: bool = False):
self.id = id_
self.is_updated_transform = transform
self.is_updated_geometry = geometry
class _FakeDepsgraph:
def __init__(self, updates):
self.updates = updates
def test_depsgraph_handler_bumps_epoch_for_updated_object():
# Synthesised depsgraph delta: one Object with a transform update. The
# handler must increment that object's epoch.
obj = _make_triangulated_quad_obj("bumped_via_handler")
before = opening_module._object_epochs.get(obj.session_uid, 0)
deps = _FakeDepsgraph([_FakeDepsgraphUpdate(obj, transform=True)])
opening_module._bump_object_epochs_for_decoration(None, deps)
assert opening_module._object_epochs[obj.session_uid] == before + 1
def test_depsgraph_handler_ignores_non_object_updates():
# Updates whose .id isn't a bpy.types.Object (Mesh, Material, NodeTree…)
# must not affect any object's epoch.
obj = _make_triangulated_quad_obj("untouched")
deps = _FakeDepsgraph([_FakeDepsgraphUpdate(obj.data, geometry=True)])
opening_module._bump_object_epochs_for_decoration(None, deps)
assert obj.session_uid not in opening_module._object_epochs
def test_depsgraph_handler_ignores_updates_without_transform_or_geometry():
# An Object update flagged only for shading must not bump the epoch —
# shading changes don't move the wire overlay.
obj = _make_triangulated_quad_obj("shading_only")
deps = _FakeDepsgraph([_FakeDepsgraphUpdate(obj)])
opening_module._bump_object_epochs_for_decoration(None, deps)
assert obj.session_uid not in opening_module._object_epochs
def test_depsgraph_handler_resolves_cow_original():
# For non-evaluated Blender objects, obj.original returns obj itself, so
# the .original-resolution path keys the SAME uid the draw handler reads.
# Pinning this prevents a future refactor that drops the .original lookup
# from silently regressing the COW-boundary case (the decorator failing to
# follow a moved object).
obj = _make_triangulated_quad_obj("cow")
deps = _FakeDepsgraph([_FakeDepsgraphUpdate(obj, transform=True)])
opening_module._bump_object_epochs_for_decoration(None, deps)
assert obj.original.session_uid in opening_module._object_epochs
def test_depsgraph_handler_tolerates_missing_depsgraph():
# Some Blender event paths may call the handler without a depsgraph; the
# handler must short-circuit instead of raising AttributeError.
opening_module._bump_object_epochs_for_decoration()
opening_module._bump_object_epochs_for_decoration(None)
opening_module._bump_object_epochs_for_decoration(None, None)
assert opening_module._object_epochs == {}
@@ -0,0 +1,178 @@
# Bonsai - OpenBIM Blender Add-on
# Copyright (C) 2026
#
# This file is part of Bonsai.
#
# Bonsai is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Bonsai is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Bonsai. If not, see <http://www.gnu.org/licenses/>.
#
# This file was generated with the assistance of an AI coding tool.
"""Tests for the parametric-edit preview registry contract.
Every test reads the live ``PREVIEW_CANCEL_OPS`` registry rather than hard-
coding preview keys or cancel-operator names, so adding a new preview to the
registry automatically exercises the same invariants without test changes."""
import types
import bpy
import pytest
pytestmark = pytest.mark.model
@pytest.fixture(autouse=True)
def _require_real_bpy():
if not isinstance(bpy, types.ModuleType) or hasattr(bpy, "_mock_name"):
pytest.skip("requires real Blender (bpy is mocked or absent)")
def _registry():
from bonsai.bim.module.model.preview_base import PREVIEW_CANCEL_OPS
return PREVIEW_CANCEL_OPS
def _preview_umbrella():
return getattr(bpy.context.scene, "BIMPreviewProperties", None)
def _registered_previews():
"""``[(attr, op_name, props)]`` for every registry entry that has a real
child PropertyGroup on the umbrella in the current addon build."""
umbrella = _preview_umbrella()
if umbrella is None:
return []
out = []
for attr, op_name in _registry():
props = getattr(umbrella, attr, None)
if props is not None:
out.append((attr, op_name, props))
return out
class TestRegistryContract:
"""Pins the invariant that every entry in PREVIEW_CANCEL_OPS resolves to
a real cancel operator the addon registers. A new preview added to the
registry without its matching cancel operator would otherwise crash
``try_cancel_active_preview`` on the first Esc."""
def test_every_registered_cancel_op_is_callable(self):
for attr, op_name in _registry():
op = getattr(bpy.ops.bim, op_name, None)
assert op is not None and callable(op), (
f"Preview '{attr}' in PREVIEW_CANCEL_OPS points to bim.{op_name} "
f"but no such operator is registered."
)
class TestGetPreviewPropsTolerance:
"""The bug-class fixed in commit ee63137c6: ``get_preview_props`` is called
from gizmo polls during addon init and from test mocks built on
``SimpleNamespace`` neither has a fully-formed Blender context. The
helper must return None rather than raise."""
def test_returns_none_when_context_has_no_scene(self):
from bonsai.bim.module.model.preview_base import get_preview_props
# Pass an arbitrary attr name — the contract is the same for every
# preview key, so picking one literally would be a maintenance trap.
for attr, _ in _registry():
assert get_preview_props(types.SimpleNamespace(), attr) is None
break
def test_returns_none_when_scene_lacks_umbrella(self):
from bonsai.bim.module.model.preview_base import get_preview_props
ctx = types.SimpleNamespace(scene=types.SimpleNamespace())
for attr, _ in _registry():
assert get_preview_props(ctx, attr) is None
break
class TestActivationCycle:
"""End-to-end contract on the real addon: each registered preview can be
activated and then cancelled to inactive. Runs for every preview that
has a wired PropertyGroup, so a new preview added to the registry +
umbrella is covered without test edits."""
def test_any_preview_active_reflects_each_preview_state(self):
from bonsai.bim.module.model.preview_base import any_preview_active
registered = _registered_previews()
if not registered:
pytest.skip("No previews wired in this build — registry-only entries")
# All inactive baseline.
for _, _, props in registered:
props.is_active = False
assert any_preview_active(bpy.context) is False
# Flip each one independently — the helper must report True.
for _, _, props in registered:
props.is_active = True
assert any_preview_active(bpy.context) is True
props.is_active = False
def test_discard_pending_previews_clears_every_active_flag(self):
from bonsai.bim.module.model.preview_base import discard_pending_previews
registered = _registered_previews()
if not registered:
pytest.skip("No previews wired in this build — registry-only entries")
for _, _, props in registered:
props.is_active = True
discard_pending_previews(bpy.context.scene)
for attr, _, props in registered:
assert props.is_active is False, f"discard_pending_previews left '{attr}' active"
class TestSaveOnDiscardWired:
"""Pins that the SaveProject operator clears preview state before writing
the IFC file a stuck is_active flag persisted through the save would
silently hide sister gizmos on the next file load.
Structural check: the SaveProject operator class must reference the
discard helper somewhere in its execute path. Behavioural integration
(actually saving a .blend with an active preview and reloading) belongs
in the bim feature suite; this is the small guard against accidental
removal of the call site."""
def test_save_project_dispatches_discard_pending_previews(self):
import inspect
from bonsai.bim.module.model import preview_base
from bonsai.bim.module.project import operator as project_operator
# Find the project save operator dynamically — looking for any
# Operator class whose bl_idname is "bim.save_project". Avoids
# hard-coding the class identifier.
save_op = None
for name in dir(project_operator):
obj = getattr(project_operator, name)
if isinstance(obj, type) and getattr(obj, "bl_idname", None) == "bim.save_project":
save_op = obj
break
assert save_op is not None, "Expected an operator with bl_idname='bim.save_project' in project/operator.py"
# Walk the class's methods for the discard call. Avoids pinning a
# specific method name (_execute vs execute vs an inner helper) so
# the test survives operator refactors.
source = inspect.getsource(save_op)
assert preview_base.discard_pending_previews.__name__ in source, (
f"{save_op.__name__} does not reference discard_pending_previews. "
"Saving with a preview open would persist its is_active flag to the "
".blend file and silently hide sister gizmos on reopen."
)
@@ -0,0 +1,154 @@
# Bonsai - OpenBIM Blender Add-on
# Copyright (C) 2026
#
# This file is part of Bonsai.
#
# Bonsai is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Bonsai is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Bonsai. If not, see <http://www.gnu.org/licenses/>.
#
# This file was generated with the assistance of an AI coding tool.
"""Behaviour contract: every wall gizmo group hides while a parametric-edit
preview is active.
Enumerates wall gizmo groups by walking the wall module for ``bpy.types.GizmoGroup``
subclasses rather than naming them adding a new wall gizmo group automatically
joins the test. The test then asserts the BEHAVIOUR (poll returns False when
``preview_base.any_preview_active`` is True) without pinning the name of the
helper function the gizmo uses internally to enforce it."""
import inspect
import types
from unittest.mock import patch
import bpy
import pytest
pytestmark = pytest.mark.model
@pytest.fixture(autouse=True)
def _require_real_bpy():
if not isinstance(bpy, types.ModuleType) or hasattr(bpy, "_mock_name"):
pytest.skip("requires real Blender (bpy is mocked or absent)")
def _wall_gizmo_groups():
"""Walk the wall module for ``bpy.types.GizmoGroup`` subclasses defined
locally (skip imported references). Returns a list of (name, cls) tuples.
A gizmo group whose ``poll`` legitimately needs to fire WHILE a preview
is active i.e. it IS the preview's own gizmo group — is excluded by
convention: classes whose bl_idname references the preview surface
(``preview`` in the idname) are the preview-owner exception."""
from bonsai.bim.module.model import wall as wall_mod
out = []
for name in dir(wall_mod):
obj = getattr(wall_mod, name)
if not isinstance(obj, type):
continue
if not issubclass(obj, bpy.types.GizmoGroup) or obj is bpy.types.GizmoGroup:
continue
# Local definitions only — skip re-exports / aliases.
if obj.__module__ != wall_mod.__name__:
continue
# Preview-owner exception: the gizmo group that drives a preview
# itself must remain visible while its preview is active, so a
# "no preview active" gate would self-block it. The bl_idname
# contains the substring 'preview' for these groups by Bonsai
# convention (e.g. OBJECT_GGT_bim_wall_fillet_preview).
bl_idname = getattr(obj, "bl_idname", "") or ""
if "preview" in bl_idname.lower():
continue
out.append((name, obj))
return out
class TestWallGizmoGroupsHideDuringPreview:
"""Behaviour contract: a parametric-edit preview is the only interactive
surface in the viewport, so every sister wall gizmo must self-hide via
its poll. The test exercises this BEHAVIOUR when ``any_preview_active``
reports True, every wall gizmo's poll returns False — without pinning
the helper function name each poll uses internally."""
def test_discovery_finds_wall_gizmo_groups(self):
"""Sanity check: at least one wall gizmo group is found. If this fails,
the discovery walk drifted out of sync with the module structure (e.g.
wall gizmo groups got moved to a separate file)."""
groups = _wall_gizmo_groups()
assert groups, "Expected at least one wall GizmoGroup subclass in wall.py — discovery walk broke?"
def test_every_wall_gizmo_hides_when_a_preview_is_active(self):
"""For each discovered wall gizmo group, mock ``any_preview_active`` to
True and call ``poll(bpy.context)``. Every poll must return False
any True is a poll that wouldn't hide during a fillet/bend preview,
leaving the user with two competing icon stacks on the same selection."""
groups = _wall_gizmo_groups()
offenders = []
with patch("bonsai.bim.module.model.preview_base.any_preview_active", return_value=True):
for name, cls in groups:
poll = getattr(cls, "poll", None)
if poll is None:
# Inherits poll from a mixin / base — the base poll's gating
# is covered separately. Skip rather than crash.
continue
try:
result = poll(bpy.context)
except Exception as exc: # noqa: BLE001
offenders.append((name, f"poll raised: {type(exc).__name__}: {exc}"))
continue
if result:
offenders.append((name, "poll returned True with preview active"))
assert not offenders, (
"Wall gizmo polls that don't gate on any_preview_active "
"(or raise instead of returning False): "
+ ", ".join(f"{n}{why}" for n, why in offenders)
+ ". Hide sister gizmos during previews so the preview is the only "
"interactive surface in the viewport. The conventional path is to "
"early-return from poll when preview_base.any_preview_active(context) "
"is True."
)
class TestBaseParametricGizmoPollHidesDuringPreview:
"""Mirror of the wall-specific test for the cross-feature parametric
framework: door / window / stair / roof / railing / array all inherit
``BaseParametricGizmoGroup``. Its poll must also short-circuit on
``any_preview_active`` so sister features behave consistently with walls."""
def test_base_parametric_poll_returns_false_when_a_preview_is_active(self):
from bonsai.bim.module.drawing.gizmos import BaseParametricGizmoGroup
# The base poll requires an active selected object before checking the
# preview gate. Mock both the selected-object check (return a sentinel)
# AND the gate so the test exercises ONLY the preview short-circuit.
with patch("bonsai.tool.Blender.get_active_object", return_value=object()):
with patch("bonsai.tool.Blender.are_viewport_gizmos_enabled", return_value=True):
with patch(
"bonsai.bim.module.model.preview_base.any_preview_active",
return_value=True,
):
assert BaseParametricGizmoGroup.poll(bpy.context) is False
class TestModulePathIsFindable:
"""If wall.py is split across multiple modules (e.g. wall_gizmos.py),
update ``_wall_gizmo_groups`` to walk each. This sanity check fails first
so the diagnostic message is obvious."""
def test_wall_module_resolves(self):
from bonsai.bim.module.model import wall as wall_mod
assert inspect.ismodule(wall_mod)
@@ -179,3 +179,112 @@ def test_poll_rejects_when_other_is_not_layer2_wall():
_run_poll(prefs_on=True, active_is_in_selected=True, len_override=None, active_usage="LAYER3", other_usage=None)
is False
)
# ----------------------------------------------------------------------------
# _iter_path_connections — IfcRelConnectsPathElements inverse-graph walk
# ----------------------------------------------------------------------------
#
# Normalises both ConnectedTo and ConnectedFrom orientations to (other, self_ct,
# other_ct) so callers always read "self first" regardless of which side of the
# rel this wall was authored on. Non-wall partners and malformed (None) refs are
# filtered out so per-frame gizmo positioning survives partial IFC state.
def _make_path_rel(relating, related, relating_ct, related_ct, kind="IfcRelConnectsPathElements"):
"""Build a stub IfcRelConnectsPathElements for inverse-walk tests."""
return SimpleNamespace(
is_a=lambda name, _k=kind: name == _k,
RelatingElement=relating,
RelatedElement=related,
RelatingConnectionType=relating_ct,
RelatedConnectionType=related_ct,
)
def _run_iter_path_connections(elem, *, is_wall_predicate=lambda _e: True):
from bonsai import tool
from bonsai.bim.module.model.wall import _iter_path_connections
with patch.object(tool.Blender.Modifier, "is_wall", side_effect=is_wall_predicate):
return _iter_path_connections(elem)
def test_iter_path_connections_empty_inverses_yields_nothing():
elem = SimpleNamespace(ConnectedTo=[], ConnectedFrom=[])
assert _run_iter_path_connections(elem) == []
def test_iter_path_connections_connected_to_orientation_is_self_first():
# Self is the rel's RelatingElement → its connection type is RelatingConnectionType.
self_elem = object()
other = object()
rel = _make_path_rel(relating=self_elem, related=other, relating_ct="ATEND", related_ct="ATSTART")
elem = SimpleNamespace(ConnectedTo=[rel], ConnectedFrom=[])
assert _run_iter_path_connections(elem) == [(other, "ATEND", "ATSTART")]
def test_iter_path_connections_connected_from_orientation_is_self_first():
# Self is the rel's RelatedElement → its connection type is RelatedConnectionType.
# The helper must FLIP the tuple so callers still see (other, self_ct, other_ct).
self_elem = object()
other = object()
rel = _make_path_rel(relating=other, related=self_elem, relating_ct="ATSTART", related_ct="ATEND")
elem = SimpleNamespace(ConnectedTo=[], ConnectedFrom=[rel])
assert _run_iter_path_connections(elem) == [(other, "ATEND", "ATSTART")]
def test_iter_path_connections_skips_non_path_rels():
# IfcRelAggregates, IfcRelContainedInSpatialStructure, etc. share the
# ConnectedTo/ConnectedFrom inverse arrays — only IfcRelConnectsPathElements
# carries the per-end connection-type semantics we care about.
self_elem = object()
other = object()
non_path = _make_path_rel(
relating=self_elem, related=other, relating_ct="ATSTART", related_ct="ATEND", kind="IfcRelAggregates"
)
path = _make_path_rel(relating=self_elem, related=other, relating_ct="ATEND", related_ct="ATSTART")
elem = SimpleNamespace(ConnectedTo=[non_path, path], ConnectedFrom=[])
assert _run_iter_path_connections(elem) == [(other, "ATEND", "ATSTART")]
def test_iter_path_connections_skips_non_wall_partners():
# Walls may path-connect to non-wall elements (columns, beams). The single-
# wall unjoin gizmo only surfaces wall-to-wall joins to match the existing
# two-wall gizmo's scope.
self_elem = object()
wall_partner = object()
non_wall_partner = object()
rel_wall = _make_path_rel(relating=self_elem, related=wall_partner, relating_ct="ATEND", related_ct="ATSTART")
rel_non_wall = _make_path_rel(
relating=self_elem, related=non_wall_partner, relating_ct="ATEND", related_ct="ATSTART"
)
elem = SimpleNamespace(ConnectedTo=[rel_wall, rel_non_wall], ConnectedFrom=[])
result = _run_iter_path_connections(elem, is_wall_predicate=lambda e: e is wall_partner)
assert result == [(wall_partner, "ATEND", "ATSTART")]
def test_iter_path_connections_tolerates_none_partner_refs():
# Malformed / partial IFC files can leave a rel's element ref unset.
# Without a None guard, `Modifier.is_wall(None)` would raise on
# `None.is_a(...)` mid-frame and silently break the gizmo group.
self_elem = object()
other = object()
rel_none = _make_path_rel(relating=self_elem, related=None, relating_ct="ATEND", related_ct="ATSTART")
rel_ok = _make_path_rel(relating=self_elem, related=other, relating_ct="ATSTART", related_ct="ATEND")
elem = SimpleNamespace(ConnectedTo=[rel_none, rel_ok], ConnectedFrom=[])
assert _run_iter_path_connections(elem) == [(other, "ATSTART", "ATEND")]
def test_iter_path_connections_walks_both_inverses_in_order():
# A wall can sit on both sides of different path rels (e.g. authored once
# as the RelatingElement, once as the RelatedElement). The helper walks
# ConnectedTo first, then ConnectedFrom — pinning the order so callers can
# depend on it for icon-slot allocation.
self_elem = object()
p1 = object()
p2 = object()
rel_to = _make_path_rel(relating=self_elem, related=p1, relating_ct="ATSTART", related_ct="ATSTART")
rel_from = _make_path_rel(relating=p2, related=self_elem, relating_ct="ATEND", related_ct="ATEND")
elem = SimpleNamespace(ConnectedTo=[rel_to], ConnectedFrom=[rel_from])
assert _run_iter_path_connections(elem) == [(p1, "ATSTART", "ATSTART"), (p2, "ATEND", "ATEND")]
@@ -75,7 +75,7 @@ def test_geom_generation_invalidates_wall_geom_cache():
sentinel_a = {"length": 1.0, "height": 2.0, "x_angle": 0.0}
sentinel_b = {"length": 1.5, "height": 2.5, "x_angle": 0.0}
with patch.object(wall_mod, "_read_wall_geometry", side_effect=[sentinel_a, sentinel_b]):
with patch.object(tool.Wall, "read_geometry", side_effect=[sentinel_a, sentinel_b]):
first = wall_mod._get_wall_geom_cached(group, fake_obj)
assert first is sentinel_a
# Same call without a generation bump must hit the cache (no extra read).
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+380
View File
@@ -0,0 +1,380 @@
# Bonsai - OpenBIM Blender Add-on
# Copyright (C) 2026 Bruno Perdigão <contact@brunopo.com>
#
# This file is part of Bonsai.
#
# Bonsai is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Bonsai is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Bonsai. If not, see <http://www.gnu.org/licenses/>.
import inspect
import os
import sys
import time
import bpy
import ifcopenshell
import pytest
from bonsai import tool as tool
from bonsai.bim.ifc import IfcStore
from bonsai.bim.module.model.data import AuthoringData as Model
GREEN = "\033[32m"
RED = "\033[31m"
RESET = "\033[0m"
def _assert_pass(message: str) -> None:
caller_name = inspect.stack()[1].function
print(f"{GREEN}{caller_name} PASSED: {message}{RESET}")
def _handle_error(e: Exception, on_done) -> None:
print(f"{RED}Assertion failed: {e}{RESET}")
if on_done:
on_done()
def run_iter_from_timer(event_iter, on_complete=None, on_error=None):
i = iter(event_iter)
done = False
def event_step():
nonlocal done, on_complete
try:
ret = next(i, "STOP")
if ret in (None, "STOP", "FINISHED"):
done = True
if on_complete:
on_complete()
return None
except StopIteration:
done = True
if on_complete:
on_complete()
return None
except Exception as e:
done = True
print(f"Exception: {e}")
if on_error:
on_error(e)
elif on_complete:
on_complete()
return None
return 0.0
bpy.app.timers.register(event_step, first_interval=0.0)
def preset_event_simulate(window, event_type, value, x, y):
if value == "TAP":
yield window.event_simulate(event_type, "PRESS", x=x, y=y)
yield window.event_simulate(event_type, "RELEASE", x=x, y=y)
else:
yield window.event_simulate(event_type, value, x=x, y=y)
def cleanup():
bpy.app.use_event_simulate = False
bpy.ops.wm.quit_blender()
def _get_valid_window() -> bpy.types.Window:
win = bpy.context.window
if win is not None:
return win
wm = getattr(bpy.context, "window_manager", None)
if wm and wm.windows:
return wm.windows[0]
raise RuntimeError("Unable to locate a Blender UI window.")
def new_project():
IfcStore.purge()
bpy.ops.wm.read_homefile(app_template="", use_factory_startup=True)
if len(bpy.data.objects) > 0:
bpy.data.batch_remove(bpy.data.objects)
bpy.ops.outliner.orphans_purge(do_local_ids=True, do_linked_ids=True, do_recursive=True)
if len(bpy.data.materials) > 0:
bpy.data.batch_remove(bpy.data.materials)
bpy.context.scene.unit_settings.system = "METRIC"
bpy.context.scene.unit_settings.length_unit = "MILLIMETERS"
props = tool.Project.get_project_props()
props.template_file = "0"
tool.Blender.get_addon_preferences().should_play_chaching_sound = False
def get_area_and_region(window):
area = next(area for area in window.screen.areas if area.type == "VIEW_3D")
region = next(region for region in area.regions if region.type == "WINDOW")
return area, region
def test_snap_object_detection(window):
yield from preset_event_simulate(window, "MOUSEMOVE", "NOTHING", 0, 0)
area, region = get_area_and_region(window)
x = round(area.width * 0.5 + area.x)
y = round(area.height * 0.54 + area.y)
yield from preset_event_simulate(window, "ESC", "TAP", x, y)
measure_settings = tool.Project.get_measure_tool_settings()
measure_settings.measurement_type = "POLYLINE"
for obj in tool.Blender.get_selected_objects():
obj.select_set(False)
with bpy.context.temp_override(area=area, region=region, space_data=area.spaces[0]):
bpy.ops.bim.measure_tool("INVOKE_DEFAULT", measure_type="POLYLINE")
yield from preset_event_simulate(window, "MOUSEMOVE", "NOTHING", x, y)
yield from preset_event_simulate(window, "LEFTMOUSE", "TAP", x, y)
snap_point = tool.Model.get_polyline_props().snap_mouse_point[0]
assert_msg = "First click should have a snap_object"
assert snap_point.snap_object, assert_msg
_assert_pass(assert_msg)
assert_msg = "snap_object should be a string with the object name"
assert type(snap_point.snap_object) == str, assert_msg
_assert_pass(assert_msg)
assert_msg = "Object should be an IfcWall"
assert snap_point.snap_object.split("/")[0] == "IfcWall", assert_msg
_assert_pass(assert_msg)
offset = 200
yield from preset_event_simulate(window, "MOUSEMOVE", "NOTHING", x - offset, y)
yield from preset_event_simulate(window, "MOUSEMOVE", "NOTHING", x - offset, y)
yield from preset_event_simulate(window, "MOUSEMOVE", "NOTHING", x - offset, y)
yield from preset_event_simulate(window, "MOUSEMOVE", "NOTHING", x - offset, y)
yield from preset_event_simulate(window, "LEFTMOUSE", "TAP", x - offset, y)
snap_point = tool.Model.get_polyline_props().snap_mouse_point[0]
assert_msg = "Second click should not have a snap_object"
assert not snap_point.snap_object, assert_msg
_assert_pass(assert_msg)
yield from preset_event_simulate(window, "RET", "TAP", x, y)
yield "FINISHED"
def test_snap_partially_behind_camera(window):
yield from preset_event_simulate(window, "MOUSEMOVE", "NOTHING", 0, 0)
area, region = get_area_and_region(window)
x = round(area.width * 0.20 + area.x)
y = round(area.height * 0.15 + area.y)
yield from preset_event_simulate(window, "ESC", "TAP", x, y)
measure_settings = tool.Project.get_measure_tool_settings()
measure_settings.measurement_type = "POLYLINE"
for obj in tool.Blender.get_selected_objects():
obj.select_set(False)
with bpy.context.temp_override(area=area, region=region, space_data=area.spaces[0]):
bpy.ops.bim.measure_tool("INVOKE_DEFAULT", measure_type="POLYLINE")
yield from preset_event_simulate(window, "MOUSEMOVE", "NOTHING", x, y)
yield from preset_event_simulate(window, "LEFTMOUSE", "TAP", x, y)
snap_point = tool.Model.get_polyline_props().snap_mouse_point[0]
assert_msg = "First click should have a snap_object"
assert snap_point.snap_object, assert_msg
_assert_pass(assert_msg)
assert_msg = "snap_object should be a string with the object name"
assert type(snap_point.snap_object) == str, assert_msg
_assert_pass(assert_msg)
assert_msg = "snap_type should be 'Edge'"
assert snap_point.snap_type == "Edge", assert_msg
_assert_pass(assert_msg)
assert_msg = "Object should be an IfcSlab"
assert snap_point.snap_object.split("/")[0] == "IfcSlab", assert_msg
_assert_pass(assert_msg)
offset = 200
yield from preset_event_simulate(window, "MOUSEMOVE", "NOTHING", x + offset, y)
yield from preset_event_simulate(window, "MOUSEMOVE", "NOTHING", x + offset, y)
yield from preset_event_simulate(window, "MOUSEMOVE", "NOTHING", x + offset, y)
yield from preset_event_simulate(window, "MOUSEMOVE", "NOTHING", x + offset, y)
yield from preset_event_simulate(window, "LEFTMOUSE", "TAP", x - offset, y)
snap_point = tool.Model.get_polyline_props().snap_mouse_point[0]
assert_msg = "Second click should have a snap_object"
assert snap_point.snap_object, assert_msg
_assert_pass(assert_msg)
assert_msg = "snap_object should be a string with the object name"
assert type(snap_point.snap_object) == str, assert_msg
_assert_pass(assert_msg)
assert_msg = "snap_type should be 'Face'"
assert snap_point.snap_type == "Face", assert_msg
_assert_pass(assert_msg)
assert_msg = "Object should be an IfcSlab"
assert snap_point.snap_object.split("/")[0] == "IfcSlab", assert_msg
_assert_pass(assert_msg)
yield from preset_event_simulate(window, "RET", "TAP", x, y)
yield "FINISHED"
def test_snap_in_xray_mode(window):
yield from preset_event_simulate(window, "MOUSEMOVE", "NOTHING", 0, 0)
area, region = get_area_and_region(window)
x = round(area.width * 0.68+ area.x)
y = round(area.height * 0.54 + area.y)
area.spaces[0].shading.show_xray = True
yield from preset_event_simulate(window, "ESC", "TAP", x, y)
measure_settings = tool.Project.get_measure_tool_settings()
measure_settings.measurement_type = "POLYLINE"
for obj in tool.Blender.get_selected_objects():
obj.select_set(False)
with bpy.context.temp_override(area=area, region=region, space_data=area.spaces[0]):
bpy.ops.bim.measure_tool("INVOKE_DEFAULT", measure_type="POLYLINE")
yield from preset_event_simulate(window, "MOUSEMOVE", "NOTHING", x, y)
yield from preset_event_simulate(window, "LEFTMOUSE", "TAP", x, y)
snap_point = tool.Model.get_polyline_props().snap_mouse_point[0]
assert_msg = "First click should have a snap_object"
assert snap_point.snap_object, assert_msg
_assert_pass(assert_msg)
assert_msg = "snap_object should be a string with the object name"
assert type(snap_point.snap_object) == str, assert_msg
_assert_pass(assert_msg)
assert_msg = "Object should be an IfcFurniture"
assert snap_point.snap_object.split("/")[0] == "IfcFurniture", assert_msg
_assert_pass(assert_msg)
yield from preset_event_simulate(window, "RET", "TAP", x, y)
yield "FINISHED"
def test_snap_far_from_origin(window):
bpy.context.view_layer.objects.active = None
bpy.ops.object.select_all(action="DESELECT")
yield from preset_event_simulate(window, "MOUSEMOVE", "NOTHING", 0, 0)
area, region = get_area_and_region(window)
x = round(area.width * 0.155 + area.x)
y = round(area.height * 0.18 + area.y)
yield from preset_event_simulate(window, "ESC", "TAP", x, y)
bpy.data.objects['IfcBuildingElementProxy/Cube'].select_set(True)
yield from preset_event_simulate(window, "MOUSEMOVE", "NOTHING", x, y)
with bpy.context.temp_override(area=area, region=region, space_data=area.spaces[0]):
bpy.ops.view3d.view_selected()
measure_settings = tool.Project.get_measure_tool_settings()
measure_settings.measurement_type = "POLYLINE"
for obj in tool.Blender.get_selected_objects():
obj.select_set(False)
with bpy.context.temp_override(area=area, region=region, space_data=area.spaces[0]):
bpy.ops.bim.measure_tool("INVOKE_DEFAULT", measure_type="POLYLINE")
yield from preset_event_simulate(window, "MOUSEMOVE", "NOTHING", x, y)
yield from preset_event_simulate(window, "MOUSEMOVE", "NOTHING", x, y)
yield from preset_event_simulate(window, "MOUSEMOVE", "NOTHING", x, y)
yield from preset_event_simulate(window, "MOUSEMOVE", "NOTHING", x, y)
yield from preset_event_simulate(window, "LEFTMOUSE", "TAP", x, y)
snap_point = tool.Model.get_polyline_props().snap_mouse_point[0]
assert_msg = "First click should have a snap_object"
assert snap_point.snap_object, assert_msg
_assert_pass(assert_msg)
assert_msg = "snap_object should be a string with the object name"
assert type(snap_point.snap_object) == str, assert_msg
_assert_pass(assert_msg)
assert_msg = "snap_type should be 'Vertex'"
assert snap_point.snap_type == "Vertex", assert_msg
_assert_pass(assert_msg)
assert_msg = "x should be 1000000"
assert round(snap_point.x, 3) == 1000.0, assert_msg
_assert_pass(assert_msg)
assert_msg = "y should be 1000000"
assert round(snap_point.y, 3) == 1000.0, assert_msg
_assert_pass(assert_msg)
yield from preset_event_simulate(window, "RET", "TAP", x, y)
yield "FINISHED"
def test_draw_polyline_wall(window, x, y):
yield from preset_event_simulate(window, "ESC", "TAP", x, y)
area, region = get_area_and_region(window)
for obj in tool.Blender.get_selected_objects():
obj.select_set(False)
with bpy.context.temp_override(area=area, region=region, space_data=area.spaces[0]):
props = tool.Model.get_model_props()
ifc = tool.Ifc.get()
relating_type = ifc.by_type("IfcWallType")[0]
if tool.Model.get_usage_type(relating_type) == "LAYER2":
props.ifc_class = "IfcWallType"
props.relating_type_id = str(relating_type.id())
bpy.ops.bim.draw_polyline_wall("INVOKE_DEFAULT")
yield from preset_event_simulate(window, "MOUSEMOVE", "NOTHING", x, y)
yield from preset_event_simulate(window, "MOUSEMOVE", "NOTHING", x, y)
yield from preset_event_simulate(window, "MOUSEMOVE", "NOTHING", x, y)
yield from preset_event_simulate(window, "MOUSEMOVE", "NOTHING", x, y)
yield from preset_event_simulate(window, "LEFTMOUSE", "TAP", x, y)
yield from preset_event_simulate(window, "X", "TAP", x, y)
offset = 200
yield from preset_event_simulate(window, "MOUSEMOVE", "NOTHING", x + offset, y)
yield from preset_event_simulate(window, "MOUSEMOVE", "NOTHING", x + offset, y)
yield from preset_event_simulate(window, "MOUSEMOVE", "NOTHING", x + offset, y)
yield from preset_event_simulate(window, "MOUSEMOVE", "NOTHING", x + offset, y)
yield from preset_event_simulate(window, "LEFTMOUSE", "TAP", x + offset, y)
yield from preset_event_simulate(window, "RET", "TAP", x, y)
element = tool.Ifc.get_entity(bpy.context.selected_objects[0])
assert_msg = "Created object should be IfcWall"
assert element.is_a() == "IfcWall"
_assert_pass(assert_msg)
assert_msg = "Created object should be typed by IfcWallType"
assert ifcopenshell.util.element.get_type(element).is_a() == "IfcWallType"
_assert_pass(assert_msg)
# TODO Asset the axis has the same X value
yield "FINISHED"
def run_tests():
module_name = os.getenv("MODULE", "snap")
if module_name == "wall":
filepath = f"./test/files/wall.ifc"
bpy.ops.bim.load_project(filepath=filepath)
window = _get_valid_window()
test_queue = [lambda w=window: test_draw_polyline_wall(w, 960, 540)]
elif module_name == "snap":
filepath = f"./test/files/snap.ifc"
bpy.ops.bim.load_project(filepath=filepath)
window = _get_valid_window()
test_queue = [
lambda w=window: test_snap_object_detection(w),
lambda w=window: test_snap_partially_behind_camera(w),
lambda w=window: test_snap_in_xray_mode(w),
lambda w=window: test_snap_far_from_origin(w),
]
else:
cleanup()
def _next():
if not test_queue:
cleanup()
return
test_fn = test_queue.pop(0)
# use the shared timer infrastructure
run_iter_from_timer(
test_fn(),
on_complete=_next,
on_error=lambda e: _handle_error(e, _next),
)
_next()
if __name__ == "__main__":
new_project()
run_tests()
@@ -26,7 +26,7 @@
#let bill_of_quantities_table = table(
#let bill_of_quantities_table(currency: "") = table(
columns: (18mm,54mm, 12mm,12mm,12mm,12mm, 20mm, 20mm, 25mm),
rows: (6mm, 248mm),
align: (center, left, center, center, center, center, center, center, center),
@@ -36,12 +36,12 @@
top: 1pt,
bottom: 1pt
),
[Hierarchy], [Description], [],[l],[w],[h/w], [Quantity], [Rate], [Total]
[Hierarchy], [Description], [],[l],[w],[h/w], [Quantity], [Rate (#currency)], [Total (#currency)]
)
#let schedule_of_rates_table = table(
#let schedule_of_rates_table(currency: "") = table(
columns: (30mm,130mm, 25mm),
rows: (6mm, 248mm),
align: (center, left, center),
@@ -51,12 +51,12 @@
top: 1pt,
bottom: 1pt
),
[Identification], [Description], [Rate]
[Identification], [Description], [Rate (#currency)]
)
#let summary_table = table(
#let summary_table(currency: "") = table(
columns: (18mm,107mm, 30mm, 30mm),
rows: (6mm, 248mm),
align: (center, left, center, center, center, center, center, center, center),
@@ -67,9 +67,9 @@
bottom: 1pt
),
text(size: 8pt)[Hierarchy],
text(size: 8pt)[Description],
text(size: 8pt)[Sub Total],
text(size: 8pt)[Total]
text(size: 8pt)[Description],
text(size: 8pt)[Sub Total (#currency)],
text(size: 8pt)[Total (#currency)]
)
@@ -127,7 +127,6 @@
#let arrange_summary_row(row, options) = {
let name = strong(upper(row.at("Name")))
let description = [#par(justify: true, text(8pt, row.at("Description", default: "")))]
let total = if row.at("RateSubtotal") == "" {0.0} else {float(row.at("RateSubtotal"))}
if row.at("ItemIsASum") == "True" {
if row.at("Index") == "1" {
// ROOT COST
@@ -216,7 +215,8 @@
format-decimal(float(row.at("Quantity")))}
let rate = if row.at("RateSubtotal") == "" {0.0} else {
format-decimal(float(row.at("RateSubtotal")))}
let total = if row.at("Quantity") == "" {0.0} else {
let total = if row.at("Quantity") == "" or row.at("RateSubtotal") == "" {
format-decimal(0.0, places: 2)} else {
format-decimal(float(row.at("Quantity")) * float(row.at("RateSubtotal")), places: 2)}
(
@@ -281,18 +281,18 @@
#let arrange_schedule_of_rates_row(row, options) = {
let name = strong(upper(row.at("Name")))
let description = [#par(justify: true, text(8pt, row.at("Description", default: "")))]
let unit = table.cell(align: right)[#unit_map.at(row.at("Unit"), default: "")]
let unit = table.cell(align: right + bottom)[#unit_map.at(row.at("Unit"), default: "")]
let rate = if row.at("RateSubtotal") == "" {0.0} else {
format-decimal(float(row.at("RateSubtotal")))}
if row.at("ItemIsASum") == "True" {return ()} //skip sections in schedule of rates
(
row.at("Identification"),
if row.at("Identification") == "" {name + linebreak() + description} else {name + linebreak() + description},
name + linebreak() + description,
[]
)
(
[],
table.cell(align: right+bottom)[#unit],
unit,
table.cell(align: right+bottom)[#rate],
)
(
@@ -342,8 +342,12 @@
) = {
let data = csv(path, delimiter: delimiter, row-type: dictionary)
let new_rows = data.map(item => arrange_summary_row(item, options))
let general_total = data.filter(row => row.at("ItemIsASum") == "False")
.map(row => float(row.at("RateSubtotal", default: 0.0))*float(row.at("Quantity", default: 0.0)))
let general_total = data.filter(row => row.at("ItemIsASum") == "False")
.map(row => {
let qty = if row.at("Quantity", default: "") == "" { 0.0 } else { float(row.at("Quantity")) }
let rate = if row.at("RateSubtotal", default: "") == "" { 0.0 } else { float(row.at("RateSubtotal")) }
qty * rate
})
.sum(default: 0.00)
set text(size: 10pt)
@@ -477,9 +481,9 @@
[#counter(page).display("1/1", both: true)]
)
],
background:
background:
place( top + left, dx: 15mm, dy: 25mm,
format_table.at(schedule_type, default: bill_of_quantities_table)
(format_table.at(schedule_type, default: bill_of_quantities_table))(currency: project_currency)
)
)
@@ -522,9 +526,9 @@
set page(
background:
place( top + left, dx: 15mm, dy: 25mm,
format_table.at("SUMMARY")
(format_table.at("SUMMARY"))(currency: project_currency)
)
)
create-summary(schedule_path, options)
}
}
}
@@ -48,6 +48,7 @@
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <cstdint>
#include <BRepExtrema_TriangleSet.hxx>
#include <BRepLProp_SLProps.hxx>
#include <BVH_BinaryTree.hxx>
@@ -1,5 +1,7 @@
#include "clash_utils.h"
#include <cassert>
#include <cstdint>
#include <cfloat>
#define GU_CULLING_EPSILON_RAY_TRIANGLE FLT_EPSILON*FLT_EPSILON
#define PX_MAX_F32 3.4028234663852885981170418348452e+38F
@@ -300,7 +300,11 @@ bool OpenCascadeKernel::convert(const taxonomy::sweep_along_curve::ptr scs, Topo
if (applied_temporary_offset) {
gp_Trsf trsf;
trsf.SetTranslation(gp_Vec(-mean.x(), -mean.y(), -mean.z()));
// Restore original position: add back the mean subtracted from the
// directrix points above. Previously negated, which placed the swept
// solid at -mean instead of its original location for geometry far
// from the origin.
trsf.SetTranslation(gp_Vec(mean.x(), mean.y(), mean.z()));
result.Move(trsf);
}
+1
View File
@@ -7,6 +7,7 @@
#include "../../ifcparse/IfcLogger.h"
#include <mutex>
#include <cstdint>
#define INCLUDE_SCHEMA(x) STRINGIFY(../../ifcparse/x.h)
#include INCLUDE_SCHEMA(IfcSchema)
+14 -7
View File
@@ -17,6 +17,13 @@
#include <tuple>
#include <exception>
#include <numeric>
#include <cstdint>
#include <cmath>
#include <array>
#include <limits>
#include <functional>
#include <algorithm>
#include <stdexcept>
#ifndef TAXONOMY_USE_UNIQUE_PTR
#ifndef TAXONOMY_USE_NAKED_PTR
@@ -1625,19 +1632,19 @@ typedef item const* ptr;
// @todo Sad... now that we have templated collection members,
// we can't generally use collection_base anymore as a cast target.
if (auto s = std::dynamic_pointer_cast<taxonomy::collection>(i)) {
visit<taxonomy::collection>(s, fn);
ifcopenshell::geometry::visit<taxonomy::collection>(s, fn);
} else if (auto s = std::dynamic_pointer_cast<taxonomy::loop>(i)) {
visit<taxonomy::loop>(s, fn);
ifcopenshell::geometry::visit<taxonomy::loop>(s, fn);
} else if (auto s = std::dynamic_pointer_cast<taxonomy::face>(i)) {
visit<taxonomy::face>(s, fn);
ifcopenshell::geometry::visit<taxonomy::face>(s, fn);
} else if (auto s = std::dynamic_pointer_cast<taxonomy::shell>(i)) {
visit<taxonomy::shell>(s, fn);
ifcopenshell::geometry::visit<taxonomy::shell>(s, fn);
} else if (auto s = std::dynamic_pointer_cast<taxonomy::solid>(i)) {
visit<taxonomy::solid>(s, fn);
ifcopenshell::geometry::visit<taxonomy::solid>(s, fn);
} else if (auto s = std::dynamic_pointer_cast<taxonomy::loft>(i)) {
visit<taxonomy::loft>(s, fn);
ifcopenshell::geometry::visit<taxonomy::loft>(s, fn);
} else if (auto s = std::dynamic_pointer_cast<taxonomy::boolean_result>(i)) {
visit<taxonomy::boolean_result>(s, fn);
ifcopenshell::geometry::visit<taxonomy::boolean_result>(s, fn);
}
else {
fn(i);
@@ -81,6 +81,13 @@ def validate_type(
if not preferred_item and remaining_items:
preferred_item = remaining_items[0]
# preferred_item must not appear in remaining_items — if it was selected from
# that list, leaving it in causes add_boolean to union it with itself, and the
# subsequent Items filter then removes ALL items (including preferred_item),
# leaving Items=[] which guess_type maps to "MappedRepresentation".
if preferred_item in remaining_items:
remaining_items = [i for i in remaining_items if i != preferred_item]
if remaining_items:
ifcopenshell.api.geometry.add_boolean(file, preferred_item, remaining_items, "UNION")
representation.Items = [i for i in representation.Items if i not in remaining_items]
@@ -916,7 +916,7 @@ class FacetTransformer(lark.Transformer):
if self.elements:
self.results.append(self.elements)
self.elements = set()
self.has_additive_facet_in_current_list = False
self.has_additive_facet_in_current_list = False
def instance(self, args):
self.has_additive_facet_in_current_list = True
+1
View File
@@ -27,6 +27,7 @@
#include "utils.h"
#include <atomic>
#include <cstdint>
#include <boost/shared_ptr.hpp>
class aggregate_of_instance;
+1 -1
View File
@@ -201,7 +201,7 @@ namespace {
if (character >= 0x20 && character <= 0x7e) {
stream.put((char)character);
} else {
stream << "\\u" << character;
stream << "\\u" << static_cast<uint32_t>(character);
}
});
return stream.str();
+3
View File
@@ -36,6 +36,9 @@
#endif
#include <cstdint>
#include <cstring>
#include <boost/optional.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/logic/tribool.hpp>
+1
View File
@@ -34,6 +34,7 @@
#include <boost/circular_buffer.hpp>
#include <iterator>
#include <map>
#include <cstdint>
#ifdef IFOPSH_WITH_ROCKSDB
#include <rocksdb/merge_operator.h>
+2
View File
@@ -25,7 +25,9 @@
#include <algorithm>
#include <boost/algorithm/string.hpp>
#include <cctype>
#include <cstdint>
#include <iterator>
#include <memory>
#include <string>
#include <vector>
+1
View File
@@ -26,6 +26,7 @@
#include <boost/shared_ptr.hpp>
#include <set>
#include <vector>
#include <algorithm>
namespace IfcParse {
class declaration;
+2
View File
@@ -30,6 +30,8 @@
#include <utility>
#include <iterator>
#include <cstddef>
#include <cstdint>
#include <cstring>
template <typename T>
struct is_std_tuple : std::false_type {};
+2
View File
@@ -25,6 +25,8 @@ namespace rocksdb {
#include <variant>
#include <iterator>
#include <cstdint>
#include <cstring>
#include <type_traits>
#include <iostream>
#include <vector>
+4
View File
@@ -33,6 +33,10 @@ variant - which is the maximum size of its constituents - is reduced.
#include <utility>
#include <memory>
#include <tuple>
#include <cstdint>
#include <cstring>
#include <cstddef>
#include <limits>
#include "IfcException.h"
+2
View File
@@ -23,6 +23,8 @@
#include "../ifcparse/utils.h"
#include <cstdint>
#ifdef WITH_PROJ
#include <proj.h>
#endif
+1
View File
@@ -34,6 +34,7 @@
#include <numeric>
#include <functional>
#include <cmath>
#include <cstdint>
#ifdef USE_BINARY
#define write_shape write_binary
+3
View File
@@ -4,6 +4,9 @@
#include <rocksdb/options.h>
#include <cstdint>
#include <cstring>
#include "../ifcparse/IfcLogger.h"
RocksDbSerializer::RocksDbSerializer(IfcParse::IfcFile* file, const std::string& rocksdb_filename)