Merge pull request 'brokkr_reference.block_plate: a plate's first free cage from its named traces across solved views (cut trace-block)' (#43) from nibu/trace-block into main

This commit is contained in:
Eureka 2026-12-03 12:33:39 +00:00
commit 24a67302be
11 changed files with 1632 additions and 8 deletions

View file

@ -14,6 +14,8 @@ cameras, scores and a fitted sheet. The edges flow_score reads are computed on e
fit_shell reads a shell's request through brokkr_kitbash (the sheet's one parser) and returns a sheet; it writes 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. nothing. brokkr_kitbash.shell is the cage's one writer: the caller applies the fitted sheet with it.
block_plate returns a plate's first sheet from traces of its outline, checked by the same parser, and the traces as
fit_shell takes them; it writes nothing either.
""" """
bl_info = {"name": "Brokkr Reference", "author": "GameCult", "version": (0, 1, 0), "blender": (4, 2, 0), 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."} "category": "Camera", "description": "Solve a reference view's camera from marked points; agent-callable through Brokkr."}
@ -263,7 +265,63 @@ class BROKKR_REFERENCE_OT_fit_shell(PolishOperator):
return {"object": obj.name, **out, "seconds": round(time.perf_counter() - started, 3)} 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) class BROKKR_REFERENCE_OT_block_plate(PolishOperator):
"""Block a plate's first free cage from traces of its outline through solved cameras, each trace naming the two
corners it runs between, and say what decided each corner's depth; nothing is written"""
bl_idname = "brokkr_reference.block_plate"
bl_label = "Block Plate From Traces"
frame_object: bpy.props.StringProperty(name="Frame", maxlen=63, description="An empty or object, unscaled, whose place in the world is the plate's frame")
plate: bpy.props.StringProperty(name="Plate", maxlen=2000, description="JSON {corners: [names in the outline's order], mirror, seam: [corners on x = 0]}")
traces: bpy.props.StringProperty(name="Traces", maxlen=12000, description="A JSON array of {camera, box, frame, from, to, side, line: [[u, v], ...]}")
plane: bpy.props.StringProperty(name="Plane", maxlen=200, description="'' for the plane through the corners the views decide, or 'x,y,z; nx,ny,nz' in the frame")
share: bpy.props.FloatProperty(name="Share", default=0.1, min=0.0009, max=10.0, description="A crown point this share of the plate's extent off the plane costs what one pixel of miss does")
tol: bpy.props.FloatProperty(name="Tolerance", default=core.TOL, min=0.09, max=100.0, description="Pixels: nine tenths of every trace must lie this near its built side, or the side gains a point")
def work(self, context):
try:
import brokkr_kitbash
except ImportError as error:
raise Refused(f"block_plate needs the brokkr_kitbash add-on beside this one ({error}).") from None
obj = bpy.data.objects.get(self.frame_object)
if obj is None or obj.name not in context.scene.objects:
raise Refused(f"frame_object {self.frame_object!r} is not an object of this scene.")
if max(abs(v - 1.0) for v in obj.matrix_world.to_scale()) > 1e-6:
raise Refused(f"frame_object {obj.name!r} is scaled {tuple(round(v, 6) for v in obj.matrix_world.to_scale())}: a plate is in metres of its frame. Apply or clear the scale.")
try:
plate, traces = json.loads(self.plate), json.loads(self.traces)
except ValueError as error:
raise Refused(f"plate and traces must be 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, frame, from, to, side, line}.")
plane = None
if self.plane.strip():
halves = self.plane.split(";")
try:
if len(halves) != 2:
raise core.ReferenceFitError(f"plane {self.plane.strip()!r} is not 'x,y,z; nx,ny,nz'")
plane = {"point": core.numbers(halves[0], 3, "plane's point"), "normal": core.numbers(halves[1], 3, "plane's normal")}
except core.ReferenceFitError as refusal:
raise Refused(f"{refusal}.") from None
own, views = [list(row) for row in obj.matrix_world], []
for k, trace in enumerate(traces):
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:
views.append((record(context, trace["camera"], "" if box is None else ",".join(repr(float(v)) for v in box)), trace.get("frame") or own))
except (Refused, core.ReferenceFitError) as refusal:
raise Refused(f"traces[{k}]: {refusal}") from None
started = time.perf_counter()
try:
out = core.block_plate(views, plate, traces, brokkr_kitbash.core.sheet, plane=plane, share=self.share, tol=self.tol)
except core.ReferenceFitError as refusal:
raise Refused(f"{refusal}. Nothing changed.") from None
return {"frame_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, BROKKR_REFERENCE_OT_block_plate)
def register(): def register():

View file

@ -174,6 +174,63 @@
"doc": "pixels: nine tenths of every trace must lie this near its built run, or the fit is refused" "doc": "pixels: nine tenths of every trace must lie this near its built run, or the fit is refused"
} }
] ]
},
{
"name": "brokkr_reference.block_plate",
"doc": "Block a plate's first free cage from traces of its outline, each seen through a scene camera and naming the two consecutive corners it runs between: the only correspondence is a trace's ends to its corners. The crown (the corners and each side's points between) is solved until the sides as built draw on the traces; a side whose trace is not explained gains a point, up to 6. Depth comes from the views where two see a corner and a pixel moves their meeting point less than share x the plate's extent, from x = 0 for a mirrored plate's seam corners whose view crosses it, and otherwise from a plane: the one given, or the one through the corners the views and the seam decide. Every corner, and every point between corners (sides[].inner), says what decided it by its prior_share: plane from 0.2 up, else mirror on the seam, else views; a side says corners, views, mirror or plane. A corner one view sees, a seam corner seen along x = 0 included, is refused when the plane stands over 66 degrees off that view. Returns the sheet for brokkr_kitbash.shell, checked by its parser, and fit_traces for brokkr_reference.fit_shell (left_out lists the traces fit_shell cannot state: another frame, or a partner's side -1). Writes nothing (docs/reference.md).",
"changesScene": true,
"editModeSafe": false,
"result": "brokkr_mesh_polish_result",
"fields": [
{
"name": "frame_object",
"type": "string",
"required": true,
"minLength": 1,
"maxLength": 63,
"doc": "an empty or object, unscaled, whose place in the world is the plate's frame"
},
{
"name": "plate",
"type": "string",
"required": true,
"minLength": 2,
"maxLength": 2000,
"doc": "JSON {corners: [names, in the outline's order], mirror: true or false, seam: [the corners on x = 0 of a mirrored plate, two or more next to each other]}; side i runs from corner i to corner i + 1 and is one hard crease"
},
{
"name": "traces",
"type": "string",
"required": true,
"minLength": 2,
"maxLength": 12000,
"doc": "a JSON array of {camera, box, frame, from, to, side, line}: camera a camera object's name; box [u0,v0,u1,v1], its frame on the image, absent for the render's own; frame a 4 x 4 (rows), the part's pose in that view, absent for frame_object's; from and to two consecutive corners; side 1, or -1 for the mirrored half or the partner across the frame's x = 0; line [[u,v],...] drawn from `from` to `to`"
},
{
"name": "plane",
"type": "string",
"required": false,
"maxLength": 200,
"default": "",
"doc": "'' for the plane through the corners the views and the seam decide, or 'x,y,z; nx,ny,nz' in the frame: a point of the plane and its normal"
},
{
"name": "share",
"type": "number",
"minimum": 0.001,
"maximum": 10,
"default": 0.1,
"doc": "the prior: a crown point this share of the corners' extent off the plane costs what one pixel of miss does"
},
{
"name": "tol",
"type": "number",
"minimum": 0.1,
"maximum": 100,
"default": 5.2,
"doc": "pixels: nine tenths of every trace must lie this near its built side, or the side gains a point"
}
]
} }
] ]
} }

View file

