Skip to content
Merged
2 changes: 1 addition & 1 deletion .fusion-addin.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "Mesora",
"display_name": "Mesora",
"description": "Experimental informational 3D dimensions (session-only safe mode).",
"description": "Informational 3D measurements with saved definitions and per-document visibility.",
"initialized": true
}
2 changes: 1 addition & 1 deletion Mesora/Mesora.manifest
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"type": "addin",
"author": "4FusionLab",
"description": {
"": "Experimental informational 3D dimensions (session-only safe mode)."
"": "Informational 3D measurements with saved definitions and per-document visibility."
},
"version": "1.0.0",
"supportedOS": "windows|mac",
Expand Down
438 changes: 369 additions & 69 deletions Mesora/Mesora.py

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions Mesora/dimensions/batch.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ def __init__(self, ident):
self.options = []
self.kind = None
self.offset = 0.0
self.visible = True

@property
def needs_second(self):
Expand Down
29 changes: 29 additions & 0 deletions Mesora/dimensions/event_scope.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
"""Own event-handler references for one active command, without importing adsk."""


class EventScope:
def __init__(self):
self.bindings = []

def bind(self, event, handler):
if not event.add(handler):
raise RuntimeError('Failed to attach Fusion command event')
self.bindings.append((event, handler))

def close(self, destroyed=False):
"""Detach active events, or release references after command destruction.

Destroyed command event wrappers may already be invalid. Keeping them
then would retain deleted inputs and the document through their handlers.
During add-in stop, failures on still-active commands remain retryable.
"""
failed = []
for event, handler in reversed(self.bindings):
try:
if not event.remove(handler) and not destroyed:
failed.append((event, handler))
except Exception:
if not destroyed:
failed.append((event, handler))
self.bindings[:] = reversed(failed)
return not self.bindings
56 changes: 56 additions & 0 deletions Mesora/dimensions/label_layout.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
"""Screen-space caption packing, independent of Fusion and model geometry."""
import math


def projection_scale(width, height, target):
"""Normalize projection pixels to viewport points on high-DPI displays.

The camera look-at target projects to the viewport centre. Fusion can report
that projection in backing pixels while width/height use logical points.
Snap only coherent positive ratios; ordinary/fake viewports default to 1.
"""
if not width or not height or target is None:
return 1.0
sx, sy = 2*target[0]/width, 2*target[1]/height
if not all(math.isfinite(v) and .5 <= v <= 4 for v in (sx, sy)):
return 1.0
scale = (sx+sy)/2
if abs(sx-sy) > .05:
return 1.0
snapped = round(scale*4)/4
return snapped if abs(snapped-scale) <= .03 else scale


def projected_caption_size(width, height, xdirection, ydirection):
"""Conservative AABB of an oriented text rectangle in screen pixels."""
def direction(value, fallback):
length = math.hypot(*value)
return tuple(v/length for v in value) if length > 1e-8 else fallback
# At grazing angles a projected axis can collapse. Reserve a conservative
# full-size perpendicular extent instead of accepting a zero-height box.
known_y = direction(ydirection, (0, 1))
x = direction(xdirection, (-known_y[1], known_y[0]))
y = direction(ydirection, (-x[1], x[0]))
return abs(x[0])*width+abs(y[0])*height, abs(x[1])*width+abs(y[1])*height


def choose_caption(width, height, occupied, candidates, padding=5, bounds=None):
"""Select the first actual projected candidate with clear padded bounds.

Candidates yield ((screen_x, screen_y), payload). The adapter supplies
projected positions reachable in the caption's model plane.
"""
if not all(math.isfinite(v) and v > 0 for v in (width, height)):
raise ValueError('Invalid caption size')
for (x, y), payload in candidates:
if not math.isfinite(x) or not math.isfinite(y):
continue
rect = (x-width/2-padding, y-height/2-padding,
x+width/2+padding, y+height/2+padding)
if bounds is not None and not (bounds[0] <= rect[0] and bounds[1] <= rect[1]
and rect[2] <= bounds[2] and rect[3] <= bounds[3]):
continue
if all(rect[2] <= other[0] or other[2] <= rect[0] or
rect[3] <= other[1] or other[3] <= rect[1] for other in occupied):
return payload, rect
raise ValueError('Cannot find a clear caption position in this view')
86 changes: 68 additions & 18 deletions Mesora/dimensions/model.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,45 @@
"""Versioned, deliberately strict dimension definitions.

No measured value is persisted: geometry is the source of truth.
"""
"""Versioned dimension definitions. Geometry, never cached values, is persisted."""

