Compare commits

...

19 Commits

Author SHA1 Message Date
Petru Conduraru 92f9dc9d60 ifcopenshell.util.element: dedupe SET-typed attributes in replace_attribute
replace_attribute() rewrites references inside aggregate attributes via
element.walk(), but never checked whether the replacement value was
already present elsewhere in the same aggregate. For an EXPRESS SET
(e.g. IfcProject.RepresentationContexts, IfcRelAggregates.RelatedObjects)
this can leave the same reference listed twice, which is invalid IFC.
LIST and BAG aggregates legitimately allow duplicates, so a blanket dedup
would be wrong; only SET-typed attributes are deduplicated, determined at
runtime from the schema declaration (IfcOpenShell#8706 review comment).

The SET/LIST/BAG check is cached per (schema, class, attribute index), and
the dedup pass itself only runs when a cheap linear pre-check finds the
replacement value already present in the aggregate, so the common case
(no duplicate produced) pays only that pre-check, not a hash-set rebuild.
Benchmarked against a 23MB (431k entities) and a 104MB (2.4M entities) IFC
model against a large SET attribute: worst case adds well under 1ms per
call; the realistic case (merging duplicate contexts, matching the PR
#8706 scenario) shows no measurable regression.

Fixes the root cause flagged in IfcOpenShell#8706 (Moult), obviating the
need for MergeDuplicateContexts' own manual aggregate-dedup pass for that
scenario.

Generated with the assistance of an AI coding tool.
2026-07-20 15:54:59 +03:00
Petru Conduraru 55a2430d71 docs: cover the Blender 5.1 / Python 3.13 transition in installation guides (#8781)
* docs: cover the Blender 5.1 / Python 3.13 transition in installation guides

The system requirements still listed Blender 4.3-4.5 with Python 3.11
only, and nothing documented the pitfall from issue 7623: importing
preferences into a Blender whose Python version changed carries over an
incompatible Bonsai build that silently fails to load. Document the two
Python generations, that Get Extensions picks the matching build
automatically while manual zip installs do not, and the
uninstall-reinstall step that resolves the upgrade case.

Generated with the assistance of an AI coding tool.

* docs: keep it simple, only Blender 5.1 and 5.2 with Python 3.13

Per review, drop the descriptive text and the Python 3.11 line.

Generated with the assistance of an AI coding tool.
2026-07-20 16:27:51 +10:00
Petru Conduraru 04a2535a98 Preserve the real cause when the ifcopenshell wrapper fails to load (#8785)
* Keep real cause in wrapper ImportError

When the compiled wrapper exists for the current interpreter but fails
to load (for example a glibc version mismatch, as on AWS Lambda in
issue 5927), the bare except rewrote the error into the misleading
"IfcOpenShell not built for '<platform>'" message. Environments such
as AWS Lambda or the Blender add-on dialog only surface the final
exception message, so the actual cause was invisible and undiagnosable.

Keep the "not built for" message only when no matching binary is
present, and otherwise include the original loader error, chaining the
cause in both branches.

This change was AI-generated.

Fixes #5927

* Simplify wrapper import failure to a single message

Per review feedback, drop the filesystem scan and the two message
variants. Always raise the classic "IfcOpenShell not built for
'<platform>'" message with the original exception appended in
parentheses, still chained as the cause. Environments that only show
the final exception message (AWS Lambda, the Blender add-on dialog)
now surface the real loader error, such as the glibc version mismatch
in issue 5927, without any extra logic.

This change was AI-generated.
2026-07-20 16:27:22 +10:00
Petru Conduraru 727b5f3475 Bonsai: add Hour zoom level to the interactive Gantt chart
The jsGantt-improved library that renders Bonsai's Gantt chart already
ships full support for an "Hour" granularity (column width, header
labels in every bundled language, hour-aware rendering math). Bonsai's
config only exposed Day/Week/Month/Quarter, with a comment claiming
Hour caused browser issues even with vUseSingleCell enabled.

Headless Chrome testing against the same library version shows that
claim no longer holds once vUseSingleCell is active (as Bonsai already
configures it at 10000): Hour-format charts render without errors from
typical schedules up through fairly extreme ones (5000 tasks across a
3 year span rendered in about 2.4s). The failure mode the old comment
described only reproduces with vUseSingleCell disabled, which is not
how Bonsai runs it.

Task start/finish times already flow through to the chart unmodified
as raw ISO datetimes (tool/sequence.py create_new_task_json), so any
schedule authored with real hour-level timestamps, for example an
imported MS Project/P6/Excel schedule or one written directly through
ifcopenshell-python, can now be viewed at hour granularity. Verified
live with a night shift schedule crossing midnight, rendered correctly
with no console errors.

Note: Bonsai's own "Edit Task Time" UI currently always snaps
ScheduleStart/ScheduleFinish to 09:00/17:00 regardless of the hour
entered (ifcopenshell/api/sequence/edit_task_time.py), and work
calendars only encode working days, not working hours. So authoring a
genuine hour-precision schedule through that UI is still not possible;
this change only unlocks viewing hour-level data that already exists
in the model. Fixing the editor and calendar model is a separate,
larger design decision for a maintainer.

Addresses #2772.

Generated with the assistance of an AI coding tool.
2026-07-20 10:19:42 +10:00
Bartok a45f2fae61 docs(ifc2ca): fix script paths in README
Point scriptSalome.py at templates/salome/ and the bonded scripts at
_deprecated/, matching the current tree so README links resolve.

Generated with the assistance of an AI coding tool.
2026-07-20 09:53:35 +10:00
dependabot[bot] 1ae50b8cce build(deps): bump ruff from 0.15.12 to 0.15.22 (#8212)
Bumps [ruff](https://github.com/astral-sh/ruff) from 0.15.12 to 0.15.22.
- [Release notes](https://github.com/astral-sh/ruff/releases)
- [Changelog](https://github.com/astral-sh/ruff/blob/main/CHANGELOG.md)
- [Commits](https://github.com/astral-sh/ruff/compare/0.15.12...0.15.22)

---
updated-dependencies:
- dependency-name: ruff
  dependency-version: 0.15.20
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-07-20 09:52:46 +10:00
dependabot[bot] 9fda996ebe build(deps): bump ruff from 0.15.12 to 0.15.22 (#8497)
Bumps [ruff](https://github.com/astral-sh/ruff) from 0.15.12 to 0.15.22.
- [Release notes](https://github.com/astral-sh/ruff/releases)
- [Changelog](https://github.com/astral-sh/ruff/blob/main/CHANGELOG.md)
- [Commits](https://github.com/astral-sh/ruff/compare/0.15.12...0.15.22)

---
updated-dependencies:
- dependency-name: ruff
  dependency-version: 0.15.21
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-07-20 09:52:38 +10:00
dependabot[bot] 7a7a250942 build(deps): bump ruff from 0.15.12 to 0.15.22
Bumps [ruff](https://github.com/astral-sh/ruff) from 0.15.12 to 0.15.22.
- [Release notes](https://github.com/astral-sh/ruff/releases)
- [Changelog](https://github.com/astral-sh/ruff/blob/main/CHANGELOG.md)
- [Commits](https://github.com/astral-sh/ruff/compare/0.15.12...0.15.22)

---
updated-dependencies:
- dependency-name: ruff
  dependency-version: 0.15.22
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-07-20 09:52:07 +10:00
Petru Conduraru bc1fb2a88d Bonsai: add one click copy of annotations to another drawing (#8719)
* Bonsai: move annotations between drawings when reassigning their group

Assigning an IfcAnnotation to a group that represents another drawing
previously left the annotation in both drawings at once: it stayed in
its old drawing group, its Blender object stayed in the old drawing
collection, and it kept the old camera depth, so the reassignment
appeared to do nothing useful. Issue #2966 documents the seven step
manual workaround users needed instead.

The assign group operator now detects when the target group represents
a drawing (via the new tool.Drawing.get_group_drawing, the inverse of
get_drawing_group), unassigns the annotation from its previous drawing
group, moves its object into the new drawing collection, and places it
on the new drawing camera plane. The target camera is imported on
demand when it has not been loaded yet, matching the pattern used by
the activate drawing operator.

Generated with the assistance of an AI coding tool.

* Bonsai: add one click copy of annotations to another drawing (#2966)

Duplicating an annotation into a different drawing used to require a
seven step manual process: loading groups in scene properties, copying
the object, fixing its group assignment by hand, and repositioning it
onto the target camera plane. A plain Blender duplicate is not enough
because the copy keeps pointing at the same IFC entity, and the Shift D
override, while it does create a genuine new entity through
root.copy_class, leaves the duplicate in the source drawing group,
collection, and camera depth.

The new copy annotation to drawing operator packages the proven recipe
already used by duplicate drawing into one action: duplicate through
tool.Geometry.duplicate_ifc_objects, unassign the copy from the source
drawing group, assign it to the chosen target group, place it on the
target camera plane at the same world XY, and file it into the target
drawing collection. The originals are left untouched and the user's
selection is restored. The target camera is imported on demand when it
has not been loaded yet.

The operator shows a target drawing dropdown and is reachable from the
annotation tool sidebar when an annotation is selected, and from the
drawings panel. Annotations already in the target drawing are skipped
and reported.

The orchestration lives in core.drawing.copy_annotations_to_drawing
with prophecy tests covering the copy, the skip, and the camera import
branches. Verified live in headless Blender 5.1: the copy is a new
IfcAnnotation with its own GlobalId and IfcTextLiteral, both texts are
editable independently, and everything survives save and reload with
each annotation loading in its own drawing.

Generated with the assistance of an AI coding tool.
2026-07-20 09:50:14 +10:00
Petru Conduraru c55a79b8b5 bonsai: allow overriding which classes join in section linework (#4395) (#8617)
Fixes #4395.

Root cause: the SVG cut-linework merge step that fuses adjacent
elements' cut polygons together (per the pset-driven JoinCriteria
setting) was hardcoded to only IfcWall and IfcSlab. IfcCovering cut
shapes were skipped unconditionally, so adjacent coverings never
joined, leaving a visible seam/broken corner in section drawings
regardless of JoinCriteria.

Fix: added an EPset_Drawing.JoinClasses property, following the
exact same user-overridable pattern already used by
EPset_Drawing.BringToFront - a comma-separated list of IFC classes
to join, defaulting to "IfcWall,IfcSlab" (unchanged behavior) when
unset. Users can override per-drawing to add IfcCovering (or any
other class) when they want it joined too. Kept this opt-in rather
than hardcoding IfcCovering into the default list, since joining a
thin finish layer the same way as a thick wall/slab could produce
unwanted mitring in some cases - the user decides per drawing.

Verified live against the reporter's own attached file
(ifcovering joining.ifc) and its cached section linework: with
JoinClasses unset, two separate closed paths reproduce the reported
seam exactly. With JoinClasses = "IfcWall,IfcSlab,IfcCovering", the
two coverings merge into a single closed polygon with the internal
seam removed. Confirmed IfcSlab join behavior is unchanged in both
runs.

Generated with the assistance of an AI coding tool.

Co-authored-by: Dion Moult <dionmoult@gmail.com>
2026-07-20 09:41:09 +10:00
sboddy b669baf793 Propagate deflection settings on reload (#8484)
reimport_element_representations() built a fresh
ifcopenshell.geom.settings() without copying deflection_tolerance /
angular_tolerance from the IfcImportSettings it had just
constructed, and never passed geometry_library to either the
iterator() or create_shape() calls it makes. As a result, exiting
Item/edit mode (which reaches this function via
switch_representation) silently fell back to IfcOpenShell's
hard-coded mesher defaults (0.001 linear deflection, ~50x finer than
the project's default of 0.05) and the default geometry kernel,
instead of the project's configured tolerance and Geometry Library.

This made geometry visibly change quality after a no-op Tab into and
back out of edit mode, since the reload path was unintentionally far
more precise (and used a different kernel) than the initial import.
Both settings, and geometry_library, are now taken from the
IfcImportSettings instance already built at the top of the function,
so a reload matches the original import.

Refs #5685.

Generated with the assistance of an AI coding tool.

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-20 09:37:04 +10:00
Petru Conduraru 32ac20e8e3 Bonsai: refresh the arc/circle decorator immediately after duplicating a loop
theoryshaw's follow-up on #6944: after the profile/curve reconstruction fix
(previous commit), the arc/circle marker for a freshly Shift+D-duplicated
loop wouldn't appear until leaving and re-entering Edit Mode.

Root cause: ProfileDecorator groups arc/circle vertices purely by
IFCARCINDEX/IFCCIRCLE vertex-group index every draw call (it has no cache
to go stale, it fully recomputes from the live edit-mesh bmesh each frame).
Duplicating a loop copies its vertex-group weights onto the new geometry,
since Blender allocates no new group for a duplicate, so the source loop
and its live duplicate land in the same dict entry. That entry then fails
the "exactly 2 verts per circle / 3 per arc" check and is skipped entirely,
so BOTH the original and the duplicate stop being drawn until the mesh is
reimported and gets fresh, distinct groups.

Verified live in headless Blender: built a bmesh with an IFCCIRCLE loop and
an IFCARCINDEX loop, then ran bmesh.ops.duplicate on each (the same
bmesh-level operation underlying Shift+D) and called ProfileDecorator's
draw method directly. Before this change, duplicating either loop dropped
both the original and the duplicate from the decorator (0 circle/arc
batches drawn instead of 2). After, both draw immediately, with no change
to the non-duplicated case (still 1) or to genuinely distinct loops (5
independent circles still resolve to 5, not merged). 500-circle timing is
unchanged (~14.3ms/draw before and after), so the added connectivity split
is not a hot-path regression.

Added test/bim/module/model/test_profile_decorator_duplicate_loop.py
pinning the new _connected_components helper's behavior for single and
duplicated circle/arc loops.

This contribution was produced with the assistance of an AI coding tool.
2026-07-20 09:34:07 +10:00
Petru Conduraru 0d5ea02169 Bonsai: fix the same duplicate-loop vertex-group bug in auto_detect_curves
auto_detect_profiles had the identical defect fixed in the previous
commit: duplicating a circle/arc loop in Edit Mode reuses the same
IFCCIRCLE/IFCARCINDEX vertex group index for the new geometry, and this
sibling function (used for curve/annotation editing rather than profile
voids) tallied group membership across the whole mesh instead of per
loop, so it also rejected a legitimately duplicated loop as malformed.

Applied the identical fix: scope the group-count sanity check to each
connected edge loop, computed after the loops are built rather than in
the initial whole-mesh vertex pass. Kept the existing forked-loop check
(more than 2 edges per vertex) in the first pass since it is unrelated
to group counting.

Verified live in headless Blender: constructed two 2-vertex IFCCIRCLE
loops sharing one vertex group index (the exact state Blender's Edit
Mode duplicate produces) and called auto_detect_curves directly.
Before this change it returned (False, "CIRCLE"); after, it returns two
valid IfcCircle curves.

Generated with the assistance of an AI coding tool.
2026-07-20 09:34:07 +10:00
Petru Conduraru 0a027d47a3 Bonsai: fix profile reconstruction after duplicating a circle/arc in Edit Mode
Duplicating a circular or filleted-arc void in the profile CAD editor
(Shift+D on the loop's vertices) reused the same IFCCIRCLE/IFCARCINDEX
vertex group index for the new geometry, since Blender's mesh duplicate
copies vertex group weights but does not allocate a new group. On exit
from Edit Mode, auto_detect_profiles tallied group membership across the
whole mesh rather than per loop, so a group meant to hold exactly 2 (circle)
or 3 (arc) vertices ended up with double that, failing its sanity check
and blocking the edit with an "INVALID PROFILE" popup. Fixes #6944.

Scope the sanity check to each connected edge loop instead, matching how
the loops are actually converted into IfcCircle/arc segments below. Also
explicitly reject an arc/circle vertex tagged onto an isolated vertex with
no edges at all, which the old whole-mesh count also caught.

Verified live in headless Blender against the issue's repro file
(IfcFurniture "Slab.004", IfcArbitraryProfileDefWithVoids with three
IfcCircle voids): entering the profile editor, duplicating one void's
2-vertex loop and moving it produced an "INVALID PROFILE" popup before
this change, and now produces a valid profile (the original 3 voids
intact, plus the duplicate as a 4th void or a separate solid profile
depending on whether it still falls inside the outer boundary).
test/tool/test_model.py passes unchanged (32 passed, 1 pre-existing
unrelated failure present on both before and after).

Generated with the assistance of an AI coding tool.
2026-07-20 09:34:07 +10:00
Petru Conduraru 6014bbd877 ci-lint: black-format two files that drifted on v0.8.0
Both files were merged unformatted and fail the Black formatter step
on every branch, keeping ci-lint red repo-wide.

Generated with the assistance of an AI coding tool.
2026-07-20 09:24:34 +10:00
Petru Conduraru 6d6d92b849 Fix all remaining ty type-check failures on ci-lint
The ci-lint workflow's ty steps fail on every branch because base
v0.8.0 has four diagnostics.

ty check (bonsai):

- root/operator.py: bpy.data.objects.get() can return None, so
  UnlinkObject._execute could put None in its objects list and crash
  on the first attribute access when an unknown object name is passed.
  Handle the miss explicitly, which also satisfies the declared
  list[bpy.types.Object] type.
- tool/sequence.py: ty does not narrow Literal types through
  membership tests on list literals, so the assert_never() exhaustive
  check was flagged. Use tuple literals, which ty narrows, keeping the
  exhaustiveness check intact.

ty check (ios):

- draw.py: arrange_polygons was called through conditional argument
  splats that let the same call site work against pre-April-2026
  wrappers lacking arrange_polygon_settings and the logger parameter.
  No runtime bug for current builds, but the dynamic splats cannot be
  typed against the fixed 3-parameter signature. Drop the old-build
  workaround and call the current signature directly, following the
  precedent of 3d8115ebc5 which dropped similar old-build workarounds
  in ifcopenshell.file. Verified against a current wrapper build that
  the direct call arranges polygons and serializes to SVG, with and
  without a logger.
- Optimise.py: igraph is an optional dependency with a guarded import
  and a toposort fallback, but it was missing from the ios type-check
  venv so ty could not resolve it. Add it to type-check-requirements
  next to the toposort fallback that is already listed.

After this, poe ty-bonsai and poe ty-ios both pass cleanly.

Generated with the assistance of an AI coding tool.
2026-07-20 09:23:48 +10:00
Petru Conduraru bb49822f2e Bonsai: make dxf2ifc.py example script skip unsupported DXF entities
The script called Polyline.get_mode() on every modelspace entity, but
that method only exists on POLYLINE entities, so any typical DXF
containing lines, circles or text crashed with AttributeError before
converting anything. Test for POLYLINE polyface meshes with
dxftype()/is_poly_face_mesh instead and skip other entities with a
message, only create the spatial containment relation when products
exist, and take the input/output paths from the command line (matching
obj2ifc.py) instead of a hardcoded input.dxf/test.ifc.

Fixes #2151

This change was written with the assistance of an AI coding tool.
2026-07-20 09:22:44 +10:00
Bruno Postle 21ea58b0e6 Fix Bonsai polyline not enough values to unpack error
Typo was introduced in b35f99e
2026-07-19 23:50:19 +01:00
Ryan Schultz b66d8b2c4d Fix #6652: Extend grab selection to include BBIM_Array members (#7968)
When grabbing an array child, the selection now expands to include
the array parent and all sibling children before the move operator
runs. Mirrors existing behavior for aggregates and nests.

Generated with the assistance of an AI coding tool.
2026-07-19 14:00:44 -05:00
32 changed files with 605 additions and 80 deletions
+1 -1
View File
@@ -1,5 +1,5 @@
black==26.3.1
ruff==0.15.12
ruff==0.15.22
poethepoet
ty==0.0.61
gersemi==0.26.1
@@ -5,7 +5,7 @@ FILE_NAME('EPset_Drawing.ifc','2020-01-01T00:00:00',$,$,'EPset_Drawing','EPset_D
FILE_SCHEMA(('IFC4'));
ENDSEC;
DATA;
#1=IFCPROPERTYSETTEMPLATE('2JhNIvqZrFnAgxfhK0XVQX',$,'EPset_Drawing','',.PSET_OCCURRENCEDRIVEN.,'IfcAnnotation/DRAWING',(#23,#22,#27,#24,#29,#30,#19,#12,#26,#9,#8,#7,#6,#4,#18,#11,#5,#20,#25,#14,#10,#17,#28,#16,#3,#21,#13,#15,#2,#31,#32,#33,#34,#35,#36));
#1=IFCPROPERTYSETTEMPLATE('2JhNIvqZrFnAgxfhK0XVQX',$,'EPset_Drawing','',.PSET_OCCURRENCEDRIVEN.,'IfcAnnotation/DRAWING',(#23,#22,#27,#24,#29,#30,#19,#12,#26,#9,#8,#7,#6,#4,#18,#11,#5,#20,#25,#14,#10,#17,#28,#16,#3,#21,#13,#15,#2,#31,#32,#33,#34,#35,#36,#37));
#2=IFCSIMPLEPROPERTYTEMPLATE('23JavTMk98ZxXhrUEnjAcf',$,'TargetView','',.P_SINGLEVALUE.,'IfcLabel',$,$,$,$,$,.READWRITE.);
#3=IFCSIMPLEPROPERTYTEMPLATE('1yVWUt5H9DAOuu0OaMMLpe',$,'Scale','The scale of this drawing represented as a numerator and denominator, such as 1/100',.P_SINGLEVALUE.,'IfcLabel',$,$,$,$,$,.READWRITE.);
#4=IFCSIMPLEPROPERTYTEMPLATE('3gsuPBtU93b8f0gg1pjkq6',$,'HumanScale','The scale of this drawing in human readable format, such as 1:100',.P_SINGLEVALUE.,'IfcLabel',$,$,$,$,$,.READWRITE.);
@@ -41,5 +41,6 @@ DATA;
#34=IFCSIMPLEPROPERTYTEMPLATE('2epSGfC4bFM9gb1X7zBIp4',$,'RenderSharp','Whether to render ''sharp'' (convex) edges. Only relevant when UseEdgeClassification is enabled.',.P_SINGLEVALUE.,'IfcBoolean',$,$,$,$,$,.READWRITE.);
#35=IFCSIMPLEPROPERTYTEMPLATE('3TZwsEjkr5WRDKcgrYzSIA',$,'RidgeAngleMinDegrees','Minimum convex dihedral deviation from flat, in degrees, for a projection edge to be classified as ''sharp'' rather than ''flush''.',.P_SINGLEVALUE.,'IfcReal',$,$,$,$,$,.READWRITE.);
#36=IFCSIMPLEPROPERTYTEMPLATE('2Jua$lO754vgZOkBoHM2gA',$,'RenderFlush','Whether to render ''flush'' edges (dihedral deviation below both ridge/valley thresholds). Only relevant when UseEdgeClassification is enabled.',.P_SINGLEVALUE.,'IfcBoolean',$,$,$,$,$,.READWRITE.);
#37=IFCSIMPLEPROPERTYTEMPLATE('1zM9sia2L8RQDnWZxgUwlZ',$,'JoinClasses','Comma separated list of IFC classes whose cut linework will be joined together when they meet (e.g. mitred at a corner).\X2\000A\X0\Defaults to ''IfcWall,IfcSlab'' if not set. Override to also join other classes, such as ''IfcWall,IfcSlab,IfcCovering''.',.P_SINGLEVALUE.,'IfcText',$,$,$,$,$,.READWRITE.);
ENDSEC;
END-ISO-10303-21;
@@ -244,7 +244,7 @@ function addGanttElement(blenderId, tasks, workSched, filename) {
vShowTaskInfoLink: 1, // Show link in tool tip (0/1)
vShowEndWeekDate: 0, // Show/Hide the date for the last day of the week in header for daily
vUseSingleCell: 10000, // Set the threshold cell per table row (Helps performance for large data.
vFormatArr: ["Day", "Week", "Month", "Quarter"], // Even with setUseSingleCell using Hour format on such a large chart can cause issues in some browsers,
vFormatArr: ["Hour", "Day", "Week", "Month", "Quarter"], // vUseSingleCell keeps Hour usable on large charts.
vShowRes: true, // Disable the resource column.
vShowComp: false, // Disable the completion column.
vShowDur: false, // Disable the duration column, because jsgantt doesn't calculate durations the way we want.
@@ -47,6 +47,7 @@ classes = (
operator.CleanWireframes,
operator.ContractSheet,
operator.ConvertSVGToDXF,
operator.CopyAnnotationToDrawing,
operator.CopyTextToSelection,
operator.CreateDrawing,
operator.CreateSheets,
@@ -228,6 +228,90 @@ class DuplicateDrawing(bpy.types.Operator, tool.Ifc.Operator):
)
def get_copy_annotation_target_drawings(self, context):
global COPY_ANNOTATION_TARGET_DRAWINGS_ENUM
drawings = [e for e in tool.Ifc.get().by_type("IfcAnnotation") if e.ObjectType == "DRAWING"]
drawings.sort(key=lambda d: d.Name or "")
COPY_ANNOTATION_TARGET_DRAWINGS_ENUM = [(str(d.id()), d.Name or "Unnamed", "") for d in drawings]
return COPY_ANNOTATION_TARGET_DRAWINGS_ENUM
COPY_ANNOTATION_TARGET_DRAWINGS_ENUM = []
class CopyAnnotationToDrawing(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.copy_annotation_to_drawing"
bl_label = "Copy Annotation To Drawing"
bl_description = (
"Copy the selected annotations to another drawing.\n\n"
"The copies become independent annotations assigned to the chosen drawing, "
"placed in its view plane. The originals stay in their current drawing"
)
bl_options = {"REGISTER", "UNDO"}
target_drawing: bpy.props.EnumProperty(name="Target Drawing", items=get_copy_annotation_target_drawings)
if TYPE_CHECKING:
target_drawing: str
@classmethod
def poll(cls, context):
if not tool.Ifc.get():
cls.poll_message_set("No IFC project loaded.")
return False
if not cls.get_selected_annotations(context):
cls.poll_message_set("No annotation selected.")
return False
return True
@classmethod
def get_selected_annotations(cls, context) -> list[ifcopenshell.entity_instance]:
return [
element
for obj in context.selected_objects
if (element := tool.Ifc.get_entity(obj))
and element.is_a("IfcAnnotation")
and element.ObjectType != "DRAWING"
]
def invoke(self, context, event):
assert context.window_manager
return context.window_manager.invoke_props_dialog(self)
def draw(self, context):
assert self.layout
row = self.layout.row()
row.prop(self, "target_drawing")
def _execute(self, context):
if not self.target_drawing:
self.report({"ERROR"}, "No target drawing selected.")
return {"CANCELLED"}
target_drawing = tool.Ifc.get().by_id(int(self.target_drawing))
annotations = self.get_selected_annotations(context)
previous_selection = [obj for a in annotations if (obj := tool.Ifc.get_object(a))]
previous_active = context.view_layer.objects.active
copied = core.copy_annotations_to_drawing(
tool.Ifc,
tool.Collector,
tool.Drawing,
tool.Geometry,
annotations=annotations,
target_drawing=target_drawing,
)
for obj in context.selected_objects:
obj.select_set(False)
for obj in previous_selection:
if obj.name in context.view_layer.objects:
obj.select_set(True)
if previous_active and previous_active.name in context.view_layer.objects:
context.view_layer.objects.active = previous_active
skipped = len(annotations) - len(copied)
message = f"Copied {len(copied)} annotations to {target_drawing.Name or 'Unnamed'}."
if skipped:
message += f" Skipped {skipped} already in that drawing."
self.report({"INFO"}, message)
class CreateDrawing(bpy.types.Operator):
"""Creates/refreshes a .svg drawing
@@ -1471,6 +1555,15 @@ class CreateDrawing(bpy.types.Operator):
"Material.Name",
]
join_classes = ifcopenshell.util.element.get_pset(self.camera_element, "EPset_Drawing", "JoinClasses")
if join_classes:
join_classes = tuple(c.strip() for c in join_classes.split(",") if c.strip())
else:
# Architectural convention only merges these objects by default. E.g. pipe
# segments and fittings shouldn't merge. Users may override this per-drawing
# via the EPset_Drawing.JoinClasses property (e.g. to also join IfcCovering).
join_classes = ("IfcWall", "IfcSlab")
group = root.find("{http://www.w3.org/2000/svg}g")
joined_paths = {}
self.is_manifold_cache = {}
@@ -1572,8 +1665,7 @@ class CreateDrawing(bpy.types.Operator):
)
path.attrib["d"] = d
# Architectural convention only merges these objects. E.g. pipe segments and fittings shouldn't merge.
if not element.is_a("IfcWall") and not element.is_a("IfcSlab"):
if not any(element.is_a(c) for c in join_classes):
continue
keys = []
@@ -332,6 +332,8 @@ class BIM_PT_drawings(Panel):
row3.separator(factor=0.5, type="SPACE")
row3.operator("bim.copy_annotation_to_drawing", icon="PASTEDOWN", text="")
row3.operator("bim.select_all_drawings", icon="CHECKBOX_HLT", text="")
row3.operator("bim.create_drawing", text="", icon="OUTPUT")
row3.operator("bim.convert_svg_to_dxf", text="", icon="SEQ_PREVIEW").view = active_drawing.name
@@ -225,6 +225,9 @@ class AnnotationToolUI:
def draw_edit_object_interface(cls, context):
if DecoratorData.get_text_data(bpy.context.active_object):
add_layout_hotkey_operator(cls.layout, "Edit Text", "S_E", "")
if bpy.ops.bim.copy_annotation_to_drawing.poll():
row = cls.layout.row(align=True)
row.operator("bim.copy_annotation_to_drawing", icon="PASTEDOWN", text="Copy To Drawing")
@classmethod
def draw_type_selection_interface(cls):
@@ -4124,6 +4124,31 @@ class OverrideMoveSelect(bpy.types.Operator):
self.new_active_obj = obj
return {"FINISHED"}
# Get arrays
ifc_file = tool.Ifc.get()
array_parents_to_move: list[bpy.types.Object] = []
for obj in list(context.selected_objects):
element = tool.Ifc.get_entity(obj)
if not element:
continue
pset = ifcopenshell.util.element.get_pset(element, "BBIM_Array")
if not pset:
continue
parent_element = ifc_file.by_guid(pset["Parent"])
parent_obj = tool.Ifc.get_object(parent_element)
if parent_obj not in array_parents_to_move:
array_parents_to_move.append(parent_obj)
if element.GlobalId != pset["Parent"]:
obj.select_set(False)
if array_parents_to_move:
for parent_obj in array_parents_to_move:
parent_element = tool.Ifc.get_entity(parent_obj)
for array_obj in tool.Array.get_all_objects(parent_element):
array_obj.select_set(True)
self.new_active_obj = parent_obj
return {"FINISHED"}
# Get nests
props = tool.Nest.get_nest_props()
not_editing_objs = [o.obj for o in props.not_editing_objects]
+39 -1
View File
@@ -163,14 +163,52 @@ class AssignGroup(bpy.types.Operator, tool.Ifc.Operator):
def _execute(self, context):
if not self.is_assigning:
return bpy.ops.bim.unassign_group(group=self.group)
ifc_file = tool.Ifc.get()
group = ifc_file.by_id(self.group)
products = [
element
for o in tool.Blender.get_selected_objects(include_active=False)
if (element := tool.Ifc.get_entity(o))
]
ifcopenshell.api.group.assign_group(tool.Ifc.get(), products=products, group=tool.Ifc.get().by_id(self.group))
relocated_annotations = self.unassign_from_previous_drawing(ifc_file, group, products)
ifcopenshell.api.group.assign_group(ifc_file, products=products, group=group)
self.relocate_annotations_to_drawing(relocated_annotations, group)
self.report({"INFO"}, f"Assigned {len(products)} objects to group.")
def unassign_from_previous_drawing(self, ifc_file, group, products) -> list[ifcopenshell.entity_instance]:
"""Assigning an annotation to a group that represents a drawing means the
annotation should belong to that drawing only, so it needs to leave
whichever drawing it was previously part of, instead of ending up
visible in both at once.
"""
new_drawing = tool.Drawing.get_group_drawing(group)
if not new_drawing:
return []
relocated = []
for product in products:
if not product.is_a("IfcAnnotation") or product.ObjectType == "DRAWING":
continue
old_drawing = tool.Drawing.get_annotation_drawing(product)
if not old_drawing or old_drawing.id() == new_drawing.id():
continue
if old_group := tool.Drawing.get_drawing_group(old_drawing):
ifcopenshell.api.group.unassign_group(ifc_file, products=[product], group=old_group)
relocated.append(product)
return relocated
def relocate_annotations_to_drawing(self, products, group) -> None:
"""Move the relocated annotations into the new drawing's collection and
depth, now that they have actually been assigned to its group.
"""
if not products:
return
new_drawing = tool.Drawing.get_group_drawing(group)
new_camera = tool.Ifc.get_object(new_drawing) or tool.Drawing.import_drawing(new_drawing)
for product in products:
if obj := tool.Ifc.get_object(product):
tool.Drawing.ensure_annotation_in_drawing_plane(obj, camera=new_camera)
tool.Collector.assign(obj)
class UnassignGroup(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.unassign_group"
@@ -93,6 +93,30 @@ def _stroke_lines_alpha(
gpu.state.blend_set("NONE")
def _connected_components(
vertex_groups: dict[int, list[bmesh.types.BMVert]],
) -> list[list[bmesh.types.BMVert]]:
"""Split each vertex group's members into their connected components,
since a duplicated arc/circle loop shares its source loop's group index."""
components = []
for verts in vertex_groups.values():
remaining = set(verts)
while remaining:
seed = remaining.pop()
stack = [seed]
component = [seed]
while stack:
v = stack.pop()
for edge in v.link_edges:
other = edge.other_vert(v)
if other in remaining:
remaining.discard(other)
stack.append(other)
component.append(other)
components.append(component)
return components
class ProfileDecorator:
installed = None
@@ -265,7 +289,7 @@ class ProfileDecorator:
# Draw arcs
arc_centroids = []
arc_segments = []
for arc in arcs.values():
for arc in _connected_components(arcs):
if len(arc) != 3:
continue
sorted_arc = [None, None, None]
@@ -292,7 +316,7 @@ class ProfileDecorator:
# Draw circles
circle_centroids = []
circle_segments = []
for circle in circles.values():
for circle in _connected_components(circles):
if len(circle) != 2:
continue
p1 = obj.matrix_world @ circle[0].co
@@ -413,12 +413,13 @@ class UnlinkObject(bpy.types.Operator, tool.Ifc.Operator):
skip_invoke: bpy.props.BoolProperty(default=False, options={"SKIP_SAVE"})
def _execute(self, context):
objects: list[bpy.types.Object]
if self.obj:
objects = [bpy.data.objects.get(self.obj)]
requested_obj = bpy.data.objects.get(self.obj)
objects = [requested_obj] if requested_obj is not None else []
else:
objects = context.selected_objects
objects: list[bpy.types.Object]
for obj in objects:
was_active_object = obj == context.active_object
@@ -12,7 +12,7 @@ function create_gantt_chart(json_data) {
vShowTaskInfoLink: 1, // Show link in tool tip (0/1)
vShowEndWeekDate: 0, // Show/Hide the date for the last day of the week in header for daily
vUseSingleCell: 10000, // Set the threshold cell per table row (Helps performance for large data.
vFormatArr: ['Day', 'Week', 'Month', 'Quarter'], // Even with setUseSingleCell using Hour format on such a large chart can cause issues in some browsers,
vFormatArr: ['Hour', 'Day', 'Week', 'Month', 'Quarter'], // vUseSingleCell keeps Hour usable on large charts.
vShowRes: true, // Disable the resource column.
vShowComp: false, // Disable the completion column.
vShowDur: false, // Disable the duration column, because jsgantt doesn't calculate durations the way we want.
@@ -117,9 +117,7 @@ class UnassignType(bpy.types.Operator, tool.Ifc.Operator):
related_object: str
@staticmethod
def _reattach_styles(
file: ifcopenshell.file, copied_entities: dict[int, ifcopenshell.entity_instance]
) -> None:
def _reattach_styles(file: ifcopenshell.file, copied_entities: dict[int, ifcopenshell.entity_instance]) -> None:
"""copy_deep only follows forward references, so IfcStyledItem (an inverse,
``StyledByItem``) is not carried onto the copied geometry. Re-create a
styled item on each copy that points at the same presentation styles as
+31
View File
@@ -411,6 +411,37 @@ def duplicate_drawing(
return new_drawing
def copy_annotations_to_drawing(
ifc: type[tool.Ifc],
collector: type[tool.Collector],
drawing_tool: type[tool.Drawing],
geometry: type[tool.Geometry],
annotations: list[ifcopenshell.entity_instance],
target_drawing: ifcopenshell.entity_instance,
) -> list[ifcopenshell.entity_instance]:
"""Duplicate annotations into another drawing, leaving the originals untouched."""
target_group = drawing_tool.get_drawing_group(target_drawing)
if not target_group:
return []
annotations = [a for a in annotations if drawing_tool.get_annotation_drawing(a) != target_drawing]
annotation_objs = [obj for a in annotations if (obj := ifc.get_object(a))]
if not annotation_objs:
return []
camera = ifc.get_object(target_drawing) or drawing_tool.import_drawing(target_drawing)
old_to_new, _ = geometry.duplicate_ifc_objects(annotation_objs)
copied: list[ifcopenshell.entity_instance] = []
for new_elements in old_to_new.values():
for new_element in new_elements:
if old_group := drawing_tool.get_drawing_group(new_element):
ifc.run("group.unassign_group", group=old_group, products=[new_element])
ifc.run("group.assign_group", group=target_group, products=[new_element])
new_obj = ifc.get_object(new_element)
drawing_tool.ensure_annotation_in_drawing_plane(new_obj, camera)
collector.assign(new_obj, should_clean_users_collection=True)
copied.append(new_element)
return copied
def remove_drawing(
ifc: type[tool.Ifc], drawing_tool: type[tool.Drawing], drawing: ifcopenshell.entity_instance
) -> None:
+4
View File
@@ -354,6 +354,7 @@ class Drawing:
def enable_editing_schedules(cls): pass
def enable_editing_sheets(cls): pass
def enable_editing_text(cls, obj): pass
def ensure_annotation_in_drawing_plane(cls, obj, camera=None): pass
def ensure_drawings_parent_document(cls): pass
def ensure_drawings_parent_group(cls): pass
def ensure_unique_drawing_name(cls, name): pass
@@ -367,6 +368,7 @@ class Drawing:
def generate_reference_attributes(cls, reference, **attributes): pass
def generate_sheet_identification(cls): pass
def get_annotation_context(cls, target_view, object_type=None): pass
def get_annotation_drawing(cls, element): pass
def get_annotation_representation(cls, element_type): pass
def get_assigned_product(cls, element): pass
def get_assigned_product_workaround(cls, element): pass
@@ -384,6 +386,7 @@ class Drawing:
def get_drawing_group(cls, drawing): pass
def get_drawing_references(cls, drawing): pass
def get_drawing_target_view(cls, drawing): pass
def get_group_drawing(cls, group): pass
def get_group_elements(cls, group): pass
def get_ifc_representation_class(cls, object_type): pass
def get_name(cls, element): pass
@@ -397,6 +400,7 @@ class Drawing:
def get_unit_system(cls): pass
def import_assigned_product(cls, obj): pass
def import_documents(cls, document_type): pass
def import_drawing(cls, drawing): pass
def import_drawings(cls): pass
def import_sheets(cls): pass
def import_text_attributes(cls, obj): pass
+11
View File
@@ -756,6 +756,17 @@ class Drawing(bonsai.core.tool.Drawing):
if rel.is_a("IfcRelAssignsToGroup") and rel.RelatingGroup.ObjectType == "DRAWING":
return rel.RelatingGroup
@classmethod
def get_group_drawing(cls, group: ifcopenshell.entity_instance) -> Union[ifcopenshell.entity_instance, None]:
"""Get the drawing that owns this group, if the group represents a drawing."""
if group.ObjectType != "DRAWING":
return None
for rel in group.IsGroupedBy or []:
for related_object in rel.RelatedObjects:
if related_object.is_a("IfcAnnotation") and related_object.ObjectType == "DRAWING":
return related_object
return None
@classmethod
def get_drawing_document(cls, drawing: ifcopenshell.entity_instance) -> ifcopenshell.entity_instance:
for rel in drawing.HasAssociations:
+11 -2
View File
@@ -1151,6 +1151,9 @@ class Geometry(bonsai.core.tool.Geometry):
settings.set("layerset-first", True)
settings.set("keep-bounding-boxes", True)
settings.set("dimensionality", ifcopenshell.ifcopenshell_wrapper.CURVES_SURFACES_AND_SOLIDS)
settings.set("mesher-linear-deflection", ifc_import_settings.deflection_tolerance)
settings.set("mesher-angular-deflection", ifc_import_settings.angular_tolerance)
geometry_library = ifc_import_settings.geometry_library
ifc_importer = bonsai.bim.import_ifc.IfcImporter(ifc_import_settings)
ifc_importer.file = tool.Ifc.get()
@@ -1162,7 +1165,11 @@ class Geometry(bonsai.core.tool.Geometry):
shape = None
if elements:
iterator = ifcopenshell.geom.iterator(
settings, tool.Ifc.get(), multiprocessing.cpu_count(), include=elements
settings,
tool.Ifc.get(),
multiprocessing.cpu_count(),
include=elements,
geometry_library=geometry_library,
)
else:
iterator = None # For example, when switching representation of a type with no occurrences
@@ -1217,7 +1224,9 @@ class Geometry(bonsai.core.tool.Geometry):
for element in element_types:
if obj := tool.Ifc.get_object(element):
if representation := ifcopenshell.util.representation.get_representation(element, context):
geometry = ifcopenshell.geom.create_shape(settings, representation)
geometry = ifcopenshell.geom.create_shape(
settings, representation, geometry_library=geometry_library
)
mesh_name = tool.Loader.get_mesh_name_from_shape(geometry)
mesh = meshes.get(mesh_name)
if mesh is None:
+48 -34
View File
@@ -2292,32 +2292,18 @@ class Model(bonsai.core.tool.Model):
deform_layer = bm.verts.layers.deform.active
# Sanity check
group_verts = {"IFCARCINDEX": {}, "IFCCIRCLE": {}}
if deform_layer:
for vert in bm.verts:
vert_group_indices = tool.Blender.bmesh_get_vertex_groups(vert, deform_layer)
is_circle = False
for group_index in vert_group_indices:
group_type = "IFCARCINDEX" if group_index in groups["IFCARCINDEX"] else "IFCCIRCLE"
group_verts[group_type].setdefault(group_index, 0)
group_verts[group_type][group_index] += 1
if group_type == "IFCCIRCLE":
is_circle = True
is_circle = any(gi in groups["IFCCIRCLE"] for gi in vert_group_indices)
is_arc = any(gi in groups["IFCARCINDEX"] for gi in vert_group_indices)
if (is_circle or is_arc) and not vert.link_edges:
return (False, "CIRCLE" if is_circle else "3POINT_ARC")
if is_circle:
pass # Circles are allowed to be unclosed
elif len(vert.link_edges) != 2: # Unclosed loop or forked loop
return (False, "UNCLOSED_LOOP")
for group_type, group_counts in group_verts.items():
if group_type == "IFCARCINDEX":
for group_count in group_counts.values():
if group_count != 3: # Each arc needs 3 verts
return (False, "3POINT_ARC")
elif group_type == "IFCCIRCLE":
for group_count in group_counts.values():
if group_count != 2: # Each circle needs 2 verts
return (False, "CIRCLE")
loop_edges = list(bm.edges)
# Create loops from edges
@@ -2340,6 +2326,28 @@ class Model(bonsai.core.tool.Model):
has_found_connected_edge = True
loops.append(loop)
# Sanity check, per loop rather than across the whole mesh
if deform_layer:
for loop in loops:
loop_group_counts = {"IFCARCINDEX": {}, "IFCCIRCLE": {}}
loop_verts = {v for edge in loop for v in edge.verts}
for vert in loop_verts:
for group_index in tool.Blender.bmesh_get_vertex_groups(vert, deform_layer):
if group_index in groups["IFCARCINDEX"]:
group_type = "IFCARCINDEX"
elif group_index in groups["IFCCIRCLE"]:
group_type = "IFCCIRCLE"
else:
continue
loop_group_counts[group_type].setdefault(group_index, 0)
loop_group_counts[group_type][group_index] += 1
for group_count in loop_group_counts["IFCARCINDEX"].values():
if group_count != 3: # Each arc needs 3 verts
return (False, "3POINT_ARC")
for group_count in loop_group_counts["IFCCIRCLE"].values():
if group_count != 2: # Each circle needs 2 verts
return (False, "CIRCLE")
tmp = ifcopenshell.file(schema=tool.Ifc.get().schema)
def is_in_group(v: bmesh.types.BMVert, group_name: str) -> bool:
@@ -2520,27 +2528,11 @@ class Model(bonsai.core.tool.Model):
deform_layer = bm.verts.layers.deform.active
# Sanity check
group_verts = {"IFCARCINDEX": {}, "IFCCIRCLE": {}}
if deform_layer:
for vert in bm.verts:
vert_group_indices = tool.Blender.bmesh_get_vertex_groups(vert, deform_layer)
for group_index in vert_group_indices:
group_type = "IFCARCINDEX" if group_index in groups["IFCARCINDEX"] else "IFCCIRCLE"
group_verts[group_type].setdefault(group_index, 0)
group_verts[group_type][group_index] += 1
if len(vert.link_edges) > 2: # Forked loop
return (False, "FORKED_LOOP")
for group_type, group_counts in group_verts.items():
if group_type == "IFCARCINDEX":
for group_count in group_counts.values():
if group_count != 3: # Each arc needs 3 verts
return (False, "3POINT_ARC")
elif group_type == "IFCCIRCLE":
for group_count in group_counts.values():
if group_count != 2: # Each circle needs 2 verts
return (False, "CIRCLE")
loop_edges = list(bm.edges)
# Create loops from edges
@@ -2563,6 +2555,28 @@ class Model(bonsai.core.tool.Model):
has_found_connected_edge = True
loops.append(loop)
# Sanity check, per loop rather than across the whole mesh
if deform_layer:
for loop in loops:
loop_group_counts = {"IFCARCINDEX": {}, "IFCCIRCLE": {}}
loop_verts = {v for edge in loop for v in edge.verts}
for vert in loop_verts:
for group_index in tool.Blender.bmesh_get_vertex_groups(vert, deform_layer):
if group_index in groups["IFCARCINDEX"]:
group_type = "IFCARCINDEX"
elif group_index in groups["IFCCIRCLE"]:
group_type = "IFCCIRCLE"
else:
continue
loop_group_counts[group_type].setdefault(group_index, 0)
loop_group_counts[group_type][group_index] += 1
for group_count in loop_group_counts["IFCARCINDEX"].values():
if group_count != 3: # Each arc needs 3 verts
return (False, "3POINT_ARC")
for group_count in loop_group_counts["IFCCIRCLE"].values():
if group_count != 2: # Each circle needs 2 verts
return (False, "CIRCLE")
tmp = ifcopenshell.file(schema=tool.Ifc.get().schema)
def is_in_group(v: bmesh.types.BMVert, group_name: str) -> bool:
+1 -1
View File
@@ -168,7 +168,7 @@ class Polyline(bonsai.core.tool.Polyline):
distance = (mouse_vector - last_point).length
if distance < 0:
return
angle, orientation_angle, angle_round_threshold = None, None
angle, orientation_angle, angle_round_threshold = None, None, None
if distance > 0:
angle = tool.Cad.angle_3_vectors(
second_to_last_point, last_point, mouse_vector, new_angle=None, degrees=True
+3 -3
View File
@@ -1159,11 +1159,11 @@ class Sequence(bonsai.core.tool.Sequence):
props.task_input_colors.clear()
for group, data in groups.items():
for predefined_type in data["PredefinedType"]:
if group in ["CREATION", "OPERATION", "MOVEMENT_TO"]:
if group in ("CREATION", "OPERATION", "MOVEMENT_TO"):
predefined_type_item = props.task_output_colors.add()
elif group in ["MOVEMENT_FROM"]:
elif group in ("MOVEMENT_FROM",):
predefined_type_item = props.task_input_colors.add()
elif group in ["USERDEFINED", "DESTRUCTION"]:
elif group in ("USERDEFINED", "DESTRUCTION"):
predefined_type_item = props.task_input_colors.add()
predefined_type_item2 = props.task_output_colors.add()
predefined_type_item2.name = predefined_type
@@ -24,7 +24,7 @@ Blender versions:
- 64-bit MacOS Intel (``macos-x64``)
- 64-bit MacOS Silicon (``macos-arm64``)
- 64-bit Windows (``windows-x64``)
- Blender 4.3, 4.4, or 4.5 with Python 3.11
- Blender 5.1 or 5.2 with Python 3.13
Developer builds may exist for different versions of Python but there will be
no guarantee of the uptime or stability of these builds.
+27 -12
View File
@@ -16,20 +16,26 @@
# You should have received a copy of the GNU General Public License
# along with Bonsai. If not, see <http://www.gnu.org/licenses/>.
import argparse
import ezdxf
import ifcopenshell
import ifcopenshell.guid
class Dxf2Ifc:
def __init__(self, dxf_path, outfile):
self.dxf_path = dxf_path
self.outfile = outfile
def execute(self):
self.create_ifc_file()
doc = ezdxf.readfile("input.dxf")
doc = ezdxf.readfile(self.dxf_path)
model = doc.modelspace()
products = []
for entity in model:
print(entity)
if entity.get_mode() == "AcDbPolyFaceMesh":
if entity.dxftype() == "POLYLINE" and entity.is_poly_face_mesh:
ifc_faces = []
for face in entity.faces():
ifc_faces.append(
@@ -67,15 +73,18 @@ class Dxf2Ifc:
"Name": entity.dxf.layer,
"ObjectPlacement": self.placement,
"Representation": representation,
}
},
)
)
else:
print("Not yet implemented")
self.file.createIfcRelContainedInSpatialStructure(
ifcopenshell.guid.new(), None, None, None, products, self.site
)
self.file.write("test.ifc")
print(f"Skipping unsupported entity: {entity.dxftype()}")
if products:
self.file.createIfcRelContainedInSpatialStructure(
ifcopenshell.guid.new(), None, None, None, products, self.site
)
else:
print("No AcDbPolyFaceMesh entities found, writing an empty IFC")
self.file.write(self.outfile)
def create_ifc_file(self):
self.file = ifcopenshell.file()
@@ -97,14 +106,20 @@ class Dxf2Ifc:
"Name": "DXF Conversion",
"RepresentationContexts": [self.context],
"UnitsInContext": units,
}
},
)
self.site = self.file.create_entity(
"IfcSite",
**{"GlobalId": ifcopenshell.guid.new(), "Name": "DXF Conversion Site", "ObjectPlacement": self.placement}
**{"GlobalId": ifcopenshell.guid.new(), "Name": "DXF Conversion Site", "ObjectPlacement": self.placement},
)
self.file.createIfcRelAggregates(ifcopenshell.guid.new(), None, None, None, self.project, [self.site])
dxf2ifc = Dxf2Ifc()
dxf2ifc.execute()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Converts DXF polyface meshes (AcDbPolyFaceMesh) to an IFC")
parser.add_argument("dxf", type=str, help="The input DXF file")
parser.add_argument("-o", "--output", type=str, help="The output IFC file", default="out.ifc")
args = parser.parse_args()
dxf2ifc = Dxf2Ifc(args.dxf, args.output)
dxf2ifc.execute()
@@ -0,0 +1,141 @@
# 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.
"""Regression tests for ``ProfileDecorator``'s ``_connected_components`` helper.
Duplicating a circle/arc void's loop in Edit Mode (Tab, Tab, select the
loop, Shift+D) copies the ``IFCARCINDEX``/``IFCCIRCLE`` vertex-group
weights onto the new geometry, since Blender's mesh duplicate never
allocates a new vertex group. Before this fix, ``ProfileDecorator``
grouped arc/circle vertices by group index alone, so the duplicate's
vertices piled into the same entry as the source loop's, failing the
"exactly 2/3 verts" check and silently dropping *both* loops from the
decorator until the mesh was re-imported (e.g. by leaving and re-entering
Edit Mode). ``_connected_components`` splits each group's vertices back
into their connected loops so a duplicate is drawn immediately, see #6944."""
import bmesh
import bpy
import pytest
from bonsai.bim.module.model.decorator import _connected_components
pytestmark = pytest.mark.model
def _bm_with_groups(verts, edges, groups):
"""Build a standalone bmesh with a deform layer, and populate ``groups``:
a list of (group_index, [vert_indices]) pairs, mirroring how
``tool.Model.import_profile``/``convert_curve_to_mesh`` assign one
vertex group per circle/arc loop."""
bm = bmesh.new()
deform_layer = bm.verts.layers.deform.new()
bm_verts = [bm.verts.new(v) for v in verts]
bm.verts.ensure_lookup_table()
for a, b in edges:
bm.edges.new((bm_verts[a], bm_verts[b]))
bm.verts.ensure_lookup_table()
bm_verts = list(bm.verts)
for group_index, vert_indices in groups:
for vi in vert_indices:
bm_verts[vi][deform_layer][group_index] = 1.0
return bm, bm_verts, deform_layer
def _group_dict(bm_verts, deform_layer, group_index, vert_indices):
return {group_index: [bm_verts[i] for i in vert_indices]}
def test_single_circle_loop_is_one_component():
# A circle is exactly 2 verts joined by 1 edge (tool.Model.convert_curve_to_mesh).
bm, bm_verts, deform_layer = _bm_with_groups(
verts=[(0, -1, 0), (0, 1, 0)],
edges=[(0, 1)],
groups=[(0, [0, 1])],
)
circles = _group_dict(bm_verts, deform_layer, 0, [0, 1])
components = _connected_components(circles)
assert len(components) == 1
assert len(components[0]) == 2
bm.free()
def test_single_arc_loop_is_one_component():
# An arc is exactly 3 verts: endpoint-midpoint-endpoint (2 edges).
bm, bm_verts, deform_layer = _bm_with_groups(
verts=[(0, -1, 0), (0, 0, 0.3), (0, 1, 0)],
edges=[(0, 1), (1, 2)],
groups=[(0, [0, 1, 2])],
)
arcs = _group_dict(bm_verts, deform_layer, 0, [0, 1, 2])
components = _connected_components(arcs)
assert len(components) == 1
assert len(components[0]) == 3
bm.free()
def test_duplicated_circle_loop_splits_into_two_components():
# Duplicating verts 0-1 (Shift+D) yields verts 2-3, connected to each
# other but NOT to the source loop, while keeping the same group index
# (0) -- exactly what bmesh.ops.duplicate produces mid Edit-Mode.
bm, bm_verts, deform_layer = _bm_with_groups(
verts=[(0, -1, 0), (0, 1, 0), (5, -1, 0), (5, 1, 0)],
edges=[(0, 1), (2, 3)],
groups=[(0, [0, 1, 2, 3])],
)
circles = _group_dict(bm_verts, deform_layer, 0, [0, 1, 2, 3])
components = _connected_components(circles)
assert len(components) == 2
assert sorted(len(c) for c in components) == [2, 2]
bm.free()
def test_duplicated_arc_loop_splits_into_two_components():
bm, bm_verts, deform_layer = _bm_with_groups(
verts=[(0, -1, 0), (0, 0, 0.3), (0, 1, 0), (5, -1, 0), (5, 0, 0.3), (5, 1, 0)],
edges=[(0, 1), (1, 2), (3, 4), (4, 5)],
groups=[(0, [0, 1, 2, 3, 4, 5])],
)
arcs = _group_dict(bm_verts, deform_layer, 0, [0, 1, 2, 3, 4, 5])
components = _connected_components(arcs)
assert len(components) == 2
assert sorted(len(c) for c in components) == [3, 3]
bm.free()
def test_distinct_circle_groups_stay_separate_and_correctly_sized():
# Multiple genuinely different circles (distinct group indices) must
# each still resolve to their own single 2-vert component.
verts = []
edges = []
groups = []
for i in range(5):
base = len(verts)
verts += [(i * 3, -1, 0), (i * 3, 1, 0)]
edges.append((base, base + 1))
groups.append((i, [base, base + 1]))
bm, bm_verts, deform_layer = _bm_with_groups(verts, edges, groups)
circles = {}
for group_index, vert_indices in groups:
circles[group_index] = [bm_verts[i] for i in vert_indices]
components = _connected_components(circles)
assert len(components) == 5
assert all(len(c) == 2 for c in components)
bm.free()
+53
View File
@@ -453,6 +453,59 @@ class TestDuplicateDrawing:
subject.duplicate_drawing(ifc, blender, drawing, geometry, drawing="drawing", should_duplicate_annotations=True)
class TestCopyAnnotationsToDrawing:
def test_run(self, ifc: Prophecy, collector: Prophecy, drawing: Prophecy, geometry: Prophecy):
drawing.get_drawing_group("target_drawing").should_be_called().will_return("target_group")
drawing.get_annotation_drawing("annotation").should_be_called().will_return("source_drawing")
ifc.get_object("annotation").should_be_called().will_return("annotation_obj")
ifc.get_object("target_drawing").should_be_called().will_return("camera")
geometry.duplicate_ifc_objects(["annotation_obj"]).should_be_called().will_return(
({"annotation": ["new_annotation"]}, None)
)
drawing.get_drawing_group("new_annotation").should_be_called().will_return("source_group")
ifc.run("group.unassign_group", group="source_group", products=["new_annotation"]).should_be_called()
ifc.run("group.assign_group", group="target_group", products=["new_annotation"]).should_be_called()
ifc.get_object("new_annotation").should_be_called().will_return("new_annotation_obj")
drawing.ensure_annotation_in_drawing_plane("new_annotation_obj", "camera").should_be_called()
collector.assign("new_annotation_obj", should_clean_users_collection=True).should_be_called()
assert subject.copy_annotations_to_drawing(
ifc, collector, drawing, geometry, annotations=["annotation"], target_drawing="target_drawing"
) == ["new_annotation"]
def test_skipping_annotations_already_in_the_target_drawing(
self, ifc: Prophecy, collector: Prophecy, drawing: Prophecy, geometry: Prophecy
):
drawing.get_drawing_group("target_drawing").should_be_called().will_return("target_group")
drawing.get_annotation_drawing("annotation").should_be_called().will_return("target_drawing")
assert (
subject.copy_annotations_to_drawing(
ifc, collector, drawing, geometry, annotations=["annotation"], target_drawing="target_drawing"
)
== []
)
def test_importing_the_target_camera_when_it_is_not_loaded(
self, ifc: Prophecy, collector: Prophecy, drawing: Prophecy, geometry: Prophecy
):
drawing.get_drawing_group("target_drawing").should_be_called().will_return("target_group")
drawing.get_annotation_drawing("annotation").should_be_called().will_return("source_drawing")
ifc.get_object("annotation").should_be_called().will_return("annotation_obj")
ifc.get_object("target_drawing").should_be_called().will_return(None)
drawing.import_drawing("target_drawing").should_be_called().will_return("camera")
geometry.duplicate_ifc_objects(["annotation_obj"]).should_be_called().will_return(
({"annotation": ["new_annotation"]}, None)
)
drawing.get_drawing_group("new_annotation").should_be_called().will_return("source_group")
ifc.run("group.unassign_group", group="source_group", products=["new_annotation"]).should_be_called()
ifc.run("group.assign_group", group="target_group", products=["new_annotation"]).should_be_called()
ifc.get_object("new_annotation").should_be_called().will_return("new_annotation_obj")
drawing.ensure_annotation_in_drawing_plane("new_annotation_obj", "camera").should_be_called()
collector.assign("new_annotation_obj", should_clean_users_collection=True).should_be_called()
assert subject.copy_annotations_to_drawing(
ifc, collector, drawing, geometry, annotations=["annotation"], target_drawing="target_drawing"
) == ["new_annotation"]
class TestRemoveDrawing:
def test_run(self, ifc, drawing):
drawing.is_active_drawing("drawing").should_be_called().will_return(True)
+19
View File
@@ -506,6 +506,25 @@ class TestGetDrawingGroup(NewFile):
assert subject.get_drawing_group(element) == group
class TestGetGroupDrawing(NewFile):
def test_run(self):
ifc = ifcopenshell.file()
tool.Ifc.set(ifc)
drawing = ifc.createIfcAnnotation(ObjectType="DRAWING")
group = ifcopenshell.api.group.add_group(ifc)
group.ObjectType = "DRAWING"
ifcopenshell.api.group.assign_group(ifc, products=[drawing], group=group)
assert subject.get_group_drawing(group) == drawing
def test_ignores_groups_that_are_not_drawings(self):
ifc = ifcopenshell.file()
tool.Ifc.set(ifc)
drawing = ifc.createIfcAnnotation(ObjectType="DRAWING")
group = ifcopenshell.api.group.add_group(ifc)
ifcopenshell.api.group.assign_group(ifc, products=[drawing], group=group)
assert subject.get_group_drawing(group) is None
class TestGetDrawingTargetView(NewFile):
def test_run(self):
ifc = ifcopenshell.file()
+3 -3
View File
@@ -6,10 +6,10 @@ Files and scripts for the use of [`Code_Aster`](https://code-aster.org) in IFC-d
## Scripts:
- [`ifc2ca.py`](ifc2ca.py): a python script to extract and create a `json` file from an `ifc` file
- [`scriptSalome.py`](scriptSalome.py): a python script to run in the [`Salome-Meca`](https://www.code-aster.org/spip.php?article303) environment. Creates the geometry and the mesh of the structure
- [`scriptSalome.py`](templates/salome/scriptSalome.py): a python script to run in the [`Salome-Meca`](https://www.code-aster.org/spip.php?article303) environment. Creates the geometry and the mesh of the structure
- [`scriptCodeAster.py`](scriptCodeAster.py): a python script to create the input file (`.comm`) for Code_Aster
- [`scriptSalomeBonded.py`](scriptSalomeBonded.py): a python script to run in the [`Salome-Meca`](https://www.code-aster.org/spip.php?article303) environment. Creates the geometry and the mesh of the structure by bonding together all structural elements (no connections are considered)
- [`scriptCodeAsterBonded.py`](scriptCodeAsterBonded.py): a python script to create the input file (`.comm`) for Code_Aster for the "bonded" case
- [`scriptSalomeBonded.py`](_deprecated/scriptSalomeBonded.py): a python script to run in the [`Salome-Meca`](https://www.code-aster.org/spip.php?article303) environment. Creates the geometry and the mesh of the structure by bonding together all structural elements (no connections are considered). Located under `_deprecated/`.
- [`scriptCodeAsterBonded.py`](_deprecated/scriptCodeAsterBonded.py): a python script to create the input file (`.comm`) for Code_Aster for the "bonded" case. Located under `_deprecated/`.
## Analysis Models
@@ -85,8 +85,8 @@ sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "lib", p
try:
from . import ifcopenshell_wrapper
except Exception:
raise ImportError("IfcOpenShell not built for '%s'" % python_distribution)
except Exception as e:
raise ImportError("IfcOpenShell not built for '%s' (%s)" % (python_distribution, e)) from e
# `_file`, `_stream` is used only for annotations inside this file,
# see https://github.com/microsoft/pyright/discussions/9065.
+2 -6
View File
@@ -42,7 +42,7 @@ WHITE = numpy.array((1.0, 1.0, 1.0))
DO_NOTHING = lambda *args: None
ARRANGE_POLYGON_SETTINGS = W.arrange_polygon_settings() if hasattr(W, "arrange_polygon_settings") else None
ARRANGE_POLYGON_SETTINGS = W.arrange_polygon_settings()
@dataclass
@@ -546,11 +546,7 @@ def main(
*(tup for i, tup in enumerate(zip(path_objects, section_polies, polies)) if has_relevant_zone(i))
)
arranged = W.arrange_polygons(
*filter(None, (ARRANGE_POLYGON_SETTINGS,)),
polies,
*((logger,) if logger is not None else ()),
)
arranged = W.arrange_polygons(ARRANGE_POLYGON_SETTINGS, polies, logger)
svg_data_3 = W.polygons_to_svg(arranged, False)
dom3 = parseString(svg_data_3)
svg3 = dom3.childNodes[0]
@@ -16,12 +16,14 @@
# You should have received a copy of the GNU Lesser General Public License
# along with IfcOpenShell. If not, see <http://www.gnu.org/licenses/>.
import functools
from collections import namedtuple
from collections.abc import Callable, Generator, Sequence
from typing import Any, Literal, Optional, Union, overload
import ifcopenshell
import ifcopenshell.guid
import ifcopenshell.ifcopenshell_wrapper
import ifcopenshell.util.element
import ifcopenshell.util.representation
@@ -1590,10 +1592,36 @@ def replace_element(element: ifcopenshell.entity_instance, replacement: ifcopens
replace_attribute(inverse, element, replacement)
@functools.cache
def _is_set_attribute(schema_identifier: str, ifc_class: str, index: int) -> bool:
"""Whether attribute `index` of `ifc_class` is declared as an EXPRESS SET.
SET aggregates may not contain duplicate members, whereas LIST and BAG
aggregates may, so only SET-typed attributes are safe to deduplicate.
"""
declaration = ifcopenshell.ifcopenshell_wrapper.schema_by_name(schema_identifier).declaration_by_name(ifc_class)
attribute = declaration.attribute_by_index(index)
aggregation = attribute.type_of_attribute().as_aggregation_type()
return aggregation is not None and aggregation.type_of_aggregation_string() == "set"
def replace_attribute(element: ifcopenshell.entity_instance, old: Any, new: Any) -> None:
for i, attribute_value in enumerate(element):
if has_element_reference(attribute_value, old):
element[i] = element.walk(lambda v: v == old, lambda v: new, attribute_value)
new_value = element.walk(lambda v: v == old, lambda v: new, attribute_value)
if (
isinstance(attribute_value, tuple)
and has_element_reference(attribute_value, new)
and _is_set_attribute(element.file.schema_identifier, element.is_a(), i)
):
seen: set[Any] = set()
deduplicated = []
for v in new_value:
if v not in seen:
seen.add(v)
deduplicated.append(v)
new_value = tuple(deduplicated)
element[i] = new_value
def has_element_reference(value: Any, element: ifcopenshell.entity_instance) -> bool:
+3 -1
View File
@@ -21,7 +21,9 @@ END-ISO-10303-21;
def test_reference_to_undefined_owning_instance():
data = "ISO-10303-21;HEADER;FILE_DESCRIPTION();FILE_NAME();FILE_SCHEMA(('IFC4'));#=IFCRELAGGREGATES((#))#5=IFCPOINT)"
data = (
"ISO-10303-21;HEADER;FILE_DESCRIPTION();FILE_NAME();FILE_SCHEMA(('IFC4'));#=IFCRELAGGREGATES((#))#5=IFCPOINT)"
)
ifcopenshell.file.from_string(data)
print(ifcopenshell.get_log())
@@ -1244,6 +1244,22 @@ class TestReplaceAttributeIFC4(test.bootstrap.IFC4):
subject.replace_attribute(rel, old, new)
assert rel.RelatedObjects == (new,)
def test_replacing_into_a_set_deduplicates_the_survivor(self):
old = self.file.createIfcWall()
new = self.file.createIfcWall()
rel = self.file.createIfcRelAggregates()
rel.RelatedObjects = [old, new]
subject.replace_attribute(rel, old, new)
assert rel.RelatedObjects == (new,)
def test_replacing_into_a_list_keeps_legitimate_duplicates(self):
p1 = self.file.createIfcCartesianPoint((0.0, 0.0, 0.0))
p2 = self.file.createIfcCartesianPoint((1.0, 0.0, 0.0))
p3 = self.file.createIfcCartesianPoint((2.0, 0.0, 0.0))
polyline = self.file.createIfcPolyline([p1, p2, p3, p1])
subject.replace_attribute(polyline, p2, p3)
assert polyline.Points == (p1, p3, p3, p1)
class TestHasElementReferenceIFC4(test.bootstrap.IFC4):
def test_if_a_element_attribute_references_another_element(self):
@@ -3,6 +3,7 @@ cjio >=0.8, <0.10
deepdiff
docutils
flask
igraph
isodate
jinja2
lark