@ -37,6 +37,13 @@ only where the built runs explain every trace; docs/reference.md, "fit_shell", s
fit_runs(views, cage, runs, movable, mirror_of, share, diag, tol) the moved cage and the report 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 fit_sheet(document, cage, frame, traces, cams, share, tol) the same for a sheet's named runs: the fitted sheet
A plate's first cage is blocked from traces of its outline, each naming the two corners it runs between: the crown
is solved by fit_runs with a plane and fairness for its prior; docs/reference.md, "block_plate".
triangulate(obs, seam) where sight lines meet, and how far apart they stand
plate_sheet(crown, corners, flare, drop, dome, mirror, seam, facing) the crown, skirt and centre free-cage document
block_plate(views, plate, traces, parse, plane, share, tol) the blocked sheet and what decided each crown point
""" """
from __future__ import annotations from __future__ import annotations
@ -527,7 +534,7 @@ def _hard_runs(cage, runs):
"more hard edges meet, or on the rim") "more hard edges meet, or on the rim")
def fit_runs(views, cage, runs, movable, mirror_of, share, diag, tol=TOL): def fit_runs(views, cage, runs, movable, mirror_of, share, diag, tol=TOL, prior_rows=None):
"""Move a cage's points until its hard runs, as built and as cameras draw them, lie on their traces. """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 views [(camera record, frame)]: the frame is the 4 x 4 that carries the cage to the world
@ -538,7 +545,10 @@ def fit_runs(views, cage, runs, movable, mirror_of, share, diag, tol=TOL):
movable (vertices, 3) of bool: the coordinates that may move. Only authored vertices move 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 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 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 share the prior's weight: a prior row that reads share x diag metres costs what one pixel of miss does
prior_rows (A, b) in metres over the movable coordinates, in the order of movable's True entries: the prior is
the rows A p - b. None is the identity, A = I and b the cage as given: a move from where each
point was blocked. block_plate gives distances to a plane and a side's second differences instead
tol pixels: PART in a hundred of each trace must lie this near its built run as drawn tol pixels: PART in a hundred of each 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 The residual per run is the pixel distance from each built point (crease_run LEVELS times, drawn through the
@ -581,6 +591,9 @@ def fit_runs(views, cage, runs, movable, mirror_of, share, diag, tol=TOL):
prepared.append((run["name"], views[run["view"]], line, W, source, np.stack([flip[chain], np.ones(len(chain)), np.ones(len(chain))], 1), 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 column.reshape(-1, 3)[source])) # the parameter column of each chain point's coordinate, -1 where held
p0 = V0.ravel()[index] p0 = V0.ravel()[index]
A0, b0 = (np.eye(len(p0)), p0) if prior_rows is None else (np.asarray(prior_rows[0], float), np.asarray(prior_rows[1], float))
if A0.ndim != 2 or A0.shape != (len(b0), len(p0)):
raise ReferenceFitError(f"prior_rows must be (A, b) with a column of A per movable coordinate ({len(p0)}) and a row per entry of b")
def terms(p): def terms(p):
"""(residual, Jacobian, each run's built points as drawn) at parameters p.""" """(residual, Jacobian, each run's built points as drawn) at parameters p."""
@ -603,7 +616,7 @@ def fit_runs(views, cage, runs, movable, mirror_of, share, diag, tol=TOL):
res += [dist, u[0] - line[0], u[-1] - line[-1]] res += [dist, u[0] - line[0], u[-1] - line[-1]]
rows.append(block) rows.append(block)
drawn.append((u, dist)) drawn.append((u, dist))
return np.concatenate(res + [prior * (p - p0)]), np.vstack(rows + [prior * np.eye(len(p))]), drawn return np.concatenate(res + [prior * (A0 @ p - b0)]), np.vstack(rows + [prior * A0]), drawn
p, lam, rounds = p0.copy(), 1e-3, 0 p, lam, rounds = p0.copy(), 1e-3, 0
r, J, drawn = terms(p) r, J, drawn = terms(p)
@ -730,6 +743,372 @@ def fit_sheet(document, cage, frame, traces, cams, share=0.1, tol=TOL):
return {"sheet": out, "traces": report["traces"], "points": points} return {"sheet": out, "traces": report["traces"], "points": points}
# --- a plate's first cage from its traces ------------------------------------------------------------------------------
FAIR = 0.2 # a side's second differences of this share of its chord cost what one pixel of miss does (0.02 held a bowed side straight; docs/reference.md)
K_MAX = 6 # points a side grows to before its trace is refused as fit_runs refuses it
SQUARE = 0.4 # the cosine between a plane's normal and a sight line under which a trace is not lifted onto it: past 66 degrees the lift stretches over 2.5 times
START = 1.0 # a corner's views start it where one pixel moves their meeting point less than this x share x the plate's extent, the prior's own scale: past it the views alone hold the corner looser than the plane would. 1 is the prior's own unit, not a derived value: tests/test_reference.py BlockTests pins it between a plate that must block (its third corner starts at 0.831, views 16.5 degrees apart at Paladin's lens and range) and one that must be refused (11 degrees: it turns to blocked between 1.22 and 1.23)
VIEWS = 0.2 # a prior_share under this: the views decide the point (fit_shell's line)
FLARE, DROP, DOME = 0.05, 0.06, 0.017 # of the crown's extent (its two furthest points): a plate's skirt out from and back of its crown, and its centre's rise. A template's proportions, not readings: the crown is what is solved
TRACE_KEYS = ("camera", "box", "frame", "from", "to", "side", "line")
def _unit(v):
v = np.asarray(v, float)
return v / max(float(np.linalg.norm(v)), 1e-12)
def _partner(frame, side):
"""The frame a trace's side is seen through: the part's own, or for side -1 its reflection across the frame's
x = 0 (the mirrored half of a plate, or the plate's partner on the other limb)."""
F = np.array(frame, float)
if side == -1:
F[:3, 0] = -F[:3, 0]
return F
def _sight(cam, frame, pixel):
"""A pixel's line of sight (origin, unit direction) in a frame's own coordinates."""
o, d = ray(cam, pixel)
inv = np.linalg.inv(np.asarray(frame, float))
return inv[:3, :3] @ o + inv[:3, 3], _unit(inv[:3, :3] @ d)
def triangulate(obs, seam=False):
"""Where sight lines meet. `obs` is [(camera record, frame, side, pixel)]: the pixel each view draws one point
of the frame at, side -1 a view of the point's reflection across x = 0. The midpoint of the sight lines, then
Gauss-Newton on the reprojection; `seam` holds the point on x = 0, which one view then decides. Returns (the
point in the frame, parallax_deg: the angle between the widest pair of sight lines, the worst reprojection miss
in pixels, m_per_px: the most one pixel of error moves the point). One sight line and no seam is no point."""
frames = [_partner(frame, side) for _, frame, side, _ in obs]
rays = [_sight(cam, F, pixel) for (cam, _, _, pixel), F in zip(obs, frames)]
free = [1, 2] if seam else [0, 1, 2]
if len(rays) < 2 and not seam:
raise ReferenceFitError("one sight line meets nothing: a point is triangulated from two or more views, or held on the mirror plane")
A, b = np.zeros((3, 3)), np.zeros(3)
for o, d in rays:
P = np.eye(3) - np.outer(d, d)
A, b = A + P, b + P @ o
X = np.zeros(3)
X[free] = np.linalg.lstsq(A[:, free], b, rcond=None)[0]
def terms(X):
drawn = [_drawn(cam, F, X[None]) for (cam, _, _, _), F in zip(obs, frames)]
if any(seen_ is None for seen_ in drawn):
raise ReferenceFitError("the sight lines meet behind a camera")
return np.concatenate([seen_[0][0] - np.asarray(pixel, float) for seen_, (_, _, _, pixel) in zip(drawn, obs)]), np.vstack([seen_[1][0] for seen_ in drawn])[:, free]
for _ in range(10):
r, J = terms(X)
X[free] -= np.linalg.lstsq(J, r, rcond=None)[0]
r, J = terms(X)
parallax = max((math.degrees(math.acos(min(1.0, abs(float(a[1] @ c[1]))))) for a in rays for c in rays), default=0.0)
return X, parallax, float(np.abs(r).max()), float(math.sqrt(max(np.linalg.eigvalsh(np.linalg.pinv(J.T @ J)).max(), 0.0)))
def plate_sheet(crown, corners, flare=FLARE, drop=DROP, dome=DOME, mirror=False, seam=(), facing=None):
"""The free-cage document of a plate whose raised outline is `crown`, a closed ring of points in the plate's
frame: the crown ring (vertices 0 to n - 1, in the ring's order), a skirt ring `flare` out from it and `drop`
back of it (the chamfered wall), and one centre vertex `dome` proud of the ring's middle; the three are shares
of the crown's extent, the distance between its two furthest points, so a plate of any size has the same
proportions. Every crown side is
creased 1; `corners` (ring indices) are pinned 1 on crown and skirt, so the crown between two corners is one
hard run, and the points between them are free to round it. The centre is the cage's pole unless the ring has
four points. `facing` is a direction the outer face looks along; the ring is taken as wound that way, or the
sheet is flipped.
mirror: `seam` names the ring's points on x = 0 (one unbroken stretch of it). The crown between them is the
crease the two halves meet at: it has no skirt, the skirt of its two ends stands on x = 0, and those ends are
poles (six edges meet there once the half is reflected). The centre stands in the half, not on the plane: a
face of three points of x = 0 is its own reflection and the cage's parser refuses it."""
P = np.asarray(crown, float)
n, seam = len(P), set(seam) if mirror else set()
extent = float(np.linalg.norm(P[:, None] - P[None], axis=2).max())
flare, drop, dome = flare * extent, drop * extent, dome * extent
Q = np.roll(P, -1, axis=0)
normal = _unit(np.cross(P, Q).sum(0)) # Newell's: the ring's own facing, counter-clockwise seen from where it points
flip = facing is not None and float(normal @ np.asarray(facing, float)) < 0
out_ = -normal if flip else normal
middle = P.mean(0)
walled = [i for i in range(n) if not (i in seam and (i - 1) % n in seam and (i + 1) % n in seam)] # a point inside the seam has no skirt
skirt = {}
for i in walled:
away = (P[i] - middle) - out_ * ((P[i] - middle) @ out_)
back = out_.copy()
if i in seam:
away[0], back[0] = 0.0, 0.0
point = P[i] + _unit(away) * flare - back * drop
if i in seam:
point[0] = 0.0
skirt[i] = point
under = {i: n + m for m, i in enumerate(walled)}
centre = n + len(walled)
verts = [[round(float(x), 6) + 0.0 for x in p] for p in list(P) + [skirt[i] for i in walled] + [middle + out_ * dome]]
faces, creases = [], []
for i in range(n):
j = (i + 1) % n
faces.append([i, j, centre])
creases.append([i, j, 1.0])
if not (i in seam and j in seam):
faces.append([under[i], under[j], j, i])
pinned = [[i, 1.0] for i in corners] + [[under[i], 1.0] for i in corners if i in under]
poles = ([] if n == 4 else [centre]) + sorted(i for i in seam if i in under)
document = {"verts": verts, "faces": faces, "creases": creases, "corners": pinned, "poles": sorted(poles), "rim": 0.0}
if mirror:
document["mirror"] = True
if flip:
document["flip"] = True
return document
def block_plate(views, plate, traces, parse, plane=None, share=0.1, tol=TOL):
"""A plate's first cage from traces of its outline across solved views; docs/reference.md, "block_plate".
plate {"corners": [names, in loop order], "mirror": bool, "seam": [corner names on x = 0]}: side i runs from
corner i to corner i + 1 and is one hard crease of the crown
traces [{"from", "to": two consecutive corners, "side": 1, or -1 for the mirrored half or partner, "line":
[[u, v], ...] drawn from `from` to `to`}]; "camera", "box" and "frame" are the caller's and are echoed
views per trace, (camera record, the 4 x 4 that carries the plate's coordinates to the world as that view
poses the part): the plate's own frame, or the trace's "frame" where it states one
parse brokkr_kitbash.core.sheet, the cage's one parser: every sheet built here goes through it
plane {"point", "normal"} in the plate's coordinates, or None for the plane through the corners the views
or the seam decide
The one correspondence is a trace's two ends to its named corners. The crown's points (the corners and each
side's points between them) are solved by fit_runs: its residual on every trace, and for a prior each crown
point's distance to the plane (one pixel per share x diag, diag the corners' extent) and each side's second
differences (one pixel per FAIR x the side's chord). A distance to a plane does not resist a move in the
plane, so the views decide wherever they see. A side starts as its two corners; a side with a trace not
explained gains a point and the plate is solved again, to K_MAX points. Skirt and centre are rebuilt from the
solved crown (plate_sheet). Returns {"sheet", "fit_traces", "left_out", "corners", "sides", "plane", "rounds"};
raises ReferenceFitError naming the field for everything it refuses.
A corner starts where its views meet when a pixel moves that point less than START x share x the plate's
extent; a seam corner where its sight line crosses x = 0, unless the line runs along the plane (SQUARE); any
other on the plane, lifted and guarded by SQUARE. What decided a point is read after the solve from its
prior_share, the same for every crown point: "plane" from VIEWS up (the prior holds its depth: the plane, and
for a side's inner points its fairness), else "mirror" on the seam, else "views". corners[] and each side's
"inner" (its points between corners) carry {"decided_by", "m_per_px", "prior_share"}; a side's own
"decided_by" is "corners" with no inner point, "plane" when any inner point is, else its inner points'."""
if not isinstance(plate, dict) or set(plate) - {"corners", "mirror", "seam"}:
raise ReferenceFitError("plate must be {corners, mirror, seam}")
names, mirror, seam_names = plate.get("corners"), plate.get("mirror", False), plate.get("seam", [])
if not isinstance(names, list) or len(names) < 3 or not all(isinstance(name, str) and name for name in names) or len(set(names)) != len(names):
raise ReferenceFitError("plate.corners must be three or more different names, in the outline's order")
if not isinstance(mirror, bool):
raise ReferenceFitError(f"plate.mirror must be true or false, not {mirror!r}")
N, at = len(names), {name: i for i, name in enumerate(names)}
if not isinstance(seam_names, list) or any(name not in at for name in seam_names) or len(set(seam_names)) != len(seam_names):
raise ReferenceFitError("plate.seam must name corners of plate.corners, none twice")
held = {at[name] for name in seam_names}
if mirror != bool(held) or (mirror and (not 2 <= len(held) < N or sum(1 for i in held if (i + 1) % N not in held) != 1)):
raise ReferenceFitError("plate.seam must name two or more corners next to each other in the outline, and not all of them, on a mirrored plate, and none otherwise: "
"the halves meet along the sides between them. A plate that only has a partner across x = 0 is not mirrored: trace the partner with side -1")
if not isinstance(traces, list) or not traces:
raise ReferenceFitError("traces must be an array of one or more {camera, box, frame, from, to, side, line}")
if len(views) != len(traces):
raise ReferenceFitError(f"views must be one (camera, frame) a trace: {len(views)} for {len(traces)} traces")
seen_by, per_side, runs_of, frames = [dict() for _ in names], [[] for _ in names], [], []
for k, trace in enumerate(traces):
where = f"traces[{k}]"
if not isinstance(trace, dict) or set(trace) - set(TRACE_KEYS):
raise ReferenceFitError(f"{where} must be {{camera, box, frame, from, to, side, line}}")
a, b, side = trace.get("from"), trace.get("to"), trace.get("side", 1)
if a not in at or b not in at:
raise ReferenceFitError(f"{where}.from and .to must name corners of plate.corners, not {a!r} and {b!r}")
step = (at[b] - at[a]) % N
if step not in (1, N - 1):
raise ReferenceFitError(f"{where}.from {a!r} and .to {b!r} are not consecutive corners: a trace is one side of the outline, drawn from one corner to the next")
if side not in (1, -1) or isinstance(side, bool):
raise ReferenceFitError(f"{where}.side must be 1, or -1 for the mirrored half or partner, not {side!r}")
cam, frame = views[k]
if cam is None:
raise ReferenceFitError(f"{where}.camera {trace.get('camera')!r} is no camera of this plate")
try:
F = np.array(frame, float)
except (TypeError, ValueError):
F = np.zeros(0)
if F.shape != (4, 4) or not np.isfinite(F).all() or np.abs(F[:3, :3].T @ F[:3, :3] - np.eye(3)).max() > 1e-5 or np.abs(F[3] - [0, 0, 0, 1]).max() > 1e-9:
raise ReferenceFitError(f"{where}.frame must be a 4 x 4 that only turns and moves the part: a scaled or sheared frame is not metres of the plate")
try:
line = np.array(trace.get("line"), float)
except (TypeError, ValueError):
line = np.zeros(0)
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"{where}.line must be two or more [u, v] points, not all in one place")
F = _partner(F, side)
frames.append(F)
i = at[a] if step == 1 else at[b]
per_side[i].append(k)
runs_of.append((i, step == 1))
view = (json.dumps([cam["C"], cam["R"], cam["f"], cam["c"]], default=float), F.tobytes())
for corner, pixel in ((at[a], line[0]), (at[b], line[-1])):
seen_by[corner].setdefault(view, (cam, F, [], k))[2].append(pixel)
for i, name in enumerate(names):
if not seen_by[i]:
raise ReferenceFitError(f"plate.corners[{i}] {name!r}: no trace ends at it. Every corner is the end of a traced side")
for i, name in enumerate(names):
if not per_side[i]:
raise ReferenceFitError(f"the side from {name!r} to {names[(i + 1) % N]!r} is traced in no view: every side of the outline is traced, or the plate is given fewer corners")
lines = sum(len(json.dumps(trace.get("line"), separators=(",", ":"))) for trace in traces)
size = 44 * (2 * N * (K_MAX - 1) + 1) + 34 * N * (K_MAX - 1) + 62 * N * (K_MAX - 2) + lines + 90 * len(traces) + 190 * N + 400
if size > RESULT_LIMIT:
raise ReferenceFitError(f"traces: the sheet and its report could be about {size} characters, over the {RESULT_LIMIT} a receipt carries: nothing was solved. "
"Trace with fewer points, or block the plate as two")
start, parallax, decided, loose = np.zeros((N, 3)), np.zeros(N), np.zeros(N, bool), np.full(N, np.inf)
obs = [[(cam, F, 1, np.mean(pixels, axis=0)) for cam, F, pixels, _ in seen_by[i].values()] for i in range(N)]
for i in range(N):
if len(obs[i]) >= 2:
start[i], parallax[i], _, loose[i] = triangulate(obs[i], seam=i in held)
met = np.isfinite(loose)
if met.any(): # the plate's extent as its views draw it: the corners' pixels at the range of where the sight lines meet, which a depth error hardly moves
middle, drawn = start[met].mean(0), {}
for i in range(N):
for view, (cam, F, pixels, _) in seen_by[i].items():
drawn.setdefault(view, (cam, F, []))[2].append(np.mean(pixels, axis=0))
extent = max(float(np.linalg.norm(np.ptp(pixels, axis=0))) * float(np.linalg.norm(_sight(cam, F, cam["c"])[0] - middle)) / cam["f"] for cam, F, pixels in drawn.values())
decided = loose < START * share * extent
for i in held: # x = 0 meets a sight line that crosses it; one that runs along it within what SQUARE allows a plane is no meeting
if not decided[i] and max(abs(float(_sight(cam, F, np.mean(pixels, axis=0))[1][0])) for cam, F, pixels, _ in seen_by[i].values()) >= SQUARE:
start[i], decided[i] = triangulate(obs[i], seam=True)[0], True
if plane is None:
if decided.sum() < 3:
raise ReferenceFitError(f"plane: none was given, and {', '.join(repr(names[i]) for i in np.flatnonzero(~decided))} are decided by no view (seen by one only, by views so close that a pixel "
f"moves where they meet over {START * share:g} of the plate's extent, or on the seam by a view that runs along x = 0): three corners the views or the seam "
"decide make the plane. Give plane, or trace those corners in another view")
point = start[decided].mean(0)
_, spread, axes = np.linalg.svd(start[decided] - point)
if spread[1] < 1e-6 * max(spread[0], 1e-12):
raise ReferenceFitError("plane: none was given, and the corners the views decide stand in one line. Give plane")
normal, source = axes[2], "corners"
else:
try:
point, normal = np.array(plane["point"], float), np.array(plane["normal"], float)
fine = point.shape == (3,) and normal.shape == (3,) and np.isfinite(point).all() and np.isfinite(normal).all() and np.linalg.norm(normal) > 1e-9
except (TypeError, ValueError, KeyError):
fine = False
if not fine:
raise ReferenceFitError("plane must be {point: [x, y, z], normal: [x, y, z]} in the plate's frame, the normal not zero")
normal, source = _unit(normal), "given"
for i in np.flatnonzero(~decided):
lifted = []
for cam, F, pixels, k in seen_by[i].values():
o, d = _sight(cam, F, np.mean(pixels, axis=0))
square = abs(float(normal @ d))
if square < SQUARE:
raise ReferenceFitError(f"plate.corners[{i}] {names[i]!r}: the plane stands {math.degrees(math.acos(square)):.0f} degrees off square-on to the view of traces[{k}], the "
f"only depth this corner has. A trace lifted onto it stretches past {1 / SQUARE:g} times: turn plane to the face the view shows, or trace the corner in another view")
lifted.append(o + d * (((point - o) @ normal) / (d @ normal)))
start[i] = np.mean(lifted, axis=0)
if i in held:
start[i, 0] = 0.0
free_ = [i for i in range(N) if i not in held]
def crossed(corners_, what):
side_ = 1.0 if sum(1 for i in free_ if corners_[i, 0] > 0) * 2 >= len(free_) else -1.0
for i in free_:
if mirror and corners_[i, 0] * side_ <= 0:
raise ReferenceFitError(f"plate.corners[{i}] {names[i]!r} {what} at x = {corners_[i, 0]:.3f}, across the mirror plane from the plate's other corners. A corner on the "
"plane is named in plate.seam; one off it is traced where the views agree which side it is on")
crossed(start, "starts")
diag = float(np.linalg.norm(np.ptp(start, axis=0)))
toward = _sight(views[0][0], frames[0], np.asarray(traces[0]["line"], float)[0])[0] - start.mean(0)
count, solves = [2] * N, 0
while True:
solves += 1
first = np.concatenate([[0], np.cumsum([k - 1 for k in count])]) # ring index of each corner; first[N] is the ring's size
n = int(first[N])
ring = np.concatenate([np.linspace(start[i], start[(i + 1) % N], count[i])[:-1] for i in range(N)])
chains = [[int(first[i]) + m for m in range(count[i] - 1)] + [int(first[i + 1]) % n] for i in range(N)]
on_seam = {v for i in range(N) if i in held and (i + 1) % N in held for v in chains[i]} | {int(first[i]) for i in held}
build = lambda crown: plate_sheet(crown, [int(first[i]) for i in range(N)], mirror=mirror, seam=sorted(on_seam), facing=toward) # noqa: E731
def parsed(document):
try:
return parse(document)
except Exception as refusal: # the parser's own error type is its package's
raise ReferenceFitError(f"sheet: the cage's parser does not take the plate as blocked ({refusal})") from None
cage = parsed(build(ring))
movable = np.zeros((len(cage.V), 3), bool)
movable[:n] = True
movable[sorted(on_seam), 0] = False
index = np.flatnonzero(movable.ravel())
column = np.full(movable.size, -1)
column[index] = np.arange(len(index))
column = column.reshape(-1, 3)
V0, A, b = np.asarray(cage.V, float), [], []
def row(parts, weight):
"""One prior row: weight x the sum of factor x coordinate over `parts`, the held coordinates on its right side."""
line_, right = np.zeros(len(index)), 0.0
for v, c, factor in parts:
if column[v, c] >= 0:
line_[column[v, c]] += weight * factor
else:
right -= weight * factor * V0[v, c]
A.append(line_)
b.append(right)
for v in range(n):
row([(v, c, normal[c]) for c in range(3)], 1.0)
b[-1] += float(normal @ point)
for i, chain in enumerate(chains):
fair = share * diag / (FAIR * max(float(np.linalg.norm(start[(i + 1) % N] - start[i])), 1e-9))
for m in range(1, len(chain) - 1):
for c in range(3):
row([(chain[m - 1], c, 1.0), (chain[m], c, -2.0), (chain[m + 1], c, 1.0)], fair)
runs = [{"name": f"traces[{k}]", "chain": chains[i] if forward else chains[i][::-1], "view": k, "line": trace["line"]} for k, (trace, (i, forward)) in enumerate(zip(traces, runs_of))]
try:
V, report = fit_runs([(cam, F) for (cam, _), F in zip(views, frames)], cage, runs, movable, cage.mirror_of, share, diag, tol, prior_rows=(np.array(A), np.array(b)))
except ReferenceFitError as refusal:
rows = getattr(refusal, "traces", None)
if rows is None:
raise
grow = sorted({runs_of[k][0] for k, row_ in enumerate(rows) if row_["unexplained_px"] > tol})
full = [i for i in grow if count[i] >= K_MAX]
if full:
error = ReferenceFitError(f"the side from {names[full[0]]!r} to {names[(full[0] + 1) % N]!r} is not explained at {K_MAX} points, the most a side is given: {refusal}")
error.traces = rows
raise error from None
for i in grow:
count[i] += 1
continue
break
crown = V[:n]
crossed(crown[first[:N]], "ends")
document = build(crown)
parsed(document)
by_vertex = {row_["vertex"]: row_ for row_ in report["points"]}
def decided_at(v):
"""What decided a crown point's depth, by its prior share: the prior (the plane, and a side's fairness) from VIEWS up, whatever the point is."""
row_ = by_vertex[v]
return {"decided_by": "plane" if row_["prior_share"] >= VIEWS else "mirror" if v in on_seam else "views", "m_per_px": round(row_["m_per_px"], 4), "prior_share": round(row_["prior_share"], 3)}
corners = []
for i, name in enumerate(names):
said = decided_at(int(first[i]))
corners.append({"name": name, "decided_by": said["decided_by"], "parallax_deg": round(float(parallax[i]), 1), "m_per_px": said["m_per_px"], "prior_share": said["prior_share"]})
sides = []
for i in range(N):
inner = [decided_at(v) for v in chains[i][1:-1]]
sides.append({"from": names[i], "to": names[(i + 1) % N], "points": count[i], "inner": inner,
"decided_by": "corners" if not inner else "plane" if any(point["decided_by"] == "plane" for point in inner) else inner[0]["decided_by"],
"traces": [report["traces"][k] for k in per_side[i]]})
fit_traces, left_out = [], []
for k, (trace, (i, forward)) in enumerate(zip(traces, runs_of)):
if (trace.get("side", 1) == -1 and not mirror) or trace.get("frame") is not None:
left_out.append(k) # fit_shell takes one frame, the shell's own, and side -1 only as a mirrored sheet's other half
continue
fit_traces.append({**{key: trace[key] for key in ("camera", "box") if key in trace}, "run": {"verts": chains[i] if forward else chains[i][::-1]}, "side": trace.get("side", 1), "line": trace["line"]})
return {"sheet": document, "fit_traces": fit_traces, "left_out": left_out, "corners": corners, "sides": sides,
"plane": {"point": [round(float(x), 6) for x in point], "normal": [round(float(x), 6) for x in normal], "from": source}, "rounds": solves}
# --- fields ---------------------------------------------------------------------------------------------------------- # --- fields ----------------------------------------------------------------------------------------------------------