from dataclasses import dataclass, field
import json
import math
import re
import uuid

SCHEMA_VERSION = 1
KINDS = {"distance": 2, "edge_length": 1, "radius": 1, "diameter": 1}
SCHEMA_VERSION = 2
KINDS = {"distance": 2, "angle": 2, "edge_length": 1, "radius": 1,
"diameter": 1, "area": 1, "perimeter": 1}
LEGACY_KINDS = {"distance", "edge_length", "radius", "diameter"}


class SchemaError(ValueError):
pass


def _valid_id(ident, legacy=False):
if not isinstance(ident, str):
return False
if not legacy and re.fullmatch(r"m[1-9][0-9]*", ident):
return True
try:
uuid.UUID(ident)
return True
except (ValueError, TypeError, AttributeError):
return False


def _json_object(value):
if not isinstance(value, dict):
raise SchemaError("Placement and display must be objects")
try:
json.dumps(value, allow_nan=False)
except (TypeError, ValueError) as exc:
raise SchemaError("Invalid JSON data") from exc


@dataclass(frozen=True)
class EntityReference:
token: str
# An occurrence is stored separately: never identify geometry by comparing tokens.
occurrence_token: str | None = None

def __post_init__(self):
Expand All @@ -42,16 +63,19 @@ class Dimension:
display: dict = field(default_factory=dict)

def __post_init__(self):
try:
uuid.UUID(self.id)
except (ValueError, TypeError, AttributeError) as exc:
raise SchemaError("Invalid dimension ID") from exc
if not _valid_id(self.id):
raise SchemaError("Invalid dimension ID")
if self.kind not in KINDS or len(self.references) != KINDS[self.kind]:
raise SchemaError("Invalid dimension kind or reference count")
if not all(isinstance(ref, EntityReference) for ref in self.references):
raise SchemaError("Invalid entity reference")
if not isinstance(self.placement, dict) or not isinstance(self.display, dict):
raise SchemaError("Placement and display must be objects")
_json_object(self.placement)
_json_object(self.display)
offset = self.placement.get('offset', 0.0)
if isinstance(offset, bool) or not isinstance(offset, (int, float)) or not math.isfinite(offset):
raise SchemaError("Offset must be a finite number")
if not isinstance(self.display.get('visible', True), bool):
raise SchemaError("Row visibility must be a boolean")

@classmethod
def create(cls, kind, references, placement=None, display=None):
Expand All @@ -67,6 +91,8 @@ def serialize(dimensions, visible=True):
dimensions = list(dimensions)
if not isinstance(visible, bool):
raise SchemaError("visible must be a boolean")
if not all(isinstance(d, Dimension) for d in dimensions):
raise SchemaError("Invalid dimension")
if len({d.id for d in dimensions}) != len(dimensions):
raise SchemaError("Duplicate dimension IDs")
try:
Expand All @@ -77,18 +103,42 @@ def serialize(dimensions, visible=True):
raise SchemaError("Invalid JSON data") from exc


def _unique_object(pairs):
result = {}
for key, value in pairs:
if key in result:
raise SchemaError("Duplicate JSON object key")
result[key] = value
return result


