Skip to content

armgit / SOMA

Public Imported from GitHub
0

Desktop app for designing parametric 3D models in CadQuery together with the coding agent of your choice

soma: Animationen schneller abtasten, to() als Schraubbewegung, alpha für Teile, Warnungen zur Bewegung

Kai-Jungsthoefela56e6de52576
diff --git a/python/soma/anim.py b/python/soma/anim.py
index 0414149..0cd4fb3 100644
--- a/python/soma/anim.py
+++ b/python/soma/anim.py
@@ -15,6 +15,7 @@ to .soma/anim/. The viewer, videos and pictures are made from it, the animation
Lengths in mm, angles in degrees, times in seconds. Parts are named as in add_part(), groups as in group=.
"""
+import bisect
import inspect
import math
@@ -118,30 +119,27 @@ def _quat(m):
return q / np.linalg.norm(q)
-def _quat_matrix(q):
- x, y, z, w = q
- return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
- [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
- [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]])
-
-
-def _slerp(q0, q1, s):
- d = float(np.dot(q0, q1))
- if d < 0:
- q1, d = -q1, -d
- if d > 0.9995:
- q = q0 + (q1 - q0) * s
- return q / np.linalg.norm(q)
- th = math.acos(d)
- return (math.sin((1 - s) * th) * q0 + math.sin(s * th) * q1) / math.sin(th)
-
-
-def _blend(m0, m1, s):
- """Zwischenlage zweier Lagen: Ursprung geradlinig, Drehung auf kuerzestem Weg."""
- out = np.eye(4)
- out[:3, :3] = _quat_matrix(_slerp(_quat(m0), _quat(m1), s))
- out[:3, 3] = m0[:3, 3] + (m1[:3, 3] - m0[:3, 3]) * s
- return out
+def _screw(m0, m1, s):
+ """Zwischenlage zweier Lagen als Schraubbewegung: Drehung um eine feste Achse im Raum plus Verschiebung entlang dieser
+ Achse, auf dem kuerzeren Weg (hoechstens 180 Grad). Frueher lief der Ursprung des Modells geradlinig und die Drehung
+ getrennt um ihn. Dann eiert jedes Teil, das weit weg vom Nullpunkt liegt, und die Bahn haengt davon ab, wo der Nullpunkt
+ zufaellig liegt. Hier nicht: eine reine Drehung laeuft auf dem Kreisbogen um ihre Achse, eine reine Verschiebung gerade."""
+ d = m1 @ np.linalg.inv(m0) # die Bewegung im Raum: m1 = d @ m0
+ q = _quat(d)
+ if q[3] < 0:
+ q = -q
+ sin_half = float(np.linalg.norm(q[:3]))
+ th = 2 * math.atan2(sin_half, q[3])
+ t = d[:3, 3]
+ if th < 1e-9: # keine Drehung (auch Rechenrauschen): gerade Verschiebung
+ return _translation(t * s) @ m0
+ u = q[:3] / sin_half
+ along = float(np.dot(u, t))
+ # Punkt der Achse, der dem Nullpunkt am naechsten liegt (Satz von Chasles). Bei kleinen Winkeln liegt die Achse weit
+ # weg und der Bogen ist fast gerade, der Fehler bleibt dabei klein (Pfeilhoehe etwa |t| * th / 8).
+ perp = t - along * u
+ p = 0.5 * (perp + np.cross(u, perp) / math.tan(th / 2))
+ return _translation(u * (along * s)) @ _axis_rotation(p, u, math.degrees(th) * s) @ m0
def _placement(loc):
@@ -242,27 +240,34 @@ class Joint:
self.anim, self.kind, self.parts, self.parent = anim, kind, parts, parent
self.value = value # Stand am Ende der bisher beschriebenen Zeitleiste
self.start = value
- self.segments = [] # (t0, t1, f(s) -> Wert, ease)
+ self.segments = [] # (t0, t1, f(s) -> Wert, ease, Endwert), zeitlich geordnet
+ self.ends = [] # t1 je Schritt, fuer die binaere Suche in value_at()
self.label = ", ".join(parts[:3]) + (" ..." if len(parts) > 3 else "")
def _own(self, value):
raise NotImplementedError
def value_at(self, t):
- v = self.start
- for t0, t1, f, ease in self.segments:
- if t >= t1:
- v = f(1.0)
- elif t >= t0:
- return f(ease((t - t0) / (t1 - t0)) if t1 > t0 else 1.0)
- else:
- break
- return v
-
- def matrix(self, t):
- """Position of all parts of this joint at time t (including the joints above it), as a 4x4 matrix."""
+ # Binaere Suche statt alle Schritte von vorn: Gekoppelte Bewegungen haben Tausende kurze Schritte je Gelenk,
+ # und abgetastet wird 30-mal je Sekunde. Abgeschlossene Schritte liefern ihren gespeicherten Endwert.
+ i = bisect.bisect_right(self.ends, t) # Schritte vor i sind zur Zeit t abgeschlossen
+ if i < len(self.segments):
+ t0, t1, f, ease, _end = self.segments[i]
+ if t >= t0: # laeuft gerade, t1 > t >= t0 und damit t1 > t0
+ return f(ease((t - t0) / (t1 - t0)))
+ return self.segments[i - 1][4] if i else self.start
+
+ def matrix(self, t, cache=None):
+ """Position of all parts of this joint at time t (including the joints above it), as a 4x4 matrix.
+ cache: dict for one time t, so that every joint (and every parent) is computed only once."""
+ if cache is not None and self in cache:
+ return cache[self]
m = self._own(self.value_at(t))
- return self.parent.matrix(t) @ m if self.parent else m
+ if self.parent:
+ m = self.parent.matrix(t, cache) @ m
+ if cache is not None:
+ cache[self] = m
+ return m
class _Hinge(Joint):
@@ -315,10 +320,12 @@ class _Free(Joint):
return value
def to(self, location):
- """Move to this location (cq.Location or (x, y, z), relative to the position in the model). Without a rotation
- axis the origin moves in a straight line: for rotations about an axis use hinge() or rotate()."""
+ """Move to this location (cq.Location or (x, y, z), relative to the position in the model). The parts move like
+ a rigid body on a screw path: a pure rotation runs on the arc about its axis (the shorter way, at most 180
+ degrees), a pure shift in a straight line, both together on a helix. For a large turn and a large shift at the
+ same time that can be a wide arc: then chain translate() and rotate(), or use parent=."""
m1 = _placement(location)
- return _Action(self, lambda m0: (lambda s: _blend(m0, m1, s), m1), lambda m0: f"{self.label}: to new location")
+ return _Action(self, lambda m0: (lambda s: _screw(m0, m1, s), m1), lambda m0: f"{self.label}: to new location")
def translate(self, vector):
"""Move by this vector (mm)."""
@@ -490,7 +497,8 @@ class Animation:
if j.anim is not self:
raise ValueError("This movement belongs to another animation")
func, end = act.make(j.value)
- j.segments.append((t0, t1, func, f))
+ j.segments.append((t0, t1, func, f, end))
+ j.ends.append(t1)
move = dict(key=f"joint{self.joints.index(j)}", label=j.label)
if j.unit:
move.update(unit=j.unit, v0=round(float(j.value), 4), v1=round(float(end), 4))
@@ -584,5 +592,6 @@ class Animation:
return [p for j in self.joints for p in j.parts]
def poses(self, t):
- """Lage jedes bewegten Bauteils zur Zeit t (4x4-Matrix)."""
- return {p: j.matrix(t) for j in self.joints for p in j.parts}
+ """Lage jedes bewegten Bauteils zur Zeit t (4x4-Matrix). Die Teile eines Gelenks teilen sich eine Matrix (nur lesen)."""
+ cache = {}
+ return {p: j.matrix(t, cache) for j in self.joints for p in j.parts}
diff --git a/python/soma/animrun.py b/python/soma/animrun.py
index 259a5a0..9b3f8ed 100644
--- a/python/soma/animrun.py
+++ b/python/soma/animrun.py
@@ -283,6 +283,121 @@ def _spans(a, duration):
return out
+# Grenzen der Bewegungspruefung (motion_warnings), bezogen auf die Diagonale der Teile eines Gelenks
+JUMP_SIZE = 0.1 # Sprung: in einem Bild weiter als 10 % der Diagonale ...
+JUMP_FACTOR = 4.0 # ... und mindestens viermal so weit wie im Bild davor und danach
+WOBBLE_SIZE = 0.02 # Eiern: Viewer und Video liegen zwischen zwei Abtastungen mehr als 2 % daneben
+WOBBLE_MIN_MM = 0.05
+MAX_WARNINGS = 30
+
+
+def _ranges(idx):
+ """Aufeinanderfolgende Indizes zu (erster, letzter)."""
+ out = []
+ for i in idx:
+ if out and i == out[-1][1] + 1:
+ out[-1][1] = i
+ else:
+ out.append([i, i])
+ return out
+
+
+def motion_warnings(a, times, poses, cams):
+ """Was beim Abspielen anders aussieht als beschrieben (soma anim build, info und check melden es):
+ - jump: ein Gelenk oder die Kamera springt. Viewer und Video blenden das ueber ein Bild, es ruckelt.
+ - wobble: Viewer und Video interpolieren zwischen den Abtastungen (30 je Sekunde) Ursprung geradlinig und Drehung auf
+ dem kuerzesten Weg. Schnelle Drehungen, vor allem um eine Achse fern vom Teil, eiern dann, ab 180 Grad je Bild
+ laufen sie rueckwaerts. Gemessen als Abstand der Ecken zwischen interpolierter und wahrer Lage in der Mitte.
+ - hidden: Teile, die am Ende noch versteckt sind (hide() ohne show(), auch ueber eine Gruppe)."""
+ from scipy.spatial.transform import Rotation
+ out = []
+ info = {p["name"]: p for p in anim._PARTS}
+ mids = (times[1:] + times[:-1]) / 2
+ mid_m = {j: [] for j in a.joints}
+ for t in mids:
+ cache = {}
+ for j in a.joints:
+ mid_m[j].append(j.matrix(float(t), cache))
+ for j in a.joints:
+ if len(times) < 3:
+ break
+ lo = np.min([info[p]["bbox"][0] for p in j.parts], axis=0)
+ hi = np.max([info[p]["bbox"][1] for p in j.parts], axis=0)
+ diag = max(float(np.linalg.norm(hi - lo)), 1e-6)
+ c = _corners((lo, hi))
+ ms = np.array([pz[j.parts[0]] for pz in poses])
+ pts = np.einsum("nij,kj->nki", ms, c)[:, :, :3]
+ step = np.linalg.norm(pts[1:] - pts[:-1], axis=2).max(axis=1) # weitester Weg einer Ecke je Bild
+ prev = np.r_[0.0, step[:-1]]
+ nxt = np.r_[step[1:], 0.0]
+ jumps = np.nonzero((step > JUMP_SIZE * diag) & (step > JUMP_FACTOR * np.maximum(prev, nxt)))[0]
+ for i in jumps:
+ out.append(dict(kind="jump", label=j.label, start=round(float(times[i]), 4), end=round(float(times[i + 1]), 4),
+ value=round(float(step[i]), 2)))
+ # Zwischenlage wie im Viewer: Ursprung linear, Drehung slerp (bei s = 0.5 die normierte Summe der Quaternionen)
+ q = Rotation.from_matrix(ms[:, :3, :3]).as_quat()
+ q0, q1 = q[:-1], q[1:] * np.where(np.sum(q[:-1] * q[1:], axis=1) < 0, -1.0, 1.0)[:, None]
+ qm = q0 + q1
+ qm /= np.linalg.norm(qm, axis=1)[:, None]
+ lin = np.repeat(np.eye(4)[None], len(qm), axis=0)
+ lin[:, :3, :3] = Rotation.from_quat(qm).as_matrix()
+ lin[:, :3, 3] = (ms[:-1, :3, 3] + ms[1:, :3, 3]) / 2
+ true = np.einsum("nij,kj->nki", np.array(mid_m[j]), c)[:, :, :3]
+ err = np.linalg.norm(np.einsum("nij,kj->nki", lin, c)[:, :, :3] - true, axis=2).max(axis=1)
+ deg = np.degrees((Rotation.from_matrix(ms[:-1, :3, :3]).inv() * Rotation.from_matrix(ms[1:, :3, :3])).magnitude())
+ bad = (err > max(WOBBLE_SIZE * diag, WOBBLE_MIN_MM)) & ~np.isin(np.arange(len(err)), jumps)
+ for i0, i1 in _ranges(np.nonzero(bad)[0]):
+ out.append(dict(kind="wobble", label=j.label, start=round(float(times[i0]), 4), end=round(float(times[i1 + 1]), 4),
+ value=round(float(err[i0:i1 + 1].max()), 2), deg=round(float(deg[i0:i1 + 1].max()), 1)))
+ # Kamera: Sprung der Blickrichtung (Grad) oder des Standorts (bezogen auf den Abstand zum Ziel)
+ if len(cams) >= 3:
+ pos = np.array([c[0] + c[1] * c[2] for c in cams])
+ dirs = np.array([c[1] for c in cams])
+ dist = np.array([c[2] for c in cams])
+ ang = np.degrees(np.arccos(np.clip(np.sum(dirs[1:] * dirs[:-1], axis=1), -1, 1)))
+ move = np.linalg.norm(pos[1:] - pos[:-1], axis=1) / np.minimum(dist[1:], dist[:-1])
+ cut = np.zeros(len(ang), dtype=bool)
+ for v, size in ((ang, 5.0), (move, JUMP_SIZE)):
+ cut |= (v > size) & (v > JUMP_FACTOR * np.maximum(np.r_[0.0, v[:-1]], np.r_[v[1:], 0.0]))
+ for i in np.nonzero(cut)[0]:
+ out.append(dict(kind="jump", label="camera", start=round(float(times[i]), 4), end=round(float(times[i + 1]), 4)))
+ hidden = {}
+ for e in sorted(a.events, key=lambda e: e["t"]):
+ for p in e["parts"]:
+ if e["kind"] in ("hide", "show"):
+ hidden[p] = e["kind"] == "hide"
+ names = [p for p, h in hidden.items() if h]
+ if names:
+ out.append(dict(kind="hidden", label=", ".join(names[:6]) + (f" and {len(names) - 6} more" if len(names) > 6 else ""),
+ start=round(float(times[-1]), 4), end=round(float(times[-1]), 4)))
+ out.sort(key=lambda w: (w["start"], w["label"]))
+ return out[:MAX_WARNINGS] + ([dict(kind="more", label="", start=0, end=0, value=len(out) - MAX_WARNINGS)]
+ if len(out) > MAX_WARNINGS else [])
+
+
+def warning_text(w):
+ span = f"{_t(w['start'])}-{_t(w['end'])} s" if w["end"] > w["start"] else f"{_t(w['start'])} s"
+ if w["kind"] == "jump":
+ what = (f"{w['label']}: jumps" + (f" {w['value']:g} mm" if w.get("value") is not None else "")
+ + " within one frame, the viewer and the video blend it over a single frame. Make it a motion in play() "
+ "(run_time of a few tenths of a second) or keep it as a deliberate cut")
+ elif w["kind"] == "wobble":
+ what = (f"{w['label']}: turns up to {w['deg']:g} deg per frame, between frames the parts are off by up to "
+ f"{w['value']:g} mm (wobble). Slow the motion down or split it: about 15 deg per frame is the limit"
+ + (", above 180 deg per frame it turns backwards" if w["deg"] > 180 else ""))
+ elif w["kind"] == "hidden":
+ what = f"still hidden at the end: {w['label']}. Intended? Otherwise show() them again (hide() of a group hides all its parts)"
+ else:
+ return f" ... {w['value']} more"
+ return f" {span:<16} {what}"
+
+
+def warnings_text(ws):
+ if not ws:
+ return "Motion: no jumps, wobble or parts hidden at the end"
+ return "\n".join(["Motion warnings:"] + [warning_text(w) for w in ws])
+
+
def finalize(a):
"""Abgetastete Daten einer Animation (fuer die Datei, die Textausgabe und die Pruefung)."""
duration = a.duration
@@ -309,7 +424,7 @@ def finalize(a):
text=lb["text"], part=lb["part"], at=[round(v, 4) for v in at]))
return dict(times=times, poses=poses, cams=cams, auto=auto, duration=duration, captions=captions, labels=labels,
titles=[dict(t, start=round(t["start"], 4), end=round(t["end"], 4)) for t in a.titles],
- spans=_spans(a, duration))
+ spans=_spans(a, duration), warnings=motion_warnings(a, times, poses, cams))
def write_glb(root, a, data):
@@ -348,7 +463,7 @@ def write_glb(root, a, data):
meta = dict(version=1, id=a.id, name=a.name, file=_rel(a.file, root), line=a.line, duration=round(data["duration"], 4),
fps=anim.SAMPLE_FPS, fov=anim.FOV, cameraAuto=data["auto"], parts=a.moving_parts(),
captions=data["captions"], titles=data["titles"], labels=data["labels"], states=data["spans"],
- steps=a.steps, built=time.time())
+ steps=a.steps, warnings=data["warnings"], built=time.time())
out = Path(root) / OUT_DIR
out.mkdir(parents=True, exist_ok=True)
path = out / f"{a.id}.glb"
@@ -386,7 +501,8 @@ def build_all(root, only=None):
data = finalize(a)
path = write_glb(root, a, data)
built.append(dict(id=a.id, name=a.name, file=rel, line=a.line, duration=round(data["duration"], 4),
- built=time.time(), glb=path.relative_to(root).as_posix(), parts=len(a.moving_parts())))
+ built=time.time(), glb=path.relative_to(root).as_posix(), parts=len(a.moving_parts()),
+ warnings=data["warnings"]))
except build.BuildError as e:
errors.append(dict(file=e.file or rel, line=e.line, message=e.message, traceback=e.tb))
except Exception as e: # Fehler beim Abtasten, etwa unbrauchbare Werte
@@ -526,6 +642,8 @@ def info_text(root, entry):
lines += ["", "Labels:"] + [
f" {_t(lb['start'])}-{_t(lb['end'])} s \"{lb['text']}\"" + (f" on {lb['part']}" if lb["part"] else "")
+ " at ({:.1f}, {:.1f}, {:.1f})".format(*lb["at"]) for lb in m["labels"]]
+ if "warnings" in m: # aelter gebaute Animationen haben keine
+ lines += ["", warnings_text(m["warnings"])]
chk = read_check(root, entry)
if chk:
lines += ["", check_text(chk)]
diff --git a/python/soma/cli.py b/python/soma/cli.py
index f766827..6cdfd15 100644
--- a/python/soma/cli.py
+++ b/python/soma/cli.py
@@ -262,6 +262,8 @@ def cmd_anim(args):
else:
for b in res["built"]:
print(f"Animation ok: \"{b['name']}\" ({b['duration']:.2f} s, {b['parts']} moving part(s)) from {b['file']}")
+ for w in b["warnings"]:
+ print(animrun.warning_text(w))
for e in res["errors"]:
where = f"{e['file']}{':' + str(e['line']) if e.get('line') else ''}"
print(f"Animation ERROR ({where}): {e['message']}", file=sys.stderr)
@@ -295,7 +297,12 @@ def cmd_anim(args):
print(animrun.info_text(root, entry))
return 0
res = animrun.check(root, args.name, step=args.step, gap=args.gap)
- print(json.dumps(res, ensure_ascii=False) if args.json else animrun.check_text(res))
+ if args.json:
+ print(json.dumps(dict(res, warnings=animrun.read_meta(root, entry).get("warnings")), ensure_ascii=False))
+ else:
+ print(animrun.check_text(res))
+ if "warnings" in (meta := animrun.read_meta(root, entry)):
+ print(animrun.warnings_text(meta["warnings"]))
return 1 if any(r["kind"] == animrun.COLLISION and not p["atRest"] for p in res["pairs"] for r in p["ranges"]) else 0
except animrun.AnimError as e:
return _fail(str(e))
diff --git a/python/soma/cqruntime.py b/python/soma/cqruntime.py
index 6588b3e..73d9eb6 100644
--- a/python/soma/cqruntime.py
+++ b/python/soma/cqruntime.py
@@ -72,7 +72,7 @@ def _soma_shape(obj):
raise TypeError(f"add_part expects a cq.Workplane, a cq.Shape, a cq.Assembly or a standard part, not {type(obj).__name__}")
-def add_part(name, obj, role=None, color=None, group=None):
+def add_part(name, obj, role=None, color=None, group=None, alpha=None):
"""Registers a part (SOMA). Here: collects it for the assembly `result` and for show_object() of the viewer."""
standard = hasattr(obj, "__soma_shape__")
role = role or (getattr(obj, "role", "part") if standard else "part")
@@ -83,7 +83,7 @@ def add_part(name, obj, role=None, color=None, group=None):
groups = ("Reference",) + groups
rgb = tuple(color[:3]) if color else _SOMA_COLORS.get(role, _SOMA_COLORS["part"])
_SOMA_PARTS.append(dict(name=str(name), shape=_soma_shape(obj), role=role, groups=groups,
- color=(*rgb, 0.45 if role == "reference" else 1.0)))
+ color=(*rgb, float(alpha) if alpha is not None else 0.45 if role == "reference" else 1.0)))
def _soma_assembly(name="Model"):
diff --git a/python/soma/registry.py b/python/soma/registry.py
index a3bfde4..0350d20 100644
--- a/python/soma/registry.py
+++ b/python/soma/registry.py
@@ -66,7 +66,7 @@ def _unique(name, taken):
return f"{name} ({i})"
-def add_part(name, obj, role=None, color=None, group=None):
+def add_part(name, obj, role=None, color=None, group=None, alpha=None):
"""Registers a part. Required for every part, otherwise the viewer and the export do not know it.
name unique name (any characters, in the STEP file it is written as ASCII)
@@ -78,17 +78,26 @@ def add_part(name, obj, role=None, color=None, group=None):
export --all). Standard parts from soma.fasteners are "hardware" if not given
color optional (r, g, b) with values 0..1 (for an assembly for all parts). Standard parts have their own
group optional, group in the part tree and in the STEP file, nested with "/", e.g. "Housing/Screws"
+ alpha optional opacity above 0 up to 1 (opaque). References are 0.45 if not given: alpha=1 makes an
+ opaque reference, e.g. a floor or a logo for an animation that should not be exported
"""
if IGNORE_ADD:
return
+ if alpha is not None:
+ try:
+ alpha = float(alpha)
+ except (TypeError, ValueError):
+ raise ValueError(f"alpha must be a number above 0 up to 1, not {alpha!r}") from None
+ if not 0 < alpha <= 1: # faengt auch nan ab. Unsichtbar: in Animationen hide()
+ raise ValueError(f"alpha must be a number above 0 up to 1, not {alpha!r}")
frame = inspect.currentframe().f_back
pos = inspect.getframeinfo(frame, context=0).positions # Startzeile und Endzeile des Aufrufs
- _add(name, obj, role, color, group, dict(file=frame.f_code.co_filename, line=pos.lineno, end_line=pos.end_lineno))
+ _add(name, obj, role, color, group, dict(file=frame.f_code.co_filename, line=pos.lineno, end_line=pos.end_lineno), alpha=alpha)
def _add(name, obj, role, color, group, where, alpha=None):
"""add_part ohne Blick auf den Aufrufer: Der Kompatibilitaetsmodus (cqcompat.py) nennt die Stelle von show_object().
- `alpha` < 1: halbtransparent wie in CQ-editor (options={"alpha": ...})."""
+ `alpha` < 1: halbtransparent wie in CQ-editor (options={"alpha": ...}). Unbrauchbare Werte gelten als nicht angegeben."""
standard_part = hasattr(obj, "__soma_shape__")
if role is None:
role = getattr(obj, "role", "part") if standard_part else "part"
@@ -146,9 +155,11 @@ def _register(name, shape, role, color, groups, where, unique_step=False, axis=N
i += 1
step_name = f"{step_name}_{i}"
rgb = tuple(color[:3]) if color else DEFAULT_COLORS[role]
+ if alpha is None or not 0 < alpha <= 1:
+ alpha = REFERENCE_ALPHA if role == "reference" else 1.0
REGISTRY.append(dict(
name=name, step_name=step_name, role=role, shape=shape, group=tuple(groups),
- color=(*rgb, REFERENCE_ALPHA if role == "reference" else alpha if alpha is not None and 0 < alpha < 1 else 1.0), axis=axis, **where,
+ color=(*rgb, alpha), axis=axis, **where,
# Das Normteil selbst (Screw, Nut ...), nur im Speicher: soma.fem liest daraus Groesse, Kopf und Lage (bolt())
fastener=fastener,
))