View file

@ -274,6 +274,170 @@ fitted; a run's depth with no mirror partner, no second view and no mirror plane
The acceptance reads nine tenths of a trace: it passes a short doubled stretch and a tip that stands off, and The acceptance reads nine tenths of a trace: it passes a short doubled stretch and a tip that stands off, and
reports both as `worst_px`. `m_per_px` is a sensitivity to one pixel, not an error bound. reports both as `worst_px`. `m_per_px` is a sensitivity to one pixel, not an error bound.
## block_plate: a plate's first cage from its traces
`fit_shell` refines a cage somebody blocked. `brokkr_reference.block_plate` makes the first one. A plate is a
closed outline of named corners in order; side i runs from corner i to corner i + 1 and is one hard crease of the
plate's crown. A trace is one side drawn in one view, `{camera, box, frame, from, to, side, line}`: `from` and `to`
are two consecutive corners and the line is drawn from the one to the other. That is the only correspondence
there is: a trace's two ends are its two corners. Every other point of the crown is placed by `fit_shell`'s
residual, the pixel distance from the side as built to the trace. Nothing matches a point of one trace to a
point of another.
`frame_object` is the plate's frame. A trace's `frame` is the part's pose in that view where it differs (a limb
swung, a hull pitched); `side` -1 is a view of the plate's reflection across the frame's x = 0, which is the
other half of a mirrored plate or the same plate on the partner limb. `plate` is `{corners, mirror, seam}`. On a
mirrored plate `seam` names the corners on x = 0, two or more next to each other: they are held there, the sides
between them lie on it, and one view decides them.
Where a corner's depth comes from, in this order:
- **the views**, where two or more see it and one pixel moves the point their sight lines meet at less than
`share` x the plate's extent, the prior's own scale. Past that the views alone hold the corner looser than the
plane would and are not used as its start. That factor of 1 is the prior's own unit, not a derived value; the
tests pin it between a plate that blocks and one that is refused. The line is metres a pixel, so it moves
with lens and range: a 1.2 m plate 17.6 m off at 663 px has three corners started at 0.72 of the scale with
its views 19 degrees apart, 0.83 at 16.5, between 1.22 and 1.23 at 11 and 2.73 at 5. With no plane given it blocks down to
16.5 degrees (73 mm from the truth) and is refused at 11, where it would have stood 104 mm off: the line
switches blocking and refusal, it is no cliff in accuracy. At 5 degrees its corners landed 0.25 to 1.5 m off;
through a lens three times as long it starts at 0.65 at 7 degrees and blocks.
- **the mirror plane**, for a seam corner whose sight line crosses x = 0 at 24 degrees or more.
- **a plane**, for the rest: `plane` (`x,y,z; nx,ny,nz`, a point and the normal, in the frame), or with none given
the plane through the corners the views and the seam decide, three or more. A corner one view sees is lifted
onto it, and refused when the plane stands more than 66 degrees off square-on to that view: the lift stretches
past 2.5 times there. A seam corner whose one view runs along x = 0 is such a corner: it is lifted onto the
plane, held on x = 0, and refused by the same 66 degrees.
That is where a corner starts. What the report says decided it is read after the solve, from the point's own
prior share, whatever kind of point it is.
The crown is then solved by the same solver as `fit_shell`, with a different prior: each crown point's distance
to the plane costs a pixel per `share` x the corners' extent, and each side's second differences a pixel per 0.2
x its chord. A distance to a plane does not resist a move in the plane, so the views decide wherever they see,
and a view that sees nothing along its own sight line leaves that to the plane. A side starts as its two
corners. After each solve a side with a trace not explained (the same nine tenths within `tol`) gains one point
and the plate is solved again, to six points a side; past that it is refused as `fit_shell` refuses a trace.
The cage is the crown ring, a skirt 0.05 of the crown's extent out and 0.06 back of it, and one centre vertex
0.017 proud (the extent is the distance between the crown's two furthest points, so a plate of any size has the
same proportions): every crown side
creased 1, the named corners pinned, the centre the declared pole unless the crown has four points. On a
mirrored plate the seam's sides have no skirt and the seam's two ends are poles too. The skirt and centre are
rebuilt from the solved crown and never solved. The sheet goes through `brokkr_kitbash`'s parser before it is
returned, and `brokkr_kitbash.shell` builds it; `block_plate` writes nothing.
The report: `sheet`; `fit_traces`, the traces as `fit_shell` takes them (each side a run of authored vertices),
and `left_out`, the traces `fit_shell` cannot state (one with its own `frame`, or a partner's side -1 on a plate
that is not mirrored); per corner `decided_by`, `parallax_deg`, `m_per_px` and `prior_share`; per side its
points, each trace's readings, `inner` (the same `decided_by`, `m_per_px` and `prior_share` for each point between
its corners) and its own `decided_by`; `plane` with `from` `given` or `corners`; `rounds`, the solves it took.
`decided_by` is read from `prior_share` for every crown point: `plane` from 0.2 up, the prior (the plane, and
for a side's inner points its fairness) holding the depth; under 0.2 `mirror` for a point on the seam and
`views` for any other. A seam corner seen from 10 degrees off the mirror plane reads `plane` (0.57), not
`mirror`. A side says `corners` when it has no point of its own, `plane` when any inner point does, else what
its inner points say: a side can read as explained to 0.1 px and stand 53 mm off with its one inner point at
0.41, and then it says `plane`.
Refused, naming the field: a corner no trace ends at, a side traced in no view, a trace whose corners are not
consecutive, an unknown camera, a scaled frame, a seam that is not one stretch of the outline, no plane where
fewer than three corners are decided, the 66 degrees, a mirrored plate's corner that starts or ends across x = 0
from the others (name it in `seam`, or trace it where the views agree), a side not explained at six points, a
sheet the cage's parser does not take, and a result that could pass the 16000 characters a receipt carries.
Measured against a known truth (`tests/test_reference.py` BlockTests, Python 3.13 on Starfire;
`tests/fixtures/spectre_truth.json`), on one plate through one pair of views. SPECTRE's pass-3 roof, a hard
mirrored cage of 11 vertices, was built by `brokkr_kitbash.shell` and rendered in Blender 5.3 through SPECTRE's
two solved cameras at the sheet's pixel size. Its edges were traced off the renders: the ridge in the side
view, the lip, outer edge and rear edge in the hero's mirrored half and the side view, 62 degrees apart. The
side view's pixel is 27.6 mm across at the plate.
How the traces were taken. No hand drew them. A search follows a seed polyline, takes the strongest brightness
step within a window across each edge, lays a straight stroke through the steps found on each segment, and ends
each stroke where it crosses its neighbours. The seed is the truth's projection moved off the answer, in eight
families: the whole seed by 0.5, 1 or 1.5 px in a drawn direction (a 2.5 px window), or each of its vertices by
a normal draw of 1 or 2 px (3.5 px), 2 px (5 px), 3 px (6 px) or 4 px (8 px). Every corner is named. A take's
worst point stands far from the truth's projection, 3 to 12 px at the families' medians: two strokes that run
nearly along each other cross far from the corner. Forty fresh draws a family (the fixture holds twelve of
each of six, 72 takes, which the test blocks; the 2 px, 5 px and the 4 px, 8 px families are in neither):
| seed | window | blocked of 40 | worst traced point, px: median, most | worst corner, mm: median, most | worst corner over worst point x 27.6 mm, at most |
| --- | --- | --- | --- | --- | --- |
| moved 0.5 px as one | 2.5 px | 40 | 3.4, 30.2 | 47, 913 | 1.11 |
| moved 1 px as one | 2.5 px | 39 | 3.5, 30.4 | 67, 916 | 1.15 |
| moved 1.5 px as one | 2.5 px | 39 | 3.6, 24.9 | 66, 370 | 1.19 |
| each vertex 1 px | 3.5 px | 35 | 8.5, 28.2 | 171, 559 | 1.13 |
| each vertex 2 px | 3.5 px | 35 | 9.1, 28.8 | 153, 745 | 1.14 |
| each vertex 2 px | 5 px | 30 | 9.4, 41.5 | 170, 512 | 1.25 |
| each vertex 3 px | 6 px | 17 | 10.2, 73.6 | 231, 2038 | 1.15 |
| each vertex 4 px | 8 px | 8 | 12.0, 29.0 | 322, 417 | 1.33 |
The fixture's 72 takes read 1.18 at most (62 block; nine are refused at a side not explained at six points,
one at the cage's parser). These ratios are not the bound. A take's worst point is one far crossing, and it
inflates what the corner is measured against: the worst a trace does for its worst point is to have no
outlier, every point the same d px off the truth's projection. With no search, the truth's projection moved:
| every traced point d px off | worst corner over d x 27.6 mm, at most |
| --- | --- |
| each view moved as one, 12 directions by 12, at 1, 2, 3 px (all 144 block) | 1.505, 1.504, 1.502 (1.10 at the median) |
| each stroke its own direction, searched | 1.58 |
| each point its own direction, searched, at 1 and 3 px | 1.67, 1.66 |
The bound: worst corner <= 2.08 x d x pixel, d the furthest any traced point stands from the truth's
projection and pixel the coarser view's. 2.08 is the geometric mean of the 1.505 and of 2.865, what the
blocking reads on the same 144 without its end terms; it stands 1.25 over the worst a search found, which is
not the worst there is, and 1.57 over the worst family of takes. The test holds the 144, the searched worst
at 1 and 3 px and the 72 takes to it. It is a reading on one plate through one pair of views, 62 degrees
apart, not a law, and it says a plate is as good as its worst traced point: one stroke end 30 px off puts a
corner 0.9 m off, and nothing in the report says so, because that trace is explained. No bound is given in
the traces' rms: against it the fixture's takes run 0.57 to 5.3. The same search seeded on the truth's
projection itself, with a 2.5 px window, reads 39 mm; that is the window ending every stroke within 2.5 px of
the answer, and it is not an accuracy.
The error is not a multiple of `m_per_px` either: a seam corner 98 mm off reports 0.0008 m a pixel, because
`m_per_px` is depth along the sight line and most of this error lies across it. With only four corners named,
the roof's ridge and outer edge are one side each and are built as smooth runs through their hard knees:
explained within `tol`, 196 mm from the true edges (5.2 px is 144 mm there). Name a hard corner as a corner.
Fairness, 0.2 x a side's chord, is set by known truth at traced noise. Over ten cells at 1 and 2 px (the rendered
roof with four corners named, its strokes those of the search seeded on the truth with the noise added, with
and without closing strokes moved 3 px, and a bowed pentagon at 60 and 30 degrees and in one view), 168 draws:
the mean of the cells' 90th percentiles and the worst draw, in mm, over the draws that blocked, and the draws
refused, which no percentile counts:
| FAIR | 0.1 | 0.15 | 0.2 | 0.25 | 0.3 | 0.4 | 0.5 | 1 |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| mean 90th percentile | 194 | 184 | 178 | 178 | 179 | 186 | 193 | 196 |
| worst draw | 301 | 275 | 273 | 272 | 312 | 382 | 494 | 577 |
| refused of 168 | 19 | 20 | 23 | 24 | 24 | 25 | 26 | 27 |
A higher FAIR, which is weaker fairness, refuses more draws, so each column's percentiles are
over a different set. On other seeds (Soul's probe, verdict cut-trace-block.s2, FAIR 0.1, 0.2, 0.3, 0.5) the
mean 90th percentile read 216, 188, 216, 250, the worst draw 542, 855, 679, 807 and the refused 18, 21, 26,
27; on a third (verdict cut-trace-block.s3, all eight) 196, 196, 195, 202, 199, 220, 234, 255, the worst draw
652, 876, 690, 843, 871, 500, 673, 741 and the refused 10, 15, 20, 20, 22, 22, 23, 23. FAIR is flat from 0.1
to 0.3 and worse above: 0.2 and 0.25 tie in the table, and 0.1 to 0.2 stand within 1 mm on the third set. 0.2
is kept as a point on that plateau, not a resolved lowest. From
exact traces weaker fairness is nearer the truth (a pentagon bowed 35% of its sides: 42 mm at 0.2, 16 at 0.5,
12 with none).
Agreement with other fits, which is not accuracy. SPECTRE's second-pass roof from its hand traces: the ridge
7.3 mm at most and the brow a median of 8.4 mm from the cage `fit_shell` had fitted to the same pixels; with
1 px of noise on those traces the brow's median read 11 to 75 mm over six draws (Soul's probe, verdict cut-trace-block.s1). Paladin's 16 plates, each a polygon traced in
one view with the plane its agent gave: every corner decided by the plane, the crown within 1 mm of the one
the harness had lifted onto the same plane. Its two thigh shields traced as partners are refused, a side 19 px
unexplained: the sheet draws two different polygons, not one plate and its reflection. RAPTOR's hull plate
bearing the 27 (`tests/fixtures/raptor_plates.json`), marked by eye in the hero and the SIDE view: seven hull
marks admit no hero camera under 25 px rms, so the sheet's two views do not draw one hull; through that camera
the plate blocks with its sight lines 34 to 40 degrees apart and the prior holding 0.17 to 0.20 of each corner.
What it gives up. One outline loop a plate: a plate that wraps a corner is two plates, and creases inside the
outline are not blocked. A bend smaller than `tol` is built straight, and a hard knee inside a side is rounded.
Fairness holds a grown side flatter than its trace while the trace still reads as explained (the side's
`decided_by` says when the prior holds it). The plane through the decided corners is a guess at a twisted
plate, and where one view sees a corner the plane is all the depth it has. Every crown point carries a skirt
vertex, so a point a side grows costs two.
## What it cannot do ## What it cannot do
It solves one pinhole camera for one view: no lens distortion, no two views solved together, one turned group and It solves one pinhole camera for one view: no lens distortion, no two views solved together, one turned group and
@ -281,6 +445,8 @@ no other pose. It does not find the points; marking them is the caller's. Points
points on rigid features of one body, because the build's pose is not the drawing's. It does not say whether the points on rigid features of one body, because the build's pose is not the drawing's. It does not say whether the
subject is the right size: a build twice too large is the same picture from twice as far. subject is the right size: a build twice too large is the same picture from twice as far.
`block_plate` blocks one outline loop a plate and no crease inside it.
## From a script ## From a script
```python ```python
@ -291,6 +457,7 @@ origin, direction = core.ray(cam, (u, v)) # a pixel's line of
point = core.lift(cam, (u, v), plane_point, plane_normal) # a traced pixel on a plane 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 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) fit = core.fit_sheet(sheet, cage, frame, traces, cams) # the fitted sheet and its report; cage is brokkr_kitbash.core.sheet(sheet)
out = core.block_plate(views, plate, traces, parse) # a plate's first sheet and what decided each corner; parse is brokkr_kitbash.core.sheet
score = core.along(line, segments, height) # on, off, run against [u0, v0, u1, v1] segments 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 params = core.blender(cam, 1000) # matrix_world, lens, shifts, resolution
cam2 = core.camera_of(params, box) # and back cam2 = core.camera_of(params, box) # and back
@ -301,4 +468,6 @@ through the action and rendered again; `reference.result.json` is its last run)
(`crease_run` against Blender's own subdivision, a box and a folded sheet scored by `flow_score`; (`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) and `tests/live/reference_fit.py` (a mirrored loft and a mirrored `reference_flow.result.json` is its last run) and `tests/live/reference_fit.py` (a mirrored loft and a mirrored
free cage, each blocked off its design, fitted through the action and rebuilt by `brokkr_kitbash.shell`; free cage, each blocked off its design, fitted through the action and rebuilt by `brokkr_kitbash.shell`;
`reference_fit.result.json` is its last run). `reference_fit.result.json` is its last run) and `tests/live/reference_block.py` (a bowed plate and a mirrored plate
blocked through the action from traces alone, built by `brokkr_kitbash.shell` and handed to `fit_shell`;
`reference_block.result.json` is its last run).

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1 @@
{"note":"RAPTOR (sheet 38): the hull plate that bears the 27, its four corners marked by eye in the hero (the right flank) and in the SIDE view (the left flank, so side -1), with the nose's front face and the two laser emitters. Coordinates are the hull's (raptor_form.SHEET at 3ced828: x right, y forward of the sheet's hip column, z up). side is raptor_form.SHEET.camera(), square-on at the sheet's 28.6 px a metre. world gives each mark's (y, z) off the SIDE view and its x from the hull's mass (the nose 0, the emitters +-0.56, a plate corner the flank's half-width at its station and height): hero is brokkr_reference.core.solve(world, pixels, box, model rolled, lens 50). The seven marks admit no camera under 21.8 px rms (left-out 44 px, lens not determined; 25.1 px at 50 mm): the sheet's two views do not draw one rigid hull, and four of the seven marks are the plate's own corners. What block_plate gives through these cameras is two views agreeing on a plate, not a measured accuracy: there is no truth for this plate.","cameras":{"hero":{"C":[11.303769012415719,10.50084330876064,1.6426541643628032],"R":[[-0.5899084170655855,0.7870428136060581,0.1804762284242304],[0.1745987487019839,-0.09389198835577137,0.9801528306719831],[0.7883675135537211,0.6097113284773865,-0.08202901620441301]],"f":944.4444444444445,"c":[400.0,320.0]},"side":{"C":[-400.0,0.0,0.0],"R":[[0.0,-1.0,0.0],[0.0,0.0,1.0],[-1.0,0.0,0.0]],"f":11441.176470588236,"c":[348.5,849.5]}},"box":[60,0,740,640],"world":{"nose":[0.0,5.681233933161954,4.038046272493573],"emitter_r":[0.56,4.96452442159383,3.7583547557840613],"emitter_l":[-0.56,4.96452442159383,3.7583547557840613],"p_ft":[0.6753672831185238,4.14293059125964,5.4365038560411305],"p_fb":[1.0477429305912596,4.317737789203084,4.632390745501285],"p_rb":[1.2748071979434448,3.0940874035989716,4.80719794344473],"p_rt":[1.282382176520994,3.0241645244215936,5.576349614395887]},"pixels":{"nose":[683,250],"emitter_r":[557,273],"emitter_l":[617,283],"p_ft":[500,120],"p_fb":[539,183],"p_rb":[461,184],"p_rt":[459,108]},"plate":{"corners":["p_ft","p_fb","p_rb","p_rt"]},"traces":[{"view":"hero","from":"p_ft","to":"p_fb","side":1,"line":[[500,120],[539,183]]},{"view":"side","from":"p_ft","to":"p_fb","side":-1,"line":[[230,694],[225,717]]},{"view":"hero","from":"p_fb","to":"p_rb","side":1,"line":[[539,183],[461,184]]},{"view":"side","from":"p_fb","to":"p_rb","side":-1,"line":[[225,717],[260,712]]},{"view":"hero","from":"p_rb","to":"p_rt","side":1,"line":[[461,184],[459,108]]},{"view":"side","from":"p_rb","to":"p_rt","side":-1,"line":[[260,712],[262,690]]},{"view":"hero","from":"p_rt","to":"p_ft","side":1,"line":[[459,108],[500,120]]},{"view":"side","from":"p_rt","to":"p_ft","side":-1,"line":[[262,690],[230,694]]}]}

