diff --git a/surfaces/blender/brokkr_reference/__init__.py b/surfaces/blender/brokkr_reference/__init__.py index 2cd7956..4f93a0b 100644 --- a/surfaces/blender/brokkr_reference/__init__.py +++ b/surfaces/blender/brokkr_reference/__init__.py @@ -1,6 +1,5 @@ -"""Fit a scene to a reference image: the camera a reference view was drawn through, solved from marked points; -lines traced on the view lifted through that camera into a part's frame; and traced lines scored against the edges -the camera sees on the build. +"""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. 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 @@ -8,10 +7,9 @@ arithmetic is core.py (numpy, tested without Blender); this file is the bpy arou JSON report to WindowManager.brokkr_mesh_polish_result, as the polish operators do. 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 (lift_pair and flow_score take 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, creases and scores. A curve lift_pair draws is for the eye; its report is the truth. The edges -flow_score reads are computed on each call and kept nowhere. +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. """ 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."} @@ -176,59 +174,6 @@ def built_edges(context, cam, objects, angle): return out -class BROKKR_REFERENCE_OT_lift_pair(PolishOperator): - """Lift two traced lines that are one crease and its mirror image through a camera into a frame, with the cage - column whose built crease passes through it""" - bl_idname = "brokkr_reference.lift_pair" - bl_label = "Lift Mirrored Pair" - camera_name: bpy.props.StringProperty(name="Camera", maxlen=63, description="The camera object the view is seen through (solve_camera stands one)") - box: bpy.props.StringProperty(name="Box", maxlen=120, description="u0,v0,u1,v1: the camera's frame on the image, in the pixels the lines were traced in; empty is the render's own frame") - frame_name: bpy.props.StringProperty(name="Frame", maxlen=63, description="An object whose matrix_world is the part's frame; its x = 0 is the mirror plane") - line_a: bpy.props.StringProperty(name="Line A", maxlen=4000, description="u,v u,v ... the crease as traced on one side") - line_b: bpy.props.StringProperty(name="Line B", maxlen=4000, description="u,v u,v ... its mirror image as traced on the other side") - samples: bpy.props.IntProperty(name="Samples", default=24, min=2, max=200, description="Points lifted, evenly along line A") - extend: bpy.props.FloatProperty(name="Extend", default=0.2, min=0.0, max=1.0, description="Line B is run on straight past its ends by this share of its length, to find mirrors for the ends of line A") - curve_name: bpy.props.StringProperty(name="Curve", maxlen=63, description="A curve object to create or update along the crease on line A's side, parented to the frame; empty draws none") - - def work(self, context): - frame = bpy.data.objects.get(self.frame_name) - if frame is None: - raise Refused(f"no object is named {self.frame_name!r}.") - if self.curve_name and getattr(bpy.data.objects.get(self.curve_name), "type", "CURVE") != "CURVE": - raise Refused(f"{self.curve_name!r} is an object that is not a curve.") - try: - cam = record(context, self.camera_name, self.box) - a, b = core.polyline(self.line_a, "line_a"), core.polyline(self.line_b, "line_b") - except core.ReferenceFitError as refusal: - raise Refused(str(refusal)) from None - F = np.array(frame.matrix_world) - try: - out = core.pair(cam, F, a, b, n=self.samples, extend=self.extend) - except core.ReferenceFitError as refusal: - raise Refused(str(refusal)) from None - if len(out["crease"]) < 2: - raise Refused(f"{out['unmatched']} of {self.samples} points of line A have no mirror on line B: the lines are not a mirrored pair in this frame through this camera.") - crease = np.array(out["crease"]) - cage = core.cage_through(crease) - run = core.crease_run(cage) - report = {**out, "crease": crease.round(5).tolist(), "cage": cage.round(5).tolist(), - "miss": {"line_a": round(core.drawn_off(cam, F, run * [out["side"], 1, 1], a), 3), "line_b": round(core.drawn_off(cam, F, run * [-out["side"], 1, 1], core.extended(b, self.extend)), 3)}, - "curve": None} - if self.curve_name: - obj = bpy.data.objects.get(self.curve_name) - if obj is None: - obj = bpy.data.objects.new(self.curve_name, bpy.data.curves.new(self.curve_name, "CURVE")) - context.scene.collection.objects.link(obj) - obj.data.dimensions = "3D" - obj.data.splines.clear() - spline = obj.data.splines.new("POLY") - spline.points.add(len(crease) - 1) - spline.points.foreach_set("co", np.c_[crease * [out["side"], 1, 1], np.ones(len(crease))].ravel()) - obj.parent, obj.matrix_parent_inverse, obj.matrix_basis = frame, Matrix(), Matrix() - report["curve"] = obj.name - return report - - class BROKKR_REFERENCE_OT_flow_score(PolishOperator): """Score traced lines against the edges a camera sees on the build: how much of each line has a built crease, contour or border running along it""" @@ -259,7 +204,7 @@ 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_lift_pair, BROKKR_REFERENCE_OT_flow_score) +classes = (BROKKR_REFERENCE_OT_solve_camera, BROKKR_REFERENCE_OT_flow_score) def register(): diff --git a/surfaces/blender/brokkr_reference/brokkr_actions.json b/surfaces/blender/brokkr_reference/brokkr_actions.json index a2cc046..9bfe98f 100644 --- a/surfaces/blender/brokkr_reference/brokkr_actions.json +++ b/surfaces/blender/brokkr_reference/brokkr_actions.json @@ -81,75 +81,6 @@ } ] }, - { - "name": "brokkr_reference.lift_pair", - "doc": "Lift two traced lines that are one crease and its mirror image, on a part symmetric about its frame's x = 0, through a camera into the frame. The result is the crease, the cage column whose level-1 crease is built through it, the counts of ambiguous and unmatched points, the points skipped, and how far the built crease draws from each line (docs/reference.md).", - "changesScene": true, - "editModeSafe": false, - "result": "brokkr_mesh_polish_result", - "fields": [ - { - "name": "camera_name", - "type": "string", - "required": true, - "minLength": 1, - "maxLength": 63, - "doc": "the camera object the view is seen through (solve_camera stands one)" - }, - { - "name": "box", - "type": "string", - "maxLength": 120, - "doc": "u0,v0,u1,v1: the camera's frame on the image, in the pixels the lines were traced in; absent is the render's own frame from 0,0" - }, - { - "name": "frame_name", - "type": "string", - "required": true, - "minLength": 1, - "maxLength": 63, - "doc": "an object whose matrix_world is the part's frame; its x = 0 is the mirror plane" - }, - { - "name": "line_a", - "type": "string", - "required": true, - "minLength": 1, - "maxLength": 4000, - "doc": "u,v u,v ... the crease as traced on one side, pixels, v down" - }, - { - "name": "line_b", - "type": "string", - "required": true, - "minLength": 1, - "maxLength": 4000, - "doc": "u,v u,v ... its mirror image as traced on the other side" - }, - { - "name": "samples", - "type": "integer", - "minimum": 2, - "maximum": 200, - "default": 24, - "doc": "points lifted, evenly along line_a" - }, - { - "name": "extend", - "type": "number", - "minimum": 0, - "maximum": 1, - "default": 0.2, - "doc": "line_b is run on straight past its ends by this share of its length, to find mirrors for the ends of line_a" - }, - { - "name": "curve_name", - "type": "string", - "maxLength": 63, - "doc": "a curve object to create or update along the crease on line_a's side, parented to the frame; absent draws none" - } - ] - }, { "name": "brokkr_reference.flow_score", "doc": "Score traced lines against the edges a camera sees on the evaluated build (creases, contours and open borders, unhidden): per line, the share with a built edge running along it (on), the mean distance to one in % of height (off) and the longest unbroken share (run); and the count of edges by kind (docs/reference.md).", diff --git a/surfaces/blender/brokkr_reference/core.py b/surfaces/blender/brokkr_reference/core.py index 41dc110..f5b7fe4 100644 --- a/surfaces/blender/brokkr_reference/core.py +++ b/surfaces/blender/brokkr_reference/core.py @@ -25,15 +25,10 @@ focal length trade against each other (a dolly zoom), and "lens_band" says how f in_frame(cam, pixels, width) image pixels as pixels of the frame blender() renders points, numbers, polyline, polylines the actions' string fields -A line traced on the view is two numbers a point; a crease in the world is three. The third comes from what is -known of the part, in a frame: a 4 x 4 frame-to-world matrix whose x = 0 is the part's mirror plane. +A traced line is pixels; a part's points are given in its frame, a 4 x 4 frame-to-world matrix. - pair(cam, frame, a, b) two traced lines that are one crease and its mirror image: the crease - on_plane(cam, frame, line, point, normal) one traced line lifted onto a plane of the frame 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 - cage_through(targets) the cage column whose built crease passes through the targets - drawn_off(cam, frame, points, line) mean distance, pixels, from a drawn polyline of the frame to a line along(line, segments, height) the flow score: how much of a traced line has a seen edge along it """ from __future__ import annotations @@ -49,9 +44,6 @@ BAND = 1.1 # lens_band: the lenses whose refitted rms is within this multiple o STEP = 0.1 # the band is walked in steps of this in log f FINE = 1.0 # pixels: no mark is placed truer than this, so the band is never judged against a smaller error (exact marks fit every lens of a flat view to 1e-6 px and would call one of them best) PLANAR = 0.12 # marks thinner than this share of their spread (their planarity) are near a plane: a band of theirs that is open at one end of LENS_MM is reported open at both. The geometric mean of 0.041, a panel with relief whose band does open at one end, and 0.36, marks with depth: separation 2.9 each side (tests/test_reference.py) -SKIP = 2.8 # pair: a point that met line b more than once may be given no crossing, at the cost of this many times the crease's median turn. On 189 exact doubled-back strokes 1.25 to 7 lift every one exactly with one point skipped in 15; 1.0 and 8 lift some wrong: the geometric mean, 2.8 each side (read with TURN out of the way, tests/test_reference.py) -TURN = 0.061 # radians: the median turn is never read as less than this, so a crease of straight runs (median turn 0) does not skip for nothing. The geometric mean of 0.0496, under which a cornered crease drops the points between two of its corners, and 0.0749, over which a wrong crossing of a gentle crease (median turn 0.025) is cheaper than its skip: separation 1.23 each side -SHARE = 0.24 # pair refuses a lift that skips more than this share of the points that met line b, and never skips more than this share in a row. The geometric mean of 4 of 23, the most skipped on 11340 noisy doubled-back strokes, and 8 of 24, a scribbled line b: separation 1.38 each side DECIDED = 1.57 # a lens is determined when its band is inside LENS_MM and spans no more than this factor. A band's span is a whole number of STEPs: this is the geometric mean of four steps (1.49, the widest that marks with depth 3 px off read) and five (1.65). An exception to lodur:ruling:deterministic-bound-margin: the two readings are one STEP apart, 1.105, and readings quantised in STEPs have no pair 1.2 apart with nothing between; a host that moves a band by a step fails the span assertion in tests/test_reference.py MODELS = {"upright": (), "rolled": ("roll",), "free": ("roll", "centre"), "square": ("square",)} # what a model solves beyond place, yaw, pitch and focal length; "square" holds the yaw at a quarter turn instead QUARTER = math.pi / 2 @@ -374,16 +366,7 @@ def in_frame(cam, pixels, width): return (np.asarray(pixels, float) - np.array([u0, v0], float)) * k + np.array([0.0, (round(k * (v1 - v0)) - k * (v1 - v0)) / 2]) -# --- traced lines lifted into a frame --------------------------------------------------------------------------------- - -MIRROR = np.diag([-1.0, 1.0, 1.0, 1.0]) # a frame's mirror plane is its x = 0 - - -def matrix(cam): - """The camera as a 3 x 4 projection: pixels = (P @ [x, y, z, 1])[:2] / its third.""" - R, C, f, c = np.asarray(cam["R"], float), np.asarray(cam["C"], float), cam["f"], cam["c"] - K = np.array([[f, 0, -c[0]], [0, -f, -c[1]], [0, 0, -1.0]]) - return K @ np.c_[R, -R @ C] +# --- traced lines and built edges ------------------------------------------------------------------------------------- def resampled(points, n): @@ -394,125 +377,6 @@ def resampled(points, n): return np.stack([np.interp(t, d, p[:, k]) for k in range(p.shape[1])], 1) -def extended(points, by): - """A polyline run on straight past both ends by `by` of its length. Refuses one whose first or last point is - given twice.""" - p = np.asarray(points, float) - length = np.linalg.norm(np.diff(p, axis=0), axis=1).sum() - head, tail = p[0] - p[1], p[-1] - p[-2] - if not (head.any() and tail.any()): - raise ReferenceFitError(f"a line to run on past its ends repeats its {'last' if head.any() else 'first'} point, so that end has no direction (line b of a pair is run on): drop the repeated point") - return np.vstack([p[0] + head / np.linalg.norm(head) * by * length, p, p[-1] + tail / np.linalg.norm(tail) * by * length]) - - -def _bend(X0, X1, X2): - """The turn, in radians, of a crease that runs X0, X1, X2 (three numbers each); a half turn where it stands - still. Plain arithmetic: _smoothest reads it a million times on a long fold.""" - u, v = (X1[0] - X0[0], X1[1] - X0[1], X1[2] - X0[2]), (X2[0] - X1[0], X2[1] - X1[1], X2[2] - X1[2]) - along = math.sqrt((u[0] * u[0] + u[1] * u[1] + u[2] * u[2]) * (v[0] * v[0] + v[1] * v[1] + v[2] * v[2])) - return math.acos(max(-1.0, min(1.0, (u[0] * v[0] + u[1] * v[1] + u[2] * v[2]) / along))) if along > 1e-24 else math.pi - - -def _smoothest(candidates, skip=None, run=0): - """One candidate per point, chosen together: the choice whose curve turns least in all (the sum of _bend over - every three taken points in a row), found by dynamic programming over pairs of neighbouring taken points, so - no point is settled before the points after it are read. With `skip` (radians) a point that has more than one - candidate may take none, at that cost, up to `run` such points in a row: the turn is then read across the gap, - over the points that are taken, so a skip cannot hide a turn. Returns the index taken at each point, None where it is skipped; ties go to the - earlier candidate and to the choice reached first.""" - m = len(candidates) - C = [[tuple(float(v) for v in X) for X in options] for options in candidates] - free = [skip is not None and len(options) > 1 for options in C] - - best = {} # (t, k, the taken point before it, its candidate) -> (cost, the state before) - for t in range(min(m, run + 1)): - for k in range(len(C[t])): - best[t, k, -1, -1] = (skip * t if t else 0.0, None) - if not free[t]: - break - end, least = None, math.inf - for t in range(m): - for state in [s for s in best if s[0] == t]: - cost, _ = best[state] - _, k, tp, kp = state - if m - 1 - t <= run and all(free[t + 1:]) and cost + (skip or 0.0) * (m - 1 - t) < least: - end, least = state, cost + (skip or 0.0) * (m - 1 - t) - for t2 in range(t + 1, min(m, t + run + 2)): - for k2, X in enumerate(C[t2]): - total = cost + (skip * (t2 - t - 1) if t2 > t + 1 else 0.0) + (_bend(C[tp][kp], C[t][k], X) if tp >= 0 else 0.0) - if (t2, k2, t, k) not in best or total < best[t2, k2, t, k][0]: - best[t2, k2, t, k] = (total, state) - if not free[t2]: - break - taken = [None] * m - while end is not None: - taken[end[0]] = end[1] - end = best[end][1] - return taken - - -def pair(cam, frame, a, b, n=24, extend=0.2): - """The crease that traced lines `a` and `b` (pixels) are the two mirror images of, on a part symmetric about its - frame's x = 0. A point of `a` and its mirror on `b` lie on a line through the vanishing point of the frame's x - axis; the pair is triangulated as one point seen by the camera and by the camera's mirror image, so each lifted - point draws back onto both lines exactly. `b` is run on past its ends by `extend` of its length to find mirrors - for the ends of `a`. - - Returns {"crease": [[x, y, z], ...] in the frame, x >= 0, in the order of `a`; "side": the side of the frame - `a` is on, +1 or -1; "unmatched": points of `a` whose line to the vanishing point never meets `b`, left out; - "ambiguous": points whose line meets `b` more than once; "skipped": the points of `a` (their indices among - its n) that met `b` more than once and were given no crossing, left out}. Every crossing of such a line - triangulates to a point that draws back onto both lines, so the drawing cannot say which is meant; the crease - can: the crossings are chosen together, as the choice whose crease turns least in all (_smoothest). That is - the true crease wherever every point's true crossing is among its crossings. Where one is not (the end of `a` - mirrors the very end of `b`, and only the doubled strokes are met) every crossing of that point kinks the - crease, and the point is skipped instead: a skip costs SKIP times the crease's median turn (the median of the - choice with no skips, never under TURN), and only a point with a choice can be skipped. A lift that skips more - than SHARE of the points it had crossings for is refused, and the choice never skips more than that in a row. - - The lift is as sure as the frame's turn to the camera: seen nearly along the mirror plane the two sight lines - are nearly parallel, and a degree of turn moves the crease a long way in depth.""" - P = matrix(cam) - F = np.asarray(frame, float) - P1, P2 = P @ F, P @ F @ MIRROR - vp = P1 @ np.array([1.0, 0, 0, 0]) - A, B = resampled(a, n), extended(b, extend) - found = [] - for q in A: - d = vp[:2] - vp[2] * q # toward the vanishing point, wherever it is (at infinity too) - s = (B - q) @ (np.array([-d[1], d[0]]) / np.linalg.norm(d)) - lifts = [] - for k in np.nonzero((s[:-1] < 0) != (s[1:] < 0))[0]: - m = B[k] + s[k] / (s[k] - s[k + 1]) * (B[k + 1] - B[k]) - M = np.array([q[0] * P1[2] - P1[0], q[1] * P1[2] - P1[1], m[0] * P2[2] - P2[0], m[1] * P2[2] - P2[1]]) - X = np.linalg.svd(M)[2][-1] - lifts.append(X[:3] / X[3]) - found.append(lifts) - fold = lambda X: np.array([abs(X[0]), X[1], X[2]]) # noqa: E731 - at = [i for i, lifts in enumerate(found) if lifts] - folded = [[fold(X) for X in found[i]] for i in at] - taken = _smoothest(folded) - if any(len(options) > 1 for options in folded) and len(at) > 2: - whole = [folded[t][k] for t, k in enumerate(taken)] - usual = float(np.median([_bend(*whole[t - 2:t + 1]) for t in range(2, len(whole))])) - taken = _smoothest(folded, SKIP * max(usual, TURN), int(SHARE * len(at))) - skipped = [i for i, k in zip(at, taken) if k is None] - if len(skipped) > SHARE * len(at): - raise ReferenceFitError(f"line b doubles back and {len(skipped)} of the {len(at)} points of line a that meet it have no crossing that fits the crease (points {skipped}; over {SHARE:g} of them is refused). Draw line b as one stroke that does not run beside itself") - lifted = [found[i][k] for i, k in zip(at, taken) if k is not None] - return {"crease": [[float(v) for v in fold(X)] for X in lifted], "side": 1 if sum(np.sign(X[0]) for X in lifted) >= 0 else -1, - "ambiguous": sum(1 for lifts in found if len(lifts) > 1), "skipped": skipped, "unmatched": sum(1 for lifts in found if not lifts)} - - -def on_plane(cam, frame, line, point, normal, n=24): - """A traced line (pixels) lifted onto the plane of the frame through `point` with `normal`: [[x, y, z], ...] in - the frame.""" - F = np.asarray(frame, float) - inv = np.linalg.inv(F) - p0, nw = F[:3, :3] @ np.asarray(point, float) + F[:3, 3], np.asarray(normal, float) @ inv[:3, :3] - return [[float(v) for v in inv[:3, :3] @ lift(cam, q, p0, nw) + inv[:3, 3]] for q in resampled(line, n)] - - def seen(cam, frame, points): """Pixels of points of a frame.""" F = np.asarray(frame, float) @@ -535,15 +399,6 @@ def crease_run(points): return out -def cage_through(targets, rounds=30): - """The cage column whose built crease (crease_run) passes through `targets` at its own points.""" - t = np.asarray(targets, float) - c = t.copy() - for _ in range(rounds): - c += t - crease_run(c)[0::2] - return c - - def _off(points, line): """Per point, its distance to a polyline.""" p, q = np.asarray(points, float), np.asarray(line, float) @@ -552,11 +407,6 @@ def _off(points, line): return np.linalg.norm(a + t[:, :, None] * d - p[:, None], axis=2).min(1) -def drawn_off(cam, frame, points, line, n=200): - """Mean distance, pixels, from where the camera draws a polyline of the frame to a traced line.""" - return float(_off(resampled(seen(cam, frame, points), n), line).mean()) - - def along(line, segments, height, near=0.01, turn=20.0, cap=0.05): """The flow score: how much of a traced line (pixels) has a seen edge running along it. `segments` are [u0, v0, u1, v1] in the same pixels, `height` the figure's height there. Per point of the line: the distance to diff --git a/surfaces/blender/docs/reference.md b/surfaces/blender/docs/reference.md index 9ae88d5..93bdc69 100644 --- a/surfaces/blender/docs/reference.md +++ b/surfaces/blender/docs/reference.md @@ -1,18 +1,18 @@ -# Reference views: the camera a picture was drawn through, and lines lifted through it +# Reference views: the camera a picture was drawn through, and traced lines scored against the build `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 world is known and the pixel where the image draws each, `solve_camera` finds that camera, so that a render through -it lays over the image pixel for pixel and a line traced on the image can be lifted into the scene. +it lays over the image pixel for pixel and a line traced on the image can be scored against the build's edges. 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 -three operators agents may run (`solve_camera`, `lift_pair`, `flow_score`); the arithmetic is `core.py` (numpy only, tested without Blender), which a script may +two operators agents may run (`solve_camera`, `flow_score`); 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, creases and scores. The images, the marks on them, traces and masks belong to whoever +The package takes points and traced lines and gives cameras and scores. The images, the marks on them, traces and masks belong to whoever made them; nothing here opens an image. ## Conventions @@ -139,72 +139,6 @@ place, not about a lift made in the view's own frame. pseudo-Huber loss; `median` beside it shows when a few points carry the error. A solve with `auto` on 13 points takes several seconds (three models, each from 16 starts, plus a left-out solve per point per model). -## lift_pair: a crease from two traced lines - -A line traced on the view is two numbers a point; a crease in the scene is three. `lift_pair` takes the third from -symmetry: two traced lines that are one crease and its mirror image, on a part symmetric about the x = 0 plane of -its frame. A point of one line and its mirror on the other lie on a line through the vanishing point of the frame's -x axis; the pair is triangulated as one point seen by the camera and by the camera's mirror image. - -| field | | -| --- | --- | -| `camera_name` | the camera object the view is seen through; `solve_camera` stands one | -| `box` | `u0,v0,u1,v1`, the camera's frame on the image, in the pixels the lines were traced in; absent is the render's own frame | -| `frame_name` | an object whose `matrix_world` is the part's frame; its x = 0 is the mirror plane | -| `line_a`, `line_b` | `u,v u,v ...`, the crease as traced on one side and its mirror image on the other | -| `samples` | points lifted, evenly along `line_a` (default 24) | -| `extend` | `line_b` is run on straight past its ends by this share of its length (default 0.2), to find mirrors for the ends of `line_a` | -| `curve_name` | a poly curve to create or update along the crease on `line_a`'s side, parented to the frame; absent draws none | - -The report: `crease` (`[[x, y, z], ...]` in the frame, x >= 0, in the order of `line_a`), `side` (+1 or -1: the side -of the frame `line_a` is on), `unmatched` (points of `line_a` whose line to the vanishing point never meets -`line_b`; they are left out), `ambiguous` (points whose line meets `line_b` more than once), `skipped`, `cage`, `miss` and -`curve`. The camera is read back from the object (`core.camera_of`): a perspective camera with a horizontal sensor -fit. The curve is for the eye; the report is the truth. - -Every lifted point draws back onto both traced lines exactly, so the drawing cannot tell two crossings apart. Where -a line folds back, the crease can: the crossings of all the points are chosen together, as the choice whose lifted -crease turns least in all (the sum of its turns at each point, by dynamic programming), so no point is settled -before the points after it are read. Wherever each point's true crossing is among its crossings, that is the true -crease. Where it is not (most often the last point of `line_a`, whose mirror is the very end of `line_b`, meeting -only the doubled strokes) every crossing of that point kinks the crease, and the point is given none: it is left -out of `crease` and named in `skipped`, the indices of such points among the `samples` of `line_a`. Only a point -with more than one crossing can be skipped. A skip costs 2.8 (`core.SKIP`) times the crease's median turn, and the -turn is read across the gap, so a skip cannot hide a turn. The median is never read as less than 0.061 radians -(`core.TURN`), so a crease of straight runs and corners, whose median turn is nothing, lifts whole. A lift that -skips more than 0.24 (`core.SHARE`) of the points that met `line_b` is refused, and no more than that are skipped -in a row: draw `line_b` as one stroke. - -On 189 exact strokes of `line_b` doubled back beside themselves (a tenth to nine tenths of the crease, three -views) every one lifts exactly, none refused; 15, all on the view 10 degrees above the crease, skip their last -point. On hand-traced lines (the same folds on traces 0.25 to 3 px off: twelve jittered points, thirty, and a slow -wobble; 11340 strokes) none is refused, 1824 skip a point or more, at most 4 of 23, and 475 lift more than 5 mm -worse than the same trace unfolded, 131 of them more than 20 mm: 21 of the 3780 wobbled, 130 of the twelve-point -and 324 of the thirty-point, where a 1 px tremor already stands in for a wrong crossing. A trace's own wobble -turns the crease as much as a wrong crossing does, and no reading of the lift tells them apart: `skipped` says -what was left out, not that the rest is right. A scribbled `line_b` can lift 0.07 m off with nothing skipped and -takes seconds. A lift with no ambiguous -point has no choice anywhere and is never refused. A line whose first or last point is given twice is refused: that end of -`line_b` has no direction to run on in. - -`cage` is the column of cage points whose hard crease, as Blender's Subdivision modifier builds it at one level, -passes through the lifted crease at the cage's own points (`core.cage_through`, `core.crease_run`). The built -crease is not the cage: with Limit Surface on (the modifier's default, and what kitbash shells use) a cage point is -built at (1, 4, 1) / 6 of itself and its neighbours along the column, the ends staying; a cage laid on the lifted -points would be built inside every bend. With Limit Surface off the weights differ and `cage` is not that -column. `miss` is the mean distance in pixels from where the camera draws that built crease to each traced line -(`line_b` run on by `extend`). - -How far to trust it: the lift is as sure as the frame and as the angle between the line of sight and the mirror -plane. Seen nearly along the mirror plane the two sight lines are nearly parallel, and a degree of the frame's turn -moves the crease a long way in depth. On twelve-point traces 1.5 px off, three views of a 2 m crease lifted within -0.6% of its length. On the Orchid's concept render (a hand trace of the upper petals' inboard edges, eight hand -marks, the frame fitted to a generated mesh's own mirror plane, 34 degrees between sight and mirror plane) the -lifted creases stood a mean 0.9% and 1.7% of the hull's length from that mesh, 4% at worst, at a petal's tip, and -moved 0.6% between the ends of the lens band. A wrong frame is not reported: the lift cannot see it. - -One traced line with no mirror is lifted onto a plane of the frame by `core.on_plane` (no action). - ## flow_score: traced lines against built edges `flow_score` says how much of each traced line the build already carries as an edge. It reads the evaluated meshes @@ -215,7 +149,8 @@ by its winding does not count as seen, so a cage with flipped normals shows no c | field | | | --- | --- | -| `camera_name`, `box` | as for `lift_pair` | +| `camera_name` | the camera object the view is seen through (`solve_camera` stands one) | +| `box` | `u0,v0,u1,v1`: the camera's frame on the image, in the pixels the lines were traced in; absent is the render's own frame from 0,0 | | `height` | the figure's height in the box's pixels; an edge within 1% of it is near. 0 (default) is the box's height | | `lines` | `tag: u,v u,v ...; tag: u,v u,v ...` | | `objects` | `name; name; ...`, the meshes whose edges are read; absent is every mesh the render shows. Everything the scene shows hides | @@ -252,14 +187,13 @@ cam = core.solve(world, pixels, box, model="auto") # dicts by name; the u_v = core.project(cam, points) # where it draws world points 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 -out = core.pair(cam, frame, line_a, line_b) # crease, side, ambiguous, unmatched, skipped -cage = core.cage_through(out["crease"]) # the column whose built crease passes through it +run = core.crease_run(column) # the hard crease Blender builds from a cage column 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 ``` 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_lift.py` -(`crease_run` against Blender's own subdivision, a crease lifted through `lift_pair`, a box and a folded sheet -scored by `flow_score`; `reference_lift.result.json` is its last run). +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). diff --git a/surfaces/blender/tests/live/reference_lift.py b/surfaces/blender/tests/live/reference_flow.py similarity index 78% rename from surfaces/blender/tests/live/reference_lift.py rename to surfaces/blender/tests/live/reference_flow.py index 3798e5e..ad03265 100644 --- a/surfaces/blender/tests/live/reference_lift.py +++ b/surfaces/blender/tests/live/reference_flow.py @@ -1,10 +1,8 @@ -"""Live proof, in a background Blender, of brokkr_reference.lift_pair and flow_score through run_intent, and of -core.crease_run against Blender's own subdivision. +"""Live proof, in a background Blender, of brokkr_reference.flow_score through run_intent, and of core.crease_run +against Blender's own subdivision. crease_run a strip of quads with its middle column creased hard, subdivided once by Blender: the built crease is where core.crease_run says (the numbers printed as BUILT are test_reference.py's fixture) - lift_pair a crease of a turned frame and its mirror image, drawn by Blender's own projection through a known - camera, lifted back; again with the lines in an image's pixels through `box`; the curve it draws flow_score a box and, beside it, a folded sheet seen from behind: the box's front edge scores 1, its back edge 0 (it faces away, so it is never read), and the sheet's fold 0, since neither of its faces is toward the camera (mutant N5, which counts such creases, reads 1 and four creases). Then the box alone at @@ -18,7 +16,7 @@ core.crease_run against Blender's own subdivision. Cameras 30 and 144 diagonals off still read every edge (O5, HIDE at 1e-6, loses four contours at 144) - blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/reference_lift.py -- + blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/reference_flow.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 @@ -64,7 +62,7 @@ for module in ("brokkr_mesh_polish", "brokkr_reference"): from brokkr_reference import core # noqa: E402 target = bt.BrokkrBlenderTarget(bpy) -target.configure_action_dirs("", tempfile.mkdtemp(prefix="brokkr-reference-lift-live-")) +target.configure_action_dirs("", tempfile.mkdtemp(prefix="brokkr-reference-flow-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]]} @@ -105,7 +103,7 @@ def traced(camera, points, scale=1.0, corner=(0.0, 0.0)): try: - check("host file admitted", not R["hostErrors"] and {"brokkr_reference.lift_pair", "brokkr_reference.flow_score"} <= set(R["hostRows"]), R["hostRows"]) + check("host file admitted", not R["hostErrors"] and "brokkr_reference.flow_score" in R["hostRows"], R["hostRows"]) scene = bpy.context.scene scene.render.resolution_x, scene.render.resolution_y, scene.render.resolution_percentage = WIDTH, HEIGHT, 100 @@ -131,49 +129,13 @@ try: strip.hide_render = True strip.hide_viewport = True - # --- lift_pair: a crease of a turned frame and its mirror image, drawn by Blender, lifted back --------------------- + # --- the camera every flow_score check below is seen through ------------------------------------------------------- truth = bpy.data.objects.new("Truth", bpy.data.cameras.new("Truth")) scene.collection.objects.link(truth) truth.data.lens, truth.data.sensor_width, truth.data.sensor_fit = 50.0, 36.0, "HORIZONTAL" truth.matrix_world = Matrix.Translation((-6.5, -8.0, 4.6)) @ Euler((1.2, 0.03, -0.72), "XYZ").to_matrix().to_4x4() - hull = bpy.data.objects.new("Hull", None) - scene.collection.objects.link(hull) - hull.matrix_world = Matrix.Translation((0.3, -0.2, 0.1)) @ Euler((0.0, 0.0, 0.2618), "XYZ").to_matrix().to_4x4() bpy.context.view_layer.update() - t = np.linspace(0, 1, 40) - crease = np.stack([0.4 + 0.2 * np.sin(2.5 * t), -1.0 + 2.0 * t, 0.5 + 0.3 * t * t], 1) - F = np.array(hull.matrix_world) - world = lambda side: (crease * [side, 1, 1]) @ F[:3, :3].T + F[:3, 3] # noqa: E731 - before = sorted(o.name for o in bpy.data.objects) - receipt, lifted = send("brokkr_reference.lift_pair", camera_name="Truth", frame_name="Hull", line_a=traced(truth, world(-1)), line_b=traced(truth, world(1))) - off = lifted and float(core._off(np.array(lifted["crease"]), crease).max()) - check("lift_pair: accepted, 24 points on the crease within 1 mm, on the frame's -x side, none ambiguous, skipped or unmatched, no object made", - receipt["status"] == "accepted" and len(lifted["crease"]) == 24 and off < 1e-3 and lifted["side"] == -1 and lifted["ambiguous"] == 0 and lifted["skipped"] == [] and lifted["unmatched"] == 0 - and lifted["curve"] is None and sorted(o.name for o in bpy.data.objects) == before, [receipt["message"], off]) - through = lifted and float(np.abs(core.crease_run(lifted["cage"])[0::2] - np.array(lifted["crease"])).max()) - check("the cage column's built crease passes through the lifted crease, and draws within 1 px of both lines", - lifted and through < 1e-4 and max(lifted["miss"].values()) < 1.0, [through, lifted and lifted["miss"]]) - R["lift"] = {"off": off, "through": through, "miss": lifted and lifted["miss"]} - box = "100,50,1700,1250" # the same view as an image twice the frame's size, its corner at 100, 50 - receipt, boxed = send("brokkr_reference.lift_pair", camera_name="Truth", box=box, frame_name="Hull", line_a=traced(truth, world(1), 2.0, (100.0, 50.0)), - line_b=traced(truth, world(-1), 2.0, (100.0, 50.0)), samples=12, curve_name="Crease") - curve = bpy.data.objects.get("Crease") - drawn_at = curve and np.array([core.project(core.camera_of({"matrix_world": [list(r) for r in truth.matrix_world], "lens": 50.0, "shift_x": 0.0, "shift_y": 0.0, - "resolution": [WIDTH, HEIGHT]}), [curve.matrix_world @ Vector(p.co[:3])])[0] for p in curve.data.splines[0].points]) - on_line = curve and float(core._off(drawn_at, core.polyline(traced(truth, world(1)), "a")).max()) - check("lift_pair through a box, with curve_name: 12 points on the +x side, a poly curve parented to the frame that the camera draws on line A", - receipt["status"] == "accepted" and len(boxed["crease"]) == 12 and boxed["side"] == 1 and float(core._off(np.array(boxed["crease"]), crease).max()) < 1e-3 - and curve is not None and curve.type == "CURVE" and curve.parent == hull and len(curve.data.splines[0].points) == 12 and on_line < 0.05, [receipt["message"], on_line]) - receipt, _ = send("brokkr_reference.lift_pair", camera_name="Truth", box=box, frame_name="Hull", line_a=traced(truth, world(1), 2.0, (100.0, 50.0)), - line_b=traced(truth, world(-1), 2.0, (100.0, 50.0)), curve_name="Crease") - check("a second run updates the one curve: 24 points, one spline", receipt["status"] == "accepted" and [o.name for o in bpy.data.objects if o.type == "CURVE"] == ["Crease"] - and len(curve.data.splines) == 1 and len(curve.data.splines[0].points) == 24, receipt["message"]) - for fields, said in (({"frame_name": "Nobody"}, "no object is named"), ({"camera_name": "Hull"}, "not a camera"), ({"line_a": "1,2"}, "no length"), - ({"curve_name": "Truth"}, "not a curve"), ({"line_b": "5000,5000 5010,5000"}, "no mirror"), - ({"line_b": " ".join(traced(truth, world(-1)).split()[:1] * 2 + traced(truth, world(-1)).split()[1:])}, "repeats its first point")): - receipt, _ = send("brokkr_reference.lift_pair", **{"camera_name": "Truth", "frame_name": "Hull", "line_a": traced(truth, world(1)), "line_b": traced(truth, world(-1)), **fields}) - check(f"lift_pair refuses {next(iter(fields))}: failed, saying '{said}'", receipt["status"] == "failed" and said in receipt["message"], receipt["message"]) # --- flow_score: the edges the camera sees on a box and on a folded sheet seen from behind ------------------------ bm = bmesh.new() @@ -216,7 +178,7 @@ try: """A box of half-width `half` standing on z = 0, alone or over a square ground `ground` across, and a camera: the first box's, scaled with the box, or one `far` box diagonals off with the lens grown to match. Returns the camera, the box's front edge, and its line as the camera draws it.""" - for obj in [o for o in bpy.data.objects if o.type in ("MESH", "CURVE")]: + for obj in [o for o in bpy.data.objects if o.type == "MESH"]: bpy.data.objects.remove(obj) name = f"Staged {half:g} {ground:g} {far:g}" staged = bpy.data.objects.new(name, bpy.data.cameras.new(name)) diff --git a/surfaces/blender/tests/live/reference_lift.result.json b/surfaces/blender/tests/live/reference_flow.result.json similarity index 100% rename from surfaces/blender/tests/live/reference_lift.result.json rename to surfaces/blender/tests/live/reference_flow.result.json diff --git a/surfaces/blender/tests/test_reference.py b/surfaces/blender/tests/test_reference.py index 2c7972a..56540c8 100644 --- a/surfaces/blender/tests/test_reference.py +++ b/surfaces/blender/tests/test_reference.py @@ -27,7 +27,6 @@ import re import sys import types import unittest -import unittest.mock from pathlib import Path SURFACE = Path(__file__).resolve().parents[1] @@ -221,15 +220,15 @@ class SolveTests(unittest.TestCase): core.lm = lambda *args, **kwargs: solved.append(1) or lm(*args, **kwargs) self.addCleanup(setattr, core, "lm", lm) plane = np.c_[self.points[:, :2], np.zeros(13)] - on_plane = dict(zip(NAMES, plane.tolist())), dict(zip(NAMES, core.project(self.oblique, plane).tolist())) - square_on = on_plane[0], dict(zip(NAMES, core.project(camera(plane, 35, 90, 50), plane).tolist())) + in_plane = dict(zip(NAMES, plane.tolist())), dict(zip(NAMES, core.project(self.oblique, plane).tolist())) + square_on = in_plane[0], dict(zip(NAMES, core.project(camera(plane, 35, 90, 50), plane).tolist())) line = dict(zip(NAMES, np.outer(np.arange(13.0), [1.0, 2.0, 0.5]).tolist())) cases = (((self.world, {k: [500.0, 400.0] for k in NAMES}), {}, "1 different pixels"), (({k: [1.0, 2.0, 3.0] for k in NAMES}, self.pixels), {}, "1 different world points"), ((self.world, {**self.pixels, **{k: self.pixels["p0"] for k in NAMES[:9]}}), {}, "5 different pixels are marked; six are needed ('p0' and 'p1'"), ((self.world, {k: [100.0 + 10 * i, 200.0 + 5 * i] for i, k in enumerate(NAMES)}), {}, "pixels lie on one line"), ((line, self.pixels), {}, "world points lie on one line"), - (on_plane, {"model": "free"}, "one plane, which does not decide the centre"), (on_plane, {"model": "free", "lens": 50.0}, "does not decide the centre")) + (in_plane, {"model": "free"}, "one plane, which does not decide the centre"), (in_plane, {"model": "free", "lens": 50.0}, "does not decide the centre")) for args, kwargs, said in cases: with self.assertRaises(core.ReferenceFitError) as caught: core.solve(*args, BOX, **kwargs) @@ -341,221 +340,17 @@ class SolveTests(unittest.TestCase): self.assertIn(said, str(refusal)) -def crease(n=2000): - """A crease of a part in its frame, x > 0: a bowed line 2 m long, as dense as a line drawn with a ruler.""" - t = np.linspace(0, 1, n) - return np.stack([0.4 + 0.2 * np.sin(2.5 * t), -1.0 + 2.0 * t, 0.5 + 0.3 * t * t], 1) - - -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 -VIEWS = ((35, 20, 50), (-60, 40, 85), (150, 10, 35)) - - @unittest.skipIf(np is None, "numpy") -class LiftTests(unittest.TestCase): - """Traced lines lifted into a frame, the cage through a crease, and the flow score. Mutants, each run once: - N1 the mirror camera without MIRROR test_a_mirrored_pair_lifts_back_to_its_crease - N2 the first crossing kept test_a_folded_line_takes_the_smoothest_crossing, and the two after it - K1 no point skipped test_strokes_doubled_back_lift_exactly_with_a_point_skipped - K2, K3 SKIP 1.0 and 8 the same, where TURN is set to 0 - K5 a skip's turn not read across the gap the same - K4 a point with one crossing may be skipped test_a_cornered_crease_lifts_whole - T1, T2 TURN 0.04 and 0.09 the same; the doubled strokes - R1, R2 SHARE 0.15 and 0.4 test_a_scribbled_line_is_refused_by_its_share_of_skips - S1 a crease that stands still costs no turn test_a_crease_that_stands_still_is_a_half_turn - H1 a crossing snapped to line b's point before it test_a_hand_traced_pair_lifts_within_a_bound +class FlowTests(unittest.TestCase): + """The crease Blender builds from a cage column, the flow score and the line parsers. Mutants, each run once: N3 crease_run without the limit step test_crease_run_is_one_level_of_subdivision N3b its first step weighs (1, 4, 1) / 6 the same N4 along without the direction test test_along_scores_edges_that_run_with_the_line - N6 cage_through stops after one round test_the_cage_through_a_crease_builds_through_it - N5 (back-facing creases counted) is claimed by tests/live/reference_lift.py.""" - - @classmethod - def setUpClass(cls): - cls.truth = crease() - F = np.array(FRAME) - both = np.vstack([cls.truth, cls.truth * [-1, 1, 1]]) @ F[:3, :3].T + F[:3, 3] - cls.cams = [camera(both, *view) for view in VIEWS] - - def traced(self, cam, side=1): - return core.seen(cam, FRAME, self.truth * [side, 1, 1]) - - def off(self, lifted): - """How far lifted points stand from the true crease, metres: the worst.""" - return float(core._off(np.array(lifted), self.truth).max()) - - def test_a_mirrored_pair_lifts_back_to_its_crease(self): - """pair-exact, N1: with nothing mirrored both sight lines are one camera's and the lift is nowhere: 6.0 m off - at the first view and on the wrong side at the second. Shipped reads 1e-15 m, float noise; 1e-6 m is the - cut's tolerance round the truth.""" - for cam, flipped in zip(self.cams, (1, -1, 1)): - out = core.pair(cam, FRAME, self.traced(cam, flipped), self.traced(cam, -flipped)) - self.assertEqual((len(out["crease"]), out["side"], out["ambiguous"], out["unmatched"]), (24, flipped, 0, 0)) - self.assertLess(self.off(out["crease"]), 1e-6) - for side, line in ((out["side"], self.traced(cam, flipped)), (-out["side"], self.traced(cam, -flipped))): - self.assertLess(float(core._off(core.seen(cam, FRAME, np.array(out["crease"]) * [side, 1, 1]), line).max()), 1e-6) - - def test_a_hand_traced_pair_lifts_within_a_bound(self): - """pair-exact at 1.5 px, H1: twelve points a line, each 1.5 px off (a hand's trace). The worst of three views - reads 0.0122 m, 0.6% of the crease's 2.05 m; with each crossing snapped to the traced point before it - instead of taken where the lines cross (H1) 0.277 m. The bound is their geometric mean, separation 4.8 - each side.""" - r = np.random.default_rng(11) - worst = 0.0 - for cam in self.cams: - a, b = (core.resampled(self.traced(cam, side), 12) + r.normal(0, 1.5, (12, 2)) for side in (1, -1)) - out = core.pair(cam, FRAME, a, b) - self.assertGreaterEqual(len(out["crease"]), 20) - worst = max(worst, self.off(out["crease"])) - self.assertLess(worst, 0.058) - - def test_a_folded_line_takes_the_smoothest_crossing(self): - """pair-folded-line, N2: line b starts with a stroke that doubles back beside itself, so the first points of - `a` meet it twice or more. Shipped reads 8.9e-16 m off the true crease, the first crossing kept (N2) - 0.00892 m: the bound is their geometric mean, separation 3.2e6 each side.""" - cam = self.cams[0] - a, b = self.traced(cam)[100:], self.traced(cam, -1) - d = b[600] - b[0] - hook = b[600:0:-40] + 0.04 * np.array([-d[1], d[0]]) - out = core.pair(cam, FRAME, a, np.vstack([hook, b]), extend=0.02) - self.assertGreater(out["ambiguous"], 3) - self.assertEqual((out["unmatched"], len(out["crease"])), (0, 24)) - self.assertLess(self.off(out["crease"]), 2.8e-9) - - def test_a_fold_at_the_far_end_is_settled(self): - """pair-folded-line: line b's last two fifths are drawn three times over, out, back and out again beside - themselves, so the last points of `a` meet it more than once and have no lifted point after them. Shipped - reads 7.2e-16 m and the first crossing kept (N2) 0.0302 m: the bound is their geometric mean, separation - 6.5e6 each side.""" - cam = self.cams[0] - b = self.traced(cam, -1) - v = b[-1] - b[1199] - d = np.array([-v[1], v[0]]) / np.linalg.norm(v) * 0.06 * np.ptp(b, axis=0).max() - out = core.pair(cam, FRAME, self.traced(cam), np.vstack([b[:1199], b[1199:] + d, b[:1198:-1] + 2 * d, b[1199:]]), extend=0.0) - self.assertEqual((out["ambiguous"], out["unmatched"], len(out["crease"])), (10, 2, 22)) - self.assertLess(self.off(out["crease"]), 4.7e-9) - - def doubled(self): - """189 strokes of line b doubled back beside themselves: seven stretches of the crease, three offsets, the - true stroke first, between or last, three views.""" - n = len(self.truth) - for view, cam in enumerate(self.cams): - a, b = self.traced(cam), self.traced(cam, -1) - for start, end in ((0.1, 0.3), (0.3, 0.5), (0.3, 0.7), (0.1, 0.9), (0.5, 0.8), (0.0, 0.4), (0.6, 1.0)): - i0, i1 = int(start * (n - 1)), int(end * (n - 1)) - v = b[i1] - b[i0] - out, back = b[i0:i1 + 1], b[i1:i0 - 1 if i0 else None:-1] - for offset in (0.01, 0.03, 0.06): - d = np.array([-v[1], v[0]]) / np.linalg.norm(v) * offset * np.ptp(b, axis=0).max() - for which, line in (("first", np.vstack([b[:i1 + 1], back + d, out + 2 * d, b[i1 + 1:]])), ("last", np.vstack([b[:i0], out + d, back + 2 * d, b[i0:]])), - ("between", np.vstack([b[:i0], out + d, back + 2 * d, out, b[i1 + 1:]]))): - yield (view, start, end, offset, which), cam, a, line - - def test_strokes_doubled_back_lift_exactly_with_a_point_skipped(self): - """pair-global-choice, aetheria-release:ruling:lift-skips-points-not-strokes: `extend` 0. The crossings are - chosen together, so every stroke whose points all have their true crossing lifts exactly with nothing - skipped: 174. In the other 15, all on the view 10 degrees above the crease, the last point of `a` meets - only the doubled strokes (its mirror is line b's very end); that point is skipped, it alone, and the other - 23 lift exactly: worst of the 189, 9.7e-16 m, none refused. Read twice: as shipped, where the crease's - median turn (0.025) is under TURN and a skip costs SKIP x TURN, 6.8 medians; and with TURN at 0, where it - costs SKIP medians and SKIP's own readings show: 1.25 to 7 read the same, 1.0 (K2) skips points that had - their true crossing and lifts strokes wrong, 0.008 m off, 8 (K3) keeps a wrong crossing, 0.018 m off: 2.8 - is the geometric mean, 2.8 each side. As shipped, TURN up to 0.0749 reads the same and 0.09 (T2) lifts - strokes wrong, 0.018 m off. K1 (no skip) lifts the 15 wrong; K5 (the turn not read across a skipped - point) skips where nothing is wrong. The lift bound is the folded-line test's.""" - for turn in (core.TURN, 0.0): - with unittest.mock.patch.object(core, "TURN", turn): - wrong, skipped = [], [] - for key, cam, a, line in self.doubled(): - lifted = core.pair(cam, FRAME, a, line, extend=0.0) - if self.off(lifted["crease"]) > 2.8e-9 or len(lifted["crease"]) + len(lifted["skipped"]) + lifted["unmatched"] != 24: - wrong.append((key, self.off(lifted["crease"]), lifted["skipped"])) - if lifted["skipped"]: - skipped.append((key[0], lifted["skipped"])) - self.assertEqual(wrong, [], turn) - self.assertEqual(skipped, [(2, [23])] * 15, turn) - - CORNERS = [[0.4, -1.0, 0.5], [0.7, -0.35, 0.55], [0.35, 0.15, 0.75], [0.6, 0.6, 0.7], [0.4, 1.0, 0.8]] - - def test_a_cornered_crease_lifts_whole(self): - """kink-refuses-exact-cornered-crease: a crease of four straight runs, corners of 1.0 to 1.2 radians, traced - exactly, no fold. Its median turn is 0 (1.5e-8), and at the first view three points between two corners - meet line b twice. All 24 lift at each view, 1.2e-15 m off, nothing skipped: the median is read as TURN. - With TURN under 0.0496 (T1 0.04) the three are skipped, which saves the 0.35 radians of the stretch - between the corners; K4 (a point with one crossing may be skipped) skips here too.""" - V = np.array(self.CORNERS) - truth = np.vstack([np.linspace(V[i], V[i + 1], 500, endpoint=False) for i in range(4)] + [V[-1:]]) - for cam, ambiguous in zip(self.cams, (3, 0, 0)): - out = core.pair(cam, FRAME, core.seen(cam, FRAME, truth), core.seen(cam, FRAME, truth * [-1, 1, 1])) - self.assertEqual((len(out["crease"]), out["ambiguous"], out["skipped"], out["unmatched"]), (24, ambiguous, [], 0)) - self.assertLess(float(core._off(np.array(out["crease"]), truth).max()), 1e-6) - - def test_a_scribbled_line_is_refused_by_its_share_of_skips(self): - """SHARE: line b scribbled over (six loops, 12% of its extent across) on the second view. Over the middle - two fifths 4 of the 23 points that meet it are skipped, 0.174, and the lift is given, with the four named; - over the whole line 8 of 24, 0.333, and it is refused. 4 of 23 is also the most skipped in 11340 noisy - doubled-back strokes (cut_report h4). SHARE 0.24 is the geometric mean, 1.38 each side: R1 (0.15) refuses - the first, R2 (0.4) gives the second. The share says how much of the stroke was left out, not that what - was kept is right: the first lift is 0.066 m off, the scribble's own width.""" - cam, n = self.cams[1], len(self.truth) - a, b = self.traced(cam), self.traced(cam, -1) - - def scribbled(start, end): - i0, i1 = int(start * (n - 1)), int(end * (n - 1)) - t = np.linspace(0, 1, i1 - i0 + 1) - d = np.gradient(b, axis=0)[i0:i1 + 1] - d /= np.linalg.norm(d, axis=1)[:, None] - wide = 0.12 * np.ptp(b, axis=0).max() - line = b.copy() - line[i0:i1 + 1] += np.stack([-d[:, 1], d[:, 0]], 1) * ((2 * np.abs((t * 6) % 1 - 0.5) - 0.5) * wide)[:, None] + d * (np.sin(12 * np.pi * t) * wide)[:, None] - return line - - out = core.pair(cam, FRAME, a, scribbled(0.3, 0.7), extend=0.0) - self.assertEqual((len(out["skipped"]), len(out["crease"]), out["unmatched"]), (4, 19, 1)) - with self.assertRaises(core.ReferenceFitError) as caught: - core.pair(cam, FRAME, a, scribbled(0.0, 1.0), extend=0.0) - self.assertIn("8 of the 24 points", str(caught.exception)) - - def test_a_crease_that_stands_still_is_a_half_turn(self): - """S1: two crossings that lift to one place are not a straight run. A retraced line a does lift a point - twice.""" - X, Y = np.array([0.4, 0.0, 0.5]), np.array([0.5, 0.2, 0.5]) - self.assertEqual(core._bend(X, X, Y), math.pi) - self.assertEqual(core._bend(X, Y, Y), math.pi) - self.assertAlmostEqual(core._bend(X, Y, 2 * Y - X), 0.0, delta=1e-7) - self.assertAlmostEqual(core._bend(X, Y, X), math.pi, delta=1e-7) - - def test_a_line_that_repeats_an_end_point_is_refused(self): - """A doubled click at an end of line b leaves that end no direction to run on in: refused by name (it was a - LinAlgError out of the triangulation). A repeat inside either line, or at an end of line a, is harmless.""" - cam = self.cams[0] - a, b = self.traced(cam), self.traced(cam, -1) - for line, which, extend in ((np.vstack([b[:1], b]), "first", 0.2), (np.vstack([b, b[-1:]]), "last", 0.2), (np.vstack([b[:1], b]), "first", 0.0)): - with self.assertRaises(core.ReferenceFitError) as caught: - core.pair(cam, FRAME, a, line, extend=extend) - self.assertIn(f"repeats its {which} point", str(caught.exception)) - for one, other in ((np.vstack([a[:1], a]), b), (a, np.vstack([b[:500], b[500:501], b[500:]]))): - out = core.pair(cam, FRAME, one, other) - self.assertEqual(len(out["crease"]), 24) - self.assertLess(self.off(out["crease"]), 1e-6) - - def test_a_line_with_no_mirror_is_counted_unmatched(self): - cam = self.cams[0] - out = core.pair(cam, FRAME, self.traced(cam), self.traced(cam, -1)[:1000], extend=0.0) - self.assertGreater(out["unmatched"], 8) - self.assertEqual(len(out["crease"]) + out["unmatched"], 24) - self.assertLess(self.off(out["crease"]), 1e-6) - - def test_a_line_lifted_onto_a_plane_stands_on_it(self): - cam = self.cams[1] - flat = np.c_[np.full(50, 0.3), np.linspace(-1, 1, 50), np.linspace(0.2, 0.9, 50) ** 2] - lifted = np.array(core.on_plane(cam, FRAME, core.seen(cam, FRAME, flat), [0.3, 0.0, 0.0], [1.0, 0.0, 0.0])) - self.assertLess(np.abs(lifted[:, 0] - 0.3).max(), 1e-9) - self.assertLess(float(core._off(lifted, flat).max()), 1e-3) + N5 (back-facing creases counted) is claimed by tests/live/reference_flow.py.""" COLUMN = [[0.5, 0.0, 0.0], [0.6, 0.2, 1.0], [0.4, 0.1, 2.0], [0.7, -0.2, 3.0], [0.5, 0.0, 4.0]] BUILT = [[0.5, 0.0, 0.0], [0.54375, 0.09375, 0.5], [0.55, 0.15, 1.0], [0.504167, 0.139583, 1.5], [0.483333, 0.066667, 2.0], [0.55, -0.04375, 2.5], - [0.616667, -0.116667, 3.0], [0.589583, -0.089583, 3.5], [0.5, 0.0, 4.0]] # Blender 5.3's level-1 Subdivision of this column creased hard, as tests/live/reference_lift.py printed it + [0.616667, -0.116667, 3.0], [0.589583, -0.089583, 3.5], [0.5, 0.0, 4.0]] # Blender 5.3's level-1 Subdivision of this column creased hard, as tests/live/reference_flow.py printed it def test_crease_run_is_one_level_of_subdivision(self): """crease-run-and-through, N3: against Blender's own numbers, which are the limit curve's (the modifier's @@ -565,13 +360,6 @@ class LiftTests(unittest.TestCase): self.assertEqual(run.shape, (9, 3)) self.assertLess(np.abs(run - np.array(self.BUILT)).max(), 6.8e-5) - def test_the_cage_through_a_crease_builds_through_it(self): - """crease-run-and-through, N6: shipped reads 3.7e-11 m between the built crease and its targets, one round - 1.57e-3: the bound is their geometric mean, separation 6500 each side.""" - targets = self.truth[::400] - cage = core.cage_through(targets) - self.assertLess(np.abs(core.crease_run(cage)[0::2] - targets).max(), 2.4e-7) - def test_along_scores_edges_that_run_with_the_line(self): """along-scores, N4: rungs 5 px apart cross the line square-on, each within the 10 px that counts as near.""" line = [[100.0, 200.0], [500.0, 200.0]] @@ -656,8 +444,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.lift_pair", "brokkr_reference.flow_score"]) - self.assertEqual(source.count("bl_idname = "), 3) + 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) for row in self.document["actions"]: self.assertIn(f'bl_idname = "{row["name"]}"', source) self.assertEqual(row.get("result"), "brokkr_mesh_polish_result") @@ -673,12 +461,9 @@ class HostFileTests(unittest.TestCase): for bad in ({"lens": 4001}, {"model": "fisheye"}, {"width": 8}, {"world": ""}): with self.assertRaises(at.IntentInvalid): at.validate({**self.envelope, **fields, **bad}, self.host) - lift = {**self.envelope, "action": "brokkr_reference.lift_pair", "camera_name": "Concept", "frame_name": "Hull", "line_a": "1,2 3,4", "line_b": "5,6 7,8"} - admitted = at.validate(lift, self.host) - self.assertEqual((admitted["samples"], admitted["extend"]), (24, 0.2)) flow = {**self.envelope, "action": "brokkr_reference.flow_score", "camera_name": "Concept", "lines": "r: 1,2 3,4"} self.assertEqual((at.validate(flow, self.host)["angle"], at.validate(flow, self.host)["height"]), (18, 0)) - for intent, bad in ((lift, {"samples": 1}), (lift, {"frame_name": ""}), (lift, {"extend": 1.5}), (flow, {"angle": 0}), (flow, {"lines": ""}), (flow, {"camera_name": "x" * 64})): + 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)