diff --git a/surfaces/blender/brokkr_reference/__init__.py b/surfaces/blender/brokkr_reference/__init__.py index 4f93a0b..ad652d6 100644 --- a/surfaces/blender/brokkr_reference/__init__.py +++ b/surfaces/blender/brokkr_reference/__init__.py @@ -1,5 +1,6 @@ """Fit a scene to a reference image: the camera a reference view was drawn through, solved from marked points, -and traced lines scored against the edges the camera sees on the build. +traced lines scored against the edges the camera sees on the build, and a kitbash shell's sheet fitted to traces of +its hard runs. A host add-on for Brokkr beside brokkr_mesh_polish (it imports that package's operator base, and nothing from Brokkr): brokkr_actions.json beside this file lists the operators agents may run (docs/reference.md). The @@ -9,12 +10,17 @@ JSON report to WindowManager.brokkr_mesh_polish_result, as the polish operators The camera record core.solve returns is the truth; a Blender camera stood at it is derived by core.blender, and core.camera_of reads one back (flow_score takes the camera that way, by its object's name). The images, traces and masks a view is marked on stay with whoever marked them: this package takes points and lines and gives -cameras and scores. The edges flow_score reads are computed on each call and kept nowhere. +cameras, scores and a fitted sheet. The edges flow_score reads are computed on each call and kept nowhere. + +fit_shell reads a shell's request through brokkr_kitbash (the sheet's one parser) and returns a sheet; it writes +nothing. brokkr_kitbash.shell is the cage's one writer: the caller applies the fitted sheet with it. """ bl_info = {"name": "Brokkr Reference", "author": "GameCult", "version": (0, 1, 0), "blender": (4, 2, 0), "category": "Camera", "description": "Solve a reference view's camera from marked points; agent-callable through Brokkr."} +import json import math +import time import bpy import numpy as np @@ -204,7 +210,60 @@ class BROKKR_REFERENCE_OT_flow_score(PolishOperator): "objects": [o.name for o in meshes], "height": height} -classes = (BROKKR_REFERENCE_OT_solve_camera, BROKKR_REFERENCE_OT_flow_score) +class BROKKR_REFERENCE_OT_fit_shell(PolishOperator): + """Fit a kitbash shell's sheet to traces of its hard runs through solved cameras, and return the fitted sheet + only where the built runs explain every trace; nothing is written""" + bl_idname = "brokkr_reference.fit_shell" + bl_label = "Fit Shell To Traces" + object_name: bpy.props.StringProperty(name="Object", maxlen=63, description="A loft shell made by brokkr_kitbash.shell, unscaled; its place in the world is the sheet's frame") + traces: bpy.props.StringProperty(name="Traces", maxlen=12000, description="A JSON array of {camera, box, run: {ring|column, from, to}, side, line: [[u, v], ...]}") + share: bpy.props.FloatProperty(name="Share", default=0.1, min=0.0009, max=10.0, description="A move of this share of the sheet's diagonal from the sheet as it stands costs what one pixel of miss does") + tol: bpy.props.FloatProperty(name="Tolerance", default=3.0, min=0.09, max=100.0, description="Pixels: every point of every trace must lie this near its built run, or the fit is refused") + + # the action table states share from 0.001 and tol from 0.1: a float property rounds those up, so its bounds stand just under + def work(self, context): + try: + import brokkr_kitbash + except ImportError as error: + raise Refused(f"fit_shell needs the brokkr_kitbash add-on beside this one ({error}).") from None + obj = bpy.data.objects.get(self.object_name) + if obj is None or obj.type != "MESH" or brokkr_kitbash.SHELL not in obj: + raise Refused(f"{self.object_name!r} is not a shell brokkr_kitbash.shell made (a mesh carrying {brokkr_kitbash.SHELL}).") + if max(abs(v - 1.0) for v in obj.matrix_world.to_scale()) > 1e-6: + raise Refused(f"{obj.name!r} is scaled {tuple(round(v, 6) for v in obj.matrix_world.to_scale())}: a sheet is in metres of the shell's own frame. Apply or clear the scale.") + try: + document = json.loads(obj[brokkr_kitbash.SHELL])["sheet"] + cage = brokkr_kitbash.core.sheet(document) + except (ValueError, KeyError, TypeError, brokkr_kitbash.core.KitError) as error: + raise Refused(f"{obj.name!r} carries a request its own parser does not take ({error}).") from None + try: + traces = json.loads(self.traces) + except ValueError as error: + raise Refused(f"traces is not JSON ({error}).") from None + if not isinstance(traces, list) or not all(isinstance(trace, dict) for trace in traces): + raise Refused("traces must be a JSON array of objects {camera, box, run, side, line}.") + cams = [] + for k, trace in enumerate(traces): + if set(trace) - {"camera", "box", "run", "side", "line"}: + raise Refused(f"traces[{k}] has {sorted(set(trace) - {'camera', 'box', 'run', 'side', 'line'})}: a trace is {{camera, box, run, side, line}}.") + box = trace.get("box") + if box is not None and not (isinstance(box, list) and len(box) == 4 and all(isinstance(v, (int, float)) and not isinstance(v, bool) for v in box)): + raise Refused(f"traces[{k}].box must be [u0, v0, u1, v1], or absent for the render's own frame.") + if not isinstance(trace.get("camera"), str): + raise Refused(f"traces[{k}].camera must name a camera object.") + try: + cams.append(record(context, trace["camera"], "" if box is None else ",".join(repr(float(v)) for v in box))) + except (Refused, core.ReferenceFitError) as refusal: + raise Refused(f"traces[{k}]: {refusal}") from None + started = time.perf_counter() + try: + out = core.fit_sheet(document, cage, [list(row) for row in obj.matrix_world], traces, cams, share=self.share, tol=self.tol) + except core.ReferenceFitError as refusal: + raise Refused(f"{refusal}. Nothing changed.") from None + return {"object": obj.name, **out, "seconds": round(time.perf_counter() - started, 3)} + + +classes = (BROKKR_REFERENCE_OT_solve_camera, BROKKR_REFERENCE_OT_flow_score, BROKKR_REFERENCE_OT_fit_shell) def register(): diff --git a/surfaces/blender/brokkr_reference/brokkr_actions.json b/surfaces/blender/brokkr_reference/brokkr_actions.json index 9bfe98f..6822511 100644 --- a/surfaces/blender/brokkr_reference/brokkr_actions.json +++ b/surfaces/blender/brokkr_reference/brokkr_actions.json @@ -133,6 +133,47 @@ "doc": "degrees between two faces' normals past which their edge is a crease" } ] + }, + { + "name": "brokkr_reference.fit_shell", + "doc": "Fit a kitbash loft shell's sheet to traces of its hard crease and rim runs, each seen through a scene camera: the traced runs' cage points move until the runs as built draw on the traces. Returns the fitted sheet for brokkr_kitbash.shell only where every point of every trace lies within tol px of its built run; otherwise it is refused naming the trace and the span. Writes nothing. Per moved point: metres per pixel along its sight line and the prior's share of that (docs/reference.md).", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63, + "doc": "a loft shell made by brokkr_kitbash.shell, unscaled; its place in the world is the sheet's frame" + }, + { + "name": "traces", + "type": "string", + "required": true, + "minLength": 2, + "maxLength": 12000, + "doc": "a JSON array of {camera, box, run, side, line}: camera a camera object's name; box [u0,v0,u1,v1], its frame on the image, absent for the render's own; run {ring, from, to} or {column, from, to} in authored indices, as the sheet's creases name runs; side 1, or -1 for the mirrored half; line [[u,v],...] drawn from `from` to `to`" + }, + { + "name": "share", + "type": "number", + "minimum": 0.001, + "maximum": 10, + "default": 0.1, + "doc": "the prior: a move of this share of the sheet's diagonal from the sheet as it stands costs what one pixel of miss does" + }, + { + "name": "tol", + "type": "number", + "minimum": 0.1, + "maximum": 100, + "default": 3, + "doc": "pixels: every point of every trace must lie this near its built run, or the fit is refused" + } + ] } ] } diff --git a/surfaces/blender/brokkr_reference/core.py b/surfaces/blender/brokkr_reference/core.py index f5b7fe4..5cea4da 100644 --- a/surfaces/blender/brokkr_reference/core.py +++ b/surfaces/blender/brokkr_reference/core.py @@ -30,9 +30,18 @@ A traced line is pixels; a part's points are given in its frame, a 4 x 4 frame-t seen(cam, frame, points) pixels of points of a frame crease_run(points) where Blender builds the hard crease of a cage column at one level along(line, segments, height) the flow score: how much of a traced line has a seen edge along it + +A shell's cage (brokkr_kitbash's sheet) is fitted to traces of its hard runs: the cage points of the traced runs +are moved until the runs, as Blender builds them and the cameras draw them, lie on the traces. The fit is returned +only where the built runs explain every trace; docs/reference.md, "fit_shell", says what the answer is worth. + + fit_runs(views, cage, runs, movable, mirror_of, share, diag, tol) the moved cage and the report + fit_sheet(document, cage, frame, traces, cams, share, tol) the same for a sheet's named runs: the fitted sheet """ from __future__ import annotations +import copy +import json import math import numpy as np @@ -438,6 +447,270 @@ def along(line, segments, height, near=0.01, turn=20.0, cap=0.05): return {"on": round(float(on.mean()), 3), "off": round(float(100 * np.minimum(dist / height, cap).mean()), 2), "run": round(best / len(on), 3)} +# --- a shell's traced runs fitted through cameras -------------------------------------------------------------------- + +LEVELS = 2 # crease_run applied this many times gives the samples of a built run the fit draws: 4k - 3 for k cage points +HARD = 1.0 - 1e-9 # a crease weight from here up is hard: the edge stays sharp at every level, which is what crease_run builds +ROUNDS = 60 +RESULT_LIMIT = 16000 # characters of a host result Brokkr copies into a receipt before it truncates (brokkr_bridge's HOST_RESULT_LIMIT; this package imports nothing from Brokkr) + + +def _drawn(cam, frame, X): + """Pixels (n, 2) of points of a frame and their derivative (n, 2, 3) by the points' own coordinates; None where + a point stands behind the camera.""" + F, R, f = np.asarray(frame, float), np.asarray(cam["R"], float), cam["f"] + A = R @ F[:3, :3] + q = (X @ F[:3, :3].T + F[:3, 3] - np.asarray(cam["C"], float)) @ R.T + z = -q[:, 2] + if z.min() <= 1e-6: + return None + u = np.stack([cam["c"][0] + f * q[:, 0] / z, cam["c"][1] - f * q[:, 1] / z], 1) + du = (f / z)[:, None] * A[0] + (f * q[:, 0] / z ** 2)[:, None] * A[2] + dv = -((f / z)[:, None] * A[1] + (f * q[:, 1] / z ** 2)[:, None] * A[2]) + return u, np.stack([du, dv], 1) + + +def _normal(points, line): + """Per point: its distance to a polyline and the unit direction that distance grows along (the nearest + segment's normal; from the segment's end where the point is past it).""" + a, d = line[:-1], line[1:] - line[:-1] + length = np.maximum((d * d).sum(1), 1e-18) + t = np.clip(((points[:, None] - a) * d).sum(2) / length, 0, 1) + off = points[:, None] - (a + t[:, :, None] * d) + dist = np.linalg.norm(off, axis=2) + k, i = dist.argmin(1), np.arange(len(points)) + dist, off = dist[i, k], off[i, k] + on = dist < 1e-9 + n = off / np.maximum(dist, 1e-12)[:, None] + n[on] = (np.stack([-d[k, 1], d[k, 0]], 1) / np.sqrt(length[k])[:, None])[on] + return dist, n + + +def _hard_runs(cage, runs): + """Refuse a run crease_run does not build. Blender builds crease_run where every edge of the run is hard, every + point between its ends has those two sharp edges and no other, and each end holds: a hard corner point, three + or more hard or boundary edges, or, on a cage whose Subdivision preserves corners (a loft's; cage.boundary), a + boundary point of two edges.""" + weight = {(int(min(a, b)), int(max(a, b))): float(w) for (a, b), w in zip(np.asarray(cage.creases).reshape(-1, 2), cage.weights)} + pinned = {int(v): float(w) for v, w in zip(cage.corners, cage.corner_weights)} + loops, sides = np.asarray(cage.faces), [] + for first, size in zip(np.concatenate([[0], np.cumsum(cage.counts)[:-1]]), cage.counts): + face = loops[first:first + size] + sides += [np.sort(np.stack([face, np.roll(face, -1)], 1), axis=1)] + sides = np.concatenate(sides) + pairs, count = np.unique(sides, axis=0, return_counts=True) + at = {} # vertex -> [(weight, on the boundary)] of its edges + for (a, b), faces in zip(pairs, count): + w = weight.get((int(a), int(b)), 0.0) + for v in (int(a), int(b)): + at.setdefault(v, []).append((w, faces == 1)) + for run in runs: + name, chain = run["name"], [int(v) for v in run["chain"]] + if len(chain) < 2 or len(set(chain)) != len(chain): + raise ReferenceFitError(f"{name}: its run must be two or more cage points, none twice (a closed loop has no end to hold)") + for m, (a, b) in enumerate(zip(chain, chain[1:])): + w = weight.get((min(a, b), max(a, b))) + if w is None or w < HARD: + raise ReferenceFitError(f"{name}: the edge after point {m} of its run has crease weight {w or 0:g}. Only a hard run (every edge 1) is built where " + "the fit draws it; a semi-sharp or uncreased edge rounds off by an amount the fit does not model. Crease it 1, or leave the run untraced") + for m, v in enumerate(chain): + sharp = [w for w, rim in at[v] if w > 0 or rim] + if 0 < m < len(chain) - 1: + if len(sharp) != 2 or pinned.get(v, 0.0) > 0: + raise ReferenceFitError(f"{name}: point {m} of its run is held or pulled by more than the run (a corner point, or another crease or the rim " + "meeting it there). Trace the run as two, one each side of that point") + elif not (pinned.get(v, 0.0) >= HARD or sum(1 for w, rim in at[v] if w >= HARD or rim) >= 3 or (len(at[v]) == 2 and cage.boundary == "PRESERVE_CORNERS")): + raise ReferenceFitError(f"{name}: the {'first' if m == 0 else 'last'} end of its run does not hold: it is a dart (the crease dies out into the surface " + "there) or runs on, on a mirrored sheet across the middle. An end holds at a corner point of weight 1, where three or " + "more hard edges meet, or on the rim") + + +def fit_runs(views, cage, runs, movable, mirror_of, share, diag, tol=3.0): + """Move a cage's points until its hard runs, as built and as cameras draw them, lie on their traces. + + views [(camera record, frame)]: the frame is the 4 x 4 that carries the cage to the world + cage the parsed sheet (brokkr_kitbash.core.Sheet's V, faces, counts, creases, weights, corners, + corner_weights, boundary) + runs [{"name", "chain": cage vertices in order, "view": index into views, "line": [[u, v], ...]}]; the + line is drawn from the chain's first point to its last + movable (vertices, 3) of bool: the coordinates that may move. Only authored vertices move + mirror_of per vertex, the authored vertex it mirrors across x = 0, or itself: a mirrored half is the same + parameters seen again, x negated + share the prior: a move of share x diag from the cage as given costs what one pixel of miss does + tol pixels: every point of every trace must lie this near its built run as drawn + + The residual per run is the pixel distance from each built point (crease_run LEVELS times, drawn through the + run's view) to the trace, and the run's two ends against the trace's; no point of the trace is matched to a + point of the run beyond that. Gauss-Newton with Levenberg-Marquardt damping on the analytic Jacobian. Returns + (V, report): the cage's vertices as fitted and {"traces": [{"miss_px": rms of the built points off the trace, + "unexplained_px": the trace's furthest point from the built run}], "points": [{"vertex", "moved_m", + "m_per_px", "prior_share"}], "rounds"}. m_per_px is how far the point slides along its sight line (the worst + of the views that trace it) per pixel of error in the traces, sqrt(r' S r) with S the point's block of the + inverse of J'J, prior included (Triggs et al. 2000, sections 9 and 10); prior_share is that over share x + diag: near 1 the traces say nothing about the point's depth and it stands where it was blocked. + + Raises ReferenceFitError for a run it cannot model (_hard_runs), and when a trace is not explained: the error + names the trace and the span of it that lies further than tol from the built run, and carries the rows as + .traces. Nothing is returned as a fit then.""" + V0, movable, mirror_of = np.array(cage.V, float), np.asarray(movable, bool), np.asarray(mirror_of, int) + mirrored = mirror_of != np.arange(len(V0)) + if (movable & mirrored[:, None]).any() or not movable.any(): + raise ReferenceFitError("movable must mark authored vertices, and at least one coordinate") + _hard_runs(cage, runs) + index = np.flatnonzero(movable.ravel()) + column = np.full(V0.size, -1) + column[index] = np.arange(len(index)) + flip, prior = np.where(mirrored, -1.0, 1.0), 1.0 / (share * diag) + prepared = [] + for run in runs: + chain, line = np.asarray(run["chain"], int), np.asarray(run["line"], float) + if not 0 <= run["view"] < len(views): + raise ReferenceFitError(f"{run['name']}: view {run['view']} is none of the {len(views)} views") + if line.ndim != 2 or line.shape[1] != 2 or len(line) < 2 or not np.isfinite(line).all() or np.linalg.norm(np.diff(line, axis=0), axis=1).sum() < 1e-9: + raise ReferenceFitError(f"{run['name']}: its line must be two or more [u, v] points, not all in one place") + W = np.eye(len(chain)) + for _ in range(LEVELS): + W = crease_run(W) + source = mirror_of[chain] + prepared.append((run["name"], views[run["view"]], line, W, source, np.stack([flip[chain], np.ones(len(chain)), np.ones(len(chain))], 1), + column.reshape(-1, 3)[source])) # the parameter column of each chain point's coordinate, -1 where held + p0 = V0.ravel()[index] + + def terms(p): + """(residual, Jacobian, each run's built points as drawn) at parameters p.""" + P = V0.copy() + P.ravel()[index] = p + res, rows, drawn = [], [], [] + for name, (cam, frame), line, W, source, sign, cols in prepared: + seen_ = _drawn(cam, frame, W @ (P[source] * sign)) + if seen_ is None: + raise ReferenceFitError(f"{name}: its run stands behind the camera") + u, Ju = seen_ + dist, n = _normal(u, line) + D = np.concatenate([np.einsum("si,sij->sj", n, Ju), Ju[0], Ju[-1]]) # per residual row, its derivative by its own built point + who = np.concatenate([np.arange(len(u)), [0, 0, len(u) - 1, len(u) - 1]]) + block = np.zeros((len(D), len(p))) + for m in range(len(source)): + for c in range(3): + if cols[m, c] >= 0: + block[:, cols[m, c]] += W[who, m] * D[:, c] * sign[m, c] + res += [dist, u[0] - line[0], u[-1] - line[-1]] + rows.append(block) + drawn.append((u, dist)) + return np.concatenate(res + [prior * (p - p0)]), np.vstack(rows + [prior * np.eye(len(p))]), drawn + + p, lam, rounds = p0.copy(), 1e-3, 0 + r, J, drawn = terms(p) + for rounds in range(1, ROUNDS + 1): + A, g = J.T @ J, J.T @ r + for _ in range(12): + step = np.linalg.solve(A + lam * np.diag(np.diag(A)), -g) + try: + r2, J2, drawn2 = terms(p + step) + except ReferenceFitError: + r2 = None + if r2 is not None and r2 @ r2 < r @ r: + p, r, J, drawn, lam = p + step, r2, J2, drawn2, lam / 3 + break + lam *= 4 + else: + break + if np.abs(step).max() < 1e-7: + break + V = V0.copy() + V.ravel()[index] = p + V = V[mirror_of] * np.stack([flip, np.ones(len(V)), np.ones(len(V))], 1) + + traces, refused = [], None + for (name, _, line, *_), (u, dist) in zip(prepared, drawn): + length = np.linalg.norm(np.diff(line, axis=0), axis=1).sum() + dense = resampled(line, int(min(max(length, len(line)), 4000)) + 1) # a point each pixel along it + off = _off(dense, u) + traces.append({"miss_px": round(float(np.sqrt(np.mean(dist ** 2))), 3), "unexplained_px": round(float(off.max()), 3)}) + if off.max() > tol and refused is None: + out = np.flatnonzero(off > tol) * length / (len(dense) - 1) + refused = (f"{name} is not explained: {len(out) * length / (len(dense) - 1):.0f} px of the trace, between {out[0]:.0f} and {out[-1]:.0f} px along it, lie " + f"more than {tol:g} px from the run as built, up to {off.max():.1f} px. Nothing is returned as a fit. The trace draws something this run " + "does not build (an overdrawn or doubled stroke, another edge, a bend the cage has too few points for): redraw it, or give the run more points") + if refused is not None: + error = ReferenceFitError(refused) + error.traces = traces + raise error + S = np.linalg.inv(J.T @ J) + points = [] + for a in np.flatnonzero(movable.any(1)): + cols = column.reshape(-1, 3)[a] + block = np.zeros((3, 3)) + held = cols >= 0 + block[np.ix_(held, held)] = S[np.ix_(cols[held], cols[held])] + worst = 0.0 + for _, (cam, frame), _, _, source, sign, _ in prepared: + for m in np.flatnonzero(source == a): + sight = V[a] * sign[m] - (np.linalg.inv(np.asarray(frame, float)) @ np.r_[np.asarray(cam["C"], float), 1.0])[:3] + sight = sight / np.linalg.norm(sight) * sign[m] # the sight line of the mirrored point, said in the authored point's coordinates + worst = max(worst, float(np.sqrt(sight @ block @ sight))) + points.append({"vertex": int(a), "moved_m": float(np.linalg.norm(V[a] - V0[a])), "m_per_px": worst, "prior_share": worst * prior}) + return V, {"traces": traces, "points": points, "rounds": rounds} + + +def fit_sheet(document, cage, frame, traces, cams, share=0.1, tol=3.0): + """fit_runs for a shell's sheet. `document` is the sheet as brokkr_kitbash.shell takes it and `cage` what + brokkr_kitbash.core.sheet parses it to; `frame` carries the shell to the world. `traces` is a list of + {"run": {"ring": i, "from": a, "to": b} or {"column": j, "from": a, "to": b}, "side": 1 or -1, "line": + [[u, v], ...]} (authored indices, as the sheet's creases name runs; side -1 is the mirrored half of a mirrored + sheet; the line is drawn from `from` to `to`), and `cams` the camera record of each. The points of the traced + runs move, a mirrored sheet's point 0 only in its plane. Returns {"sheet": the document with those points + moved, "traces": [{"miss_px", "unexplained_px"}], "points": [{"ring", "point", "moved_m", "m_per_px", + "prior_share"}]}; refuses, before fitting, a result that would pass RESULT_LIMIT characters.""" + mirror, closed = document.get("mirror", False) is True, bool(document.get("closed", False)) + R, N = cage.rings, cage.points + if R is None: + raise ReferenceFitError("the sheet is a free cage: fit_sheet names runs by ring and column, which a loft has and a free cage does not. " + "core.fit_runs takes any cage's vertex chains") + C = (N + 1) // 2 if mirror else N + if not isinstance(traces, list) or not traces: + raise ReferenceFitError("traces must be an array of one or more {camera, box, run, side, line}") + mirror_of = np.arange(R * N) + if mirror: + for i in range(R): + mirror_of[i * N + C - 1 - np.arange(1, C)] = i * N + C - 1 + np.arange(1, C) + movable, runs = np.zeros((R * N, 3), bool), [] + for k, trace in enumerate(traces): + where = f"traces[{k}]" + if not isinstance(trace, dict) or not isinstance(trace.get("run"), dict): + raise ReferenceFitError(f"{where} must be an object with a run") + if cams[k] is None: + raise ReferenceFitError(f"{where}.camera {trace.get('camera')!r} is no camera of this fit") + run, side = trace["run"], trace.get("side", 1) + if side not in (1, -1) or (side == -1 and not mirror): + raise ReferenceFitError(f"{where}.side must be 1, or -1 for the mirrored half of a mirrored sheet, not {side!r}") + ring = "ring" in run + if ring == ("column" in run) or set(run) != {"ring" if ring else "column", "from", "to"}: + raise ReferenceFitError(f"{where}.run must be {{ring, from, to}} or {{column, from, to}}") + across, most = (R, C if closed else C - 1) if ring else (C, R - 1) + numbers_ = [run["ring" if ring else "column"], run["from"], run["to"]] + if any(isinstance(v, bool) or not isinstance(v, int) for v in numbers_) or not (0 <= numbers_[0] < across and 0 <= numbers_[1] < numbers_[2] <= most): + raise ReferenceFitError(f"{where}.run must name a {'ring under ' + str(R) if ring else 'column under ' + str(C)} and from under to, to at most {most}") + fixed, first, last = numbers_ + authored = [(fixed, j % C) if ring else (j, fixed) for j in range(first, last + 1)] + chain = [i * N + ((C - 1 + side * j) if mirror else j) for i, j in authored] + for i, j in authored: + movable[i * N + (C - 1 + j if mirror else j)] = (not (mirror and j == 0), True, True) + runs.append({"name": where, "chain": chain, "view": k, "line": trace.get("line")}) + moved = [(int(v) // N, int(v) % N - (C - 1 if mirror else 0)) for v in np.flatnonzero(movable.any(1))] + size = len(json.dumps(document, separators=(",", ":"))) + 36 * len(moved) + 45 * len(traces) + 95 * len(moved) + 40 + if size > RESULT_LIMIT: + raise ReferenceFitError(f"the fitted sheet and its report would be about {size} characters, over the {RESULT_LIMIT} a receipt carries: nothing was fitted. " + "Fit fewer runs at a time, or a sparser sheet") + V0 = np.array(cage.V, float) + V, report = fit_runs([(cam, frame) for cam in cams], cage, runs, movable, mirror_of, share, float(np.linalg.norm(np.ptp(V0, axis=0))), tol) + out = copy.deepcopy(document) + for i, j in moved: + out["rings"][i][j] = [round(float(x), 6) + 0.0 for x in V[i * N + (C - 1 + j if mirror else j)]] + return {"sheet": out, "traces": report["traces"], "points": [{"ring": i, "point": j, "moved_m": round(row["moved_m"], 4), "m_per_px": round(row["m_per_px"], 4), + "prior_share": round(row["prior_share"], 3)} for (i, j), row in zip(moved, report["points"])]} + + # --- fields ---------------------------------------------------------------------------------------------------------- diff --git a/surfaces/blender/docs/reference.md b/surfaces/blender/docs/reference.md index 93bdc69..3617042 100644 --- a/surfaces/blender/docs/reference.md +++ b/surfaces/blender/docs/reference.md @@ -1,4 +1,4 @@ -# Reference views: the camera a picture was drawn through, and traced lines scored against the build +# Reference views: the camera a picture was drawn through, traced lines scored against the build, and a shell fitted to them `surfaces/blender/brokkr_reference` is a Blender add-on that fits a scene to a reference image. A concept sheet, a render or a photograph draws its subject through a camera nobody wrote down; given points whose place in the @@ -8,11 +8,11 @@ it lays over the image pixel for pixel and a line traced on the image can be sco It is a host add-on in Brokkr's sense (`install.md`, "Host add-on actions"), a sibling of `brokkr_mesh_polish`: it imports that package's operator base and `Refused`, and nothing from `brokkr_bridge`. Enable `brokkr_mesh_polish` first; `brokkr_reference` refuses to register without it. `brokkr_actions.json` beside its `__init__.py` lists the -two operators agents may run (`solve_camera`, `flow_score`); the arithmetic is `core.py` (numpy only, tested without Blender), which a script may +three operators agents may run (`solve_camera`, `flow_score`, `fit_shell`); the arithmetic is `core.py` (numpy only, tested without Blender), which a script may import directly. The action writes its JSON report to `brokkr_mesh_polish_result`, returned in the receipt's `hostResult`. -The package takes points and traced lines and gives cameras and scores. The images, the marks on them, traces and masks belong to whoever +The package takes points and traced lines and gives cameras, scores and a fitted sheet. The images, the marks on them, traces and masks belong to whoever made them; nothing here opens an image. ## Conventions @@ -172,6 +172,83 @@ surface has the hull's margin, and a surface nearer it than a thousandth of the about 20000 diagonals off, where the ray's own rounding reaches the margin. The action writes nothing to the scene (its row says `changesScene` because the operator base pushes an undo step). +## fit_shell: a shell's sheet fitted to traces of its hard runs + +A kitbash shell (`kitbash.md`, "Making a shell") is blocked in by eye; `fit_shell` moves the cage points of its +traced runs until the runs, as Blender builds them and the cameras draw them, lie on the traces. A run is a hard +crease or rim run of a loft, named as the sheet's creases name runs. The unknowns are the authored points on the +traced runs; a mirrored sheet is one set of points seen twice, so a trace of each half through one camera is two +views of the run (Francois et al. 2003), and that is where depth comes from in a single picture. Each built point +of a run is pulled onto its trace along the trace's normal, and the run's two ends onto the trace's ends; no +point of a trace is matched to a point of the run or of another trace (after Debevec's Facade and Drummond and +Cipolla's edge tracker). A prior holds every point to the sheet as it stands: a move of `share` of the sheet's +diagonal costs what one pixel of miss does. + +```json +{"action": "brokkr_reference.fit_shell", "object_name": "Pauldron", "tol": 3, + "traces": "[{\"camera\": \"Concept\", \"box\": [0, 0, 1024, 1024], \"run\": {\"column\": 3, \"from\": 0, \"to\": 5}, \"side\": 1, \"line\": [[412.5, 96.0], [431.0, 180.2], [440.8, 266.0]]}, {\"camera\": \"Concept\", \"box\": [0, 0, 1024, 1024], \"run\": {\"column\": 3, \"from\": 0, \"to\": 5}, \"side\": -1, \"line\": [[612.0, 90.5], [590.2, 176.0], [583.1, 262.4]]}]"} +``` + +| field | | +| --- | --- | +| `object_name` | a loft shell made by `brokkr_kitbash.shell`, unscaled; its place in the world is the sheet's frame | +| `traces` | a JSON array, up to 12000 characters, of `{camera, box, run, side, line}` | +| `share` | the prior (default 0.1) | +| `tol` | pixels (default 3): every point of every trace must lie this near its built run | + +In a trace, `camera` names a camera object (`solve_camera` stands one) and `box` is its frame on the image, absent +for the render's own; `run` is `{"ring": i, "from": a, "to": b}` or `{"column": j, "from": a, "to": b}` in authored +indices; `side` is 1, or -1 for the mirrored half of a mirrored sheet; `line` is `[[u, v], ...]` in the box's +pixels, drawn from the run's `from` end to its `to` end. + +**It returns a fit only where the built runs explain every trace.** After the fit, each trace is walked a pixel +at a time, and every point of it must lie within `tol` of its run as built and drawn. Otherwise the action is +refused, naming the trace, how much of it is unexplained, where along it and by how much, and nothing is returned +as a fit. The fit's own residual is no such test: on strokes doubled back over part of themselves 3% of the view +off, every fit converged and without this check all of them came back, up to 0.10 m wrong on a 2 m crease; with +it every one is refused (the least reads 9 px against the 3 asked). The check also binds the ends: a trace that +runs on past where its run ends, or two traces of a mirrored pair whose tips are not one point and its mirror +image through the camera, are refused at the tip. + +**It writes nothing.** The report carries `sheet`, the shell's own request with the traced points moved, ready +for `brokkr_kitbash.shell`, which is the cage's one writer; `flow_score` on the rebuilt shell is the score. The +rest of the report: `traces` (`[{miss_px, unexplained_px}]`: the root mean square distance of the built points +from the trace, and the trace's furthest point from the built run), `points` (`[{ring, point, moved_m, m_per_px, +prior_share}]`, one per moved point) and `seconds`. + +`m_per_px` says how far a point slides along its line of sight per pixel of error in the traces (the worst of +the views that trace it), from the inverse of the fit's normal matrix, prior included (Triggs et al. 2000, +sections 9 and 10). `prior_share` is that over `share` x the diagonal: at 1 the traces say nothing about the +point along the sight line and it stands where the blocking put it. Read it per point: + +- A run traced on one half only, in one view, reads 1.0 on every point: its depth is the blocking's. +- A mirrored pair reads low where the mirror plane stands well off the sight line. On the Orchid's concept c09 + (plane 34 degrees off, a nearly orthographic camera) the pair's points read 0.12 at most, 0.024 m per px on a + ship one unit long. +- The sight line is taken whole. Where a run recedes along the view, a cage point's slide along its own run is + in the reading: the traces do not decide that slide and it does not move the built run. A column 24 to 38 + degrees off the sight line, both halves traced and its built run right to 0.2 mm, reads 0.63 to 0.88 on its + inner points. A high reading on such a run is not a depth error. +- A run on the mirror plane itself (a spine, a keel) has no partner and reads 1.0. + +What it refuses before fitting, naming the trace: a run with an edge under weight 1 (a semi-sharp edge rounds +off by an amount the fit does not model), a run whose end does not hold (a dart; a ring run from point 0 of a +mirrored sheet, which runs on across the middle), a run with a point held partway (a corner point or a crossing +crease: trace it as two), a closed loop, an unknown camera, a line of fewer than two points, a free cage (it has +no rings or columns; `core.fit_runs` takes vertex chains), a scaled shell, and a result that would pass the +16000 characters a receipt carries. + +Measured (Blender 5.3 and Python 3.13 on Starfire): a mirrored column of 10 points traced in one view at a time, +from blockings 0.10 m and 0.30 m off a 2 m crease, came back within 0.7 mm in 0.1 to 0.6 s. The Orchid's c09 +petal edges, traced by hand through a camera solved from hand marks (13 px rms), are refused at 3 px: the left +trace's first 10 px stand up to 9.2 px off the built run. At 18.5 px they fit in 0.2 s, and from blockings 5%, +10% and 20% of the ship's length off the built run lands in one place, 2.0% of the length from a stand-in mesh +in the mean and 3.4% at worst. A trace drawn by hand through a camera solved by hand wants a `tol` near that +camera's own `rms`, and the acceptance is then that much weaker. + +What it gives up: it fits hard runs of a loft only. Silhouettes of the smooth surface, semi-sharp creases and +free cages are not fitted; a run's depth with no mirror partner and no second view is the blocking's. + ## What it cannot do It solves one pinhole camera for one view: no lens distortion, no two views solved together, one turned group and @@ -188,6 +265,7 @@ u_v = core.project(cam, points) # where it draws wor origin, direction = core.ray(cam, (u, v)) # a pixel's line of sight point = core.lift(cam, (u, v), plane_point, plane_normal) # a traced pixel on a plane run = core.crease_run(column) # the hard crease Blender builds from a cage column +fit = core.fit_sheet(sheet, cage, frame, traces, cams) # the fitted sheet and its report; cage is brokkr_kitbash.core.sheet(sheet) score = core.along(line, segments, height) # on, off, run against [u0, v0, u1, v1] segments params = core.blender(cam, 1000) # matrix_world, lens, shifts, resolution cam2 = core.camera_of(params, box) # and back @@ -196,4 +274,6 @@ cam2 = core.camera_of(params, box) # and back The tests are `tests/test_reference.py` (no Blender), `tests/live/reference.py` (a known scene rendered, solved through the action and rendered again; `reference.result.json` is its last run) and `tests/live/reference_flow.py` (`crease_run` against Blender's own subdivision, a box and a folded sheet scored by `flow_score`; -`reference_flow.result.json` is its last run). +`reference_flow.result.json` is its last run) and `tests/live/reference_fit.py` (a mirrored shell blocked off its +design, fitted through the action, rebuilt by `brokkr_kitbash.shell` and scored; `reference_fit.result.json` is +its last run). diff --git a/surfaces/blender/tests/fixtures/orchid_c09_traces.json b/surfaces/blender/tests/fixtures/orchid_c09_traces.json new file mode 100644 index 0000000..b172a7f --- /dev/null +++ b/surfaces/blender/tests/fixtures/orchid_c09_traces.json @@ -0,0 +1,224 @@ +{ + "what": "Orchid concept c09 (one view): the camera record brokkr_reference.solve_camera solved from hand marks, the frame of the ship's mirror plane, the inboard edge of the two upper petals traced by eye (left is the mirrored half), and a blocking column of 8 stations standing up to a tenth of the ship's length off. No mesh and no hull: the sheet the test builds round the column is a strip that exists to carry it.", + "camera": { + "C": [ + -6.168901501633792, + -121.90792252280691, + 2.8948965905734094 + ], + "R": [ + [ + 0.9987259467882663, + -0.05046269128654356, + 0.0 + ], + [ + 0.0009919726785528231, + 0.019632501305770517, + 0.9998067717727681 + ], + [ + -0.05045294047016491, + -0.9985329647440779, + 0.01965754606547003 + ] + ], + "f": 113777.77777777778, + "c": [ + 512.0, + 512.0 + ], + "box": [ + 0.0, + 0.0, + 1024.0, + 1024.0 + ], + "lens": 4000.0 + }, + "frame": [ + [ + 0.7946956336528872, + 0.5885955750367245, + -0.14837148951272178, + 0.03987530991435051 + ], + [ + -0.6006879570259439, + 0.7273858746251298, + -0.3317887395313959, + 0.013782020658254623 + ], + [ + -0.08736605826654754, + 0.35279602951708855, + 0.9316126520286978, + 0.5812516808509827 + ], + [ + 0.0, + 0.0, + 0.0, + 1.0 + ] + ], + "left": [ + [ + 556.3, + 34.2 + ], + [ + 533.3, + 50.0 + ], + [ + 518.8, + 64.6 + ], + [ + 500.0, + 89.6 + ], + [ + 483.3, + 118.8 + ], + [ + 466.7, + 147.9 + ], + [ + 450.0, + 178.3 + ], + [ + 433.3, + 208.3 + ], + [ + 408.3, + 258.3 + ], + [ + 389.6, + 295.8 + ], + [ + 375.0, + 329.2 + ], + [ + 356.3, + 360.4 + ], + [ + 337.5, + 389.6 + ], + [ + 320.8, + 418.8 + ], + [ + 306.3, + 445.8 + ] + ], + "right": [ + [ + 888.8, + 86.7 + ], + [ + 853.3, + 97.9 + ], + [ + 815.8, + 112.5 + ], + [ + 778.3, + 129.2 + ], + [ + 740.8, + 152.1 + ], + [ + 703.3, + 179.2 + ], + [ + 665.8, + 210.4 + ], + [ + 636.7, + 233.3 + ], + [ + 607.5, + 262.5 + ], + [ + 582.5, + 295.8 + ], + [ + 559.6, + 337.5 + ], + [ + 532.5, + 395.8 + ], + [ + 503.3, + 466.7 + ] + ], + "left_side": -1, + "blocking": [ + [ + 0.2278, + 0.3586, + 0.279 + ], + [ + 0.1764, + 0.183, + 0.3436 + ], + [ + 0.1489, + 0.0666, + 0.297 + ], + [ + 0.2226, + 0.1029, + 0.2136 + ], + [ + 0.251, + 0.1112, + 0.0995 + ], + [ + 0.2813, + 0.1228, + 0.0095 + ], + [ + 0.2259, + -0.0472, + 0.0286 + ], + [ + 0.4158, + 0.1062, + -0.1008 + ] + ] +} \ No newline at end of file diff --git a/surfaces/blender/tests/live/reference_fit.py b/surfaces/blender/tests/live/reference_fit.py new file mode 100644 index 0000000..a88935e --- /dev/null +++ b/surfaces/blender/tests/live/reference_fit.py @@ -0,0 +1,219 @@ +"""Live proof, in a background Blender, of brokkr_reference.fit_shell through run_intent. + +A mirrored loft shell made by brokkr_kitbash.shell stands turned and moved in the world: a hard crease column and +the rim's outer column on each half. A camera looks at it from the side, and the four runs are traced where +Blender's own projection draws them on the shell as designed. Then: + + blocked the shell is rebuilt from a sheet whose two traced columns stand up to 0.12 m off: flow_score reads + the four traced lines against the build, and little of them is on a built edge + fit_shell from that shell and the traces: every trace explained, the request and the mesh untouched + applied brokkr_kitbash.shell rebuilds the shell from the returned sheet; flow_score reads every traced line + on a built edge (the bound sits between the mean of this reading and of the blocked build's, as CHECK prints) + crease_run the fitted shell at one level: the rim run and the crease stand where core.crease_run says + refusals a trace doubled back over itself, an unknown camera, a scaled shell and a mesh that is no shell, + each a failed receipt naming its cause, the shell unchanged + +The Jacobian by differences (mutant F6: core.lm on the same residual) costs time only: the mirrored column of +tests/test_reference.py, views one at a time, medians of 3 interleaved runs on Starfire, read +SECONDS_ANALYTIC against SECONDS_DIFFERENCES below. + + blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/reference_fit.py -- + +Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses +without them). is an absolute path: it writes .result.json and exits 1 when a check failed. Not part +of the unittest run: it needs Blender. +""" +import json +import math +import os +import sys +import tempfile +import time +import traceback +import types +from pathlib import Path + +import bpy +import numpy as np +from bpy_extras.object_utils import world_to_camera_view +from mathutils import Euler, Matrix, Vector + +SECONDS_ANALYTIC, SECONDS_DIFFERENCES = (0.07, 0.21), (2.3, 3.9) # least and most of the three views, 2026-12-03; the fitted cages agree within 0.11 mm + +SURFACE = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(SURFACE / "tools")) +import private_dirs # noqa: E402 + +_refused = private_dirs.refusal(os.environ, os.path.expanduser("~"), lambda kind: bpy.utils.user_resource(kind)) +if _refused: + raise SystemExit(_refused) +OUT = sys.argv[sys.argv.index("--") + 1] +if not os.path.isabs(OUT): + raise SystemExit(f" must be an absolute path, not {OUT!r}: a relative one lands in Blender's start directory") +package = types.ModuleType("brokkr_bridge") +package.__path__ = [str(SURFACE / "brokkr_bridge")] +sys.modules["brokkr_bridge"] = package +from brokkr_bridge import blender_target as bt # noqa: E402 + +import addon_utils # noqa: E402 + +sys.path.append(str(SURFACE)) +bpy.ops.wm.read_factory_settings(use_empty=True) +for module in ("brokkr_mesh_polish", "brokkr_kitbash", "brokkr_reference"): + addon_utils.enable(module, default_set=True) +from brokkr_reference import core # noqa: E402 + +target = bt.BrokkrBlenderTarget(bpy) +target.configure_action_dirs("", tempfile.mkdtemp(prefix="brokkr-reference-fit-live-")) +target.reload_host_actions() +R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1], + "hostRows": [row["name"] for row in target.host_actions()[0]]} +COUNT = [0] +T0 = time.time() +WIDTH, HEIGHT = 800, 600 +RINGS, CREASE, RIM = 6, 1, 3 # the sheet's rings, and its two traced columns + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + + +def send(action, **fields): + COUNT[0] += 1 + receipt = target.run_intent(bpy.context, {"commandId": f"live-{COUNT[0]}", "requestedBy": "test/driver", "action": action, **fields}) + result = json.loads(receipt["hostResult"]) if receipt.get("hostResult") else None + print("SEND", f"{time.time() - T0:.1f}s", action, receipt["status"], str(receipt["message"])[:400], flush=True) + return receipt, result + + +def designed(): + """The sheet as designed: six rings from y -1 to 1, each from the middle out and down, a fold at column 1.""" + rings = [] + for i in range(RINGS): + t = i / (RINGS - 1) + y, lift = -1.0 + 2.0 * t, 0.12 * math.sin(math.pi * t) + rings.append([[0.0, y, 0.55 + lift], [0.42 + 0.08 * math.sin(2.5 * t), y, 0.5 + lift], [0.8 + 0.05 * t, y, 0.12 + lift], [1.05 + 0.12 * math.sin(3.0 * t), y, -0.3 + 0.1 * t]]) + return {"mirror": True, "rim": 1.0, "creases": [{"column": CREASE, "from": 0, "to": RINGS - 1, "weight": 1.0}], "rings": rings} + + +def blocking(sheet): + """The designed sheet with its two traced columns pushed off by smooth bumps, up to 0.12 m.""" + out, r, t = json.loads(json.dumps(sheet)), np.random.default_rng(5), np.linspace(0, 1, RINGS) + for column in (CREASE, RIM): + bump = sum(r.normal(0, 1, 3)[None] * np.sin(np.pi * (j + 1) * t + 0.4)[:, None] for j in range(2)) + bump *= 0.12 / np.abs(bump).max() + for i in range(RINGS): + out["rings"][i][column] = [round(float(v + d), 6) for v, d in zip(sheet["rings"][i][column], bump[i])] + return out + + +def run_of(sheet, column, side): + """A column's built run in the shell's frame, as core.crease_run builds it twice over.""" + return core.crease_run(core.crease_run(np.array(sheet["rings"])[:, column] * [side, 1, 1])) + + +def pixels(camera, shell, points): + out = [] + for p in points: + x, y, _ = world_to_camera_view(bpy.context.scene, camera, shell.matrix_world @ Vector(p)) + out.append([round(x * WIDTH, 3), round((1.0 - y) * HEIGHT, 3)]) + return out + + +def flow(lines, shell): + _, result = send("brokkr_reference.flow_score", camera_name="View", objects=shell.name, + lines="; ".join(f"{tag}: " + " ".join(f"{u},{v}" for u, v in line) for tag, line in lines.items())) + return {tag: row["on"] for tag, row in result["lines"].items()} if result else None + + +def state(shell): + return shell["kit_shell"], [tuple(round(c, 7) for c in v.co) for v in shell.data.vertices] + + +try: + check("host files admitted with the fit_shell row", not R["hostErrors"] and "brokkr_reference.fit_shell" in R["hostRows"], R["hostErrors"] or R["hostRows"]) + scene = bpy.context.scene + scene.render.resolution_x, scene.render.resolution_y, scene.render.resolution_percentage = WIDTH, HEIGHT, 100 + truth = designed() + send("brokkr_kitbash.shell", object_name="Plate", sheet=json.dumps(truth), thickness=0.03, levels=2) + shell = bpy.data.objects["Plate"] + shell.matrix_world = Matrix.Translation((0.3, -0.2, 0.1)) @ Euler((0.0, 0.0, math.radians(15.0))).to_matrix().to_4x4() + camera = bpy.data.objects.new("View", bpy.data.cameras.new("View")) + scene.collection.objects.link(camera) + camera.data.lens, camera.data.sensor_fit = 50.0, "HORIZONTAL" + camera.location = (3.2, -3.0, 5.2) + camera.rotation_euler = (Vector((0.3, -0.1, 0.25)) - camera.location).to_track_quat("-Z", "Y").to_euler() + bpy.context.view_layer.update() + runs = {"crease": (CREASE, 1), "crease_m": (CREASE, -1), "rim": (RIM, 1), "rim_m": (RIM, -1)} + lines = {tag: pixels(camera, shell, core.resampled(run_of(truth, column, side), 40)) for tag, (column, side) in runs.items()} + inside = all(0 <= u <= WIDTH and 0 <= v <= HEIGHT for line in lines.values() for u, v in line) + designed_on = flow(lines, shell) + check("the designed shell: the camera frames all four runs, and flow_score reads each traced line on a built edge", inside and designed_on and min(designed_on.values()) >= 0.9, designed_on) + + # --- blocked: the shell rebuilt from a sheet whose traced columns stand off --------------------------------------- + blocked = blocking(truth) + send("brokkr_kitbash.shell", object_name="Plate", sheet=json.dumps(blocked), thickness=0.03, levels=2) + bpy.context.view_layer.update() + blocked_on = flow(lines, shell) + before = state(shell) + + # --- fit_shell ----------------------------------------------------------------------------------------------------- + traces = [{"camera": "View", "run": {"column": column, "from": 0, "to": RINGS - 1}, "side": side, "line": lines[tag]} for tag, (column, side) in runs.items()] + receipt, fit = send("brokkr_reference.fit_shell", object_name="Plate", traces=json.dumps(traces, separators=(",", ":"))) + ok = receipt["status"] == "accepted" and fit is not None + check("fit_shell returns a sheet with every trace explained within 3 px, and a row for each of the 12 moved points", + ok and max(row["unexplained_px"] for row in fit["traces"]) <= 3.0 and len(fit["points"]) == 2 * RINGS and len(receipt["hostResult"]) < 16000, + fit and {"traces": fit["traces"], "seconds": fit["seconds"], "chars": len(receipt["hostResult"])}) + check("fit_shell wrote nothing: the shell's request and its cage are as they were", state(shell) == before) + if ok: + gap, off = (max(float(core._off(core.resampled(run_of(sheet, column, 1), 200), run_of(truth, column, 1)).max()) for column in (CREASE, RIM)) for sheet in (fit["sheet"], blocked)) + check("the fitted runs stand within 5 mm of the designed ones, from a blocking over 0.05 m off them", gap < 0.005 and off > 0.05, [gap, off]) + shares = {(row["ring"], row["point"]): row["prior_share"] for row in fit["points"]} + check("every moved point reports metres per pixel and a prior share from 0 to 1", all(0.0 <= row["prior_share"] <= 1.0 and row["m_per_px"] >= 0.0 for row in fit["points"]), shares and max(shares.values())) + + # --- applied: brokkr_kitbash.shell is the writer --------------------------------------------------------------- + applied, _ = send("brokkr_kitbash.shell", object_name="Plate", sheet=json.dumps(fit["sheet"]), thickness=0.03, levels=2) + bpy.context.view_layer.update() + fitted_on = flow(lines, shell) + low, high = sum(blocked_on.values()) / 4, sum(fitted_on.values()) / 4 + bound = math.sqrt(low * high) + check(f"applied with brokkr_kitbash.shell, flow_score reads the four traced lines on a built edge over {bound:.3f} in the mean: the geometric mean of the fitted build's " + f"reading ({high:.3f}) and the blocked build's ({low:.3f}), separation {high / bound:.2f} each side; no fitted line reads under 0.9", + applied["status"] == "accepted" and high / bound >= 1.2 and min(fitted_on.values()) >= 0.9, {"blocked": blocked_on, "fitted": fitted_on}) + + # --- crease_run is what Blender builds of both runs ---------------------------------------------------------------- + send("brokkr_kitbash.shell", object_name="Plate", sheet=json.dumps(fit["sheet"]), thickness=0.03, levels=1) + wall = shell.modifiers["Kit Solidify"] + wall.show_viewport = False + mesh = shell.evaluated_get(bpy.context.evaluated_depsgraph_get()).to_mesh() + built = np.array([v.co for v in mesh.vertices]) + wall.show_viewport = True + worst = {tag: max(float(np.linalg.norm(built - p, axis=1).min()) for p in core.crease_run(np.array(fit["sheet"]["rings"])[:, column] * [side, 1, 1])) for tag, (column, side) in runs.items()} + check("at one level Blender builds the rim run and the crease, on both halves, where core.crease_run says, within 1e-4 m", max(worst.values()) < 1e-4, worst) + send("brokkr_kitbash.shell", object_name="Plate", sheet=json.dumps(blocked), thickness=0.03, levels=2) + + # --- refusals ---------------------------------------------------------------------------------------------------------- + before = state(shell) + line = np.array(lines["crease_m"]) + doubled = np.vstack([line[:25], line[24:9:-1] + [0.0, 14.0], line[10:25] + [0.0, 28.0], line[25:]]).round(3).tolist() + receipt, _ = send("brokkr_reference.fit_shell", object_name="Plate", traces=json.dumps([traces[0], dict(traces[1], line=doubled)], separators=(",", ":"))) + check("a trace doubled back over itself is refused, naming the trace and the span no built run draws", receipt["status"] == "failed" and "traces[1] is not explained" in receipt["message"] and "px along it" in receipt["message"], receipt["message"]) + receipt, _ = send("brokkr_reference.fit_shell", object_name="Plate", traces=json.dumps([dict(traces[0], camera="Nobody")])) + check("an unknown camera is refused naming the trace", receipt["status"] == "failed" and "traces[0]" in receipt["message"] and "Nobody" in receipt["message"], receipt["message"]) + receipt, _ = send("brokkr_reference.fit_shell", object_name="View", traces=json.dumps(traces[:1])) + check("an object that is no shell is refused", receipt["status"] == "failed" and "is not a shell" in receipt["message"], receipt["message"]) + shell.scale = (2.0, 2.0, 2.0) + bpy.context.view_layer.update() + receipt, _ = send("brokkr_reference.fit_shell", object_name="Plate", traces=json.dumps(traces[:1])) + shell.scale = (1.0, 1.0, 1.0) + bpy.context.view_layer.update() + check("a scaled shell is refused", receipt["status"] == "failed" and "is scaled" in receipt["message"], receipt["message"]) + check("no refusal changed the shell", state(shell) == before) +except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, printed and written, not a missing result file + check(f"no uncaught error after: {R['checks'][-1]['name'] if R['checks'] else 'the start'}", False, traceback.format_exc().splitlines()[-6:]) + +R["ok"] = all(c["ok"] for c in R["checks"]) +for c in R["checks"]: + print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True) +Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") +sys.exit(0 if R["ok"] else 1) diff --git a/surfaces/blender/tests/live/reference_fit.result.json b/surfaces/blender/tests/live/reference_fit.result.json new file mode 100644 index 0000000..cc4d101 --- /dev/null +++ b/surfaces/blender/tests/live/reference_fit.result.json @@ -0,0 +1,184 @@ +{ + "blender": "5.3.0", + "checks": [ + { + "name": "host files admitted with the fit_shell row", + "ok": true, + "detail": [ + "brokkr_mesh_polish.audit", + "brokkr_mesh_polish.repair", + "brokkr_mesh_polish.orient", + "brokkr_mesh_polish.delight", + "brokkr_mesh_polish.scrub_markings", + "brokkr_mesh_polish.cut_parts", + "brokkr_mesh_polish.pick", + "brokkr_kitbash.place_part", + "brokkr_kitbash.set_params", + "brokkr_kitbash.describe", + "brokkr_kitbash.report", + "brokkr_kitbash.attach", + "brokkr_kitbash.detach", + "brokkr_kitbash.roll", + "brokkr_kitbash.aim", + "brokkr_kitbash.reach", + "brokkr_kitbash.joint", + "brokkr_kitbash.slide", + "brokkr_kitbash.joints", + "brokkr_kitbash.close", + "brokkr_kitbash.boolean", + "brokkr_kitbash.cut", + "brokkr_kitbash.cut_many", + "brokkr_kitbash.freeze", + "brokkr_kitbash.thaw", + "brokkr_kitbash.ribs", + "brokkr_kitbash.shell", + "brokkr_kitbash.hose", + "brokkr_reference.solve_camera", + "brokkr_reference.flow_score", + "brokkr_reference.fit_shell" + ] + }, + { + "name": "the designed shell: the camera frames all four runs, and flow_score reads each traced line on a built edge", + "ok": true, + "detail": { + "crease": 1.0, + "crease_m": 1.0, + "rim": 1.0, + "rim_m": 0.963 + } + }, + { + "name": "fit_shell returns a sheet with every trace explained within 3 px, and a row for each of the 12 moved points", + "ok": true, + "detail": { + "traces": [ + { + "miss_px": 0.004, + "unexplained_px": 0.021 + }, + { + "miss_px": 0.008, + "unexplained_px": 0.082 + }, + { + "miss_px": 0.005, + "unexplained_px": 0.071 + }, + { + "miss_px": 0.003, + "unexplained_px": 0.055 + } + ], + "seconds": 0.12, + "chars": 2059 + } + }, + { + "name": "fit_shell wrote nothing: the shell's request and its cage are as they were", + "ok": true, + "detail": null + }, + { + "name": "the fitted runs stand within 5 mm of the designed ones, from a blocking over 0.05 m off them", + "ok": true, + "detail": [ + 0.0006199003550468113, + 0.132354157889395 + ] + }, + { + "name": "every moved point reports metres per pixel and a prior share from 0 to 1", + "ok": true, + "detail": 0.617 + }, + { + "name": "applied with brokkr_kitbash.shell, flow_score reads the four traced lines on a built edge over 0.747 in the mean: the geometric mean of the fitted build's reading (0.991) and the blocked build's (0.563), separation 1.33 each side; no fitted line reads under 0.9", + "ok": true, + "detail": { + "blocked": { + "crease": 0.713, + "crease_m": 0.613, + "rim": 0.138, + "rim_m": 0.787 + }, + "fitted": { + "crease": 1.0, + "crease_m": 1.0, + "rim": 1.0, + "rim_m": 0.963 + } + } + }, + { + "name": "at one level Blender builds the rim run and the crease, on both halves, where core.crease_run says, within 1e-4 m", + "ok": true, + "detail": { + "crease": 1.341720156294607e-07, + "crease_m": 1.341720156294607e-07, + "rim": 1.6729111618262465e-07, + "rim_m": 1.6729111618262465e-07 + } + }, + { + "name": "a trace doubled back over itself is refused, naming the trace and the span no built run draws", + "ok": true, + "detail": "Error: traces[1] is not explained: 281 px of the trace, between 110 and 466 px along it, lie more than 3 px from the run as built, up to 15.7 px. Nothing is returned as a fit. The trace draws something this run does not build (an overdrawn or doubled stroke, another edge, a bend the cage has too few points for): redraw it, or give the run more points. Nothing changed." + }, + { + "name": "an unknown camera is refused naming the trace", + "ok": true, + "detail": "Error: traces[0]: 'Nobody' is not a camera object." + }, + { + "name": "an object that is no shell is refused", + "ok": true, + "detail": "Error: 'View' is not a shell brokkr_kitbash.shell made (a mesh carrying kit_shell)." + }, + { + "name": "a scaled shell is refused", + "ok": true, + "detail": "Error: 'Plate' is scaled (2.0, 2.0, 2.0): a sheet is in metres of the shell's own frame. Apply or clear the scale." + }, + { + "name": "no refusal changed the shell", + "ok": true, + "detail": null + } + ], + "hostErrors": [], + "hostRows": [ + "brokkr_mesh_polish.audit", + "brokkr_mesh_polish.repair", + "brokkr_mesh_polish.orient", + "brokkr_mesh_polish.delight", + "brokkr_mesh_polish.scrub_markings", + "brokkr_mesh_polish.cut_parts", + "brokkr_mesh_polish.pick", + "brokkr_kitbash.place_part", + "brokkr_kitbash.set_params", + "brokkr_kitbash.describe", + "brokkr_kitbash.report", + "brokkr_kitbash.attach", + "brokkr_kitbash.detach", + "brokkr_kitbash.roll", + "brokkr_kitbash.aim", + "brokkr_kitbash.reach", + "brokkr_kitbash.joint", + "brokkr_kitbash.slide", + "brokkr_kitbash.joints", + "brokkr_kitbash.close", + "brokkr_kitbash.boolean", + "brokkr_kitbash.cut", + "brokkr_kitbash.cut_many", + "brokkr_kitbash.freeze", + "brokkr_kitbash.thaw", + "brokkr_kitbash.ribs", + "brokkr_kitbash.shell", + "brokkr_kitbash.hose", + "brokkr_reference.solve_camera", + "brokkr_reference.flow_score", + "brokkr_reference.fit_shell" + ], + "ok": true +} \ No newline at end of file diff --git a/surfaces/blender/tests/test_reference.py b/surfaces/blender/tests/test_reference.py index 56540c8..eaacde6 100644 --- a/surfaces/blender/tests/test_reference.py +++ b/surfaces/blender/tests/test_reference.py @@ -44,6 +44,10 @@ if np is not None: spec = importlib.util.spec_from_file_location("brokkr_reference_core", SURFACE / "brokkr_reference" / "core.py") core = importlib.util.module_from_spec(spec) spec.loader.exec_module(core) + spec = importlib.util.spec_from_file_location("brokkr_kitbash_core_for_reference", SURFACE / "brokkr_kitbash" / "core.py") + kit = importlib.util.module_from_spec(spec) # the sheet's one parser: fit_sheet takes what it parses + sys.modules[spec.name] = kit + spec.loader.exec_module(kit) BOX = [100.0, 50.0, 1100.0, 800.0] NAMES = [f"p{i}" for i in range(13)] @@ -381,6 +385,222 @@ class FlowTests(unittest.TestCase): self.assertIn(said, str(caught.exception)) +FIT_FRAME = [[0.9659258262890683, -0.25881904510252074, 0.0, 0.3], [0.25881904510252074, 0.9659258262890683, 0.0, -0.2], [0.0, 0.0, 1.0, 0.1], [0.0, 0.0, 0.0, 1.0]] # turned 15 degrees about z and moved +FIT_VIEWS = ((35, 20, 50), (-60, 40, 85), (150, 10, 35)) +FIT_K = 10 # cage points in the traced column + + +def crease(A, w, n=400): + """A crease 2 m long on the +x side of a mirror plane, in the shell's frame: the family the fit was mapped on.""" + t = np.linspace(0, 1, n) + return np.stack([0.4 + A * np.sin(w * t), -1.0 + 2.0 * t, 0.5 + 0.3 * t * t], 1) + + +def overdrawn(line, start, stop, off, kind): + """A stroke that runs along `line`, and between two shares of it doubles back and over again, each pass `off` + of the line's extent further to one side: a trace drawn twice over.""" + n = len(line) + i0, i1 = int(start * (n - 1)), int(stop * (n - 1)) + v = line[i1] - line[i0] + d = np.array([-v[1], v[0]]) / np.linalg.norm(v) * off * np.ptp(line, axis=0).max() + forward, back = line[i0:i1 + 1], line[i1:i0 - 1 if i0 > 0 else None:-1] + if kind == "mid": + return np.vstack([line[:i1 + 1], back + d, forward + 2 * d, line[i1 + 1:]]) + if kind == "truth-last": + return np.vstack([line[:i0], forward + d, back + 2 * d, line[i0:]]) + return np.vstack([line[:i0], forward + d, back + 2 * d, forward, line[i1 + 1:]]) + + +def strip(column, weight=1.0, last=None): + """A mirrored sheet three points wide whose column 1 is `column`, creased from ring 0 to `last` (the far rim).""" + return {"mirror": True, "rim": 1.0, "creases": [{"column": 1, "from": 0, "to": len(column) - 1 if last is None else last, "weight": weight}], + "rings": [[[0.0, float(p[1]), float(p[2]) + 0.15], [float(v) for v in p], [float(p[0]) + 0.5, float(p[1]), float(p[2]) - 0.2]] for p in column]} + + +def blocked(A, w, share): + """(the true crease, a strip whose column stands up to `share` of the crease's 2 m off it).""" + truth, t, r = crease(A, w), np.linspace(0, 1, FIT_K), np.random.default_rng(int(A * 100 + w * 10)) + bump = sum(r.normal(0, 1, 3)[None] * np.sin(np.pi * (j + 1) * t)[:, None] for j in range(2)) + return truth, strip(core.resampled(truth, FIT_K) + share * 2.0 * bump / np.abs(bump).max()) + + +def fit_views(truth): + both = np.vstack([truth, truth * [-1, 1, 1]]) @ np.array(FIT_FRAME)[:3, :3].T + np.array(FIT_FRAME)[:3, 3] + return [camera(both, *view) for view in FIT_VIEWS] + + +def pair_traces(a, b=None): + run = {"column": 1, "from": 0, "to": FIT_K - 1} + return [{"camera": "View", "run": run, "side": side, "line": np.asarray(line).tolist()} for side, line in ((1, a), (-1, b)) if line is not None] + + +def fitted(document, traces, cam, **more): + return core.fit_sheet(document, kit.sheet(document), FIT_FRAME, traces, [cam] * len(traces), **more) + + +def off_truth(document, truth): + """The furthest the column's built run stands from the true crease, or the crease's ends from the run.""" + run = core.resampled(core.crease_run(core.crease_run(np.array(document["rings"])[:, 1])), 400) + return max(float(core._off(run, truth).max()), float(core._off(truth[[0, -1]], run).max())) + + +@unittest.skipIf(np is None, "numpy") +class FitTests(unittest.TestCase): + """fit_runs and fit_sheet: a shell's traced runs fitted through cameras, accepted only where the built runs + explain every trace. Bounds follow lodur:ruling:deterministic-bound-margin. Mutants, each run once on a copy: + F1 no explained check test_an_overdrawn_stroke_is_refused_naming_its_trace + F2 sensitivity across the run's tangent, not the ray test_the_sight_line_reading_holds_the_points_slide_along_its_run + F3 the prior left out of S test_one_trace_alone_reads_as_held_by_the_blocking + F4 no end terms test_a_mirrored_column_is_recovered_from_a_blocking_well_off + F5 a semi-sharp run admitted test_refusals_name_their_field_before_fitting + F6 (the Jacobian by differences) costs time only: tests/live/reference_fit.py's header says how much.""" + + @classmethod + def setUpClass(cls): + cls.orchid = json.loads((Path(__file__).resolve().parent / "fixtures" / "orchid_c09_traces.json").read_text(encoding="utf-8")) + + def test_the_projection_derivative_is_the_projections(self): + cam, X = camera(cloud(), 35, 20, 50), cloud() + u, J = core._drawn(cam, FIT_FRAME, X) + self.assertLess(np.abs(u - core.seen(cam, FIT_FRAME, X)).max(), 1e-9) + self.assertLess(np.abs(core.seen(cam, FIT_FRAME, X) - core.project(cam, X @ np.array(FIT_FRAME)[:3, :3].T + np.array(FIT_FRAME)[:3, 3])).max(), 1e-9) # seen is project past the frame + for c in range(3): + step = np.zeros(3) + step[c] = 1e-6 + numeric = (core.seen(cam, FIT_FRAME, X + step) - core.seen(cam, FIT_FRAME, X - step)) / 2e-6 + self.assertLess(np.abs(numeric - J[:, :, c]).max(), 1e-4 * np.abs(J).max()) + self.assertIsNone(core._drawn(cam, np.eye(4), np.array([cam["C"]]) - np.array(cam["R"])[2] * -1.0)) # a point behind it + + def test_a_mirrored_column_is_recovered_from_a_blocking_well_off(self): + """fit-recovers, F4: each of three views alone, both halves traced, from blockings 0.10 m and 0.30 m off. + Shipped: the built run ends within 0.67 mm of the true crease (the 3 mm asked is a tolerance round a known + truth) and the worst trace is explained within 0.196 px. F4 (no end terms): the run stops short of its + traces, three fits are refused at 3.6 px and up, and the worst it explains reads 2.06 px: the bound is the + geometric mean of 0.196 and 2.06, separation 3.2 each side.""" + worst = 0.0 + for A, w in ((0.2, 2.5), (0.1, 5.0), (0.4, 1.0)): + for share in (0.05, 0.15): + truth, document = blocked(A, w, share) + self.assertGreater(off_truth(document, truth), 0.09) + for cam in fit_views(truth): + out = fitted(document, pair_traces(core.seen(cam, FIT_FRAME, truth), core.seen(cam, FIT_FRAME, truth * [-1, 1, 1])), cam) + worst = max(worst, off_truth(out["sheet"], truth)) + self.assertLess(max(row["unexplained_px"] for row in out["traces"]), 0.64) + self.assertEqual(len(out["points"]), FIT_K) + self.assertLess(worst, 0.003) + + def test_an_overdrawn_stroke_is_refused_naming_its_trace(self): + """overdraw-refused, F1: the mirrored half's trace doubled back over part of itself 3% of its extent off. + All 27 are refused, naming the trace and the span that no built run draws; the least unexplained reads + 8.98 px against the 3 asked, separation 3.0. F1 returns all 27 as fits, the worst 0.104 m off the truth.""" + truth, document = blocked(0.2, 2.5, 0.05) + least = 1e9 + for cam in fit_views(truth): + a, b = core.seen(cam, FIT_FRAME, truth), core.seen(cam, FIT_FRAME, truth * [-1, 1, 1]) + for start, stop in ((0.1, 0.3), (0.3, 0.7), (0.6, 1.0)): + for kind in ("mid", "truth-last", "truth-first"): + with self.assertRaisesRegex(core.ReferenceFitError, r"^traces\[[01]\] is not explained: \d+ px of the trace, between \d+ and \d+ px along it") as caught: + fitted(document, pair_traces(a, overdrawn(b, start, stop, 0.03, kind)), cam) + least = min(least, max(row["unexplained_px"] for row in caught.exception.traces)) + self.assertGreater(least, 3.0 * 1.2) # lodur:ruling:deterministic-bound-margin's least separation + + def test_an_accepted_fit_is_within_its_own_reported_reach(self): + """accepted-bounded: the same strokes 0.2% off pass as explained (they are under 3 px from one line), and + every accepted fit stands within tol x the worst m_per_px it reports of the truth: all 27 are accepted, + the worst 8.9 mm off, 0.024 of that reach (F2 reads 0.27 of its own). No mutant claims this bound.""" + truth, document = blocked(0.2, 2.5, 0.05) + accepted, most = 0, 0.0 + for cam in fit_views(truth): + a, b = core.seen(cam, FIT_FRAME, truth), core.seen(cam, FIT_FRAME, truth * [-1, 1, 1]) + for start, stop in ((0.1, 0.3), (0.3, 0.7), (0.6, 1.0)): + for kind in ("mid", "truth-last", "truth-first"): + try: + out = fitted(document, pair_traces(a, overdrawn(b, start, stop, 0.002, kind)), cam) + except core.ReferenceFitError: + continue + accepted += 1 + most = max(most, off_truth(out["sheet"], truth) / (3.0 * max(row["m_per_px"] for row in out["points"]))) + self.assertEqual(accepted, 27) + self.assertLess(most, 1.0) + + def test_one_trace_alone_reads_as_held_by_the_blocking(self): + """F3: one half traced in one view decides nothing along the sight line, and the prior is all that holds + each point there: prior_share reads 1.0, its ceiling. F3 (the prior left out of S) reads 771366.""" + truth, document = blocked(0.2, 2.5, 0.05) + cam = fit_views(truth)[0] + shares = [row["prior_share"] for row in fitted(document, pair_traces(core.seen(cam, FIT_FRAME, truth)), cam)["points"]] + self.assertEqual((min(shares), max(shares)), (1.0, 1.0)) + + def test_the_sight_line_reading_holds_the_points_slide_along_its_run(self): + """F2: m_per_px is along the sight line whole. This column recedes along the view (its tangent 24 to 38 + degrees off the sight line), so with both halves traced, which decide the built run to 0.2 mm, an inner + cage point still slides along its own run on the prior alone and reads a prior_share of 0.633 to 0.88; the + ends, which hold, read 0.024 and under. F2 (the ray's part across the tangent) reads the inner points 0.039 + at most: the bound is the geometric mean of 0.633 and 0.039, separation 4.0 each side.""" + truth, document = blocked(0.2, 2.5, 0.05) + cam = fit_views(truth)[0] + shares = [row["prior_share"] for row in fitted(document, pair_traces(core.seen(cam, FIT_FRAME, truth), core.seen(cam, FIT_FRAME, truth * [-1, 1, 1])), cam)["points"]] + self.assertGreater(min(shares[1:-1]), 0.157) + self.assertLess(max(shares[0], shares[-1]), 0.157) + self.assertLessEqual(max(shares), 1.0) + + def orchid_strip(self): + return strip(np.array(self.orchid["blocking"])) + + def orchid_fit(self, lines, tol): + document, run = self.orchid_strip(), {"column": 1, "from": 0, "to": 7} + traces = [{"camera": "Concept", "run": run, "side": side, "line": line} for side, line in lines] + return core.fit_sheet(document, kit.sheet(document), self.orchid["frame"], traces, [self.orchid["camera"]] * len(traces), tol=tol) + + ORCHID_TOL = 18.5 # px: the geometric mean of 9.2, the pair's unexplained reading as drawn, and 37.3, its reading with the right trace moved 40 px: separation 2.0 each side + + def test_orchid_c09_hand_traces(self): + """orchid-c09: the inboard edges of two petals traced by hand on one concept view, through a camera solved + from hand marks (13 px rms). At the default 3 px the pair is refused: the left trace's first 10 px stand up + to 9.2 px off the built run, because the two traces' tips are not one point and its mirror image through + that camera (the right trace reads 2.4 px). Asked at ORCHID_TOL the pair is explained, and the worst + prior_share of its points is 0.119 (0.024 m per px); either trace alone reads 1.0 on every point: the bound + is the geometric mean of 0.119 and 1.0, separation 2.9 each side. The right trace moved 40 px is refused.""" + left, right, side = self.orchid["left"], self.orchid["right"], self.orchid["left_side"] + with self.assertRaisesRegex(core.ReferenceFitError, r"^traces\[0\] is not explained: 11 px of the trace, between 0 and 10 px along it, .* up to 9\.2 px"): + self.orchid_fit([(side, left), (-side, right)], 3.0) + pair = self.orchid_fit([(side, left), (-side, right)], self.ORCHID_TOL) + self.assertLess(max(row["unexplained_px"] for row in pair["traces"]), self.ORCHID_TOL / 2.0) + self.assertLess(max(row["prior_share"] for row in pair["points"]), 0.345) + self.assertEqual(pair["sheet"]["rings"][3][0], self.orchid_strip()["rings"][3][0]) # only the traced column moves + for alone in ([(side, left)], [(-side, right)]): + self.assertGreater(min(row["prior_share"] for row in self.orchid_fit(alone, self.ORCHID_TOL)["points"]), 0.345) + with self.assertRaisesRegex(core.ReferenceFitError, r"^traces\[0\] is not explained") as caught: + self.orchid_fit([(side, left), (-side, (np.array(right) + [0.0, 40.0]).tolist())], self.ORCHID_TOL) + self.assertGreater(max(row["unexplained_px"] for row in caught.exception.traces), self.ORCHID_TOL * 2.0) + + def test_refusals_name_their_field_before_fitting(self): + """refusals, F5 (which takes the semi-sharp run as far as its end and refuses it there for another cause).""" + truth, document = blocked(0.2, 2.5, 0.05) + cam = fit_views(truth)[0] + a = core.seen(cam, FIT_FRAME, truth) + column = np.array(document["rings"])[:, 1] + crossed = strip(column) + crossed["creases"].append({"ring": 4, "from": 0, "to": 2, "weight": 1.0}) + big = strip(core.resampled(column, 64)) + big["rings"] = [[ring[0]] + [[ring[1][0] + 0.01 * j, ring[1][1], ring[1][2]] for j in range(30)] for ring in big["rings"]] + whole = {"column": 1, "from": 0, "to": 63} + for sheet_, traces, cams, message in ( + (strip(column, weight=0.6), pair_traces(a), [cam], r"^traces\[0\]: the edge after point 0 of its run has crease weight 0\.6"), + (strip(column, last=FIT_K - 2), [dict(pair_traces(a)[0], run={"column": 1, "from": 0, "to": FIT_K - 2})], [cam], r"^traces\[0\]: the last end of its run does not hold: it is a dart"), + (strip(column, last=FIT_K - 2), pair_traces(a), [cam], r"^traces\[0\]: the edge after point 8 of its run has crease weight 0\b"), + (crossed, pair_traces(a), [cam], r"^traces\[0\]: point 4 of its run is held or pulled by more than the run"), + (document, pair_traces(a), [None], r"^traces\[0\]\.camera 'View' is no camera"), + (document, [dict(pair_traces(a)[0], line=[[10.0, 20.0]])], [cam], r"^traces\[0\]: its line must be two or more"), + (document, [dict(pair_traces(a)[0], side=2)], [cam], r"^traces\[0\]\.side must be 1"), + (document, [dict(pair_traces(a)[0], run={"column": 3, "from": 0, "to": 2})], [cam], r"^traces\[0\]\.run must name a column under 3"), + (document, [dict(pair_traces(a)[0], run={"ring": 0, "from": 0, "to": 2})], [cam], r"^traces\[0\]: the first end of its run does not hold"), + ({"verts": [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]], "faces": [[0, 1, 2, 3]]}, pair_traces(a), [cam], r"^the sheet is a free cage"), + (big, [dict(pair_traces(a)[0], run=whole)], [cam], r"would be about \d+ characters, over the 16000 a receipt carries: nothing was fitted")): + with self.assertRaisesRegex(core.ReferenceFitError, message): + core.fit_sheet(sheet_, kit.sheet(sheet_), FIT_FRAME, traces, cams) + + @unittest.skipIf(np is None, "numpy") class CameraTests(unittest.TestCase): CAM = {"C": [3.0, -7.0, 2.5], "f": 1400.0, "c": [640.0, 395.0], "box": BOX} @@ -444,8 +664,8 @@ class HostFileTests(unittest.TestCase): def test_the_row_names_the_operator_and_properties_the_add_on_defines(self): source = (SURFACE / "brokkr_reference" / "__init__.py").read_text(encoding="utf-8") - self.assertEqual([row["name"] for row in self.document["actions"]], ["brokkr_reference.solve_camera", "brokkr_reference.flow_score"]) - self.assertEqual(source.count("bl_idname = "), 2) + self.assertEqual([row["name"] for row in self.document["actions"]], ["brokkr_reference.solve_camera", "brokkr_reference.flow_score", "brokkr_reference.fit_shell"]) + self.assertEqual(source.count("bl_idname = "), 3) for row in self.document["actions"]: self.assertIn(f'bl_idname = "{row["name"]}"', source) self.assertEqual(row.get("result"), "brokkr_mesh_polish_result") @@ -466,6 +686,11 @@ class HostFileTests(unittest.TestCase): for intent, bad in ((flow, {"angle": 0}), (flow, {"lines": ""}), (flow, {"camera_name": "x" * 64})): with self.assertRaises(at.IntentInvalid): at.validate({**intent, **bad}, self.host) + fit = {**self.envelope, "action": "brokkr_reference.fit_shell", "object_name": "Plate", "traces": "[{}]"} + self.assertEqual((at.validate(fit, self.host)["share"], at.validate(fit, self.host)["tol"]), (0.1, 3)) + for bad in ({"tol": 0}, {"share": 11}, {"traces": ""}, {"object_name": "x" * 64}): + with self.assertRaises(at.IntentInvalid): + at.validate({**fit, **bad}, self.host) class OwnershipTests(unittest.TestCase): @@ -481,6 +706,14 @@ class OwnershipTests(unittest.TestCase): if path.is_file(): self.assertIsNone(re.search(r"concepts\.json|PIL|Image\.open|centre_plate|silhouette|polygon_mask|knotted", path.read_text(encoding="utf-8")), path.name) + def test_fit_shell_never_writes_the_request_and_nothing_here_searches_a_correspondence(self): + """The cut's negative patterns: brokkr_kitbash.shell is the cage's one writer, and no point's depth is + decided by matching trace points to each other.""" + for path in (SURFACE / "brokkr_reference").glob("*.py"): + text = path.read_text(encoding="utf-8") + self.assertIsNone(re.search(r"def pair|_smoothest|cage_through|on_plane", text), path.name) + self.assertIsNone(re.search(r"SHELL\] *=|kit_shell\"\] *=|\.data\.vertices|foreach_set|from_pydata", text), path.name) + def test_no_other_package_names_this_one(self): for package in ("brokkr_kitbash", "brokkr_rig", "brokkr_bridge", "brokkr_mesh_polish"): for path in (SURFACE / package).rglob("*.py"):