View file

@ -0,0 +1 @@
{"note":"SPECTRE's roof and cheek as plates. Cameras: spectre_skel.cameras() at nibu/fable-spectre-2 74fc241, solved by this repo's brokkr_reference.core; frames: the hull pitched about the waist by spectre_skel.PITCH (hero 3 degrees, side 0). Traces marked hand are spectre_skel.TRACES (roof brow and ridge, cheek chine); a trace marked fitted-edge is the straight edge between two vertices of spectre_fits.json's fitted cage drawn through the camera, standing in for a side nobody traced, so the outline closes. reference is spectre_fits.json's fitted cage along the traced runs: a fit from a hand blocking, not ground truth.","cameras":{"hero":{"C":[-9.721115556958573,18.859090658741355,5.242272804029844],"R":[[-0.862189601405842,-0.5065857195259607,0.0],[0.034125232508362004,-0.05807984607580026,0.9977285201827507],[-0.5054350202883507,0.8602311551276064,0.06736319480204615]],"f":1785.0,"c":[378.0,353.0]},"side":{"C":[60.84416742645475,1.422308134553987,3.13474760877321],"R":[[3.061616997868383e-16,1.0,0.0],[0.011634411213376642,-3.5620111131064444e-18,0.9999323179474289],[0.9999323179474289,-3.0614097813457806e-16,-0.011634411213376642]],"f":2200.0,"c":[892.0,532.0]}},"frames":{"hero":[[1.0,0.0,0.0,0.0],[0.0,0.9986295347545738,0.052335956242943835,-0.2773805680876023],[0.0,-0.052335956242943835,0.9986295347545738,0.007263465800758873],[0.0,0.0,0.0,1.0]],"side":[[1.0,0.0,0.0,0.0],[0.0,1.0,0.0,0.0],[0.0,-0.0,1.0,0.0],[0.0,0.0,0.0,1.0]]},"plates":{"roof":{"plate":{"corners":["ridge_rear","nose","brow_rear"],"mirror":true,"seam":["ridge_rear","nose"]},"traces":[{"view":"side","from":"ridge_rear","to":"nose","side":1,"line":[[883,400],[898,408],[930,426],[958,441]],"source":"hand"},{"view":"hero","from":"brow_rear","to":"nose","side":-1,"line":[[487,47],[443,92],[427,126],[400,128],[360,135],[325,142]],"source":"hand"},{"view":"side","from":"brow_rear","to":"nose","side":1,"line":[[883,404],[900.7,413.6],[919,423.6],[938.6,436.4],[958.6,443]],"source":"hand"},{"view":"hero","from":"brow_rear","to":"ridge_rear","side":-1,"line":[[487.1,47.1],[424.7,35.3]],"source":"fitted-edge"},{"view":"side","from":"brow_rear","to":"ridge_rear","side":1,"line":[[883.0,404.1],[883.0,399.9]],"source":"fitted-edge"}],"reference":{"ridge":[[0.0,1.173941,7.498167],[0.0,2.063931,7.015758],[0.0,2.624251,6.687296],[0.0,3.079302,6.461668],[0.0,3.280227,6.334663]],"brow":[[0.776479,1.177565,7.327593],[0.653669,2.30313,6.743599],[0.929821,2.609515,6.428508],[0.197231,2.908778,6.436474],[0.0,3.280227,6.334663]]}},"cheek":{"plate":{"corners":["chine_rear","jaw","chin"],"mirror":true,"seam":["jaw","chin"]},"traces":[{"view":"hero","from":"chine_rear","to":"jaw","side":-1,"line":[[472,169],[438,180],[390,170],[312,182]],"source":"hand"},{"view":"side","from":"chine_rear","to":"jaw","side":1,"line":[[919,447],[945,456.5],[961,459]],"source":"hand"},{"view":"side","from":"jaw","to":"chin","side":1,"line":[[965.6,456.7],[957.7,463.1]],"source":"fitted-edge"},{"view":"hero","from":"chin","to":"chine_rear","side":-1,"line":[[331.3,199.5],[472.1,167.8]],"source":"fitted-edge"},{"view":"side","from":"chin","to":"chine_rear","side":1,"line":[[957.7,463.1],[921.1,451.0]],"source":"fitted-edge"}],"reference":{"chine":[[1.097992,2.211844,6.0315],[0.924701,2.658187,5.897007],[0.340462,2.978516,6.057156],[0.0,3.458134,5.926945]]}}}}

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,245 @@
"""Live proof, in a background Blender, of brokkr_reference.block_plate through run_intent.
A plate stands in a frame turned and moved in the world: an empty, "Frame". Its truth is a five-sided crown with
bowed sides, built by brokkr_kitbash.shell from core.plate_sheet, and two cameras 60 degrees apart look at it. Each
side is traced in both views where Blender's own projection draws the side as core.crease_run builds it. Then:
block_plate from the frame, the corner names and the ten traces, no blocking: a sheet with every trace
explained, each corner decided by the views, nothing written to the scene
built brokkr_kitbash.shell takes the sheet without refusal, and at one level Blender builds each crown
side where core.crease_run says
fit_shell with the returned fit_traces on the built plate: accepted, every trace explained, and no point
moved over MOVED (fairness holds a bowed side in and fit_shell's own prior lets it out:
tests/test_reference.py test_the_blocking_goes_to_the_parser_and_to_fit_shell reads 74 mm of
it where a pixel is 27 mm; here a pixel is 5 mm). MOVED, GAP and GAP_MIRRORED each stand between
this scene's reading and a mutant's
mirrored a mirrored plate with two seam corners, traced the same way: the seam stays on x = 0,
brokkr_kitbash.shell builds both halves, and Blender builds the seam's side and a free side where
core.crease_run says
refusals a scaled frame, an unknown camera and a side nobody traced, each a failed receipt naming its cause
blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/reference_block.py -- <out>
Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses
without them). <out> is an absolute path: it writes <out>.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
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"<out> 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-block-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 = 1000, 800
MOVED, GAP, GAP_MIRRORED = 0.0165, 0.0088, 0.0273 # metres, each the geometric mean of this scene's reading and its least mutant's (lodur:ruling:deterministic-bound-margin), the mutants run through this script on a copy of the surface: fit_shell moves a point of the blocked plate 0.0048 (FAIR 0.05: 0.0565), the blocked crown stands 0.0027 from its truth (FAIR 0.05: 0.0288), the mirrored crown 0.0140 (FAIR 0.05: 0.0534; no end terms: 0.0646). Separations 3.4, 3.3 and 1.95 each side. A pixel is 5 mm here and the traces are exact, where weaker fairness reads nearer (FAIR 0.5: 0.0011, 0.0018, 0.0054): tests/test_reference.py test_fairness_is_set_by_the_rendered_roof says why 0.2 stands
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 built(chain):
return core.crease_run(core.crease_run(np.asarray(chain, float)))
def pentagon():
"""Five sides as five-point cage chains: a plate 1.2 m across facing -y, its corners up to 0.15 m off the plane
y = 0, each side bowed 8% of its length toward -y and 35% outward in the plate."""
angles = [2 * math.pi * i / 5 + 0.3 for i in range(5)]
P = np.array([[0.6 * math.cos(t), 0.15 * math.cos(2 * t), 0.6 * math.sin(t)] for t in angles])
s, sides = np.linspace(0, 1, 5)[:, None], []
for a, b in zip(P, np.roll(P, -1, axis=0)):
sides.append(a + s * (b - a) + np.sin(math.pi * s) * np.linalg.norm(b - a) * (0.08 * np.array([0, -1.0, 0]) + 0.35 * (a + b) / np.linalg.norm(a + b)))
return sides
def half():
"""A mirrored plate's authored half as chains: the seam's side on x = 0, bowed in the plane, and three free sides."""
P = np.array([[0.0, 0.0, 0.5], [0.0, 0.0, -0.5], [0.5, 0.1, -0.4], [0.3, 0.1, 0.4]])
s, sides = np.linspace(0, 1, 5)[:, None], []
for i, (a, b) in enumerate(zip(P, np.roll(P, -1, axis=0))):
bow = np.array([0.0, -0.3, 0.0]) if i == 0 else np.array([0.25, -0.1, 0.0]) if i == 1 else np.zeros(3)
sides.append(a + s * (b - a) + np.sin(math.pi * s) * np.linalg.norm(b - a) * bow)
return sides
def pixels(camera, frame, points, side=1):
out = []
for p in np.asarray(points, float) * [side, 1, 1]:
x, y, _ = world_to_camera_view(bpy.context.scene, camera, frame.matrix_world @ Vector(p))
out.append([round(x * WIDTH, 3), round((1.0 - y) * HEIGHT, 3)])
return out
def chains_of(out):
n, first, chains = sum(side["points"] - 1 for side in out["sides"]), 0, []
for side in out["sides"]:
chains.append([(first + m) % n for m in range(side["points"])])
first += side["points"] - 1
return chains
def at_one_level(name, sheet, chains, mirror=False):
"""The furthest a crown side as core.crease_run builds it at one level stands from a vertex Blender built."""
send("brokkr_kitbash.shell", object_name=name, sheet=json.dumps(sheet), thickness=0.03, levels=1)
shell = bpy.data.objects[name]
wall = shell.modifiers["Kit Solidify"]
wall.show_viewport = False
mesh = np.array([v.co for v in shell.evaluated_get(bpy.context.evaluated_depsgraph_get()).to_mesh().vertices])
wall.show_viewport = True
verts = np.array(sheet["verts"])
return max(float(np.linalg.norm(mesh - p * [side, 1, 1], axis=1).min()) for chain in chains for side in ((1, -1) if mirror else (1,)) for p in core.crease_run(verts[chain]))
def snapshot():
return sorted((o.name, o.type, tuple(round(c, 6) for row in o.matrix_world for c in row), o.get("kit_shell")) for o in bpy.data.objects)
try:
check("host files admitted with the block_plate row", not R["hostErrors"] and "brokkr_reference.block_plate" in R["hostRows"], R["hostErrors"] or R["hostRows"][-4:])
scene = bpy.context.scene
scene.render.resolution_x, scene.render.resolution_y, scene.render.resolution_percentage = WIDTH, HEIGHT, 100
frame = bpy.data.objects.new("Frame", None)
scene.collection.objects.link(frame)
frame.matrix_world = Matrix.Translation((0.3, -0.2, 1.0)) @ Euler((0.0, 0.0, math.radians(15.0))).to_matrix().to_4x4()
cameras = []
for name, azimuth in (("A", 15.0), ("B", 75.0)):
camera = bpy.data.objects.new(name, bpy.data.cameras.new(name))
scene.collection.objects.link(camera)
camera.data.lens, camera.data.sensor_fit = 50.0, "HORIZONTAL"
a = math.radians(azimuth)
camera.location = Vector((0.3, -0.2, 1.0)) + 7.0 * Vector((math.sin(a), -math.cos(a), 0.15))
camera.rotation_euler = (Vector((0.3, -0.2, 1.0)) - camera.location).to_track_quat("-Z", "Y").to_euler()
cameras.append(camera)
bpy.context.view_layer.update()
# --- the truth, built by brokkr_kitbash.shell, and its sides traced in both views -------------------------------
names = [f"c{i}" for i in range(5)]
sides = pentagon()
crown = np.concatenate([side[:-1] for side in sides])
truth = core.plate_sheet(crown, [0, 4, 8, 12, 16], facing=[0.0, -1.0, 0.0])
made, _ = send("brokkr_kitbash.shell", object_name="Truth", sheet=json.dumps(truth), thickness=0.03, levels=2)
bpy.data.objects["Truth"].matrix_world = frame.matrix_world
bpy.context.view_layer.update()
traces = [{"camera": camera.name, "from": names[i], "to": names[(i + 1) % 5], "side": 1, "line": pixels(camera, frame, core.resampled(built(side), 24))} for i, side in enumerate(sides) for camera in cameras]
inside = all(0 <= u <= WIDTH and 0 <= v <= HEIGHT for trace in traces for u, v in trace["line"])
check("brokkr_kitbash.shell builds the truth from core.plate_sheet, and both cameras frame every side", made["status"] == "accepted" and inside, made["message"])
# --- block_plate ------------------------------------------------------------------------------------------------------
before = snapshot()
receipt, out = send("brokkr_reference.block_plate", frame_object="Frame", plate=json.dumps({"corners": names}), traces=json.dumps(traces, separators=(",", ":")))
ok = receipt["status"] == "accepted" and out is not None
check(f"block_plate returns a sheet with every trace explained within {core.TOL:g} px and each corner decided by the views",
ok and max(row["unexplained_px"] for side in out["sides"] for row in side["traces"]) <= core.TOL and {corner["decided_by"] for corner in out["corners"]} == {"views"}
and len(receipt["hostResult"]) < 16000,
out and {"sides": [side["points"] for side in out["sides"]], "corners": [[corner["parallax_deg"], corner["m_per_px"], corner["prior_share"]] for corner in out["corners"]],
"rounds": out["rounds"], "seconds": out["seconds"], "chars": len(receipt["hostResult"])} or receipt["message"])
check("block_plate wrote nothing: every object is as it was", snapshot() == before)
if ok:
chains = chains_of(out)
verts = np.array(out["sheet"]["verts"])
gap = max(float(core._off(built(verts[chain]), core.resampled(built(side), 400)).max()) for chain, side in zip(chains, sides))
check(f"the blocked crown as built stands within {GAP:g} m of the truth's", gap < GAP, gap)
worst = at_one_level("Blocked", out["sheet"], chains)
check("brokkr_kitbash.shell takes the blocked sheet, and at one level Blender builds every crown side where core.crease_run says, within 1e-4 m",
"Blocked" in bpy.data.objects and worst < 1e-4, worst)
applied, _ = send("brokkr_kitbash.shell", object_name="Blocked", sheet=json.dumps(out["sheet"]), thickness=0.03, levels=2)
bpy.data.objects["Blocked"].matrix_world = frame.matrix_world
bpy.context.view_layer.update()
receipt, fit = send("brokkr_reference.fit_shell", object_name="Blocked", traces=json.dumps(out["fit_traces"], separators=(",", ":")))
moved = fit and max(point["moved_m"] for point in fit["points"])
check(f"fit_shell takes the returned fit_traces on the built plate: accepted, every trace explained, no point moved over {MOVED:g} m",
applied["status"] == "accepted" and receipt["status"] == "accepted" and len(out["fit_traces"]) == 10 and out["left_out"] == [] and moved < MOVED
and max(row["unexplained_px"] for row in fit["traces"]) <= core.TOL, {"moved_m": moved} if fit else receipt["message"])
# --- a mirrored plate ---------------------------------------------------------------------------------------------------
names = ["top", "bottom", "low", "high"]
sides = half()
traces = [{"camera": camera.name, "from": names[i], "to": names[(i + 1) % 4], "side": side_, "line": pixels(camera, frame, core.resampled(built(side), 24), side_)}
for i, side in enumerate(sides) for camera, side_ in ((cameras[0], 1), (cameras[1], 1), (cameras[0], -1))]
traces = [trace for trace in traces if not (trace["from"] == "top" and trace["side"] == -1)] # the seam's side is its own reflection
receipt, out = send("brokkr_reference.block_plate", frame_object="Frame", plate=json.dumps({"corners": names, "mirror": True, "seam": ["top", "bottom"]}),
traces=json.dumps(traces, separators=(",", ":")))
ok = receipt["status"] == "accepted" and out is not None
if ok:
chains = chains_of(out)
verts = np.array(out["sheet"]["verts"])
gap = max(float(core._off(built(verts[chain]), core.resampled(built(side), 400)).max()) for chain, side in zip(chains, sides))
check(f"a mirrored plate: the seam's corners are decided by the mirror plane, its side stays on x = 0, and the crown as built stands within {GAP_MIRRORED:g} m of the truth's",
[corner["decided_by"] for corner in out["corners"]][:2] == ["mirror", "mirror"] and float(np.abs(verts[chains[0], 0]).max()) == 0.0 and gap < GAP_MIRRORED,
{"gap": gap, "sides": [side["points"] for side in out["sides"]], "corners": [corner["decided_by"] for corner in out["corners"]], "poles": out["sheet"]["poles"]})
worst = at_one_level("Mirrored", out["sheet"], chains, mirror=True)
check("brokkr_kitbash.shell builds both halves of the mirrored sheet, and at one level Blender builds the seam's side and the free sides, on both halves, where core.crease_run says, within 1e-4 m",
"Mirrored" in bpy.data.objects and worst < 1e-4, worst)
else:
check("block_plate blocks a mirrored plate", False, receipt["message"])
# --- refusals ---------------------------------------------------------------------------------------------------------
before = snapshot()
plate, text = json.dumps({"corners": names, "mirror": True, "seam": ["top", "bottom"]}), json.dumps(traces, separators=(",", ":"))
receipt, _ = send("brokkr_reference.block_plate", frame_object="Frame", plate=plate, traces=json.dumps([dict(traces[0], camera="Nobody")] + traces[1:], separators=(",", ":")))
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.block_plate", frame_object="Frame", plate=plate, traces=json.dumps([trace for trace in traces if trace["from"] != "low"], separators=(",", ":")))
check("a side nobody traced is refused by its corners' names", receipt["status"] == "failed" and "the side from 'low' to 'high' is traced in no view" in receipt["message"], receipt["message"])
receipt, _ = send("brokkr_reference.block_plate", frame_object="Frame", plate=plate, traces=text, plane="0,0,0; 0,0")
check("a plane that is not a point and a normal is refused", receipt["status"] == "failed" and "plane" in receipt["message"], receipt["message"])
check("no refusal changed the scene", snapshot() == before)
frame.scale = (2.0, 2.0, 2.0)
bpy.context.view_layer.update()
receipt, _ = send("brokkr_reference.block_plate", frame_object="Frame", plate=plate, traces=text)
check("a scaled frame is refused", receipt["status"] == "failed" and "scaled" in receipt["message"], receipt["message"])
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)

View file

@ -0,0 +1,175 @@
{
"blender": "5.3.0",
"checks": [
{
"name": "host files admitted with the block_plate row",
"ok": true,
"detail": [
"brokkr_reference.solve_camera",
"brokkr_reference.flow_score",
"brokkr_reference.fit_shell",
"brokkr_reference.block_plate"
]
},
{
"name": "brokkr_kitbash.shell builds the truth from core.plate_sheet, and both cameras frame every side",
"ok": true,
"detail": "Operator brokkr_kitbash.shell finished."
},
{
"name": "block_plate returns a sheet with every trace explained within 5.2 px and each corner decided by the views",
"ok": true,
"detail": {
"sides": [
3,
3,
3,
3,
3
],
"corners": [
[
60.6,
0.0031,
0.019
],
[
61.0,
0.0042,
0.026
],
[
56.4,
0.0035,
0.022
],
[
57.3,
0.0036,
0.022
],
[
60.1,
0.0037,
0.023
]
],
"rounds": 2,
"seconds": 0.137,
"chars": 7703
}
},
{
"name": "block_plate wrote nothing: every object is as it was",
"ok": true,
"detail": null
},
{
"name": "the blocked crown as built stands within 0.0088 m of the truth's",
"ok": true,
"detail": 0.002711610846938251
},
{
"name": "brokkr_kitbash.shell takes the blocked sheet, and at one level Blender builds every crown side where core.crease_run says, within 1e-4 m",
"ok": true,
"detail": 1.1421151381392388e-07
},
{
"name": "fit_shell takes the returned fit_traces on the built plate: accepted, every trace explained, no point moved over 0.0165 m",
"ok": true,
"detail": {
"moved_m": 0.0048
}
},
{
"name": "a mirrored plate: the seam's corners are decided by the mirror plane, its side stays on x = 0, and the crown as built stands within 0.0273 m of the truth's",
"ok": true,
"detail": {
"gap": 0.013972102623404082,
"sides": [
3,
3,
2,
2
],
"corners": [
"mirror",
"mirror",
"views",
"views"
],
"poles": [
0,
2,
11
]
}
},
{
"name": "brokkr_kitbash.shell builds both halves of the mirrored sheet, and at one level Blender builds the seam's side and the free sides, on both halves, where core.crease_run says, within 1e-4 m",
"ok": true,
"detail": 8.42242114374928e-08
},
{
"name": "an unknown camera is refused naming the trace",
"ok": true,
"detail": "Error: traces[0]: 'Nobody' is not a camera object."
},
{
"name": "a side nobody traced is refused by its corners' names",
"ok": true,
"detail": "Error: the side from 'low' to 'high' is traced in no view: every side of the outline is traced, or the plate is given fewer corners. Nothing changed."
},
{
"name": "a plane that is not a point and a normal is refused",
"ok": true,
"detail": "Error: plane's normal '0,0' is not 3 finite numbers with commas between."
},
{
"name": "no refusal changed the scene",
"ok": true,
"detail": null
},
{
"name": "a scaled frame is refused",
"ok": true,
"detail": "Error: frame_object 'Frame' is scaled (2.0, 2.0, 2.0): a plate is in metres of its frame. Apply or clear the scale."
}
],
"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",
"brokkr_reference.block_plate"
],
"ok": true
}

View file

@ -717,6 +717,538 @@ class FitTests(unittest.TestCase):
core.fit_sheet(sheet_, kit.sheet(sheet_), FIT_FRAME, traces, cams) core.fit_sheet(sheet_, kit.sheet(sheet_), FIT_FRAME, traces, cams)
EYE = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]
PLATE = [f"c{i}" for i in range(5)]
ON_Y = {"point": [0, 0, 0], "normal": [0, 1, 0]}
def plate_camera(azimuth, distance=17.6, f=663.0):
"""A camera `distance` off the origin, level, turned `azimuth` degrees from looking along +y: Paladin's hero's
lens and range (663 px, 17.6 m)."""
a = math.radians(azimuth)
C = distance * np.array([math.sin(a), -math.cos(a), 0.0])
right = np.cross(-C / distance, [0, 0, 1.0])
right /= np.linalg.norm(right)
return {"C": C.tolist(), "R": np.stack([right, np.cross(right, -C / distance), C / distance]).tolist(), "f": f, "c": [500.0, 500.0]}
def pentagon(bow, lateral=0.0, twist=0.15):
"""The sides of a pentagon plate 1.2 m across facing -y, as five-point cage chains: its corners `twist` metres
off the plane y = 0 (a twisted plate), each side bowed `bow` of its length toward -y, which a view from there
sees end on, and `lateral` of it outward in the plate."""
angles = [2 * math.pi * i / 5 + 0.3 for i in range(5)]
P = np.array([[0.6 * math.cos(t), twist * math.cos(2 * t), 0.6 * math.sin(t)] for t in angles])
s, sides = np.linspace(0, 1, 5)[:, None], []
for a, b in zip(P, np.roll(P, -1, axis=0)):
sides.append(a + s * (b - a) + np.sin(math.pi * s) * np.linalg.norm(b - a) * (bow * np.array([0, -1.0, 0]) + lateral * (a + b) / np.linalg.norm(a + b)))
return sides
def plate_traces(cams, sides, sigma=0.0, seed=7):
"""(views, traces) of a plate's sides as built, drawn through each camera in 12 points, `sigma` px of noise."""
rng, views, traces = np.random.default_rng(seed), [], []
for i, side in enumerate(sides):
for k, cam in enumerate(cams):
u = core.resampled(core.project(cam, core.crease_run(core.crease_run(side))), 12)
traces.append({"camera": f"View{k}", "from": PLATE[i], "to": PLATE[(i + 1) % 5], "side": 1, "line": (u + rng.normal(0, sigma, u.shape)).tolist()})
views.append((cam, EYE))
return views, traces
def crown_chains(out):
"""Per side of a block_plate report, its crown vertices in the sheet."""
n, first, chains = sum(side["points"] - 1 for side in out["sides"]), 0, []
for side in out["sides"]:
chains.append([(first + m) % n for m in range(side["points"])])
first += side["points"] - 1
return chains
def off_run(out, chain, truth):
"""The furthest a blocked side as built stands from a true cage chain as built, metres."""
built = core.crease_run(core.crease_run(np.array(out["sheet"]["verts"])[chain]))
return core._off(built, core.resampled(core.crease_run(core.crease_run(np.asarray(truth, float))), 400))
def off_plate(out, sides):
return max(float(off_run(out, chain, side).max()) for chain, side in zip(crown_chains(out), sides))
def blocked_plate(views, traces, **more):
return core.block_plate(views, {"corners": PLATE}, traces, kit.sheet, **more)
def rendered(name, corners, sigma=0.0, close=0.0, seed=0, take=None, off=None):
"""(views, plate, traces, the true sides, the fixture's plate) of a plate of tests/fixtures/spectre_truth.json
with `corners` of its loop named: each stroke traced from the renders is cut at the named corners it passes
through, every point `sigma` px off, a closing stroke moved `close` px as one. The strokes are the fixture's
own, searched from the truth's projection, or those of its `take`, searched from a seed off it, or with
`off` (d, degrees) no search at all: the truth's projection, each point of each stroke in turn moved d px
in its own direction."""
fixture = json.loads((Path(__file__).resolve().parent / "fixtures" / "spectre_truth.json").read_text(encoding="utf-8"))
plate, rng, views, traces = fixture["plates"][name], np.random.default_rng(seed), [], []
turns = iter(np.radians(off[1])) if off else None
for k, stroke in enumerate(plate["strokes"]):
line = np.array(stroke["line"] if take is None else plate["takes"][take]["lines"][k])
if off:
line = core.seen(fixture["cameras"][stroke["view"]], fixture["frames"][stroke["view"]], np.array([plate["truth"][corner] for corner in stroke["through"]]) * [stroke["side"], 1, 1])
line = line + off[0] * np.array([[math.cos(turn), math.sin(turn)] for _, turn in zip(line, turns)])
line = line + (rng.normal(0, sigma, line.shape) if sigma else 0.0)
if stroke["closing"] and close:
turn = rng.uniform(0, 2 * math.pi)
line = line + close * np.array([math.cos(turn), math.sin(turn)])
cuts = [k for k, corner in enumerate(stroke["through"]) if corner in corners]
for a, b in zip(cuts, cuts[1:]):
traces.append({"camera": stroke["view"], "from": stroke["through"][a], "to": stroke["through"][b], "side": stroke["side"], "line": line[a:b + 1].tolist(),
**({"frame": fixture["frames"]["hero"]} if stroke["view"] == "hero" else {})})
views.append((fixture["cameras"][stroke["view"]], fixture["frames"][stroke["view"]]))
loop, named = plate["loop"], [corner for corner in plate["loop"] if corner in corners]
sides = []
for i, corner in enumerate(named):
a, b = loop.index(corner), loop.index(named[(i + 1) % len(named)])
sides.append(np.array([plate["truth"][loop[k % len(loop)]] for k in range(a, (b if b > a else b + len(loop)) + 1)]))
return views, {"corners": named, "mirror": True, "seam": [corner for corner in plate["seam"] if corner in corners]}, traces, sides, (fixture, plate)
def off_projection(fixture, plate, take):
"""The furthest a point of a take's strokes stands from the truth's projection, px."""
worst = 0.0
for stroke, line in zip(plate["strokes"], plate["takes"][take]["lines"]):
drawn = core.seen(fixture["cameras"][stroke["view"]], fixture["frames"][stroke["view"]], np.array([plate["truth"][corner] for corner in stroke["through"]]) * [stroke["side"], 1, 1])
worst = max(worst, float(np.linalg.norm(np.array(line) - drawn, axis=1).max()))
return worst
def off_rendered(out, sides):
"""(the furthest a blocked corner stands from its own, the furthest a side as built and its true edge, a polyline
through the truth's corners, stand apart either way), metres."""
verts, chains = np.array(out["sheet"]["verts"]), crown_chains(out)
edge = 0.0
for chain, side in zip(chains, sides):
built = core.crease_run(core.crease_run(verts[chain]))
edge = max(edge, float(core._off(built, side).max()), float(core._off(core.resampled(side, 300), built).max()))
return max(float(np.linalg.norm(verts[chain[0]] - side[0])) for chain, side in zip(chains, sides)), edge
@unittest.skipIf(np is None, "numpy")
class BlockTests(unittest.TestCase):
"""block_plate: a plate's first cage from traces of its outline. Bounds follow
lodur:ruling:deterministic-bound-margin; the other numbers are tolerances round a known truth. Mutants, each
run once on a copy:
M1 no end terms test_spectre_roof_and_cheek, test_every_point_as_far_off_bounds_the_rendered_roof
M2 a point prior (fit_shell's) for the plane distance test_one_view_and_a_plane_block_a_bowed_plate, test_fairness_is_set_by_the_rendered_roof
M3 a seam corner's x free test_spectre_roof_and_cheek, test_the_rendered_roof_blocks_from_traces_of_its_renders
M4 no fairness test_fairness_is_set_by_the_rendered_roof
M5 the 66 degree guard off test_a_plane_far_off_square_on_to_its_one_view_is_refused, test_a_seam_corner_says_what_decided_it
M6 no growth (K_MAX 2) test_a_side_grows_until_its_trace_is_explained, test_spectre_roof_and_cheek
F5 FAIR 0.5, F05 FAIR 0.05 test_fairness_is_set_by_the_rendered_roof; test_a_side_grows_until_its_trace_is_explained
S1 a seam point labelled mirror whatever its share test_a_seam_corner_says_what_decided_it
S2 a seam corner never sent to the plane's guard test_a_seam_corner_says_what_decided_it
I1 a side's label from its first point only, never plane test_a_side_says_what_decided_its_inner_points
T06, T08, T2, T26, T3 START 0.6, 0.8, 2.0, 2.6, 3.3 test_views_5_degrees_apart_take_their_depth_from_a_plane_or_are_refused
K1 a skirt of fixed metres test_a_plate_keeps_its_proportions_at_any_size
What the blocking is worth against a known truth is test_the_rendered_roof_blocks_from_traces_of_its_renders:
a built plate, rendered, its edges traced off the renders. test_spectre_roof_and_cheek and
test_paladin_plates_one_view_each read agreement with another fit and with a harness's lift on the same
pixels, not accuracy."""
def test_a_twisted_bowed_plate_blocks_from_two_views(self):
"""block-synthetic. Views 60 and 19 degrees apart, traces 0.5 and 1.5 px off: every trace is explained with
two points a side, and the crown as built ends 39.3, 52.1 (60 degrees) and 65.0, 135.1 mm (19) from the
truth: the 56 mm bow toward the first camera reads under 2 px, the default tol explains it with a straight
side, and the bow is the error. At 60 degrees every corner is decided by the views (prior_share 0.138 at
most, under core.VIEWS by 1.45); at 19 the plane has 0.30 to 0.38 of each. A side of two points has no
point of its own: it says corners."""
sides = pentagon(0.08)
for apart, sigma, most, by in ((60, 0.5, 0.06, "views"), (60, 1.5, 0.08, "views"), (19, 0.5, 0.1, "plane"), (19, 1.5, 0.2, "plane")):
out = blocked_plate(*plate_traces([plate_camera(0), plate_camera(apart)], sides, sigma))
self.assertLess(off_plate(out, sides), most, (apart, sigma))
self.assertEqual({corner["decided_by"] for corner in out["corners"]}, {by}, (apart, sigma))
self.assertLess(max(abs(corner["parallax_deg"] - apart) for corner in out["corners"]), 1.5)
self.assertEqual(out["plane"]["from"], "corners")
self.assertEqual([(side["decided_by"], side["inner"]) for side in out["sides"]], [("corners", [])] * 5)
kit.sheet(out["sheet"])
def test_views_5_degrees_apart_take_their_depth_from_a_plane_or_are_refused(self):
"""block-low-parallax, T06, T3, T08, T2, T26 (Soul s2, start-unpinned-and-comment-stale). The views start a
corner where one pixel moves their meeting point less than core.START x share x the plate's extent, the
prior's own scale; with no plane a plate blocks when three corners start. START is 1, the prior's own
unit: it is not derived from a measurement, it is pinned between two. At Paladin's lens and range the
pentagon's third corner starts at START 0.724 with the views 19 degrees apart, 0.831 at 16.5 and 2.729 at 5;
at 11 this test's plate (0.5 px, seed 7) turns from refused to blocked between START 1.22 and 1.23. So
at 16.5 degrees it blocks with no plane (73.0 mm from the truth) and at 11 it is refused naming its
corners: 1 stands 1.20 over the one reading and 1.22 under the other, the two's geometric mean within
1%. START 0.6 and 0.8 refuse the 16.5 degrees; 2.0, 2.6 and 3.3 block the 11 (104.4
mm off; the line switches blocking and refusal and is no cliff in accuracy). At 5 degrees the corners
triangulate 0.25 to 1.5 m off: with a plane every corner is decided by it (prior_share 0.795 to 0.838),
with none the plate is refused. The line is metres a pixel, not degrees: through a lens three times as
long the same plate 7 degrees apart starts at 0.648 and blocks from its views, 60.5 mm from the truth
(65.0 at 19 degrees through the short lens)."""
sides = pentagon(0.08)
self.assertEqual(blocked_plate(*plate_traces([plate_camera(0), plate_camera(16.5)], sides, 0.5))["plane"]["from"], "corners")
with self.assertRaisesRegex(core.ReferenceFitError, r"^plane: none was given, and 'c0', 'c1', 'c2', 'c3', 'c4' are decided by no view"):
blocked_plate(*plate_traces([plate_camera(0), plate_camera(11)], sides, 0.5))
views, traces = plate_traces([plate_camera(0), plate_camera(5)], pentagon(0.08), 0.5)
out = blocked_plate(views, traces, plane=ON_Y)
self.assertEqual([corner["decided_by"] for corner in out["corners"]], ["plane"] * 5)
self.assertGreater(min(corner["prior_share"] for corner in out["corners"]), 0.7)
self.assertEqual(out["plane"]["from"], "given")
with self.assertRaisesRegex(core.ReferenceFitError, r"^plane: none was given, and 'c0', 'c1', 'c2', 'c3', 'c4' are decided by no view"):
blocked_plate(views, traces)
sides = pentagon(0.08)
out = blocked_plate(*plate_traces([plate_camera(0, f=1989.0), plate_camera(7, f=1989.0)], sides, 0.5))
self.assertEqual(out["plane"]["from"], "corners")
self.assertLess(off_plate(out, sides), 0.1)
def test_a_side_grows_until_its_trace_is_explained(self):
"""block-growth, M6. A straight-sided plate blocks with its corners alone, 1.9 mm from the truth (the plane
draws its twisted corners in). Sides bowed 35% of their length in the plate grow to three points and every
trace reads under 1 px; M6 refuses the plate, its first side not explained at two points. The grown crown
ends 41.6 mm off: fairness holds the bow in while the traces stay explained (M4, in the class's notes)."""
cams = [plate_camera(0), plate_camera(60)]
out = blocked_plate(*plate_traces(cams, pentagon(0.0)))
self.assertEqual(([side["points"] for side in out["sides"]], out["rounds"], len(out["sheet"]["verts"])), ([2] * 5, 1, 11))
self.assertLess(off_plate(out, pentagon(0.0)), 0.004)
sides = pentagon(0.08, 0.35)
out = blocked_plate(*plate_traces(cams, sides))
self.assertEqual(([side["points"] for side in out["sides"]], out["rounds"], len(out["sheet"]["verts"])), ([3] * 5, 2, 21))
self.assertLess(max(trace["unexplained_px"] for side in out["sides"] for trace in side["traces"]), core.TOL / 1.2)
self.assertLess(off_plate(out, sides), 0.06)
def test_a_side_says_what_decided_its_inner_points(self):
"""interior-points (Soul s1), I1. The bowed pentagon from exact traces 60 degrees apart, asked at tol 0.1:
the sides grow to 4, 4, 4, 3, 4 points and every trace reads under 0.12 px, every corner is decided by the
views, and the side from c3 still ends 52.8 mm off the truth (the others 2.4 to 7.4). Its one inner point
has prior_share 0.405, twice core.VIEWS: the side says plane, and its inner point says why. A side whose
trace is explained is not thereby a side the views decided."""
sides = pentagon(0.08)
out = blocked_plate(*plate_traces([plate_camera(0), plate_camera(60)], sides), tol=0.1)
self.assertEqual([side["points"] for side in out["sides"]], [4, 4, 4, 3, 4])
self.assertEqual([len(side["inner"]) for side in out["sides"]], [2, 2, 2, 1, 2])
self.assertEqual({corner["decided_by"] for corner in out["corners"]}, {"views"})
self.assertLess(max(trace["unexplained_px"] for side in out["sides"] for trace in side["traces"]), 0.12)
off = [float(off_run(out, chain, side).max()) for chain, side in zip(crown_chains(out), sides)]
self.assertEqual(int(np.argmax(off)), 3)
self.assertEqual((out["sides"][3]["decided_by"], out["sides"][3]["inner"][0]["decided_by"]), ("plane", "plane"))
self.assertGreater(out["sides"][3]["inner"][0]["prior_share"], 1.2 * core.VIEWS)
self.assertEqual(set(out["sides"][3]["inner"][0]), {"decided_by", "m_per_px", "prior_share"})
def test_a_seam_corner_says_what_decided_it(self):
"""seam-corner-grazing (Soul s1), S1, S2, M5. A mirrored plate, its seam a to b on x = 0, traced in one view
0.5 px off with the plane y = 0.05 given. From 60 degrees off the mirror plane the seam's corners are
decided by it (prior_share 0.135 and 0.117, under core.VIEWS by 1.48; 7 mm off). From 10 degrees the sight
lines run along x = 0: the seam's corners are lifted onto the plane as any corner one view sees, and read
plane (0.571 and 0.513; 33 mm off): S1 reads them mirror. With a plane the view also runs along (its
normal 73 degrees off x) there is no depth at all, and the plate is refused naming the seam's corner: S2
and M5 block it."""
P, names = np.array([[0, 0, 0.6], [0, 0, -0.6], [0.5, 0.1, -0.5], [0.45, 0.1, 0.5]]), ["a", "b", "c", "d"]
def block(azimuth, normal):
rng, cam, traces = np.random.default_rng(1), plate_camera(azimuth), []
for i in range(4):
u = core.project(cam, P[[i, (i + 1) % 4]])
traces.append({"from": names[i], "to": names[(i + 1) % 4], "side": 1, "line": (np.linspace(u[0], u[1], 6) + rng.normal(0, 0.5, (6, 2))).tolist()})
return core.block_plate([(cam, EYE)] * 4, {"corners": names, "mirror": True, "seam": ["a", "b"]}, traces, kit.sheet, plane={"point": [0, 0.05, 0], "normal": normal})
out = block(60, [0, 1, 0])
self.assertEqual([corner["decided_by"] for corner in out["corners"]], ["mirror", "mirror", "plane", "plane"])
self.assertLess(max(corner["prior_share"] for corner in out["corners"][:2]), core.VIEWS / 1.2)
self.assertLess(max(float(np.linalg.norm(np.array(out["sheet"]["verts"])[k] - P[k])) for k in (0, 1)), 0.012)
out = block(10, [0, 1, 0])
self.assertEqual([corner["decided_by"] for corner in out["corners"]], ["plane"] * 4)
self.assertGreater(min(corner["prior_share"] for corner in out["corners"][:2]), 1.2 * core.VIEWS)
self.assertEqual([float(x) for x in np.array(out["sheet"]["verts"])[:2, 0]], [0.0, 0.0])
with self.assertRaisesRegex(core.ReferenceFitError, r"^plate\.corners\[0\] 'a': the plane stands 83 degrees off square-on to the view of traces\[0\]"):
block(10, [1, 0.3, 0])
def test_a_plate_keeps_its_proportions_at_any_size(self):
"""plate-template (Soul s1), K1. The pentagon at 0.1, 1 and 10 times its size through cameras as many times
as far: the skirt stands 0.078 of the crown's extent from the crown and the centre 0.017 of it proud at
every size, where a skirt of fixed metres stood 0.81 of a 0.11 m plate's extent out and 0.008 of an 11 m
one's. The crown blocks within a ten-thousandth of the extent at each."""
for scale in (0.1, 1.0, 10.0):
sides = [side * scale for side in pentagon(0.0, twist=0.0)]
out = blocked_plate(*plate_traces([plate_camera(0, distance=17.6 * scale), plate_camera(60, distance=17.6 * scale)], sides))
verts = np.array(out["sheet"]["verts"])
extent = float(np.linalg.norm(verts[:5, None] - verts[None, :5], axis=2).max())
self.assertAlmostEqual(float(np.linalg.norm(verts[5:10] - verts[:5], axis=1).mean()) / extent, math.hypot(core.FLARE, core.DROP), places=4)
self.assertAlmostEqual(float(np.linalg.norm(verts[10] - verts[:5].mean(0))) / extent, core.DOME, places=4)
self.assertLess(off_plate(out, sides), 1e-4 * extent)
def test_one_view_and_a_plane_block_a_bowed_plate(self):
"""M2. A flat plate in the plane it is given, its sides bowed 35% in the plate, traced exactly in one view
30 degrees off square-on: every corner is decided by the plane, the sides grow to three points and the
crown ends 85.1 mm off the truth. M2, which holds each point where it was started instead of to the plane,
ends 109.7 mm off: the bound is their geometric mean, separation 1.14 each side (1.29 across), the least
the ruling takes."""
sides = pentagon(0.0, 0.35, twist=0.0)
out = blocked_plate(*plate_traces([plate_camera(30)], sides), plane=ON_Y)
self.assertEqual([corner["decided_by"] for corner in out["corners"]], ["plane"] * 5)
self.assertEqual([corner["parallax_deg"] for corner in out["corners"]], [0.0] * 5)
self.assertEqual([side["points"] for side in out["sides"]], [3] * 5)
self.assertLess(off_plate(out, sides), 0.0966)
def test_a_plane_far_off_square_on_to_its_one_view_is_refused(self):
"""M5: the guard promoted from the Paladin harness (paladin_limbs.plate, the 8 m pauldron). One view 64
degrees off the plane's normal blocks the plate on it; at 68 degrees (cosine 0.375, under core.SQUARE) the
plate is refused naming the corner, the trace and the angle. M5 blocks it."""
sides = pentagon(0.0, twist=0.0)
out = blocked_plate(*plate_traces([plate_camera(64)], sides), plane=ON_Y)
self.assertLess(off_plate(out, sides), 1e-4)
with self.assertRaisesRegex(core.ReferenceFitError, r"^plate\.corners\[0\] 'c0': the plane stands 67 degrees off square-on to the view of traces\[0\]"):
blocked_plate(*plate_traces([plate_camera(68)], sides), plane=ON_Y)
def spectre(self, name):
fixture = json.loads((Path(__file__).resolve().parent / "fixtures" / "spectre_plates.json").read_text(encoding="utf-8"))
plate = fixture["plates"][name]
traces = [{"camera": trace["view"], **{key: trace[key] for key in ("from", "to", "side", "line")}, **({"frame": fixture["frames"]["hero"]} if trace["view"] == "hero" else {})} for trace in plate["traces"]]
return fixture, plate, core.block_plate([(fixture["cameras"][trace["view"]], fixture["frames"][trace["view"]]) for trace in plate["traces"]], plate["plate"], traces, kit.sheet)
def test_spectre_roof_and_cheek(self):
"""block-spectre, M1, M3, M6. SPECTRE's roof and cheek from no blocking (tests/fixtures/spectre_plates.json:
the brow, ridge and chine are hand traces, the sides nobody traced are edges of the fitted cage). Roof: the
brow's free corner is decided by the views (62.8 degrees, prior_share 0.054), the ridge's two by the mirror
plane; the ridge, traced in the side view alone, is built 7.3 mm at most from the fitted ridge and the brow
a median of 8.4 mm from the fitted brow (78.6 at most), in four points. M1 reads 27.7 and 18.9 (M4 19.8 on the brow): the bounds
are the geometric means, separations 1.95 and 1.50 each side. Cheek: the jaw, where the two hand traces
disagree by 0.27 m, stays on x = 0. M3 lands the roof's nose at x = -0.049 and the jaw at -0.140 and the
cage's parser refuses both; M1 puts the cheek's skirt across the plane and it is refused; M6 refuses both
at two points a side."""
fixture, plate, out = self.spectre("roof")
self.assertEqual([(corner["name"], corner["decided_by"]) for corner in out["corners"]], [("ridge_rear", "mirror"), ("nose", "mirror"), ("brow_rear", "views")])
self.assertLess(out["corners"][2]["prior_share"], core.VIEWS / 1.2)
self.assertGreater(out["corners"][2]["parallax_deg"], 60)
ridge, brow, rear = crown_chains(out)
self.assertEqual([side["points"] for side in out["sides"]], [2, 4, 2])
self.assertLess(float(off_run(out, ridge, plate["reference"]["ridge"]).max()), 0.0142)
self.assertLess(float(np.median(off_run(out, brow, plate["reference"]["brow"]))), 0.0126)
verts = np.array(out["sheet"]["verts"])
self.assertEqual(float(np.abs(verts[ridge, 0]).max()), 0.0)
self.assertEqual(out["left_out"], [1, 3]) # the hero poses the hull 3 degrees down: fit_shell has one frame
self.assertEqual([trace["run"] for trace in out["fit_traces"]], [{"verts": ridge}, {"verts": brow[::-1]}, {"verts": rear}])
fixture, plate, out = self.spectre("cheek")
self.assertEqual([(corner["name"], corner["decided_by"]) for corner in out["corners"]], [("chine_rear", "views"), ("jaw", "mirror"), ("chin", "mirror")])
chine, seam, _ = crown_chains(out)
self.assertEqual([float(x) for x in np.array(out["sheet"]["verts"])[seam, 0]], [0.0, 0.0])
self.assertEqual(out["sheet"]["mirror"], True)
self.assertEqual(out["sheet"]["poles"], [seam[0], seam[1], len(out["sheet"]["verts"]) - 1])
def test_the_rendered_roof_blocks_from_traces_of_its_renders(self):
"""block-truth (Soul s1, real-readings-not-accuracy; Soul s2, bound-premise-seeded-by-truth), M3. SPECTRE's
pass-3 roof, a hard mirrored cage of 11 known vertices, built by brokkr_kitbash.shell, rendered through
SPECTRE's two solved cameras at the sheet's pixel size and its edges traced off the renders: one plate,
one pair of views. The ridge is traced in the side view alone, the lip, the outer edge and the rear edge
in the hero's mirrored half and in the side view, 62 degrees apart; the side view's pixel is 27.6 mm
across at the plate, the hero's 11.6.
The traces are the fixture's takes (tests/fixtures/spectre_truth.json says how): a search for the
strongest brightness step across each edge, from a seed that is not on the answer. Six families of twelve
draws: the truth's projection moved as one by 0.5, 1 and 1.5 px in a drawn direction (a 2.5 px window),
and each of its vertices moved by a normal draw of 1 and 2 px (3.5 px) and of 3 px (6 px). Such a take's
points stand 2.1 to 30.7 px from the truth's projection, 6.8 at the median: a stroke ends where it
crosses its neighbours, and two that run nearly along each other cross far off. 62 of the 72 block (12,
12, 11, 10, 10, 7 by family; nine are refused at a side not explained at six points, one at the cage's
parser), every one with the ridge's six corners decided by the mirror plane and the outer edge's five by
the views (prior_share 0.037 at most).
What the takes read: a blocked plate's worst corner over its take's worst point x the coarser view's
pixel is 1.18 at most (1.12, 1.16, 1.18, 1.04, 1.06, 1.11 by family), 33 to 929 mm, 142 at the median;
the three draws that grow a side stand at 0.51, 0.75 and 1.08. That is no bound: a take's worst point is
one far crossing, and it inflates the denominator (Soul s3, bound-is-the-takes-outliers). The bound is
BOUND, set by test_every_point_as_far_off_bounds_the_rendered_roof, and the takes are held to it. M3
lands the ridge off x = 0 and every take is refused. No bound is stated in the takes' rms: against the
rms the same readings reach 5.3. A search seeded on the truth's projection itself is no reading: its
2.5 px window ends its strokes 2.5 px off and its plate 39 mm off."""
corners = ["ridge_rear", "r4", "r3", "r2", "r1", "nose", "a", "b", "c", "d", "e"]
views, plate, traces, sides, (fixture, record) = rendered("roof", corners)
middle = np.mean(list(record["truth"].values()), axis=0)
pixel = max(float(np.linalg.norm(np.array(cam["C"]) - middle)) / cam["f"] for cam in fixture["cameras"].values())
self.assertAlmostEqual(pixel, 0.0276, places=4)
self.assertEqual(len(record["takes"]), 72)
blocked = 0
for take in range(len(record["takes"])):
views, plate, traces, sides, _ = rendered("roof", corners, take=take)
try:
out = core.block_plate(views, plate, traces, kit.sheet)
except core.ReferenceFitError:
continue
blocked += 1
self.assertEqual([corner["decided_by"] for corner in out["corners"]], ["mirror"] * 6 + ["views"] * 5, take)
self.assertLess(max(corner["prior_share"] for corner in out["corners"]), core.VIEWS / 1.2, take)
self.assertGreater(min(corner["parallax_deg"] for corner in out["corners"][6:]), 59, take)
self.assertEqual(max(abs(float(np.array(out["sheet"]["verts"])[chain[0], 0])) for chain in crown_chains(out)[:6]), 0.0, take)
self.assertLess(off_rendered(out, sides)[0], self.BOUND * off_projection(fixture, record, take) * pixel, take)
self.assertGreaterEqual(blocked, 52)
BOUND = 2.08 # a blocked plate's worst corner, in its worst traced point x the coarser view's pixel: one plate, one pair of views
FAR = [0, 107, 45, 33, 216, 300, 270, 165, 99, 150, 45, 30, 90, 270, 180, 285, 345, 270, 90, 240, 125, 184, 321, 279] # degrees, a point: the worst a search found
def test_every_point_as_far_off_bounds_the_rendered_roof(self):
"""block-bound (Soul s3, bound-is-the-takes-outliers, bound-families-left-out), M1. The worst a trace
does for its worst point is to have no outlier: every point of every stroke the same d px off the
truth's projection. No search, no renders: the rendered roof's truth drawn through its two cameras and
moved. Each view moved as one, 12 directions by 12 at 1 px: all 144 block and the worst corner stands
1.005 to 1.505 x d x the coarser view's pixel off (1.096 at the median; 1.504 and 1.502 at 2 and 3 px).
M1 reads 2.865 there: BOUND, 2.08, is the geometric mean, separation 1.38 each side. Each stroke its own
direction reaches 1.582 (a coordinate ascent over 12 and 36 directions, six starts) and each point its
own 1.666 at 1 px and 1.659 at 3: FAR, a coordinate ascent over 8 directions from nine starts, which
end at 1.57 to 1.65, the best refined over 24. FAR is the worst found, not the worst there is; BOUND
stands 1.25 over it and claims no mutant there (M1 reads 1.994). The eight families of searched takes,
40 fresh draws each, read 1.11 to 1.33 (docs/reference.md), every one under the 1.505."""
corners = ["ridge_rear", "r4", "r3", "r2", "r1", "nose", "a", "b", "c", "d", "e"]
_, _, _, _, (fixture, record) = rendered("roof", corners)
middle = np.mean(list(record["truth"].values()), axis=0)
pixel = max(float(np.linalg.norm(np.array(cam["C"]) - middle)) / cam["f"] for cam in fixture["cameras"].values())
def reads(d, degrees):
views, plate, traces, sides, _ = rendered("roof", corners, off=(d, degrees))
return off_rendered(core.block_plate(views, plate, traces, kit.sheet), sides)[0] / (d * pixel)
moved = [reads(1.0, [side if stroke["view"] == "side" else hero for stroke in record["strokes"] for _ in stroke["through"]])
for hero in range(0, 360, 30) for side in range(0, 360, 30)]
self.assertLess(max(moved), self.BOUND)
for d in (1.0, 3.0):
self.assertLess(1.6, reads(d, self.FAR), d) # still the far draw
self.assertLess(reads(d, self.FAR), self.BOUND, d)
def test_fairness_is_set_by_the_rendered_roof(self):
"""fair (Soul s1, fair-default-tuned-to-a-fit), F5, M4, M2. The rendered roof with four corners named
(ridge_rear, nose, a, e), so the ridge and the outer edge are one side each and grow through their knees:
from the traces as taken they grow to three points and stand 196.0 mm from the true edges at most, the
hard knees cut by a run that reads as explained within tol (5.2 px is 144 mm in the side view). With every
point 2 px off and the closing strokes moved 3 px, 24 draws: 15 block, and nine tenths of those stand
within 196.9 mm. FAIR 0.5 reads 369.5 there, no fairness 394.0, M2 388.8: the bound is the geometric mean
of 196.9 and 369.5, separation 1.37 each side. Over ten cells of known truth at 1 and 2 px (this roof four
ways, and the bowed pentagon at 60 and 30 degrees and in one view) the mean of the cells' 90th percentiles
reads 194, 184, 178, 178, 179, 186, 193, 196 mm at FAIR 0.1, 0.15, 0.2, 0.25, 0.3, 0.4, 0.5, 1 and the
worst draw 301, 275, 273, 272, 312, 382, 494, 577, over the draws that blocked: 19, 20, 23, 24, 24, 25,
26, 27 of the 168 are refused and counted in neither. FAIR is flat from 0.1 to 0.3: 0.2 and 0.25
tie here, and on Soul's seeds (verdict cut-trace-block.s3) 0.1, 0.15 and 0.2 read 196, 196, 195. 0.2 is
kept as a point on that plateau, not a resolved lowest (docs/reference.md has all three sets). The roof's strokes here are the fixture's
own, searched from the truth's projection, with the noise added on top. From exact traces weaker
fairness is nearer the truth (the bowed pentagon: 41.6 mm at 0.2, 16.2 at 0.5, 12.1 with none); nobody
traces exactly, and at 1 px the difference is 16 mm at 60 degrees and the other way at 30."""
corners = ["ridge_rear", "nose", "a", "e"]
views, plate, traces, sides, _ = rendered("roof", corners)
out = core.block_plate(views, plate, traces, kit.sheet)
self.assertEqual([side["points"] for side in out["sides"]], [3, 2, 3, 2])
self.assertLess(off_rendered(out, sides)[1], 0.235)
edges = []
for seed in range(24):
views, plate, traces, sides, _ = rendered("roof", corners, 2.0, 3.0, seed)
try:
edges.append(off_rendered(core.block_plate(views, plate, traces, kit.sheet), sides)[1])
except core.ReferenceFitError:
pass
self.assertGreaterEqual(len(edges), 12)
self.assertLess(sorted(edges)[math.ceil(0.9 * len(edges)) - 1], 0.270)
def test_raptor_plate_from_two_views(self):
"""block-raptor (tests/fixtures/raptor_plates.json): the hull plate bearing RAPTOR's 27, its corners marked
by eye in the hero (right flank) and in the SIDE view (left flank, side -1). The hero camera is solved
from hull marks alone (the nose, both emitters, the plate's corners): the seven admit none under 25.1 px
rms at 50 mm (the sheet's hero and SIDE view do not draw one rigid hull), where the first hero, solved
from leg joints, stood 18.5 degrees from the SIDE view and drew the hull tens of pixels off. Through it
the plate blocks from its two views: sight lines 33.9 to 40.1 degrees apart, every trace explained
within 3.2 px, the corners on the right flank at x 0.87 to 1.72 m. The prior has 0.173 to 0.197 of each
corner, under core.VIEWS by less than the margin, so the label is not asserted: on this sheet two views
decide a flank corner only just. No truth exists for the plate and four of the camera's seven marks are
its corners: this is two views agreeing, pinned as it read, not an accuracy."""
fixture = json.loads((Path(__file__).resolve().parent / "fixtures" / "raptor_plates.json").read_text(encoding="utf-8"))
solved = core.solve(fixture["world"], fixture["pixels"], fixture["box"], model="rolled", lens=50)
self.assertGreater(solved["rms"], 20)
self.assertLess(float(np.abs(np.array(solved["C"]) - fixture["cameras"]["hero"]["C"]).max()), 1e-6)
traces = [{key: trace[key] for key in ("from", "to", "side", "line")} for trace in fixture["traces"]]
out = core.block_plate([(fixture["cameras"][trace["view"]], EYE) for trace in fixture["traces"]], fixture["plate"], traces, kit.sheet)
self.assertGreater(min(corner["parallax_deg"] for corner in out["corners"]), 30)
self.assertLess(max(corner["prior_share"] for corner in out["corners"]), 1.2 * core.VIEWS)
self.assertLess(max(trace["unexplained_px"] for side in out["sides"] for trace in side["traces"]), core.TOL / 1.2)
self.assertEqual((out["plane"]["from"], [side["points"] for side in out["sides"]]), ("corners", [2] * 4))
crown = np.array(out["sheet"]["verts"])[:4]
self.assertTrue((crown[:, 0] > 0.8).all() and (crown[:, 0] < 1.8).all(), crown[:, 0])
def test_paladin_plates_one_view_each(self):
"""block-paladin (tests/fixtures/paladin_plates.json). Paladin's 16 traced plates, each a polygon traced in
one view with the plane the agent gave it: every corner is decided by the plane (prior_share 1.00 to 2.13:
over 1 where the sight line leans on the plane), every side stays two points, and the crown is the one the
harness lifted onto that plane, within 1 mm (its fit_shell read 0.65 to 1.0 on the same plates). None of
the 16 planes stands over 66 degrees off its view at e688951 (ForearmL.Outer, 61.6, is the furthest): the
guard is claimed by test_a_plane_far_off_square_on_to_its_one_view_is_refused. The thigh shields as
partners, the left's polygon seen as the right's reflection in the left thigh's frame, are refused, a side
19.0 px unexplained at six points: the sheet's two polygons are not one plate mirrored (their lifted corners
stand 0.16 to 0.77 m apart), so no Paladin plate has a corner decided by a partner view here."""
fixture = json.loads((Path(__file__).resolve().parent / "fixtures" / "paladin_plates.json").read_text(encoding="utf-8"))
def block(name):
plate = fixture["plates"][name]
views = [(fixture["cameras"][trace["view"]], fixture["frames"][trace["frame"]]) for trace in plate["traces"]]
return plate, core.block_plate(views, plate["plate"], [{key: trace[key] for key in ("from", "to", "side", "line")} for trace in plate["traces"]], kit.sheet, plane=plate.get("plane"))
single = sorted(name for name in fixture["plates"] if name != "ThighShield.partners")
self.assertEqual(len(single), 16)
for name in single:
plate, out = block(name)
n = len(plate["plate"]["corners"])
self.assertEqual(({corner["decided_by"] for corner in out["corners"]}, [side["points"] for side in out["sides"]], out["plane"]["from"]), ({"plane"}, [2] * n, "given"), name)
self.assertGreater(min(corner["prior_share"] for corner in out["corners"]), 0.9, name)
crown, lifted = np.array(out["sheet"]["verts"])[:n], np.array(plate["reference"]["crown"]) # the harness turned some crowns to face out: the same ring from another corner, or the other way round
self.assertLess(min(float(np.abs(crown - np.roll(lifted[::way], turn, axis=0)).max()) for way in (1, -1) for turn in range(n)), 0.001, name)
with self.assertRaisesRegex(core.ReferenceFitError, r"^the side from 'c0' to 'c1' is not explained at 6 points, the most a side is given: traces\[0\] is not explained"):
block("ThighShield.partners")
def test_the_blocking_goes_to_the_parser_and_to_fit_shell(self):
"""block-then-fit without Blender (tests/live/reference_block.py builds it): the sheet is one the cage's
parser takes, fit_traces name each side as a run of authored vertices, and fit_sheet takes both. On the
straight plate fit_shell's own prior moves no point 5 mm (2.2 at most: the plane had drawn the twisted
corners in); on the bowed plate it moves the grown points up to 74 mm, back toward the bow fairness held in."""
cams = [plate_camera(0), plate_camera(60)]
for sides, most in ((pentagon(0.0), 0.005), (pentagon(0.08, 0.35), 0.09)):
views, traces = plate_traces(cams, sides)
out = blocked_plate(views, traces)
self.assertEqual((len(out["fit_traces"]), out["left_out"]), (10, []))
self.assertEqual(set(out["fit_traces"][0]), {"camera", "run", "side", "line"})
fit = core.fit_sheet(out["sheet"], kit.sheet(out["sheet"]), EYE, out["fit_traces"], [cam for cam, _ in views])
self.assertLess(max(point["moved_m"] for point in fit["points"]), most)
self.assertLess(len(json.dumps(out, separators=(",", ":"))), core.RESULT_LIMIT)
def test_block_refusals_name_their_field(self):
"""block-refusals."""
cams = [plate_camera(0), plate_camera(60)]
views, traces = plate_traces(cams, pentagon(0.0))
def refused(pattern, views_=views, traces_=traces, plate=None, parse=None, **more):
with self.assertRaisesRegex(core.ReferenceFitError, pattern):
core.block_plate(views_, plate or {"corners": PLATE}, traces_, parse or kit.sheet, **more)
keep = [k for k, trace in enumerate(traces) if trace["from"] != "c2"]
refused(r"^the side from 'c2' to 'c3' is traced in no view", [views[k] for k in keep], [traces[k] for k in keep])
keep = [k for k, trace in enumerate(traces) if trace["from"] not in ("c1", "c2")]
refused(r"^plate\.corners\[2\] 'c2': no trace ends at it", [views[k] for k in keep], [traces[k] for k in keep])
refused(r"^traces\[0\]\.from 'c0' and \.to 'c2' are not consecutive corners", traces_=[{**traces[0], "to": "c2"}] + traces[1:])
refused(r"^traces\[0\]\.from and \.to must name corners", traces_=[{**traces[0], "to": "c9"}] + traces[1:])
refused(r"^traces\[3\]\.camera 'View1' is no camera of this plate", views[:3] + [(None, EYE)] + views[4:])
refused(r"^traces\[1\]\.frame must be a 4 x 4 that only turns and moves", views[:1] + [(cams[1], (2 * np.eye(4)).tolist())] + views[2:])
refused(r"^traces\[2\]\.side must be 1, or -1", traces_=traces[:2] + [{**traces[2], "side": 2}] + traces[3:])
refused(r"^traces\[2\]\.line must be two or more", traces_=traces[:2] + [{**traces[2], "line": [[1, 2]]}] + traces[3:])
refused(r"^traces\[2\] must be \{camera, box, frame, from, to, side, line\}", traces_=traces[:2] + [{**traces[2], "run": {}}] + traces[3:])
refused(r"^plate\.corners must be three or more different names", plate={"corners": ["a", "b"]})
refused(r"^plate\.seam must name two or more corners next to each other", plate={"corners": PLATE, "mirror": True, "seam": ["c0"]})
refused(r"^plate\.seam must name two or more corners next to each other", plate={"corners": PLATE, "seam": ["c0", "c1"]})
refused(r"^plane must be \{point: \[x, y, z\], normal: \[x, y, z\]\}", plane={"point": [0, 0, 0], "normal": [0, 0, 0]})
def no(document):
raise kit.KitError("sheet.verts[0] is not to its taste")
refused(r"^sheet: the cage's parser does not take the plate as blocked \(sheet\.verts\[0\] is not to its taste\)", parse=no)
long = [{**trace, "line": core.resampled(np.array(trace["line"]), 160).round(1).tolist()} for trace in traces]
refused(r"^traces: the sheet and its report could be about \d+ characters, over the 16000", traces_=long)
# a mirrored plate's corner drawn across the mirror plane from the others
P, names = np.array([[0, 0, 0.5], [0, 0, -0.5], [0.5, 0.1, -0.4], [-0.05, 0.1, 0.4]]), ["a", "b", "c", "d"]
mirrored = [{"from": names[i], "to": names[(i + 1) % 4], "side": 1, "line": core.project(cam, P[[i, (i + 1) % 4]]).tolist()} for i in range(4) for cam in cams]
refused(r"^plate\.corners\[3\] 'd' starts at x = -0\.050, across the mirror plane", [(cam, EYE) for _ in range(4) for cam in cams], mirrored, {"corners": names, "mirror": True, "seam": ["a", "b"]})
@unittest.skipIf(np is None, "numpy") @unittest.skipIf(np is None, "numpy")
class CameraTests(unittest.TestCase): class CameraTests(unittest.TestCase):
CAM = {"C": [3.0, -7.0, 2.5], "f": 1400.0, "c": [640.0, 395.0], "box": BOX} CAM = {"C": [3.0, -7.0, 2.5], "f": 1400.0, "c": [640.0, 395.0], "box": BOX}
@ -780,8 +1312,8 @@ class HostFileTests(unittest.TestCase):
def test_the_row_names_the_operator_and_properties_the_add_on_defines(self): 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") 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", "brokkr_reference.fit_shell"]) self.assertEqual([row["name"] for row in self.document["actions"]], ["brokkr_reference.solve_camera", "brokkr_reference.flow_score", "brokkr_reference.fit_shell", "brokkr_reference.block_plate"])
self.assertEqual(source.count("bl_idname = "), 3) self.assertEqual(source.count("bl_idname = "), 4)
for row in self.document["actions"]: for row in self.document["actions"]:
self.assertIn(f'bl_idname = "{row["name"]}"', source) self.assertIn(f'bl_idname = "{row["name"]}"', source)
self.assertEqual(row.get("result"), "brokkr_mesh_polish_result") self.assertEqual(row.get("result"), "brokkr_mesh_polish_result")
@ -807,6 +1339,11 @@ class HostFileTests(unittest.TestCase):
for bad in ({"tol": 0}, {"share": 11}, {"traces": ""}, {"object_name": "x" * 64}): for bad in ({"tol": 0}, {"share": 11}, {"traces": ""}, {"object_name": "x" * 64}):
with self.assertRaises(at.IntentInvalid): with self.assertRaises(at.IntentInvalid):
at.validate({**fit, **bad}, self.host) at.validate({**fit, **bad}, self.host)
block = {**self.envelope, "action": "brokkr_reference.block_plate", "frame_object": "Frame", "plate": "{}", "traces": "[{}]"}
self.assertEqual((at.validate(block, self.host)["share"], at.validate(block, self.host)["tol"], at.validate(block, self.host)["plane"]), (0.1, core.TOL, ""))
for bad in ({"tol": 0}, {"share": 11}, {"traces": ""}, {"plate": ""}, {"frame_object": "x" * 64}, {"plane": "x" * 201}):
with self.assertRaises(at.IntentInvalid):
at.validate({**block, **bad}, self.host)
class OwnershipTests(unittest.TestCase): class OwnershipTests(unittest.TestCase):
@ -827,7 +1364,7 @@ class OwnershipTests(unittest.TestCase):
decided by matching trace points to each other.""" decided by matching trace points to each other."""
for path in (SURFACE / "brokkr_reference").glob("*.py"): for path in (SURFACE / "brokkr_reference").glob("*.py"):
text = path.read_text(encoding="utf-8") 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"def pair|_smoothest|cage_through|on_plane|epipolar", text), path.name)
self.assertIsNone(re.search(r"SHELL\] *=|kit_shell\"\] *=|\.data\.vertices|foreach_set|from_pydata", 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): def test_no_other_package_names_this_one(self):