def deserialize(payload):
try:
data = json.loads(payload, parse_constant=lambda x: (_ for _ in ()).throw(ValueError(x)))
if not isinstance(data, dict) or data.get("schema_version") != SCHEMA_VERSION:
data = json.loads(payload, object_pairs_hook=_unique_object,
parse_constant=lambda x: (_ for _ in ()).throw(ValueError(x)))
if not isinstance(data, dict):
raise SchemaError("Invalid document payload")
version = data.get("schema_version")
if type(version) is not int or version not in (1, SCHEMA_VERSION):
raise SchemaError("Unsupported schema version")
if set(data) != {'schema_version', 'visible', 'dimensions'}:
raise SchemaError("Unrecognized document fields")
if not isinstance(data.get("visible"), bool) or not isinstance(data.get("dimensions"), list):
raise SchemaError("Invalid document payload")
dimensions = []
for item in data["dimensions"]:
refs = tuple(EntityReference(ref["token"], ref.get("occurrence_token"))
for ref in item["references"])
dimensions.append(Dimension(item["id"], item["type"], refs,
if set(item) != {'id', 'type', 'references', 'placement', 'display'}:
raise SchemaError("Unrecognized dimension fields")
if not isinstance(item['references'], list):
raise SchemaError("References must be an array")
if version == 1 and (not _valid_id(item['id'], legacy=True) or item['type'] not in LEGACY_KINDS):
raise SchemaError("Invalid legacy dimension")
refs = []
for ref in item['references']:
if not isinstance(ref, dict) or not {'token'} <= set(ref) <= {'token', 'occurrence_token'}:
raise SchemaError("Invalid reference fields")
refs.append(EntityReference(ref['token'], ref.get('occurrence_token')))
dimensions.append(Dimension(item["id"], item["type"], tuple(refs),
item["placement"], item["display"]))
if len({d.id for d in dimensions}) != len(dimensions):
raise SchemaError("Duplicate dimension IDs")
Expand Down
8 changes: 7 additions & 1 deletion Mesora/dimensions/persistence.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,10 @@ def load(design):
if not attribute:
return [], True
# Refuse to interpret or overwrite corrupt and future schemas.
return deserialize(attribute.value)
payload = attribute.value
if not isinstance(payload, str) or len(payload.encode('utf-8')) > MAX_BYTES:
raise PersistenceError('Dimension definitions exceed Fusion attribute limit')
return deserialize(payload)


def save(design, dimensions, visible):
Expand All @@ -25,6 +28,9 @@ def save(design, dimensions, visible):
payload = serialize(dimensions, visible)
if len(payload.encode('utf-8')) > MAX_BYTES:
raise PersistenceError('Dimension definitions exceed Fusion attribute limit')
current = design.attributes.itemByName(GROUP, NAME)
if current and current.value == payload:
return
attribute = design.attributes.add(GROUP, NAME, payload)
if not attribute or attribute.value != payload:
raise PersistenceError('Fusion did not store the dimension definitions')
57 changes: 57 additions & 0 deletions Mesora/dimensions/runtime_persistence.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
"""Translate committed runtime definitions to document storage, without adsk.

Loading restores references only. Callers resolve and remeasure them against the
current model, retaining unresolved definitions for later repair/removal.
"""
from dataclasses import dataclass
import re

from .model import Dimension, SchemaError, serialize
from .persistence import GROUP, NAME, load, save


@dataclass
class RuntimeDefinitions:
items: list
offsets: dict
hidden_ids: set
visible: bool
next_id: int


def load_state(design):
dimensions, visible = load(design)
numeric_ids = [int(d.id[1:]) for d in dimensions if re.fullmatch(r'm[1-9][0-9]*', d.id)]
return RuntimeDefinitions(
[(d.id, d.kind, d.references) for d in dimensions],
{d.id: d.placement.get('offset', 0.0) for d in dimensions},
{d.id for d in dimensions if not d.display.get('visible', True)},
visible, max(numeric_ids, default=0) + 1)


def save_state(design, items, offsets, hidden_ids, visible):
"""Persist an explicit command commit; return whether an attribute was written.

Validate existing data first, and do not replace extension fields that this
runtime does not understand. This is safer than silently losing user data.
"""
previous, _ = load(design)
for dimension in previous:
if set(dimension.placement) - {'offset'} or set(dimension.display) - {'visible'}:
raise SchemaError('Stored dimension settings are not supported by this Mesora version')
items = list(items)
ids = {item[0] for item in items}
if set(offsets) - ids or set(hidden_ids) - ids:
raise SchemaError('Settings reference an unknown measurement')
dimensions = [Dimension(ident, kind, tuple(refs),
{'offset': offsets.get(ident, 0.0)},
{'visible': ident not in hidden_ids})
for ident, kind, refs in items]
payload = serialize(dimensions, visible)
attribute = design.attributes.itemByName(GROUP, NAME)
if attribute and attribute.value == payload:
return False
if attribute is None and not dimensions and visible:
return False
save(design, dimensions, visible)
return True
Loading
Loading