From 4eb6d12bca1993b5db38daaa98eca4d5bae2dc94 Mon Sep 17 00:00:00 2001 From: Roberto Dolfini Date: Wed, 11 Nov 2026 16:45:41 +0100 Subject: [PATCH 1/4] Wait for the handshake before sending, notice dropped connections Blender now sends nothing but the hello until Revit answers with hello_ack: a second Blender sitting in the listener backlog no longer looks connected, and an error before hello_ack (protocol mismatch) disconnects. The drain notices a dropped connection: it redraws the panel and marks a bake or proxy still waiting as lost. Connect and Disconnect are enabled one at a time. Co-Authored-By: Claude Opus 5.5 --- DESIGN.md | 11 ++++++-- src/blender_addon/__init__.py | 40 ++++++++++++++++++++++++++- src/blender_addon/bridge_bake_send.py | 12 ++++---- src/blender_addon/bridge_client.py | 19 ++++++++++++- src/blender_addon/bridge_proxy.py | 4 +-- src/blender_addon/bridge_sync.py | 4 +-- src/blender_addon/panel.py | 24 ++++++++++------ tests/blender/smoke_bake.py | 3 ++ tests/python/test_bridge_client.py | 26 +++++++++++++++++ 9 files changed, 119 insertions(+), 24 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index 3a47a51..6a22009 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -83,7 +83,11 @@ removes it. the preview restarts empty and a Sync is needed. - Only one active connection at a time. A second client is not refused: its connection waits in the listener backlog, with no hello_ack, until - the first one disconnects. + the first one disconnects. The Blender side sends nothing but the + `hello` until the `hello_ack` arrives: the panel says "waiting for + Revit" and Sync, Bake, Proxy and the live transforms stay off. +- When the connection drops, a bake or proxy still waiting for its result + is marked as lost on the panel: its outcome will not arrive. --- @@ -186,7 +190,8 @@ failure would have to be treated as terminal. `hello` is answered with `hello_ack` only when `protocol_version` matches the add-in's (an absent field is accepted); a different version gets an `error` frame that names both versions. The Blender side makes the same check on -`hello_ack` and disconnects on a mismatch. +`hello_ack` and disconnects on a mismatch; an `error` that arrives before +any `hello_ack` disconnects as well, with Revit's message as the status. `sync_begin` lists the ids that are about to arrive: it lets Revit remove, at the end, the objects no longer present in the collection, atomically and @@ -209,7 +214,7 @@ the server takes part in Revit's transparent pass: the faces are drawn there, with the transparency both in the vertex colors and on the face effects, and the edges stay opaque in the opaque pass so the outline stays readable. At 1 the preview is drawn in the opaque pass only, as before. -Blender sends it at Connect, at every Sync and whenever the user changes a +Blender sends it at the handshake, at every Sync and whenever the user changes a color or the opacity; Revit ignores it when nothing changed, otherwise it rebuilds the GPU buffers once, because the colors are stored in the vertex buffers. Out-of-range components or opacity are an `error`. diff --git a/src/blender_addon/__init__.py b/src/blender_addon/__init__.py index 278911b..4040292 100644 --- a/src/blender_addon/__init__.py +++ b/src/blender_addon/__init__.py @@ -75,7 +75,7 @@ @bpy.app.handlers.persistent def _on_depsgraph_update(scene, depsgraph): - if not client.CLIENT.running: + if not client.CLIENT.ready: return collection = coll.find_collection() @@ -162,8 +162,21 @@ def _handle_message(header, payload, now): client.CLIENT.status = problem _log(problem) else: + client.CLIENT.handshake_ok = True client.CLIENT.status = "handshake ok, Revit {}".format( header.get("revit_version", "?")) + # Revit starts with the default colors: send the scene's now + sync.send_style(bpy.context.scene) + _tag_redraw() + + elif kind == "error" and not client.CLIENT.handshake_ok: + # an error instead of the hello_ack: Revit refused the hello (a + # different protocol version). Staying connected would only get + # every later message rejected. + client.CLIENT.disconnect() + client.CLIENT.status = "Revit refused the connection: {}".format( + header.get("message", "?")) + _log(client.CLIENT.status) _tag_redraw() elif kind == "error": @@ -240,6 +253,27 @@ def _handle_safely(header, payload): # perf_counter when the previous tick stopped with messages still queued _DRAIN_PAUSED_AT = None +# (running, status) seen by the previous tick. The read thread changes +# both when the connection drops, but it cannot touch bpy: the redraw and +# the bookkeeping of the drop happen here. +_LAST_STATE = None + + +def _check_connection_state(): + global _LAST_STATE + state = (client.CLIENT.running, client.CLIENT.status) + if state == _LAST_STATE: + return + dropped = _LAST_STATE is not None and _LAST_STATE[0] and not state[0] + _LAST_STATE = state + if dropped: + # a bake or proxy still waiting will never get its outcome: the + # panel would say "waiting" forever + for last in (bake.LAST_BAKE, proxy.LAST_PROXY): + if client.OUTCOME_PENDING in last["message"]: + last["message"] = "connection lost before Revit replied: check the outcome in Revit" + _tag_redraw() + def _drain_incoming(): # runs on the main thread: bpy is usable here @@ -271,6 +305,10 @@ def _drain_incoming(): _log("pull interrupted: {}".format(imp.LAST_PULL.message)) _tag_redraw() + # after the queue: a result already queued when the connection dropped + # is read before the drop is declared + _check_connection_state() + return DRAIN_INTERVAL diff --git a/src/blender_addon/bridge_bake_send.py b/src/blender_addon/bridge_bake_send.py index ac775ac..4248276 100644 --- a/src/blender_addon/bridge_bake_send.py +++ b/src/blender_addon/bridge_bake_send.py @@ -294,7 +294,7 @@ def bake_selected(context=None, target="directshape", together=False): return 'ERROR', "unknown bake mode: {!r}".format(target) family = target == "family" - if not client.CLIENT.running: + if not client.CLIENT.ready: return 'ERROR', "not connected to Revit: press Connect" targets = bake_targets(context) @@ -467,7 +467,7 @@ def bake_selected(context=None, target="directshape", together=False): message = "no object sent" else: level = 'WARNING' if notes else 'INFO' - message = "{} - waiting for the outcome from Revit".format(_sent_text(sent)) + message = "{} - {}".format(_sent_text(sent), client.OUTCOME_PENDING) if family: # the directshape stays as it was in Phase B; the family # declares itself, because the wait for a family bake is much @@ -627,7 +627,7 @@ def _prepare_mesh(obj, obj_id, depsgraph, reject_limit, family=False): def _connected(): - return client.CLIENT.running and client.CLIENT.socket is not None + return client.CLIENT.ready and client.CLIENT.socket is not None def _sent_text(count): @@ -659,7 +659,7 @@ def remove_bake_selected(context=None): if context is None: context = bpy.context - if not client.CLIENT.running: + if not client.CLIENT.ready: return 'ERROR', "not connected to Revit: press Connect" objects, ids = remove_targets(context) @@ -675,8 +675,8 @@ def remove_bake_selected(context=None): if not client.CLIENT.send(header): return 'ERROR', "connection lost during removal" - return _record('INFO', "removal requested for {} - waiting for the outcome from Revit".format( - _objects_text(len(objects)))) + return _record('INFO', "removal requested for {} - {}".format( + _objects_text(len(objects)), client.OUTCOME_PENDING)) def apply_category_to_selected(context=None): diff --git a/src/blender_addon/bridge_client.py b/src/blender_addon/bridge_client.py index ca01fe3..53c143b 100644 --- a/src/blender_addon/bridge_client.py +++ b/src/blender_addon/bridge_client.py @@ -16,6 +16,11 @@ import bridge_protocol as protocol +# End of the panel line of a bake, removal or proxy sent and not answered +# yet. The drain looks for it when the connection drops, to say that the +# outcome will not come. +OUTCOME_PENDING = "waiting for the outcome from Revit" + class BridgeClient(object): @@ -23,6 +28,11 @@ def __init__(self): self.socket = None self.thread = None self.running = False + # True once Revit answered the hello with a valid hello_ack. A TCP + # connect alone proves nothing: a second Blender is accepted into + # the backlog of a Revit already serving the first one, and nobody + # reads it. + self.handshake_ok = False self.status = "disconnected" self.incoming = queue.Queue() self._write_lock = threading.Lock() @@ -56,8 +66,9 @@ def connect(self, host=None, port=None): return self.socket = sock + self.handshake_ok = False self.running = True - self.status = "connected to {}:{}".format(host, port) + self.status = "connected to {}:{}, waiting for Revit".format(host, port) # The thread gets ITS socket: see _owns for why it must not read # self.socket instead. @@ -69,6 +80,12 @@ def connect(self, host=None, port=None): "protocol_version": protocol.PROTOCOL_VERSION, "client": "blender"}) + @property + def ready(self): + """Connected AND handshake done: the only state in which anything + but the hello may be sent.""" + return self.running and self.handshake_ok + def disconnect(self): self.running = False self._force_close() diff --git a/src/blender_addon/bridge_proxy.py b/src/blender_addon/bridge_proxy.py index 39f2eb7..8c1edb2 100644 --- a/src/blender_addon/bridge_proxy.py +++ b/src/blender_addon/bridge_proxy.py @@ -202,7 +202,7 @@ def send_proxy(context=None): if context is None: context = bpy.context - if not client.CLIENT.running: + if not client.CLIENT.ready: return 'ERROR', "not connected to Revit: press Connect" obj = active_mesh(context) @@ -262,7 +262,7 @@ def send_proxy(context=None): sent = edges.describe_prepared(len(kept), dropped) if mode == MODE_ARCS: sent = "{} -> {} lines and {} arcs".format(sent, len(lines), len(arcs)) - notes.insert(0, "sent: {} - waiting for the outcome from Revit".format(sent)) + notes.insert(0, "sent: {} - {}".format(sent, client.OUTCOME_PENDING)) message = "; ".join(notes) LAST_PROXY["message"] = message diff --git a/src/blender_addon/bridge_sync.py b/src/blender_addon/bridge_sync.py index 64a5a6f..31ef9c2 100644 --- a/src/blender_addon/bridge_sync.py +++ b/src/blender_addon/bridge_sync.py @@ -150,7 +150,7 @@ def sync_all(context=None): if context is None: context = bpy.context - if not client.CLIENT.running: + if not client.CLIENT.ready: return 'ERROR', "not connected to Revit: press Connect" scene = context.scene @@ -264,7 +264,7 @@ def send_clear(): def send_style(scene): """Sends the preview colors of the scene. False if not connected or if the colors are invalid (they cannot be, the properties are clamped).""" - if not client.CLIENT.running: + if not client.CLIENT.ready: return False try: header = style.build_style_header( diff --git a/src/blender_addon/panel.py b/src/blender_addon/panel.py index 9c823f5..ea4d3fa 100644 --- a/src/blender_addon/panel.py +++ b/src/blender_addon/panel.py @@ -21,9 +21,9 @@ class BILOCUS_OT_connect(bpy.types.Operator): def execute(self, context): client.CLIENT.connect() - # Revit starts with the default colors: send the scene's right away. - sync.send_style(context.scene) - self.report({'INFO'}, client.CLIENT.status) + # the scene colors go out with the hello_ack, see _handle_message + self.report({'INFO'} if client.CLIENT.running else {'ERROR'}, + client.CLIENT.status) return {'FINISHED'} @@ -274,9 +274,15 @@ def draw(self, context): box = layout.box() box.label(text="Port: {}".format(protocol.DEFAULT_PORT)) box.label(text=client.CLIENT.status) + # one of the two at a time: Disconnect after a drop would overwrite + # the reason ("connection closed by Revit") with "disconnected" row = box.row() - row.operator("bilocus.connect") - row.operator("bilocus.disconnect") + connect = row.row() + connect.enabled = not client.CLIENT.running + connect.operator("bilocus.connect") + disconnect = row.row() + disconnect.enabled = client.CLIENT.running + disconnect.operator("bilocus.disconnect") # draw() runs on every redraw of the sidebar: only objects are # counted here (a pass over the collection), NEVER triangles. @@ -305,7 +311,7 @@ def draw(self, context): column = box.column() column.scale_y = 1.6 - column.enabled = client.CLIENT.running and not editing + column.enabled = client.CLIENT.ready and not editing column.operator("bilocus.sync", icon='FILE_REFRESH') box.operator("bilocus.clear", icon='TRASH') @@ -371,7 +377,7 @@ def draw(self, context): column.scale_y = 1.4 # selected None means "not counted", not "zero": the button stays # pressable and the real check is done by the operator, only once - column.enabled = (client.CLIENT.running and target is not None + column.enabled = (client.CLIENT.ready and target is not None and not proxy_editing and selected != 0) # EXPORT is the twin of IMPORT, already used below for the opposite # direction: a wrong icon identifier does not give a button with no @@ -437,7 +443,7 @@ def draw(self, context): # knows how to say WHICH object was skipped. Disabling "Bake # Family" here for a single wall in the selection would hide the # reason. - column.enabled = client.CLIENT.running and bool(targets) and not bake_editing + column.enabled = client.CLIENT.ready and bool(targets) and not bake_editing # EXPORT on both: it is the only icon identifier already seen # working inside Blender 5.1 and 5.2. The text tells them apart. column.operator("bilocus.bake_directshape", icon='EXPORT') @@ -446,7 +452,7 @@ def draw(self, context): box.prop(context.scene, bake.TOGETHER_PROPERTY) row = box.row() - row.enabled = client.CLIENT.running and bake.has_remove_candidates(context) + row.enabled = client.CLIENT.ready and bake.has_remove_candidates(context) row.operator("bilocus.remove_bake", icon='TRASH') box.label(text=bake.LAST_BAKE["message"]) diff --git a/tests/blender/smoke_bake.py b/tests/blender/smoke_bake.py index 8a20b31..ccdec67 100644 --- a/tests/blender/smoke_bake.py +++ b/tests/blender/smoke_bake.py @@ -646,6 +646,9 @@ def test_end_to_end(scene, collection, sample, addon_module): check(client.CLIENT.running, "bridge_client connected to the fake Revit on port {}".format( server.port)) check(server.wait_for("hello"), "hello received from the fake Revit") + # the fake Revit sends no hello_ack, and in background mode no timer + # would drain it anyway: stand in for the handshake + client.CLIENT.handshake_ok = True select_only([outside]) level, message = bake_send.bake_selected(bpy.context) diff --git a/tests/python/test_bridge_client.py b/tests/python/test_bridge_client.py index c992b26..9914303 100644 --- a/tests/python/test_bridge_client.py +++ b/tests/python/test_bridge_client.py @@ -392,3 +392,29 @@ def test_bridge_client_module_never_imports_bpy(): with open(path, "r") as handle: source = handle.read() assert "bpy" not in source + + +def test_ready_only_after_handshake(): + # A TCP connect is not enough to send: a second Blender lands in the + # backlog of a Revit busy with the first one and nobody reads it. + server = FakeServer() + client_obj = bridge_client.BridgeClient() + try: + client_obj.connect(host=protocol.DEFAULT_HOST, port=server.port) + server.accept_one() + assert client_obj.running + assert not client_obj.ready + assert "waiting for Revit" in client_obj.status + + client_obj.handshake_ok = True # what the drain does on hello_ack + assert client_obj.ready + + client_obj.disconnect() + assert not client_obj.ready + + # a new connection starts over, it does not inherit the old ack + client_obj.connect(host=protocol.DEFAULT_HOST, port=server.port) + assert client_obj.running and not client_obj.ready + finally: + client_obj.disconnect() + server.close() From ea0bf3a1968a562622113432a5b419c3a34cb63c Mon Sep 17 00:00:00 2001 From: Roberto Dolfini Date: Wed, 11 Nov 2026 16:49:21 +0100 Subject: [PATCH 2/4] Harden the socket server, the preview loop and the Blender timers - A failed Send closes the client only if it is still the current one: a Blender that reconnected meanwhile is no longer dropped. - SendTimeout on the accepted client: a Blender that stops reading can no longer freeze Revit inside a write. - The preview draws each object in its own try/catch: one bad object no longer hides the others or skips the transform reset. - GpuChunk.IsValid also checks vertex formats and effect instances. - The two Blender timers catch their own exceptions instead of being switched off by Blender. Co-Authored-By: Claude Opus 5.5 --- src/Bilocus.Revit/Net/BridgeServer.cs | 19 +++++++++++++++++-- src/Bilocus.Revit/Preview/GpuChunk.cs | 7 ++++++- src/Bilocus.Revit/Preview/PreviewServer.cs | 20 +++++++++++++++----- src/blender_addon/__init__.py | 21 ++++++++++++++++++++- 4 files changed, 58 insertions(+), 9 deletions(-) diff --git a/src/Bilocus.Revit/Net/BridgeServer.cs b/src/Bilocus.Revit/Net/BridgeServer.cs index a6fbf95..a1e3c32 100644 --- a/src/Bilocus.Revit/Net/BridgeServer.cs +++ b/src/Bilocus.Revit/Net/BridgeServer.cs @@ -132,6 +132,8 @@ public void Stop() : "stopped (the listener thread did not respond within 2 seconds)"; } + private const int SendTimeoutMs = 10000; + // Returns true if the frame went out in full. public bool Send(Frame frame) { @@ -166,8 +168,15 @@ public bool Send(Frame frame) // promised bytes. The protocol has no delimiters, there is // no realignment, so this is terminal for the connection: // the socket is closed and listening resumes. - _status = "write error, connection closed: " + ex.Message; - CloseClient(); + // Only if the failed stream is still THE connection: + // Blender may have reconnected while this Send was + // writing to the old one, and closing now would drop + // the new client for nothing. + if (ReferenceEquals(_stream, stream)) + { + _status = "write error, connection closed: " + ex.Message; + CloseClient(); + } return false; } } @@ -190,6 +199,12 @@ private void Loop() // that shows on screen. client.NoDelay = true; + // Send runs on Revit's main thread: a Blender that stops + // reading (suspended, hung) would freeze Revit inside a + // write with no way out. The timeout turns that into a + // write error, which Send already treats as terminal. + client.SendTimeout = SendTimeoutMs; + accepted = true; _client = client; diff --git a/src/Bilocus.Revit/Preview/GpuChunk.cs b/src/Bilocus.Revit/Preview/GpuChunk.cs index aec1d18..062b783 100644 --- a/src/Bilocus.Revit/Preview/GpuChunk.cs +++ b/src/Bilocus.Revit/Preview/GpuChunk.cs @@ -47,7 +47,12 @@ public sealed class GpuChunk public bool IsValid() { - return _litVertices != null && _litVertices.IsValid() + return _litFormat != null && _litFormat.IsValid() + && _flatFormat != null && _flatFormat.IsValid() + && _litEffect != null && _litEffect.IsValid() + && _flatEffect != null && _flatEffect.IsValid() + && _flatFaceEffect != null && _flatFaceEffect.IsValid() + && _litVertices != null && _litVertices.IsValid() && _flatFaceVertices != null && _flatFaceVertices.IsValid() && _triangleIndices != null && _triangleIndices.IsValid() && (_lineCount == 0 diff --git a/src/Bilocus.Revit/Preview/PreviewServer.cs b/src/Bilocus.Revit/Preview/PreviewServer.cs index df28c0e..5f32038 100644 --- a/src/Bilocus.Revit/Preview/PreviewServer.cs +++ b/src/Bilocus.Revit/Preview/PreviewServer.cs @@ -96,14 +96,24 @@ public void RenderScene(View view, DisplayStyle displayStyle) foreach (StoredObject item in objects) { - List chunks = GetOrBuild(item); + // Per object: a failure on one (a GPU allocation, say) + // must not hide every object after it, nor skip the + // transform reset below. + try + { + List chunks = GetOrBuild(item); - DrawContext.SetWorldTransform(ToRevitTransform(item.Matrix)); + DrawContext.SetWorldTransform(ToRevitTransform(item.Matrix)); - foreach (GpuChunk chunk in chunks) + foreach (GpuChunk chunk in chunks) + { + if (DrawContext.IsInterrupted()) { return; } + chunk.Draw(displayStyle, drawFaces, drawEdges); + } + } + catch (Exception ex) { - if (DrawContext.IsInterrupted()) { return; } - chunk.Draw(displayStyle, drawFaces, drawEdges); + LastError = string.Format("{0}: {1}: {2}", item.Name, ex.GetType().Name, ex.Message); } } // Precaution: the DrawContext is shared across the registered diff --git a/src/blender_addon/__init__.py b/src/blender_addon/__init__.py index 4040292..5c155e1 100644 --- a/src/blender_addon/__init__.py +++ b/src/blender_addon/__init__.py @@ -116,6 +116,17 @@ def _on_depsgraph_update(scene, depsgraph): def _flush_transforms(): + # Same safety net as _handle_safely, for the whole tick: an exception + # that reaches Blender unregisters the timer, and the addon would stay + # connected but deaf without telling anyone. + try: + _flush_step() + except Exception as error: + _log("transform flush failed: {}: {}".format(type(error).__name__, error)) + return TRANSFORM_INTERVAL + + +def _flush_step(): if _PENDING: # drain BEFORE sending: send() is synchronous and can take a few # milliseconds, and whatever arrives meanwhile must end up in the @@ -124,7 +135,6 @@ def _flush_transforms(): _PENDING.clear() for obj_id, matrix in batch: sync.send_transform(obj_id, matrix) - return TRANSFORM_INTERVAL def _log(message): @@ -276,6 +286,15 @@ def _check_connection_state(): def _drain_incoming(): + # same safety net as _flush_transforms + try: + return _drain_step() + except Exception as error: + _log("drain failed: {}: {}".format(type(error).__name__, error)) + return DRAIN_INTERVAL + + +def _drain_step(): # runs on the main thread: bpy is usable here global _DRAIN_PAUSED_AT budget = receive.DRAIN_BUDGET_SECONDS From 3ec22eda53ec99e28cab5dcc67b6307478bb40f2 Mon Sep 17 00:00:00 2001 From: Roberto Dolfini Date: Wed, 11 Nov 2026 16:49:21 +0100 Subject: [PATCH 3/4] Fix together bakes, report the Note, keep BL_ parameters with formulas - Bake together: a member announced but never arrived keeps its FreeFormElement instead of being deleted as "no longer selected". - A mesh that Revit turns into more than one solid is refused with a reason instead of keeping only the first solid. - The Note of the Status now travels at the end of bake_result message, so Blender shows it. - A BL_ parameter with a formula of its own is no longer removed. - Cleanup: dead members, stale comments, the unused limit argument of _normalize_object_ids; DESIGN.md aligned (template, temp save, the non-host member baked alone). Co-Authored-By: Claude Opus 5.5 --- DESIGN.md | 17 +++++-- src/Bilocus.Revit/Bake/BakeBuilder.cs | 2 +- src/Bilocus.Revit/Bake/BakeResult.cs | 11 +++++ src/Bilocus.Revit/Bake/FamilyBaker.cs | 48 ++++++++++++++----- src/Bilocus.Revit/Bake/FamilyParameters.cs | 7 +++ src/Bilocus.Revit/Net/MessageRouter.cs | 5 +- src/blender_addon/bridge_bake.py | 15 ++---- src/blender_addon/bridge_bake_send.py | 2 +- .../BakeResultMessageTests.cs | 16 +++++++ 9 files changed, 91 insertions(+), 32 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index 6a22009..8a0be3c 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -494,7 +494,8 @@ and a rejection fails only that object. **Two modes, `target` on the batch** (Phase B2): `"directshape"` (default if absent) or `"family"`. In family mode each object becomes a loadable family `BL_` with a `FreeFormElement`, created from -`English\Metric Generic Model.rft`, loaded without saving and with an +`English\Metric Generic Model.rft` (falling back to the imperial +templates), saved as `BL_.rfa` in a temp folder, loaded, and with an instance on the nearest level below the origin. Revit decomposes the matrix (`FamilyPlacement`): translation and rotation around Z go to the instance, tilts and scale go into the geometry. Re-bake does `EditFamily` @@ -521,11 +522,16 @@ normal family bake is the same thing with a group of one. Re-bake with the same host aligns the family to the objects of THIS bake: their `FreeFormElement`s are updated or added, the bridge's ones of objects no longer in the bake are deleted (the user's own elements have no mark and -stay). A member that fails is reported and keeps its previous -`FreeFormElement`; if the host fails, nothing is written. The DirectShapes +stay). A member that fails, or is announced and never arrives, keeps its +previous `FreeFormElement`; if the host fails, nothing is written. A mesh +that Revit turns into more than one solid is refused: split it into one +object per piece. The DirectShapes of all members and the families of their own of the non-host members are removed (`switched`). Remove Bake finds a together family through its host -only. +only, and so does a bake: baking a non-host member on its own creates its +own family or DirectShape while its `FreeFormElement` stays in the host's +family, so the geometry is there twice. Re-bake the group from the host, or +remove the member from it first. `bake_remove` deletes all `DirectShape` elements, families and instances marked with those ids, copies included: it is the explicit request to @@ -752,7 +758,8 @@ Blender side, a failure also produces the `error` frame. `ok` says whether the write to the document succeeded. An object that fails inside an otherwise successful bake does not make it false: it ends up in `failed` and `message` carries the reason for the last one that -failed. `as_mesh` counts the objects that came out of the builder as a +failed, followed by the Note of the Status (`; ` between them) when there +is one. `as_mesh` counts the objects that came out of the builder as a mesh rather than a solid (open mesh or non-manifold). `faces_planar` and `faces_triangulated` say how many polygons arrived whole and how many fell back to triangles. `target` repeats the batch's mode (`"all"` for diff --git a/src/Bilocus.Revit/Bake/BakeBuilder.cs b/src/Bilocus.Revit/Bake/BakeBuilder.cs index 02b6173..09290e1 100644 --- a/src/Bilocus.Revit/Bake/BakeBuilder.cs +++ b/src/Bilocus.Revit/Bake/BakeBuilder.cs @@ -286,7 +286,6 @@ private static string ResolveCategory(Document document, string category, out El return null; } - // Fills the builder with the object's faces. Returns the rejection // What BuildShape hands back: the builder, its result and the face // set it was filled with. The caller owns them: the DirectShape bake // disposes them after SetShape, the family bake keeps them alive @@ -402,6 +401,7 @@ private static string BuildOnce(BakeFaceSet faces, double[] points, bool meshOnl } } + // Fills the builder with the object's faces. Returns the rejection // reason if no face is left, otherwise null. // // FamilyBaker reaches it through BuildShape, passing points in FAMILY diff --git a/src/Bilocus.Revit/Bake/BakeResult.cs b/src/Bilocus.Revit/Bake/BakeResult.cs index 081b6db..65685a3 100644 --- a/src/Bilocus.Revit/Bake/BakeResult.cs +++ b/src/Bilocus.Revit/Bake/BakeResult.cs @@ -189,6 +189,17 @@ public string BuildMessage() return Succeeded ? "" : UnknownReason; } + // The message of bake_result: BuildMessage plus the Note. Without the + // Note, whoever pressed Bake in Blender would never read what the + // Status says (a BL_ value not written, a name already used, the + // batch run without the undo group). + public string BuildWireMessage() + { + string message = BuildMessage(); + if (string.IsNullOrEmpty(Note)) { return message; } + return message.Length == 0 ? Note : message + "; " + Note; + } + private string DescribeLastFailure() { string reason = string.IsNullOrEmpty(LastFailureReason) ? UnknownReason : LastFailureReason; diff --git a/src/Bilocus.Revit/Bake/FamilyBaker.cs b/src/Bilocus.Revit/Bake/FamilyBaker.cs index 09adde9..f25b7bc 100644 --- a/src/Bilocus.Revit/Bake/FamilyBaker.cs +++ b/src/Bilocus.Revit/Bake/FamilyBaker.cs @@ -43,10 +43,11 @@ namespace Bilocus.Revit.Bake // Note. // // CTRL+Z. A TransactionGroup is tried around the whole batch, as in the - // DirectShape bake. If Revit rejects LoadFamily or EditFamily with the - // group open (nobody could test it outside the add-in), the group rolls - // back, it is remembered for the session and the batch is run again from - // scratch without a group: more undo entries, stated in the Status Note. + // DirectShape bake. Verified in Revit that LoadFamily and EditFamily + // accept the open group. Kept as a safety net: if Revit ever rejects + // them, the group rolls back, it is remembered for the session and the + // batch is run again from scratch without a group: more undo entries, + // stated in the Status Note. // // As in BakeBuilder: a failure that concerns an object fails only that // ONE object, counted and named in BakeResult. No TaskDialog. @@ -89,11 +90,6 @@ public static class FamilyBaker // half the batch every time. private static bool? _groupAllowsFamilyLoad; - public static bool? GroupAllowsFamilyLoad - { - get { return _groupAllowsFamilyLoad; } - } - // The candidate template paths for this version of Revit, in the // order they are tried. Public because the error message cites them, // and whoever reads the Status must be able to compare them with the @@ -510,6 +506,16 @@ private string BakeFamily(BakeMeshRequest host, List members) { List built = new List(); HashSet requested = new HashSet(StringComparer.Ordinal); + if (_batch.Together) + { + // Announced but never arrived (pack failed in + // Blender, frame rejected) is not "no longer + // selected": its FreeFormElement stays, like a + // member that fails. Only together: in a normal + // bake the other announced ids are families of + // their own and must leave the host's. + foreach (string id in _batch.AnnouncedIds) { requested.Add(id); } + } List otherCategories = new List(); int facesPlanar = 0; int facesTriangulated = 0; @@ -631,16 +637,25 @@ private string BuildMemberSolid(BakeMeshRequest member, bool isHost, FamilyPlace return NonManifoldRefusal; } - Solid first = FirstSolid(built.GetGeometricalObjects()); + IList geometry = built.GetGeometricalObjects(); + Solid first = FirstSolid(geometry); if (first == null) { return "the builder did not return a solid (outcome " + outcome + ")"; } + int solids = CountSolids(geometry); + if (solids > 1) + { + // Only the first would become a FreeFormElement: the rest + // would disappear without a word. + return string.Format( + "the mesh became {0} separate solids: split it into one object per piece (P > By Loose Parts)", + solids); + } solid = new MemberSolid { ObjectId = member.ObjectId, - Name = member.Name, Solid = first, OpenShell = openShell, FacesPlanar = faces.PlanarCount, @@ -650,6 +665,16 @@ private string BuildMemberSolid(BakeMeshRequest member, bool isHost, FamilyPlace return null; } + private static int CountSolids(IList geometry) + { + int count = 0; + foreach (GeometryObject item in geometry) + { + if (item is Solid) { count++; } + } + return count; + } + private static Solid FirstSolid(IList geometry) { if (geometry == null) { return null; } @@ -1374,7 +1399,6 @@ public static ObjectWrite Done(bool created, int switched, bool notMoved, string private sealed class MemberSolid { public string ObjectId; - public string Name; public Solid Solid; public bool OpenShell; public int FacesPlanar; diff --git a/src/Bilocus.Revit/Bake/FamilyParameters.cs b/src/Bilocus.Revit/Bake/FamilyParameters.cs index d494e52..1040771 100644 --- a/src/Bilocus.Revit/Bake/FamilyParameters.cs +++ b/src/Bilocus.Revit/Bake/FamilyParameters.cs @@ -49,6 +49,13 @@ public static List Apply(Document familyDoc, IList if (!wanted.TryGetValue(name, out p) || fp.IsInstance || fp.Definition.GetDataType() != SpecOf(p.Kind)) { + if (!string.IsNullOrEmpty(fp.Formula)) + { + // The user gave it a formula: it is theirs now + keptAsIs.Add(name); + left.Add(name + " kept, it has a formula"); + continue; + } string user = FormulaUsing(existing, fp); if (user != null) { diff --git a/src/Bilocus.Revit/Net/MessageRouter.cs b/src/Bilocus.Revit/Net/MessageRouter.cs index e48db28..0f69fea 100644 --- a/src/Bilocus.Revit/Net/MessageRouter.cs +++ b/src/Bilocus.Revit/Net/MessageRouter.cs @@ -350,8 +350,7 @@ private void HandleBakeBegin(JsonElement root) try { // Phase B2: target absent = directshape, so a Phase B Blender - // keeps doing the bake it used to do. The target is read - // before the ids because it decides their cap. + // keeps doing the bake it used to do. string target = OptionalTarget(root); // host present = "Bake together" (DESIGN.md 5.3). Present @@ -809,7 +808,7 @@ public static string BuildBakeResult(BakeResult result) writer.WriteString("target", result.Target); writer.WriteNumber("switched", result.SwitchedCount); writer.WriteNumber("not_moved", result.NotMovedCount); - writer.WriteString("message", result.BuildMessage()); + writer.WriteString("message", result.BuildWireMessage()); writer.WriteEndObject(); } return Encoding.UTF8.GetString(buffer.ToArray()); diff --git a/src/blender_addon/bridge_bake.py b/src/blender_addon/bridge_bake.py index 96a2871..6042aa0 100644 --- a/src/blender_addon/bridge_bake.py +++ b/src/blender_addon/bridge_bake.py @@ -339,7 +339,7 @@ def build_bake_begin_header(obj_ids, target="directshape", host=None): target is ALWAYS written, even when it equals the default: Revit treats its absence as directshape, but an explicit header reads in the logs - without knowing that rule. The object limit depends on the target. + without knowing that rule. host: None for a normal bake. The obj_id of the active object for "Bake together": one family with all the objects, named after the host, @@ -355,7 +355,7 @@ def build_bake_begin_header(obj_ids, target="directshape", host=None): target, ", ".join(BAKE_TARGETS))) header = { "type": "bake_begin", - "obj_ids": _normalize_object_ids(obj_ids, "bake_begin", MAX_BAKE_OBJECTS), + "obj_ids": _normalize_object_ids(obj_ids, "bake_begin"), "target": target, } if host is not None: @@ -473,7 +473,7 @@ def _header_count(value, name): raise BridgeFramingError("{} must be an integer, is {!r}".format(name, value)) -def _normalize_object_ids(obj_ids, message_type, limit=None): +def _normalize_object_ids(obj_ids, message_type): # A string is iterable: without this check "abc" would become three # objects named "a", "b" and "c". if obj_ids is None or isinstance(obj_ids, (str, bytes)): @@ -482,15 +482,10 @@ def _normalize_object_ids(obj_ids, message_type, limit=None): values = list(obj_ids) if not values: raise BridgeFramingError("{}: no object in the message".format(message_type)) - # The default is resolved here and not in the signature: a default in - # the signature would freeze the value at import time, and bake_remove - # stays on the directshape limit because it removes in both modes. - if limit is None: - limit = MAX_BAKE_OBJECTS - if len(values) > limit: + if len(values) > MAX_BAKE_OBJECTS: raise BridgeFramingError( "{}: {} objects is over the maximum of {}".format( - message_type, len(values), limit)) + message_type, len(values), MAX_BAKE_OBJECTS)) # a loop per OBJECT, at most 500: not the forbidden per-vertex loop normalized = [_normalize_object_id(value) for value in values] diff --git a/src/blender_addon/bridge_bake_send.py b/src/blender_addon/bridge_bake_send.py index 4248276..77caafe 100644 --- a/src/blender_addon/bridge_bake_send.py +++ b/src/blender_addon/bridge_bake_send.py @@ -407,7 +407,7 @@ def bake_selected(context=None, target="directshape", together=False): return 'ERROR', "bake cannot be sent: {}".format(error) if not client.CLIENT.send(begin): - return 'ERROR', "connection lost before the bake" + return _record('ERROR', "connection lost before the bake") sent = 0 failed = [] diff --git a/tests/Bilocus.Revit.Net.Tests/BakeResultMessageTests.cs b/tests/Bilocus.Revit.Net.Tests/BakeResultMessageTests.cs index eb2f4c9..f682c1f 100644 --- a/tests/Bilocus.Revit.Net.Tests/BakeResultMessageTests.cs +++ b/tests/Bilocus.Revit.Net.Tests/BakeResultMessageTests.cs @@ -180,6 +180,22 @@ public void BuildBakeResult_OnPartialSuccess_MessageNamesTheLastFailedObject() Assert.Contains("Wall", root.GetProperty("message").GetString()); } + [Fact] + public void BuildBakeResult_NoteTravelsInTheMessage() + { + BakeResult result = new BakeResult(BakeResult.ActionBake); + result.Succeeded = true; + result.CreatedCount = 1; + result.Note = "BL_Volume not written, it has a formula"; + + Assert.Equal(result.Note, Parse(result).GetProperty("message").GetString()); + + result.AddFailure("Wall", "category not allowed"); + string message = Parse(result).GetProperty("message").GetString(); + Assert.StartsWith(result.BuildMessage() + "; ", message); + Assert.EndsWith(result.Note, message); + } + [Fact] public void BuildBakeResult_Remove_HasActionRemove() { From bbdeb979943d61ae80fad65a98415429996044cd Mon Sep 17 00:00:00 2001 From: Roberto Dolfini Date: Wed, 11 Nov 2026 17:24:44 +0100 Subject: [PATCH 4/4] Drop the multi-solid refusal: loose parts come back as one solid Tried in Revit 2025: two cubes joined with Ctrl+J become one solid with two volumes, so the check never fired. Co-Authored-By: Claude Opus 5.5 --- DESIGN.md | 5 ++--- src/Bilocus.Revit/Bake/FamilyBaker.cs | 25 ++++--------------------- 2 files changed, 6 insertions(+), 24 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index 8a0be3c..ef3a9df 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -523,9 +523,8 @@ same host aligns the family to the objects of THIS bake: their `FreeFormElement`s are updated or added, the bridge's ones of objects no longer in the bake are deleted (the user's own elements have no mark and stay). A member that fails, or is announced and never arrives, keeps its -previous `FreeFormElement`; if the host fails, nothing is written. A mesh -that Revit turns into more than one solid is refused: split it into one -object per piece. The DirectShapes +previous `FreeFormElement`; if the host fails, nothing is written. Loose +parts of one object become one solid with several volumes. The DirectShapes of all members and the families of their own of the non-host members are removed (`switched`). Remove Bake finds a together family through its host only, and so does a bake: baking a non-host member on its own creates its diff --git a/src/Bilocus.Revit/Bake/FamilyBaker.cs b/src/Bilocus.Revit/Bake/FamilyBaker.cs index f25b7bc..b6448f3 100644 --- a/src/Bilocus.Revit/Bake/FamilyBaker.cs +++ b/src/Bilocus.Revit/Bake/FamilyBaker.cs @@ -637,21 +637,14 @@ private string BuildMemberSolid(BakeMeshRequest member, bool isHost, FamilyPlace return NonManifoldRefusal; } - IList geometry = built.GetGeometricalObjects(); - Solid first = FirstSolid(geometry); + // Loose parts (two cubes joined with Ctrl+J) come back as ONE + // solid with several volumes, verified in Revit 2025: the + // first solid is the whole object. + Solid first = FirstSolid(built.GetGeometricalObjects()); if (first == null) { return "the builder did not return a solid (outcome " + outcome + ")"; } - int solids = CountSolids(geometry); - if (solids > 1) - { - // Only the first would become a FreeFormElement: the rest - // would disappear without a word. - return string.Format( - "the mesh became {0} separate solids: split it into one object per piece (P > By Loose Parts)", - solids); - } solid = new MemberSolid { @@ -665,16 +658,6 @@ private string BuildMemberSolid(BakeMeshRequest member, bool isHost, FamilyPlace return null; } - private static int CountSolids(IList geometry) - { - int count = 0; - foreach (GeometryObject item in geometry) - { - if (item is Solid) { count++; } - } - return count; - } - private static Solid FirstSolid(IList geometry) { if (geometry == null) { return null; }