Merge pull request 'brokkr_reference.fit_shell: a shell's traced runs fitted through solved cameras, accepted only where the built runs explain every trace (cut trace-fit)' (#41) from nibu/trace-fit into main
This commit is contained in:
commit
e141d003b8
9 changed files with 1572 additions and 12 deletions
|
|
@ -1044,7 +1044,8 @@ class Sheet(NamedTuple):
|
|||
poles (P,) are the cage's vertices of irregular valence, as built; triangles is how many faces have 3 sides.
|
||||
boundary is the Subdivision's Boundary Smooth, by Blender's name: PRESERVE_CORNERS on a loft (a boundary vertex
|
||||
of two edges stays a corner), ALL on a free cage (the boundary is smoothed through it unless a corner pins it),
|
||||
which is how a cage modelled by hand is set."""
|
||||
which is how a cage modelled by hand is set. mirror_of (V,) is, per vertex, the authored vertex it reflects
|
||||
across x = 0, or itself: an authored vertex, one on the mirror plane, every vertex of a sheet not mirrored."""
|
||||
V: np.ndarray
|
||||
faces: np.ndarray
|
||||
counts: np.ndarray
|
||||
|
|
@ -1059,6 +1060,7 @@ class Sheet(NamedTuple):
|
|||
poles: np.ndarray
|
||||
triangles: int
|
||||
boundary: str
|
||||
mirror_of: np.ndarray
|
||||
|
||||
|
||||
def _index(value: Any, where: str, least: int, most: int) -> int:
|
||||
|
|
@ -1130,6 +1132,9 @@ def sheet(document: Any) -> Sheet:
|
|||
vertex = lambda i, j: i * N + j % N # noqa: E731
|
||||
quads = np.array([[vertex(i, j), vertex(i, j + 1), vertex(i + 1, j + 1), vertex(i + 1, j)] for i in range(R - 1) for j in range(wrap)], dtype=np.int32)
|
||||
V = P.reshape(-1, 3)
|
||||
mirror_of = np.arange(R * N).reshape(R, N)
|
||||
if mirror:
|
||||
mirror_of[:, :C - 1] = mirror_of[:, :C - 1:-1]
|
||||
corners = V[quads]
|
||||
areas = 0.5 * (np.linalg.norm(np.cross(corners[:, 1] - corners[:, 0], corners[:, 3] - corners[:, 0]), axis=1)
|
||||
+ np.linalg.norm(np.cross(corners[:, 3] - corners[:, 2], corners[:, 1] - corners[:, 2]), axis=1))
|
||||
|
|
@ -1196,7 +1201,7 @@ def sheet(document: Any) -> Sheet:
|
|||
return Sheet(V=V.copy(), faces=quads.ravel().astype(np.int32), counts=np.full(len(quads), 4, dtype=np.int32), smooth=np.ones(len(quads), dtype=bool),
|
||||
sharp=NO_SHARP, creases=np.array([key for key, _ in kept], dtype=np.int64).reshape(-1, 2), weights=np.array([w for _, w in kept], dtype=np.float64),
|
||||
corners=np.array([key for key, _ in pinned], dtype=np.int64), corner_weights=np.array([w for _, w in pinned], dtype=np.float64), rings=R, points=N,
|
||||
poles=np.zeros(0, dtype=np.int64), triangles=0, boundary="PRESERVE_CORNERS")
|
||||
poles=np.zeros(0, dtype=np.int64), triangles=0, boundary="PRESERVE_CORNERS", mirror_of=mirror_of.ravel())
|
||||
|
||||
|
||||
def _cage_facts(vertices: int, faces, counts):
|
||||
|
|
@ -1321,6 +1326,7 @@ def _cage(document: Any, gate: bool = True) -> Sheet:
|
|||
if mirror and seam[a] and seam[b] and len(both) == 2:
|
||||
raise KitError(f"sheet.faces[{both[0]}] and sheet.faces[{both[1]}] share the edge between vertices {min(a, b)} and {max(a, b)}, which lies on the mirror plane: "
|
||||
"with their reflections that edge is in four faces (a fin on the plane)")
|
||||
mirror_of = np.concatenate([np.arange(A), np.flatnonzero(~seam)]) if mirror else np.arange(A)
|
||||
twin = np.arange(A)
|
||||
if mirror:
|
||||
twin[~seam] = A + np.arange(int((~seam).sum()))
|
||||
|
|
@ -1398,7 +1404,7 @@ def _cage(document: Any, gate: bool = True) -> Sheet:
|
|||
return Sheet(V=V, faces=flat, counts=counts, smooth=np.ones(len(counts), dtype=bool), sharp=NO_SHARP,
|
||||
creases=np.array([key for key, _ in kept], dtype=np.int64).reshape(-1, 2), weights=np.array([w for _, w in kept], dtype=np.float64),
|
||||
corners=np.array([key for key, _ in held], dtype=np.int64), corner_weights=np.array([w for _, w in held], dtype=np.float64),
|
||||
rings=None, points=None, poles=poles, triangles=int((counts == 3).sum()), boundary="ALL")
|
||||
rings=None, points=None, poles=poles, triangles=int((counts == 3).sum()), boundary="ALL", mirror_of=mirror_of)
|
||||
|
||||
|
||||
# --- reports -------------------------------------------------------------------------------------------------
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
"""Fit a scene to a reference image: the camera a reference view was drawn through, solved from marked points,
|
||||
and traced lines scored against the edges the camera sees on the build.
|
||||
traced lines scored against the edges the camera sees on the build, and a kitbash shell's sheet fitted to traces of
|
||||
its hard runs.
|
||||
|
||||
A host add-on for Brokkr beside brokkr_mesh_polish (it imports that package's operator base, and nothing from
|
||||
Brokkr): brokkr_actions.json beside this file lists the operators agents may run (docs/reference.md). The
|
||||
|
|
@ -9,12 +10,17 @@ JSON report to WindowManager.brokkr_mesh_polish_result, as the polish operators
|
|||
The camera record core.solve returns is the truth; a Blender camera stood at it is derived by core.blender, and
|
||||
core.camera_of reads one back (flow_score takes the camera that way, by its object's name). The images, traces
|
||||
and masks a view is marked on stay with whoever marked them: this package takes points and lines and gives
|
||||
cameras and scores. The edges flow_score reads are computed on each call and kept nowhere.
|
||||
cameras, scores and a fitted sheet. The edges flow_score reads are computed on each call and kept nowhere.
|
||||
|
||||
fit_shell reads a shell's request through brokkr_kitbash (the sheet's one parser) and returns a sheet; it writes
|
||||
nothing. brokkr_kitbash.shell is the cage's one writer: the caller applies the fitted sheet with it.
|
||||
"""
|
||||
bl_info = {"name": "Brokkr Reference", "author": "GameCult", "version": (0, 1, 0), "blender": (4, 2, 0),
|
||||
"category": "Camera", "description": "Solve a reference view's camera from marked points; agent-callable through Brokkr."}
|
||||
|
||||
import json
|
||||
import math
|
||||
import time
|
||||
|
||||
import bpy
|
||||
import numpy as np
|
||||
|
|
@ -204,7 +210,60 @@ class BROKKR_REFERENCE_OT_flow_score(PolishOperator):
|
|||
"objects": [o.name for o in meshes], "height": height}
|
||||
|
||||
|
||||
classes = (BROKKR_REFERENCE_OT_solve_camera, BROKKR_REFERENCE_OT_flow_score)
|
||||
class BROKKR_REFERENCE_OT_fit_shell(PolishOperator):
|
||||
"""Fit a kitbash shell's sheet to traces of its hard runs through solved cameras, and return the fitted sheet
|
||||
only where the built runs explain every trace; nothing is written"""
|
||||
bl_idname = "brokkr_reference.fit_shell"
|
||||
bl_label = "Fit Shell To Traces"
|
||||
object_name: bpy.props.StringProperty(name="Object", maxlen=63, description="A shell made by brokkr_kitbash.shell, unscaled; its place in the world is the sheet's frame")
|
||||
traces: bpy.props.StringProperty(name="Traces", maxlen=12000, description="A JSON array of {camera, box, run: {ring|column, from, to} on a loft or {verts: [v, ...]} on a free cage, side, line: [[u, v], ...]}")
|
||||
share: bpy.props.FloatProperty(name="Share", default=0.1, min=0.0009, max=10.0, description="A move of this share of the sheet's diagonal from the sheet as it stands costs what one pixel of miss does")
|
||||
tol: bpy.props.FloatProperty(name="Tolerance", default=core.TOL, min=0.09, max=100.0, description="Pixels: nine tenths of every trace must lie this near its built run, or the fit is refused")
|
||||
|
||||
# the action table states share from 0.001 and tol from 0.1: a float property rounds those up, so its bounds stand just under
|
||||
def work(self, context):
|
||||
try:
|
||||
import brokkr_kitbash
|
||||
except ImportError as error:
|
||||
raise Refused(f"fit_shell needs the brokkr_kitbash add-on beside this one ({error}).") from None
|
||||
obj = bpy.data.objects.get(self.object_name)
|
||||
if obj is None or obj.type != "MESH" or brokkr_kitbash.SHELL not in obj:
|
||||
raise Refused(f"{self.object_name!r} is not a shell brokkr_kitbash.shell made (a mesh carrying {brokkr_kitbash.SHELL}).")
|
||||
if max(abs(v - 1.0) for v in obj.matrix_world.to_scale()) > 1e-6:
|
||||
raise Refused(f"{obj.name!r} is scaled {tuple(round(v, 6) for v in obj.matrix_world.to_scale())}: a sheet is in metres of the shell's own frame. Apply or clear the scale.")
|
||||
try:
|
||||
document = json.loads(obj[brokkr_kitbash.SHELL])["sheet"]
|
||||
cage = brokkr_kitbash.core.sheet(document)
|
||||
except (ValueError, KeyError, TypeError, brokkr_kitbash.core.KitError) as error:
|
||||
raise Refused(f"{obj.name!r} carries a request its own parser does not take ({error}).") from None
|
||||
try:
|
||||
traces = json.loads(self.traces)
|
||||
except ValueError as error:
|
||||
raise Refused(f"traces is not JSON ({error}).") from None
|
||||
if not isinstance(traces, list) or not all(isinstance(trace, dict) for trace in traces):
|
||||
raise Refused("traces must be a JSON array of objects {camera, box, run, side, line}.")
|
||||
cams = []
|
||||
for k, trace in enumerate(traces):
|
||||
if set(trace) - {"camera", "box", "run", "side", "line"}:
|
||||
raise Refused(f"traces[{k}] has {sorted(set(trace) - {'camera', 'box', 'run', 'side', 'line'})}: a trace is {{camera, box, run, side, line}}.")
|
||||
box = trace.get("box")
|
||||
if box is not None and not (isinstance(box, list) and len(box) == 4 and all(isinstance(v, (int, float)) and not isinstance(v, bool) for v in box)):
|
||||
raise Refused(f"traces[{k}].box must be [u0, v0, u1, v1], or absent for the render's own frame.")
|
||||
if not isinstance(trace.get("camera"), str):
|
||||
raise Refused(f"traces[{k}].camera must name a camera object.")
|
||||
try:
|
||||
cams.append(record(context, trace["camera"], "" if box is None else ",".join(repr(float(v)) for v in box)))
|
||||
except (Refused, core.ReferenceFitError) as refusal:
|
||||
raise Refused(f"traces[{k}]: {refusal}") from None
|
||||
started = time.perf_counter()
|
||||
try:
|
||||
out = core.fit_sheet(document, cage, [list(row) for row in obj.matrix_world], traces, cams, share=self.share, tol=self.tol)
|
||||
except core.ReferenceFitError as refusal:
|
||||
raise Refused(f"{refusal}. Nothing changed.") from None
|
||||
return {"object": obj.name, **out, "seconds": round(time.perf_counter() - started, 3)}
|
||||
|
||||
|
||||
classes = (BROKKR_REFERENCE_OT_solve_camera, BROKKR_REFERENCE_OT_flow_score, BROKKR_REFERENCE_OT_fit_shell)
|
||||
|
||||
|
||||
def register():
|
||||
|
|
|
|||
|
|
@ -133,6 +133,47 @@
|
|||
"doc": "degrees between two faces' normals past which their edge is a crease"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "brokkr_reference.fit_shell",
|
||||
"doc": "Fit a kitbash shell's sheet (a loft or a free cage) to traces of its hard crease and rim runs, each seen through a scene camera: the traced runs' cage points move until the runs as built draw on the traces. Returns the fitted sheet for brokkr_kitbash.shell only where nine tenths of every trace lies within tol px of its built run; otherwise it is refused naming the trace, its reading and the span. A very unsteady hand and a 1 to 2% overdraw read alike: each trace's reading (unexplained_px) and worst point (worst_px) are in the report to judge by. Writes nothing. Per moved point: its depth sensitivity (metres one pixel of trace error moves it along its sight line, across its run; a sensitivity, not an error bound) and the prior's share of that: under 0.2 the traces decide the point, over it the blocking holds it (docs/reference.md).",
|
||||
"changesScene": true,
|
||||
"editModeSafe": false,
|
||||
"result": "brokkr_mesh_polish_result",
|
||||
"fields": [
|
||||
{
|
||||
"name": "object_name",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"minLength": 1,
|
||||
"maxLength": 63,
|
||||
"doc": "a shell made by brokkr_kitbash.shell, unscaled; its place in the world is the sheet's frame"
|
||||
},
|
||||
{
|
||||
"name": "traces",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"minLength": 2,
|
||||
"maxLength": 12000,
|
||||
"doc": "a JSON array of {camera, box, run, side, line}: camera a camera object's name; box [u0,v0,u1,v1], its frame on the image, absent for the render's own; run {ring, from, to} or {column, from, to} on a loft, {verts: [v, ...]} on a free cage, in authored indices, as the sheet's creases name runs; side 1, or -1 for the mirrored half; line [[u,v],...] drawn from the run's first point to its last"
|
||||
},
|
||||
{
|
||||
"name": "share",
|
||||
"type": "number",
|
||||
"minimum": 0.001,
|
||||
"maximum": 10,
|
||||
"default": 0.1,
|
||||
"doc": "the prior: a move of this share of the sheet's diagonal from the sheet as it stands costs what one pixel of miss does"
|
||||
},
|
||||
{
|
||||
"name": "tol",
|
||||
"type": "number",
|
||||
"minimum": 0.1,
|
||||
"maximum": 100,
|
||||
"default": 5.2,
|
||||
"doc": "pixels: nine tenths of every trace must lie this near its built run, or the fit is refused"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -30,9 +30,18 @@ A traced line is pixels; a part's points are given in its frame, a 4 x 4 frame-t
|
|||
seen(cam, frame, points) pixels of points of a frame
|
||||
crease_run(points) where Blender builds the hard crease of a cage column at one level
|
||||
along(line, segments, height) the flow score: how much of a traced line has a seen edge along it
|
||||
|
||||
A shell's cage (brokkr_kitbash's sheet) is fitted to traces of its hard runs: the cage points of the traced runs
|
||||
are moved until the runs, as Blender builds them and the cameras draw them, lie on the traces. The fit is returned
|
||||
only where the built runs explain every trace; docs/reference.md, "fit_shell", says what the answer is worth.
|
||||
|
||||
fit_runs(views, cage, runs, movable, mirror_of, share, diag, tol) the moved cage and the report
|
||||
fit_sheet(document, cage, frame, traces, cams, share, tol) the same for a sheet's named runs: the fitted sheet
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import json
|
||||
import math
|
||||
|
||||
import numpy as np
|
||||
|
|
@ -438,6 +447,289 @@ def along(line, segments, height, near=0.01, turn=20.0, cap=0.05):
|
|||
return {"on": round(float(on.mean()), 3), "off": round(float(100 * np.minimum(dist / height, cap).mean()), 2), "run": round(best / len(on), 3)}
|
||||
|
||||
|
||||
# --- a shell's traced runs fitted through cameras --------------------------------------------------------------------
|
||||
|
||||
LEVELS = 2 # crease_run applied this many times gives the samples of a built run the fit draws: 4k - 3 for k cage points
|
||||
HARD = 1.0 - 1e-9 # a crease weight from here up is hard: the edge stays sharp at every level, which is what crease_run builds
|
||||
ROUNDS = 60
|
||||
PART = 90 # the percentile of a trace's distances from its built run that fit_runs reads against tol: a hand trace's tip is where two traces cannot agree, and a tenth of it may stand off
|
||||
TOL = 5.2 # pixels. tests/test_reference.py FitTests states the sets PART and TOL were read from, and what they do not separate
|
||||
RESULT_LIMIT = 16000 # characters of a host result Brokkr copies into a receipt before it truncates (brokkr_bridge's HOST_RESULT_LIMIT; this package imports nothing from Brokkr)
|
||||
|
||||
|
||||
def _drawn(cam, frame, X):
|
||||
"""Pixels (n, 2) of points of a frame and their derivative (n, 2, 3) by the points' own coordinates; None where
|
||||
a point stands behind the camera."""
|
||||
F, R, f = np.asarray(frame, float), np.asarray(cam["R"], float), cam["f"]
|
||||
A = R @ F[:3, :3]
|
||||
q = (X @ F[:3, :3].T + F[:3, 3] - np.asarray(cam["C"], float)) @ R.T
|
||||
z = -q[:, 2]
|
||||
if z.min() <= 1e-6:
|
||||
return None
|
||||
u = np.stack([cam["c"][0] + f * q[:, 0] / z, cam["c"][1] - f * q[:, 1] / z], 1)
|
||||
du = (f / z)[:, None] * A[0] + (f * q[:, 0] / z ** 2)[:, None] * A[2]
|
||||
dv = -((f / z)[:, None] * A[1] + (f * q[:, 1] / z ** 2)[:, None] * A[2])
|
||||
return u, np.stack([du, dv], 1)
|
||||
|
||||
|
||||
def _normal(points, line):
|
||||
"""Per point: its distance to a polyline and the unit direction that distance grows along (the nearest
|
||||
segment's normal; from the segment's end where the point is past it)."""
|
||||
a, d = line[:-1], line[1:] - line[:-1]
|
||||
length = np.maximum((d * d).sum(1), 1e-18)
|
||||
t = np.clip(((points[:, None] - a) * d).sum(2) / length, 0, 1)
|
||||
off = points[:, None] - (a + t[:, :, None] * d)
|
||||
dist = np.linalg.norm(off, axis=2)
|
||||
k, i = dist.argmin(1), np.arange(len(points))
|
||||
dist, off = dist[i, k], off[i, k]
|
||||
on = dist < 1e-9
|
||||
n = off / np.maximum(dist, 1e-12)[:, None]
|
||||
n[on] = (np.stack([-d[k, 1], d[k, 0]], 1) / np.sqrt(length[k])[:, None])[on]
|
||||
return dist, n
|
||||
|
||||
|
||||
def _hard_runs(cage, runs):
|
||||
"""Refuse a run crease_run does not build. Blender builds crease_run where every edge of the run is hard, every
|
||||
point between its ends has those two sharp edges and no other, and each end holds: a hard corner point, three
|
||||
or more hard or boundary edges, or, on a cage whose Subdivision preserves corners (a loft's; cage.boundary), a
|
||||
boundary point of two edges."""
|
||||
weight = {(int(min(a, b)), int(max(a, b))): float(w) for (a, b), w in zip(np.asarray(cage.creases).reshape(-1, 2), cage.weights)}
|
||||
pinned = {int(v): float(w) for v, w in zip(cage.corners, cage.corner_weights)}
|
||||
loops, sides = np.asarray(cage.faces), []
|
||||
for first, size in zip(np.concatenate([[0], np.cumsum(cage.counts)[:-1]]), cage.counts):
|
||||
face = loops[first:first + size]
|
||||
sides += [np.sort(np.stack([face, np.roll(face, -1)], 1), axis=1)]
|
||||
sides = np.concatenate(sides)
|
||||
pairs, count = np.unique(sides, axis=0, return_counts=True)
|
||||
at = {} # vertex -> [(weight, on the boundary)] of its edges
|
||||
for (a, b), faces in zip(pairs, count):
|
||||
w = weight.get((int(a), int(b)), 0.0)
|
||||
for v in (int(a), int(b)):
|
||||
at.setdefault(v, []).append((w, faces == 1))
|
||||
for run in runs:
|
||||
name, chain = run["name"], [int(v) for v in run["chain"]]
|
||||
if len(chain) < 2 or len(set(chain)) != len(chain):
|
||||
raise ReferenceFitError(f"{name}: its run must be two or more cage points, none twice (a closed loop has no end to hold)")
|
||||
for m, (a, b) in enumerate(zip(chain, chain[1:])):
|
||||
w = weight.get((min(a, b), max(a, b)))
|
||||
if w is None or w < HARD:
|
||||
raise ReferenceFitError(f"{name}: the edge after point {m} of its run has crease weight {w or 0:g}. Only a hard run (every edge 1) is built where "
|
||||
"the fit draws it; a semi-sharp or uncreased edge rounds off by an amount the fit does not model. Crease it 1, or leave the run untraced")
|
||||
for m, v in enumerate(chain):
|
||||
sharp = [w for w, rim in at[v] if w > 0 or rim]
|
||||
if 0 < m < len(chain) - 1:
|
||||
if len(sharp) != 2 or pinned.get(v, 0.0) > 0:
|
||||
raise ReferenceFitError(f"{name}: point {m} of its run is held or pulled by more than the run (a corner point, or another crease or the rim "
|
||||
"meeting it there). Trace the run as two, one each side of that point")
|
||||
elif not (pinned.get(v, 0.0) >= HARD or sum(1 for w, rim in at[v] if w >= HARD or rim) >= 3 or (len(at[v]) == 2 and cage.boundary == "PRESERVE_CORNERS")):
|
||||
raise ReferenceFitError(f"{name}: the {'first' if m == 0 else 'last'} end of its run does not hold: it is a dart (the crease dies out into the surface "
|
||||
"there) or runs on, on a mirrored sheet across the middle. An end holds at a corner point of weight 1, where three or "
|
||||
"more hard edges meet, or on the rim")
|
||||
|
||||
|
||||
def fit_runs(views, cage, runs, movable, mirror_of, share, diag, tol=TOL):
|
||||
"""Move a cage's points until its hard runs, as built and as cameras draw them, lie on their traces.
|
||||
|
||||
views [(camera record, frame)]: the frame is the 4 x 4 that carries the cage to the world
|
||||
cage the parsed sheet (brokkr_kitbash.core.Sheet's V, faces, counts, creases, weights, corners,
|
||||
corner_weights, boundary)
|
||||
runs [{"name", "chain": cage vertices in order, "view": index into views, "line": [[u, v], ...]}]; the
|
||||
line is drawn from the chain's first point to its last
|
||||
movable (vertices, 3) of bool: the coordinates that may move. Only authored vertices move
|
||||
mirror_of per vertex, the authored vertex it mirrors across x = 0, or itself: a mirrored half is the same
|
||||
parameters seen again, x negated
|
||||
share the prior: a move of share x diag from the cage as given costs what one pixel of miss does
|
||||
tol pixels: 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
|
||||
run's view) to the trace, and the run's two ends against the trace's; no point of the trace is matched to a
|
||||
point of the run beyond that. Gauss-Newton with Levenberg-Marquardt damping on the analytic Jacobian. Returns
|
||||
(V, report): the cage's vertices as fitted and {"traces": [{"unexplained_px": the reading tol is asked of,
|
||||
"worst_px": the whole trace's furthest point from the built run}], "points": [{"vertex", "moved_m", "m_per_px",
|
||||
"prior_share"}], "rounds"}. m_per_px is the point's depth sensitivity: how many metres one pixel of error in
|
||||
the traces moves that point along its sight line, taken on the part of the sight line that stands across the
|
||||
run's tangent there (the worst of the traces that draw it), sqrt(r' S r) with S the point's block of the
|
||||
inverse of J'J, prior included (Triggs et al. 2000, sections 9 and 10). A point's slide along its own run is
|
||||
left out: the traces do not decide it and it does not move the built run. It is a sensitivity to one pixel on
|
||||
one point and no bound on the fit's error: of 24 fits to hand traces whose wander holds over 30 px, 13 ended
|
||||
further from the truth than tol x m_per_px, up to 2.45 times. prior_share is m_per_px over share x diag: near
|
||||
1 the traces say nothing about the point's depth and it stands where it was blocked.
|
||||
|
||||
Raises ReferenceFitError for a run it cannot model (_hard_runs), and when a trace is not explained: the error
|
||||
names the trace, its reading and the span of it that lies further than tol from the built run, and carries the
|
||||
rows as .traces. Nothing is returned as a fit then."""
|
||||
V0, movable, mirror_of = np.array(cage.V, float), np.asarray(movable, bool), np.asarray(mirror_of, int)
|
||||
mirrored = mirror_of != np.arange(len(V0))
|
||||
if (movable & mirrored[:, None]).any() or not movable.any():
|
||||
raise ReferenceFitError("movable must mark authored vertices, and at least one coordinate")
|
||||
_hard_runs(cage, runs)
|
||||
index = np.flatnonzero(movable.ravel())
|
||||
column = np.full(V0.size, -1)
|
||||
column[index] = np.arange(len(index))
|
||||
flip, prior = np.where(mirrored, -1.0, 1.0), 1.0 / (share * diag)
|
||||
prepared = []
|
||||
for run in runs:
|
||||
chain, line = np.asarray(run["chain"], int), np.asarray(run["line"], float)
|
||||
if not 0 <= run["view"] < len(views):
|
||||
raise ReferenceFitError(f"{run['name']}: view {run['view']} is none of the {len(views)} views")
|
||||
if line.ndim != 2 or line.shape[1] != 2 or len(line) < 2 or not np.isfinite(line).all() or np.linalg.norm(np.diff(line, axis=0), axis=1).sum() < 1e-9:
|
||||
raise ReferenceFitError(f"{run['name']}: its line must be two or more [u, v] points, not all in one place")
|
||||
W = np.eye(len(chain))
|
||||
for _ in range(LEVELS):
|
||||
W = crease_run(W)
|
||||
source = mirror_of[chain]
|
||||
prepared.append((run["name"], views[run["view"]], line, W, source, np.stack([flip[chain], np.ones(len(chain)), np.ones(len(chain))], 1),
|
||||
column.reshape(-1, 3)[source])) # the parameter column of each chain point's coordinate, -1 where held
|
||||
p0 = V0.ravel()[index]
|
||||
|
||||
def terms(p):
|
||||
"""(residual, Jacobian, each run's built points as drawn) at parameters p."""
|
||||
P = V0.copy()
|
||||
P.ravel()[index] = p
|
||||
res, rows, drawn = [], [], []
|
||||
for name, (cam, frame), line, W, source, sign, cols in prepared:
|
||||
seen_ = _drawn(cam, frame, W @ (P[source] * sign))
|
||||
if seen_ is None:
|
||||
raise ReferenceFitError(f"{name}: its run stands behind the camera")
|
||||
u, Ju = seen_
|
||||
dist, n = _normal(u, line)
|
||||
D = np.concatenate([np.einsum("si,sij->sj", n, Ju), Ju[0], Ju[-1]]) # per residual row, its derivative by its own built point
|
||||
who = np.concatenate([np.arange(len(u)), [0, 0, len(u) - 1, len(u) - 1]])
|
||||
block = np.zeros((len(D), len(p)))
|
||||
for m in range(len(source)):
|
||||
for c in range(3):
|
||||
if cols[m, c] >= 0:
|
||||
block[:, cols[m, c]] += W[who, m] * D[:, c] * sign[m, c]
|
||||
res += [dist, u[0] - line[0], u[-1] - line[-1]]
|
||||
rows.append(block)
|
||||
drawn.append((u, dist))
|
||||
return np.concatenate(res + [prior * (p - p0)]), np.vstack(rows + [prior * np.eye(len(p))]), drawn
|
||||
|
||||
p, lam, rounds = p0.copy(), 1e-3, 0
|
||||
r, J, drawn = terms(p)
|
||||
for rounds in range(1, ROUNDS + 1):
|
||||
A, g = J.T @ J, J.T @ r
|
||||
for _ in range(12):
|
||||
step = np.linalg.solve(A + lam * np.diag(np.diag(A)), -g)
|
||||
try:
|
||||
r2, J2, drawn2 = terms(p + step)
|
||||
except ReferenceFitError:
|
||||
r2 = None
|
||||
if r2 is not None and r2 @ r2 < r @ r:
|
||||
p, r, J, drawn, lam = p + step, r2, J2, drawn2, lam / 3
|
||||
break
|
||||
lam *= 4
|
||||
else:
|
||||
break
|
||||
if np.abs(step).max() < 1e-7:
|
||||
break
|
||||
V = V0.copy()
|
||||
V.ravel()[index] = p
|
||||
V = V[mirror_of] * np.stack([flip, np.ones(len(V)), np.ones(len(V))], 1)
|
||||
|
||||
traces, refused = [], None
|
||||
for (name, _, line, *_), (u, dist) in zip(prepared, drawn):
|
||||
length = np.linalg.norm(np.diff(line, axis=0), axis=1).sum()
|
||||
dense = resampled(line, int(min(max(length, len(line)), 4000)) + 1) # a point each pixel along it
|
||||
off = _off(dense, u)
|
||||
reading = float(np.percentile(off, PART))
|
||||
traces.append({"unexplained_px": round(reading, 3), "worst_px": round(float(off.max()), 3)})
|
||||
if reading > tol and refused is None:
|
||||
out = np.flatnonzero(off > tol) * length / (len(dense) - 1)
|
||||
refused = (f"{name} is not explained: {len(out) * length / (len(dense) - 1):.0f} px of the trace, between {out[0]:.0f} and {out[-1]:.0f} px along it, lie "
|
||||
f"more than {tol:g} px from the run as built ({reading:.1f} px at the {PART}th of a hundred; up to "
|
||||
f"{off.max():.1f} px). Nothing is returned as a fit. The trace draws something this run does not build (an overdrawn or doubled stroke, another "
|
||||
"edge, a bend the cage has too few points for): redraw it, or give the run more points. A very unsteady hand reads the same as a slight "
|
||||
"overdraw: if the trace is one clean stroke, ask again with tol over this reading")
|
||||
if refused is not None:
|
||||
error = ReferenceFitError(refused)
|
||||
error.traces = traces
|
||||
raise error
|
||||
S = np.linalg.inv(J.T @ J)
|
||||
points = []
|
||||
for a in np.flatnonzero(movable.any(1)):
|
||||
cols = column.reshape(-1, 3)[a]
|
||||
block = np.zeros((3, 3))
|
||||
held = cols >= 0
|
||||
block[np.ix_(held, held)] = S[np.ix_(cols[held], cols[held])]
|
||||
worst = 0.0
|
||||
for _, (cam, frame), _, _, source, sign, _ in prepared:
|
||||
run = V[source] * sign
|
||||
for m in np.flatnonzero(source == a):
|
||||
sight = run[m] - (np.linalg.inv(np.asarray(frame, float)) @ np.r_[np.asarray(cam["C"], float), 1.0])[:3]
|
||||
along = run[min(m + 1, len(run) - 1)] - run[max(m - 1, 0)]
|
||||
sight = sight - (sight @ along) / (along @ along) * along
|
||||
if np.linalg.norm(sight) > 1e-9: # a run seen end on has no depth across itself
|
||||
sight = sight / np.linalg.norm(sight) * sign[m] # said in the authored point's coordinates
|
||||
worst = max(worst, float(np.sqrt(sight @ block @ sight)))
|
||||
points.append({"vertex": int(a), "moved_m": float(np.linalg.norm(V[a] - V0[a])), "m_per_px": worst, "prior_share": worst * prior})
|
||||
return V, {"traces": traces, "points": points, "rounds": rounds}
|
||||
|
||||
|
||||
def fit_sheet(document, cage, frame, traces, cams, share=0.1, tol=TOL):
|
||||
"""fit_runs for a shell's sheet. `document` is the sheet as brokkr_kitbash.shell takes it and `cage` what
|
||||
brokkr_kitbash.core.sheet parses it to; `frame` carries the shell to the world. `traces` is a list of
|
||||
{"run", "side": 1 or -1, "line": [[u, v], ...]} and `cams` the camera record of each. A loft's run is {"ring":
|
||||
i, "from": a, "to": b} or {"column": j, "from": a, "to": b}, a free cage's {"verts": [v, ...]}: authored
|
||||
indices, as the sheet's creases name runs. Side -1 is the mirrored half of a mirrored sheet (cage.mirror_of);
|
||||
the line is drawn from the run's first point to its last. The points of the traced runs move, one on the
|
||||
mirror plane only in it. Returns {"sheet": the document with those points moved, "traces": [{"unexplained_px",
|
||||
"worst_px"}], "points": [{"ring", "point" (a loft) or "vertex" (a free cage), "moved_m", "m_per_px",
|
||||
"prior_share"}]}; refuses, before fitting, a result that would pass RESULT_LIMIT characters."""
|
||||
mirror, closed = document.get("mirror", False) is True, bool(document.get("closed", False))
|
||||
R, N, mirror_of = cage.rings, cage.points, np.asarray(cage.mirror_of)
|
||||
loft, authored = R is not None, np.flatnonzero(mirror_of == np.arange(len(mirror_of)))
|
||||
twin = np.arange(len(mirror_of)) # an authored vertex's reflection: itself on the mirror plane
|
||||
twin[mirror_of[mirror_of != twin]] = np.flatnonzero(mirror_of != twin)
|
||||
C = ((N + 1) // 2 if mirror else N) if loft else None
|
||||
if not isinstance(traces, list) or not traces:
|
||||
raise ReferenceFitError("traces must be an array of one or more {camera, box, run, side, line}")
|
||||
movable, runs = np.zeros((len(mirror_of), 3), bool), []
|
||||
for k, trace in enumerate(traces):
|
||||
where = f"traces[{k}]"
|
||||
if not isinstance(trace, dict) or not isinstance(trace.get("run"), dict):
|
||||
raise ReferenceFitError(f"{where} must be an object with a run")
|
||||
if cams[k] is None:
|
||||
raise ReferenceFitError(f"{where}.camera {trace.get('camera')!r} is no camera of this fit")
|
||||
run, side = trace["run"], trace.get("side", 1)
|
||||
if side not in (1, -1) or (side == -1 and not mirror):
|
||||
raise ReferenceFitError(f"{where}.side must be 1, or -1 for the mirrored half of a mirrored sheet, not {side!r}")
|
||||
if loft:
|
||||
ring = "ring" in run
|
||||
if ring == ("column" in run) or set(run) != {"ring" if ring else "column", "from", "to"}:
|
||||
raise ReferenceFitError(f"{where}.run must be {{ring, from, to}} or {{column, from, to}}: the sheet is a loft")
|
||||
across, most = (R, C if closed else C - 1) if ring else (C, R - 1)
|
||||
numbers_ = [run["ring" if ring else "column"], run["from"], run["to"]]
|
||||
if any(isinstance(v, bool) or not isinstance(v, int) for v in numbers_) or not (0 <= numbers_[0] < across and 0 <= numbers_[1] < numbers_[2] <= most):
|
||||
raise ReferenceFitError(f"{where}.run must name a {'ring under ' + str(R) if ring else 'column under ' + str(C)} and from under to, to at most {most}")
|
||||
fixed, first, last = numbers_
|
||||
chain = [i * N + (C - 1 if mirror else 0) + j for i, j in ((fixed, j % C) if ring else (j, fixed) for j in range(first, last + 1))]
|
||||
else:
|
||||
chain = run.get("verts")
|
||||
if set(run) != {"verts"} or not isinstance(chain, list) or any(isinstance(v, bool) or not isinstance(v, int) or not 0 <= v < len(authored) for v in chain):
|
||||
raise ReferenceFitError(f"{where}.run must be {{verts: [v, ...]}}, authored vertices under {len(authored)} in the run's order: the sheet is a free cage")
|
||||
for v in chain:
|
||||
movable[v] = (twin[v] != v or not mirror, True, True)
|
||||
runs.append({"name": where, "chain": chain if side == 1 else [int(twin[v]) for v in chain], "view": k, "line": trace.get("line")})
|
||||
moved = [int(v) for v in np.flatnonzero(movable.any(1))]
|
||||
size = len(json.dumps(document, separators=(",", ":"))) + 36 * len(moved) + 45 * len(traces) + 95 * len(moved) + 40
|
||||
if size > RESULT_LIMIT:
|
||||
raise ReferenceFitError(f"the fitted sheet and its report would be about {size} characters, over the {RESULT_LIMIT} a receipt carries: nothing was fitted. "
|
||||
"Fit fewer runs at a time, or a sparser sheet")
|
||||
V0 = np.array(cage.V, float)
|
||||
V, report = fit_runs([(cam, frame) for cam in cams], cage, runs, movable, mirror_of, share, float(np.linalg.norm(np.ptp(V0, axis=0))), tol)
|
||||
out, points = copy.deepcopy(document), []
|
||||
for v, row in zip(moved, report["points"]):
|
||||
place = {"ring": v // N, "point": v % N - (C - 1 if mirror else 0)} if loft else {"vertex": v}
|
||||
point = [round(float(x), 6) + 0.0 for x in V[v]]
|
||||
if loft:
|
||||
out["rings"][place["ring"]][place["point"]] = point
|
||||
else:
|
||||
out["verts"][v] = point
|
||||
points.append({**place, "moved_m": round(row["moved_m"], 4), "m_per_px": round(row["m_per_px"], 4), "prior_share": round(row["prior_share"], 3)})
|
||||
return {"sheet": out, "traces": report["traces"], "points": points}
|
||||
|
||||
|
||||
# --- fields ----------------------------------------------------------------------------------------------------------
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
# Reference views: the camera a picture was drawn through, and traced lines scored against the build
|
||||
# Reference views: the camera a picture was drawn through, traced lines scored against the build, and a shell fitted to them
|
||||
|
||||
`surfaces/blender/brokkr_reference` is a Blender add-on that fits a scene to a reference image. A concept sheet,
|
||||
a render or a photograph draws its subject through a camera nobody wrote down; given points whose place in the
|
||||
|
|
@ -8,11 +8,11 @@ it lays over the image pixel for pixel and a line traced on the image can be sco
|
|||
It is a host add-on in Brokkr's sense (`install.md`, "Host add-on actions"), a sibling of `brokkr_mesh_polish`: it
|
||||
imports that package's operator base and `Refused`, and nothing from `brokkr_bridge`. Enable `brokkr_mesh_polish`
|
||||
first; `brokkr_reference` refuses to register without it. `brokkr_actions.json` beside its `__init__.py` lists the
|
||||
two operators agents may run (`solve_camera`, `flow_score`); the arithmetic is `core.py` (numpy only, tested without Blender), which a script may
|
||||
three operators agents may run (`solve_camera`, `flow_score`, `fit_shell`); the arithmetic is `core.py` (numpy only, tested without Blender), which a script may
|
||||
import directly. The action writes its JSON report to `brokkr_mesh_polish_result`, returned in the receipt's
|
||||
`hostResult`.
|
||||
|
||||
The package takes points and traced lines and gives cameras and scores. The images, the marks on them, traces and masks belong to whoever
|
||||
The package takes points and traced lines and gives cameras, scores and a fitted sheet. The images, the marks on them, traces and masks belong to whoever
|
||||
made them; nothing here opens an image.
|
||||
|
||||
## Conventions
|
||||
|
|
@ -172,6 +172,108 @@ surface has the hull's margin, and a surface nearer it than a thousandth of the
|
|||
about 20000 diagonals off, where the ray's own rounding reaches the margin. The action writes nothing to the scene (its row says `changesScene`
|
||||
because the operator base pushes an undo step).
|
||||
|
||||
## fit_shell: a shell's sheet fitted to traces of its hard runs
|
||||
|
||||
A kitbash shell (`kitbash.md`, "Making a shell") is blocked in by eye; `fit_shell` moves the cage points of its
|
||||
traced runs until the runs, as Blender builds them and the cameras draw them, lie on the traces. A run is a hard
|
||||
crease or rim run of a loft or of a free cage, named as the sheet's creases name runs. The unknowns are the authored points on the
|
||||
traced runs; a mirrored sheet is one set of points seen twice, so a trace of each half through one camera is two
|
||||
views of the run (Francois et al. 2003), and that is where depth comes from in a single picture. Each built point
|
||||
of a run is pulled onto its trace along the trace's normal, and the run's two ends onto the trace's ends; no
|
||||
point of a trace is matched to a point of the run or of another trace (after Debevec's Facade and Drummond and
|
||||
Cipolla's edge tracker). A prior holds every point to the sheet as it stands: a move of `share` of the sheet's
|
||||
diagonal costs what one pixel of miss does.
|
||||
|
||||
```json
|
||||
{"action": "brokkr_reference.fit_shell", "object_name": "Pauldron",
|
||||
"traces": "[{\"camera\": \"Concept\", \"box\": [0, 0, 1024, 1024], \"run\": {\"column\": 3, \"from\": 0, \"to\": 5}, \"side\": 1, \"line\": [[412.5, 96.0], [431.0, 180.2], [440.8, 266.0]]}, {\"camera\": \"Concept\", \"box\": [0, 0, 1024, 1024], \"run\": {\"column\": 3, \"from\": 0, \"to\": 5}, \"side\": -1, \"line\": [[612.0, 90.5], [590.2, 176.0], [583.1, 262.4]]}]"}
|
||||
```
|
||||
|
||||
| field | |
|
||||
| --- | --- |
|
||||
| `object_name` | a shell made by `brokkr_kitbash.shell`, unscaled; its place in the world is the sheet's frame |
|
||||
| `traces` | a JSON array, up to 12000 characters, of `{camera, box, run, side, line}` |
|
||||
| `share` | the prior (default 0.1) |
|
||||
| `tol` | pixels (default 5.2): nine tenths of every trace must lie this near its built run |
|
||||
|
||||
In a trace, `camera` names a camera object (`solve_camera` stands one) and `box` is its frame on the image, absent
|
||||
for the render's own; `run` is `{"ring": i, "from": a, "to": b}` or `{"column": j, "from": a, "to": b}` on a loft and
|
||||
`{"verts": [v, ...]}`, the run's vertices in order, on a free cage, all in authored indices; `side` is 1, or -1
|
||||
for the mirrored half of a mirrored sheet (the reflections `brokkr_kitbash`'s parser makes: `Sheet.mirror_of`);
|
||||
`line` is `[[u, v], ...]` in the box's pixels, drawn from the run's first point to its last.
|
||||
|
||||
**It returns a fit only where the built runs explain every trace.** After the fit, each trace is walked a pixel
|
||||
at a time and each point's distance from its run, as built and drawn, is taken. The trace's reading,
|
||||
`unexplained_px`, is the 90th percentile of those distances; over `tol` the action is refused, naming the trace,
|
||||
its reading, how much of it lies past `tol` and where, and nothing is returned as a fit. `worst_px` is the
|
||||
furthest any point of the trace stands. The fit's own residual is no such test: on strokes doubled back over
|
||||
part of themselves 3% of the view off, every fit converged and without this check all of them came back, up to
|
||||
0.10 m wrong on a 2 m crease.
|
||||
|
||||
The reading is not the worst point because a hand trace's tip is where two traces cannot agree: the Orchid's
|
||||
hand-traced pair reads 0.80 px, with one tip 9.2 px off its run, and that pair's least 1% overdraw has a worst
|
||||
point of 9.1 px. The percentile and the default were read from 296 fits and set by the margin rule
|
||||
(`tests/test_reference.py`, `FitTests`): what should pass reads 3.76 px at most (hand traces wandering 1 and 2
|
||||
px), what should not reads 7.27 and up (the Orchid's traces overdrawn 2% of their extent; synthetic strokes 3%
|
||||
off read 7.70), and 5.2 sits 1.39 from each.
|
||||
|
||||
**A very unsteady hand and a slight overdraw are not told apart.** Hand traces wandering 4 px read up to 5.84
|
||||
(31 of 36 pass the default); strokes overdrawn 1% read from 2.57 (11 of 45 pass) and 2% from 5.10 (2 of 45
|
||||
pass). The reading orders 99.6% of hand trace against 2 to 3% overdraw pairs rightly, but no threshold stands 1.2
|
||||
from both the 4 px hand traces and the 2% overdraws. So the reading is in the report of every accepted fit and
|
||||
in every refusal: near 5, look at the trace. An accepted trace reading 3 to 5 px may be a 1 or 2% overdraw; a
|
||||
refused one reading 5 to 6 may be a clean stroke from an unsteady hand, and asking again with `tol` over its
|
||||
reading is the caller's judgement. A doubled stretch shorter than a tenth of the trace does not move the
|
||||
reading: `worst_px` shows it.
|
||||
|
||||
**It writes nothing.** The report carries `sheet`, the shell's own request with the traced points moved, ready
|
||||
for `brokkr_kitbash.shell`, which is the cage's one writer; `flow_score` on the rebuilt shell is the score. The
|
||||
rest of the report: `traces` (`[{unexplained_px, worst_px}]`), `points` (`[{ring, point, moved_m, m_per_px,
|
||||
prior_share}]` on a loft, `[{vertex, ...}]` on a free cage, one per moved point) and `seconds`.
|
||||
|
||||
`m_per_px` is a point's depth sensitivity: how many metres one pixel of error in the traces moves that point
|
||||
along its line of sight, taken on the part of the line of sight that stands across the run there (the worst of
|
||||
the traces that draw it), from the inverse of the fit's normal matrix, prior included (Triggs et al. 2000, sections 9 and 10). A point's slide along its own
|
||||
run is left out: the traces do not decide it and it does not move the built run. `prior_share` is `m_per_px` over
|
||||
`share` x the diagonal: near 1 the traces say nothing about the point's depth and it stands where the blocking
|
||||
put it. Read it per point against 0.2:
|
||||
|
||||
- **Under 0.2 the traces decide the point.** A mirrored pair traced in one view: over 18 fits every point reads
|
||||
0.080 or under and the built run is right to 0.7 mm. The Orchid's concept c09 pair reads 0.018 at most.
|
||||
- **Over 0.2 the blocking holds it.** One half traced in one view: over the same 18 fits every inner point reads
|
||||
0.50 to 1.0 (the sine of the angle its run stands off the line of sight) and the built run is 18 to 355 mm
|
||||
wrong. Either Orchid trace alone reads 0.27 and up on every point. 0.2 is the geometric mean of 0.080 and
|
||||
0.50, 2.5 from each.
|
||||
- A run's end seen along the run reads low even on a single trace (down to 0.005): there the line of sight is
|
||||
the run's own direction, and the depth across the run is decided.
|
||||
- A run on the mirror plane (a spine, a keel) has no partner and needs none: its points stay on the plane, which
|
||||
decides their depth. A spine traced once read 0.019 at most and came back within 0.15 mm.
|
||||
|
||||
`m_per_px` is a sensitivity, and `tol` x `m_per_px` is no bound on the fit's error. Clean strokes came back
|
||||
within 0.16 of `tol` x the worst `m_per_px` they report. Hand traces whose wander holds over 30 px did not: of 24
|
||||
fitted (wander 2 and 4 px), 13 ended further off than that, up to 2.45 times (20 to 87 mm on a 2 m crease),
|
||||
while every point read a `prior_share` under 0.05. A low reading says the traces decide the point; how well they decide it
|
||||
is as good as the traces are.
|
||||
|
||||
What it refuses before fitting, naming the trace: a run with an edge under weight 1 (a semi-sharp edge rounds
|
||||
off by an amount the fit does not model), a run whose end does not hold (a dart; a ring run from point 0 of a
|
||||
mirrored sheet, which runs on across the middle), a run with a point held partway (a corner point or a crossing
|
||||
crease: trace it as two), a closed loop, an unknown camera, a line of fewer than two points, a run named in the
|
||||
other form's words (`verts` on a loft, a ring or column on a free cage), a scaled shell, and a result that would
|
||||
pass the 16000 characters a receipt carries.
|
||||
|
||||
Measured (Blender 5.3 and Python 3.13 on Starfire): a mirrored column of 10 points traced in one view at a time,
|
||||
from blockings 0.10 m and 0.30 m off a 2 m crease, came back within 0.7 mm in 0.1 to 0.6 s. The Orchid's c09
|
||||
petal edges, traced by hand through a camera solved from hand marks (13 px rms), are accepted at the default,
|
||||
reading 0.80 and 0.68 px, in 0.2 s; from blockings 5%, 10% and 20% of the ship's length off the built run lands
|
||||
in one place, 2.0% of the length from a stand-in mesh in the mean and 3.4% at worst. A mirrored free cage's
|
||||
crease of six vertices, blocked 0.056 m off, came back within 0.43 mm through the action in 0.02 s.
|
||||
|
||||
What it gives up: it fits hard runs only. Silhouettes of the smooth surface and semi-sharp creases are not
|
||||
fitted; a run's depth with no mirror partner, no second view and no mirror plane under it is the blocking's.
|
||||
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.
|
||||
|
||||
## What it cannot do
|
||||
|
||||
It solves one pinhole camera for one view: no lens distortion, no two views solved together, one turned group and
|
||||
|
|
@ -188,6 +290,7 @@ u_v = core.project(cam, points) # where it draws wor
|
|||
origin, direction = core.ray(cam, (u, v)) # a pixel's line of sight
|
||||
point = core.lift(cam, (u, v), plane_point, plane_normal) # a traced pixel on a plane
|
||||
run = core.crease_run(column) # the hard crease Blender builds from a cage column
|
||||
fit = core.fit_sheet(sheet, cage, frame, traces, cams) # the fitted sheet and its report; cage is brokkr_kitbash.core.sheet(sheet)
|
||||
score = core.along(line, segments, height) # on, off, run against [u0, v0, u1, v1] segments
|
||||
params = core.blender(cam, 1000) # matrix_world, lens, shifts, resolution
|
||||
cam2 = core.camera_of(params, box) # and back
|
||||
|
|
@ -196,4 +299,6 @@ cam2 = core.camera_of(params, box) # and back
|
|||
The tests are `tests/test_reference.py` (no Blender), `tests/live/reference.py` (a known scene rendered, solved
|
||||
through the action and rendered again; `reference.result.json` is its last run) and `tests/live/reference_flow.py`
|
||||
(`crease_run` against Blender's own subdivision, a box and a folded sheet scored by `flow_score`;
|
||||
`reference_flow.result.json` is its last run).
|
||||
`reference_flow.result.json` is its last run) and `tests/live/reference_fit.py` (a mirrored loft and a mirrored
|
||||
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).
|
||||
|
|
|
|||
224
surfaces/blender/tests/fixtures/orchid_c09_traces.json
vendored
Normal file
224
surfaces/blender/tests/fixtures/orchid_c09_traces.json
vendored
Normal file
|
|
@ -0,0 +1,224 @@
|
|||
{
|
||||
"what": "Orchid concept c09 (one view): the camera record brokkr_reference.solve_camera solved from hand marks, the frame of the ship's mirror plane, the inboard edge of the two upper petals traced by eye (left is the mirrored half), and a blocking column of 8 stations standing up to a tenth of the ship's length off. No mesh and no hull: the sheet the test builds round the column is a strip that exists to carry it.",
|
||||
"camera": {
|
||||
"C": [
|
||||
-6.168901501633792,
|
||||
-121.90792252280691,
|
||||
2.8948965905734094
|
||||
],
|
||||
"R": [
|
||||
[
|
||||
0.9987259467882663,
|
||||
-0.05046269128654356,
|
||||
0.0
|
||||
],
|
||||
[
|
||||
0.0009919726785528231,
|
||||
0.019632501305770517,
|
||||
0.9998067717727681
|
||||
],
|
||||
[
|
||||
-0.05045294047016491,
|
||||
-0.9985329647440779,
|
||||
0.01965754606547003
|
||||
]
|
||||
],
|
||||
"f": 113777.77777777778,
|
||||
"c": [
|
||||
512.0,
|
||||
512.0
|
||||
],
|
||||
"box": [
|
||||
0.0,
|
||||
0.0,
|
||||
1024.0,
|
||||
1024.0
|
||||
],
|
||||
"lens": 4000.0
|
||||
},
|
||||
"frame": [
|
||||
[
|
||||
0.7946956336528872,
|
||||
0.5885955750367245,
|
||||
-0.14837148951272178,
|
||||
0.03987530991435051
|
||||
],
|
||||
[
|
||||
-0.6006879570259439,
|
||||
0.7273858746251298,
|
||||
-0.3317887395313959,
|
||||
0.013782020658254623
|
||||
],
|
||||
[
|
||||
-0.08736605826654754,
|
||||
0.35279602951708855,
|
||||
0.9316126520286978,
|
||||
0.5812516808509827
|
||||
],
|
||||
[
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
1.0
|
||||
]
|
||||
],
|
||||
"left": [
|
||||
[
|
||||
556.3,
|
||||
34.2
|
||||
],
|
||||
[
|
||||
533.3,
|
||||
50.0
|
||||
],
|
||||
[
|
||||
518.8,
|
||||
64.6
|
||||
],
|
||||
[
|
||||
500.0,
|
||||
89.6
|
||||
],
|
||||
[
|
||||
483.3,
|
||||
118.8
|
||||
],
|
||||
[
|
||||
466.7,
|
||||
147.9
|
||||
],
|
||||
[
|
||||
450.0,
|
||||
178.3
|
||||
],
|
||||
[
|
||||
433.3,
|
||||
208.3
|
||||
],
|
||||
[
|
||||
408.3,
|
||||
258.3
|
||||
],
|
||||
[
|
||||
389.6,
|
||||
295.8
|
||||
],
|
||||
[
|
||||
375.0,
|
||||
329.2
|
||||
],
|
||||
[
|
||||
356.3,
|
||||
360.4
|
||||
],
|
||||
[
|
||||
337.5,
|
||||
389.6
|
||||
],
|
||||
[
|
||||
320.8,
|
||||
418.8
|
||||
],
|
||||
[
|
||||
306.3,
|
||||
445.8
|
||||
]
|
||||
],
|
||||
"right": [
|
||||
[
|
||||
888.8,
|
||||
86.7
|
||||
],
|
||||
[
|
||||
853.3,
|
||||
97.9
|
||||
],
|
||||
[
|
||||
815.8,
|
||||
112.5
|
||||
],
|
||||
[
|
||||
778.3,
|
||||
129.2
|
||||
],
|
||||
[
|
||||
740.8,
|
||||
152.1
|
||||
],
|
||||
[
|
||||
703.3,
|
||||
179.2
|
||||
],
|
||||
[
|
||||
665.8,
|
||||
210.4
|
||||
],
|
||||
[
|
||||
636.7,
|
||||
233.3
|
||||
],
|
||||
[
|
||||
607.5,
|
||||
262.5
|
||||
],
|
||||
[
|
||||
582.5,
|
||||
295.8
|
||||
],
|
||||
[
|
||||
559.6,
|
||||
337.5
|
||||
],
|
||||
[
|
||||
532.5,
|
||||
395.8
|
||||
],
|
||||
[
|
||||
503.3,
|
||||
466.7
|
||||
]
|
||||
],
|
||||
"left_side": -1,
|
||||
"blocking": [
|
||||
[
|
||||
0.2278,
|
||||
0.3586,
|
||||
0.279
|
||||
],
|
||||
[
|
||||
0.1764,
|
||||
0.183,
|
||||
0.3436
|
||||
],
|
||||
[
|
||||
0.1489,
|
||||
0.0666,
|
||||
0.297
|
||||
],
|
||||
[
|
||||
0.2226,
|
||||
0.1029,
|
||||
0.2136
|
||||
],
|
||||
[
|
||||
0.251,
|
||||
0.1112,
|
||||
0.0995
|
||||
],
|
||||
[
|
||||
0.2813,
|
||||
0.1228,
|
||||
0.0095
|
||||
],
|
||||
[
|
||||
0.2259,
|
||||
-0.0472,
|
||||
0.0286
|
||||
],
|
||||
[
|
||||
0.4158,
|
||||
0.1062,
|
||||
-0.1008
|
||||
]
|
||||
]
|
||||
}
|
||||
272
surfaces/blender/tests/live/reference_fit.py
Normal file
272
surfaces/blender/tests/live/reference_fit.py
Normal file
|
|
@ -0,0 +1,272 @@
|
|||
"""Live proof, in a background Blender, of brokkr_reference.fit_shell through run_intent.
|
||||
|
||||
A mirrored loft shell made by brokkr_kitbash.shell stands turned and moved in the world: a hard crease column and
|
||||
the rim's outer column on each half. A camera looks at it from the side, and the four runs are traced where
|
||||
Blender's own projection draws them on the shell as designed. Then:
|
||||
|
||||
blocked the shell is rebuilt from a sheet whose two traced columns stand up to 0.12 m off: flow_score reads
|
||||
the four traced lines against the build, and little of them is on a built edge
|
||||
fit_shell from that shell and the traces: every trace explained, the request and the mesh untouched
|
||||
applied brokkr_kitbash.shell rebuilds the shell from the returned sheet; flow_score reads every traced line
|
||||
on a built edge (the bound sits between the mean of this reading and of the blocked build's, as CHECK prints)
|
||||
crease_run the fitted shell at one level: the rim run and the crease stand where core.crease_run says
|
||||
refusals a trace doubled back over itself, an unknown camera, a scaled shell and a mesh that is no shell,
|
||||
each a failed receipt naming its cause, the shell unchanged
|
||||
free cage a mirrored free cage with one hard crease, blocked off its design and traced on both halves: fit_shell
|
||||
takes the run as {verts}, brokkr_kitbash.shell rebuilds it, and Blender builds the crease on both
|
||||
halves where core.crease_run says
|
||||
|
||||
The Jacobian by differences (mutant F6: core.lm on the same residual) costs time only: the mirrored column of
|
||||
tests/test_reference.py, views one at a time, medians of 3 interleaved runs on Starfire, read
|
||||
SECONDS_ANALYTIC against SECONDS_DIFFERENCES below.
|
||||
|
||||
blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/reference_fit.py -- <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
|
||||
|
||||
SECONDS_ANALYTIC, SECONDS_DIFFERENCES = (0.07, 0.21), (2.3, 3.9) # least and most of the three views, 2026-12-03; the fitted cages agree within 0.11 mm
|
||||
|
||||
SURFACE = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(SURFACE / "tools"))
|
||||
import private_dirs # noqa: E402
|
||||
|
||||
_refused = private_dirs.refusal(os.environ, os.path.expanduser("~"), lambda kind: bpy.utils.user_resource(kind))
|
||||
if _refused:
|
||||
raise SystemExit(_refused)
|
||||
OUT = sys.argv[sys.argv.index("--") + 1]
|
||||
if not os.path.isabs(OUT):
|
||||
raise SystemExit(f"<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-fit-live-"))
|
||||
target.reload_host_actions()
|
||||
R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1],
|
||||
"hostRows": [row["name"] for row in target.host_actions()[0]]}
|
||||
COUNT = [0]
|
||||
T0 = time.time()
|
||||
WIDTH, HEIGHT = 800, 600
|
||||
RINGS, CREASE, RIM = 6, 1, 3 # the sheet's rings, and its two traced columns
|
||||
|
||||
|
||||
def check(name, ok, detail=None):
|
||||
R["checks"].append({"name": name, "ok": bool(ok), "detail": detail})
|
||||
|
||||
|
||||
def send(action, **fields):
|
||||
COUNT[0] += 1
|
||||
receipt = target.run_intent(bpy.context, {"commandId": f"live-{COUNT[0]}", "requestedBy": "test/driver", "action": action, **fields})
|
||||
result = json.loads(receipt["hostResult"]) if receipt.get("hostResult") else None
|
||||
print("SEND", f"{time.time() - T0:.1f}s", action, receipt["status"], str(receipt["message"])[:400], flush=True)
|
||||
return receipt, result
|
||||
|
||||
|
||||
def designed():
|
||||
"""The sheet as designed: six rings from y -1 to 1, each from the middle out and down, a fold at column 1."""
|
||||
rings = []
|
||||
for i in range(RINGS):
|
||||
t = i / (RINGS - 1)
|
||||
y, lift = -1.0 + 2.0 * t, 0.12 * math.sin(math.pi * t)
|
||||
rings.append([[0.0, y, 0.55 + lift], [0.42 + 0.08 * math.sin(2.5 * t), y, 0.5 + lift], [0.8 + 0.05 * t, y, 0.12 + lift], [1.05 + 0.12 * math.sin(3.0 * t), y, -0.3 + 0.1 * t]])
|
||||
return {"mirror": True, "rim": 1.0, "creases": [{"column": CREASE, "from": 0, "to": RINGS - 1, "weight": 1.0}], "rings": rings}
|
||||
|
||||
|
||||
def blocking(sheet):
|
||||
"""The designed sheet with its two traced columns pushed off by smooth bumps, up to 0.12 m."""
|
||||
out, r, t = json.loads(json.dumps(sheet)), np.random.default_rng(5), np.linspace(0, 1, RINGS)
|
||||
for column in (CREASE, RIM):
|
||||
bump = sum(r.normal(0, 1, 3)[None] * np.sin(np.pi * (j + 1) * t + 0.4)[:, None] for j in range(2))
|
||||
bump *= 0.12 / np.abs(bump).max()
|
||||
for i in range(RINGS):
|
||||
out["rings"][i][column] = [round(float(v + d), 6) for v, d in zip(sheet["rings"][i][column], bump[i])]
|
||||
return out
|
||||
|
||||
|
||||
def free_cage(points=6):
|
||||
"""A mirrored free cage three columns wide (x 0 on the mirror plane, 0.5, 1) whose middle column is a hard crease,
|
||||
and that column's vertices in order."""
|
||||
verts = [[x, -1 + 2 * i / (points - 1), 0.5 - x * x + 0.1 * math.sin(3 * i / (points - 1)) * (c == 1)] for c, x in enumerate((0.0, 0.5, 1.0)) for i in range(points)]
|
||||
faces = [[c * points + i, c * points + i + 1, c * points + i + 1 + points, c * points + i + points] for c in range(2) for i in range(points - 1)]
|
||||
chain = list(range(points, 2 * points))
|
||||
return {"verts": verts, "faces": faces, "creases": [[a, b, 1.0] for a, b in zip(chain, chain[1:])], "mirror": True, "rim": 1.0}, chain
|
||||
|
||||
|
||||
def run_of(sheet, column, side):
|
||||
"""A column's built run in the shell's frame, as core.crease_run builds it twice over."""
|
||||
return core.crease_run(core.crease_run(np.array(sheet["rings"])[:, column] * [side, 1, 1]))
|
||||
|
||||
|
||||
def pixels(camera, shell, points):
|
||||
out = []
|
||||
for p in points:
|
||||
x, y, _ = world_to_camera_view(bpy.context.scene, camera, shell.matrix_world @ Vector(p))
|
||||
out.append([round(x * WIDTH, 3), round((1.0 - y) * HEIGHT, 3)])
|
||||
return out
|
||||
|
||||
|
||||
def flow(lines, shell):
|
||||
_, result = send("brokkr_reference.flow_score", camera_name="View", objects=shell.name,
|
||||
lines="; ".join(f"{tag}: " + " ".join(f"{u},{v}" for u, v in line) for tag, line in lines.items()))
|
||||
return {tag: row["on"] for tag, row in result["lines"].items()} if result else None
|
||||
|
||||
|
||||
def state(shell):
|
||||
return shell["kit_shell"], [tuple(round(c, 7) for c in v.co) for v in shell.data.vertices]
|
||||
|
||||
|
||||
try:
|
||||
check("host files admitted with the fit_shell row", not R["hostErrors"] and "brokkr_reference.fit_shell" in R["hostRows"], R["hostErrors"] or R["hostRows"])
|
||||
scene = bpy.context.scene
|
||||
scene.render.resolution_x, scene.render.resolution_y, scene.render.resolution_percentage = WIDTH, HEIGHT, 100
|
||||
truth = designed()
|
||||
send("brokkr_kitbash.shell", object_name="Plate", sheet=json.dumps(truth), thickness=0.03, levels=2)
|
||||
shell = bpy.data.objects["Plate"]
|
||||
shell.matrix_world = Matrix.Translation((0.3, -0.2, 0.1)) @ Euler((0.0, 0.0, math.radians(15.0))).to_matrix().to_4x4()
|
||||
camera = bpy.data.objects.new("View", bpy.data.cameras.new("View"))
|
||||
scene.collection.objects.link(camera)
|
||||
camera.data.lens, camera.data.sensor_fit = 50.0, "HORIZONTAL"
|
||||
camera.location = (3.2, -3.0, 5.2)
|
||||
camera.rotation_euler = (Vector((0.3, -0.1, 0.25)) - camera.location).to_track_quat("-Z", "Y").to_euler()
|
||||
bpy.context.view_layer.update()
|
||||
runs = {"crease": (CREASE, 1), "crease_m": (CREASE, -1), "rim": (RIM, 1), "rim_m": (RIM, -1)}
|
||||
lines = {tag: pixels(camera, shell, core.resampled(run_of(truth, column, side), 40)) for tag, (column, side) in runs.items()}
|
||||
inside = all(0 <= u <= WIDTH and 0 <= v <= HEIGHT for line in lines.values() for u, v in line)
|
||||
designed_on = flow(lines, shell)
|
||||
check("the designed shell: the camera frames all four runs, and flow_score reads each traced line on a built edge", inside and designed_on and min(designed_on.values()) >= 0.9, designed_on)
|
||||
|
||||
# --- blocked: the shell rebuilt from a sheet whose traced columns stand off ---------------------------------------
|
||||
blocked = blocking(truth)
|
||||
send("brokkr_kitbash.shell", object_name="Plate", sheet=json.dumps(blocked), thickness=0.03, levels=2)
|
||||
bpy.context.view_layer.update()
|
||||
blocked_on = flow(lines, shell)
|
||||
before = state(shell)
|
||||
|
||||
# --- fit_shell -----------------------------------------------------------------------------------------------------
|
||||
traces = [{"camera": "View", "run": {"column": column, "from": 0, "to": RINGS - 1}, "side": side, "line": lines[tag]} for tag, (column, side) in runs.items()]
|
||||
receipt, fit = send("brokkr_reference.fit_shell", object_name="Plate", traces=json.dumps(traces, separators=(",", ":")))
|
||||
ok = receipt["status"] == "accepted" and fit is not None
|
||||
check(f"fit_shell returns a sheet with every trace explained within {core.TOL:g} px, and a row for each of the 12 moved points",
|
||||
ok and max(row["unexplained_px"] for row in fit["traces"]) <= core.TOL and len(fit["points"]) == 2 * RINGS and len(receipt["hostResult"]) < 16000,
|
||||
fit and {"traces": fit["traces"], "seconds": fit["seconds"], "chars": len(receipt["hostResult"])})
|
||||
check("fit_shell wrote nothing: the shell's request and its cage are as they were", state(shell) == before)
|
||||
if ok:
|
||||
gap, off = (max(float(core._off(core.resampled(run_of(sheet, column, 1), 200), run_of(truth, column, 1)).max()) for column in (CREASE, RIM)) for sheet in (fit["sheet"], blocked))
|
||||
check("the fitted runs stand within 5 mm of the designed ones, from a blocking over 0.05 m off them", gap < 0.005 and off > 0.05, [gap, off])
|
||||
shares = {(row["ring"], row["point"]): row["prior_share"] for row in fit["points"]}
|
||||
check("every moved point reports metres per pixel and a prior share from 0 to 1", all(0.0 <= row["prior_share"] <= 1.0 and row["m_per_px"] >= 0.0 for row in fit["points"]), shares and max(shares.values()))
|
||||
|
||||
# --- applied: brokkr_kitbash.shell is the writer ---------------------------------------------------------------
|
||||
applied, _ = send("brokkr_kitbash.shell", object_name="Plate", sheet=json.dumps(fit["sheet"]), thickness=0.03, levels=2)
|
||||
bpy.context.view_layer.update()
|
||||
fitted_on = flow(lines, shell)
|
||||
low, high = sum(blocked_on.values()) / 4, sum(fitted_on.values()) / 4
|
||||
bound = math.sqrt(low * high)
|
||||
check(f"applied with brokkr_kitbash.shell, flow_score reads the four traced lines on a built edge over {bound:.3f} in the mean: the geometric mean of the fitted build's "
|
||||
f"reading ({high:.3f}) and the blocked build's ({low:.3f}), separation {high / bound:.2f} each side; no fitted line reads under 0.9",
|
||||
applied["status"] == "accepted" and high / bound >= 1.2 and min(fitted_on.values()) >= 0.9, {"blocked": blocked_on, "fitted": fitted_on})
|
||||
|
||||
# --- crease_run is what Blender builds of both runs ----------------------------------------------------------------
|
||||
send("brokkr_kitbash.shell", object_name="Plate", sheet=json.dumps(fit["sheet"]), thickness=0.03, levels=1)
|
||||
wall = shell.modifiers["Kit Solidify"]
|
||||
wall.show_viewport = False
|
||||
mesh = shell.evaluated_get(bpy.context.evaluated_depsgraph_get()).to_mesh()
|
||||
built = np.array([v.co for v in mesh.vertices])
|
||||
wall.show_viewport = True
|
||||
worst = {tag: max(float(np.linalg.norm(built - p, axis=1).min()) for p in core.crease_run(np.array(fit["sheet"]["rings"])[:, column] * [side, 1, 1])) for tag, (column, side) in runs.items()}
|
||||
check("at one level Blender builds the rim run and the crease, on both halves, where core.crease_run says, within 1e-4 m", max(worst.values()) < 1e-4, worst)
|
||||
send("brokkr_kitbash.shell", object_name="Plate", sheet=json.dumps(blocked), thickness=0.03, levels=2)
|
||||
|
||||
# --- refusals ----------------------------------------------------------------------------------------------------------
|
||||
before = state(shell)
|
||||
line = np.array(lines["crease_m"])
|
||||
doubled = np.vstack([line[:25], line[24:9:-1] + [0.0, 14.0], line[10:25] + [0.0, 28.0], line[25:]]).round(3).tolist()
|
||||
receipt, _ = send("brokkr_reference.fit_shell", object_name="Plate", traces=json.dumps([traces[0], dict(traces[1], line=doubled)], separators=(",", ":")))
|
||||
check("a trace doubled back over itself is refused, naming the trace and the span no built run draws", receipt["status"] == "failed" and "traces[1] is not explained" in receipt["message"] and "px along it" in receipt["message"], receipt["message"])
|
||||
receipt, _ = send("brokkr_reference.fit_shell", object_name="Plate", traces=json.dumps([dict(traces[0], camera="Nobody")]))
|
||||
check("an unknown camera is refused naming the trace", receipt["status"] == "failed" and "traces[0]" in receipt["message"] and "Nobody" in receipt["message"], receipt["message"])
|
||||
receipt, _ = send("brokkr_reference.fit_shell", object_name="View", traces=json.dumps(traces[:1]))
|
||||
check("an object that is no shell is refused", receipt["status"] == "failed" and "is not a shell" in receipt["message"], receipt["message"])
|
||||
shell.scale = (2.0, 2.0, 2.0)
|
||||
bpy.context.view_layer.update()
|
||||
receipt, _ = send("brokkr_reference.fit_shell", object_name="Plate", traces=json.dumps(traces[:1]))
|
||||
shell.scale = (1.0, 1.0, 1.0)
|
||||
bpy.context.view_layer.update()
|
||||
check("a scaled shell is refused", receipt["status"] == "failed" and "is scaled" in receipt["message"], receipt["message"])
|
||||
check("no refusal changed the shell", state(shell) == before)
|
||||
|
||||
# --- a free cage, by its vertex chains ---------------------------------------------------------------------------------
|
||||
design, chain = free_cage()
|
||||
|
||||
def crease(sheet, side, levels=core.LEVELS):
|
||||
run = np.array(sheet["verts"])[chain] * [side, 1, 1]
|
||||
for _ in range(levels):
|
||||
run = core.crease_run(run)
|
||||
return run
|
||||
|
||||
send("brokkr_kitbash.shell", object_name="Free", sheet=json.dumps(design), thickness=0.03, levels=2)
|
||||
free = bpy.data.objects["Free"]
|
||||
free.matrix_world = shell.matrix_world.copy()
|
||||
bpy.context.view_layer.update()
|
||||
free_lines = {side: pixels(camera, free, core.resampled(crease(design, side), 120)) for side in (1, -1)}
|
||||
rough, bump = json.loads(json.dumps(design)), np.random.default_rng(1).normal(0, 0.06, (len(chain), 3))
|
||||
for v, d in zip(chain, bump):
|
||||
rough["verts"][v] = [round(float(x + y), 6) for x, y in zip(design["verts"][v], d)]
|
||||
send("brokkr_kitbash.shell", object_name="Free", sheet=json.dumps(rough), thickness=0.03, levels=2)
|
||||
bpy.context.view_layer.update()
|
||||
before = state(free)
|
||||
receipt, fit = send("brokkr_reference.fit_shell", object_name="Free",
|
||||
traces=json.dumps([{"camera": "View", "run": {"verts": chain}, "side": side, "line": free_lines[side]} for side in (1, -1)], separators=(",", ":")))
|
||||
ok = receipt["status"] == "accepted" and fit is not None
|
||||
if ok:
|
||||
gap, off = (float(core._off(core.resampled(crease(sheet, 1), 200), crease(design, 1)).max()) for sheet in (fit["sheet"], rough))
|
||||
check("a mirrored free cage's crease, traced on both halves and named {verts}, is fitted within 1 mm of the designed run from a blocking over 0.05 m off: "
|
||||
"a row for each of its six vertices and no other, every trace explained, nothing written",
|
||||
gap < 0.001 and off > 0.05 and [row["vertex"] for row in fit["points"]] == chain and max(row["unexplained_px"] for row in fit["traces"]) <= core.TOL
|
||||
and all(0 <= u <= WIDTH and 0 <= v <= HEIGHT for line in free_lines.values() for u, v in line) and state(free) == before,
|
||||
{"gap": gap, "off": off, "traces": fit["traces"], "prior_share": max(row["prior_share"] for row in fit["points"]), "seconds": fit["seconds"]})
|
||||
applied, _ = send("brokkr_kitbash.shell", object_name="Free", sheet=json.dumps(fit["sheet"]), thickness=0.03, levels=1)
|
||||
wall = free.modifiers["Kit Solidify"]
|
||||
wall.show_viewport = False
|
||||
built = np.array([v.co for v in free.evaluated_get(bpy.context.evaluated_depsgraph_get()).to_mesh().vertices])
|
||||
wall.show_viewport = True
|
||||
worst = {side: max(float(np.linalg.norm(built - p, axis=1).min()) for p in crease(fit["sheet"], side, 1)) for side in (1, -1)}
|
||||
check("brokkr_kitbash.shell takes the fitted free cage, and at one level Blender builds its crease on both halves where core.crease_run says, within 1e-4 m",
|
||||
applied["status"] == "accepted" and max(worst.values()) < 1e-4, worst)
|
||||
else:
|
||||
check("fit_shell fits a mirrored free cage by its vertex chains", False, 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)
|
||||
212
surfaces/blender/tests/live/reference_fit.result.json
Normal file
212
surfaces/blender/tests/live/reference_fit.result.json
Normal file
|
|
@ -0,0 +1,212 @@
|
|||
{
|
||||
"blender": "5.3.0",
|
||||
"checks": [
|
||||
{
|
||||
"name": "host files admitted with the fit_shell row",
|
||||
"ok": true,
|
||||
"detail": [
|
||||
"brokkr_mesh_polish.audit",
|
||||
"brokkr_mesh_polish.repair",
|
||||
"brokkr_mesh_polish.orient",
|
||||
"brokkr_mesh_polish.delight",
|
||||
"brokkr_mesh_polish.scrub_markings",
|
||||
"brokkr_mesh_polish.cut_parts",
|
||||
"brokkr_mesh_polish.pick",
|
||||
"brokkr_kitbash.place_part",
|
||||
"brokkr_kitbash.set_params",
|
||||
"brokkr_kitbash.describe",
|
||||
"brokkr_kitbash.report",
|
||||
"brokkr_kitbash.attach",
|
||||
"brokkr_kitbash.detach",
|
||||
"brokkr_kitbash.roll",
|
||||
"brokkr_kitbash.aim",
|
||||
"brokkr_kitbash.reach",
|
||||
"brokkr_kitbash.joint",
|
||||
"brokkr_kitbash.slide",
|
||||
"brokkr_kitbash.joints",
|
||||
"brokkr_kitbash.close",
|
||||
"brokkr_kitbash.boolean",
|
||||
"brokkr_kitbash.cut",
|
||||
"brokkr_kitbash.cut_many",
|
||||
"brokkr_kitbash.freeze",
|
||||
"brokkr_kitbash.thaw",
|
||||
"brokkr_kitbash.ribs",
|
||||
"brokkr_kitbash.shell",
|
||||
"brokkr_kitbash.hose",
|
||||
"brokkr_reference.solve_camera",
|
||||
"brokkr_reference.flow_score",
|
||||
"brokkr_reference.fit_shell"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "the designed shell: the camera frames all four runs, and flow_score reads each traced line on a built edge",
|
||||
"ok": true,
|
||||
"detail": {
|
||||
"crease": 1.0,
|
||||
"crease_m": 1.0,
|
||||
"rim": 1.0,
|
||||
"rim_m": 0.963
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "fit_shell returns a sheet with every trace explained within 5.2 px, and a row for each of the 12 moved points",
|
||||
"ok": true,
|
||||
"detail": {
|
||||
"traces": [
|
||||
{
|
||||
"unexplained_px": 0.01,
|
||||
"worst_px": 0.021
|
||||
},
|
||||
{
|
||||
"unexplained_px": 0.054,
|
||||
"worst_px": 0.082
|
||||
},
|
||||
{
|
||||
"unexplained_px": 0.052,
|
||||
"worst_px": 0.071
|
||||
},
|
||||
{
|
||||
"unexplained_px": 0.036,
|
||||
"worst_px": 0.055
|
||||
}
|
||||
],
|
||||
"seconds": 0.176,
|
||||
"chars": 2066
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "fit_shell wrote nothing: the shell's request and its cage are as they were",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "the fitted runs stand within 5 mm of the designed ones, from a blocking over 0.05 m off them",
|
||||
"ok": true,
|
||||
"detail": [
|
||||
0.0006199003550468113,
|
||||
0.132354157889395
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "every moved point reports metres per pixel and a prior share from 0 to 1",
|
||||
"ok": true,
|
||||
"detail": 0.069
|
||||
},
|
||||
{
|
||||
"name": "applied with brokkr_kitbash.shell, flow_score reads the four traced lines on a built edge over 0.747 in the mean: the geometric mean of the fitted build's reading (0.991) and the blocked build's (0.563), separation 1.33 each side; no fitted line reads under 0.9",
|
||||
"ok": true,
|
||||
"detail": {
|
||||
"blocked": {
|
||||
"crease": 0.713,
|
||||
"crease_m": 0.613,
|
||||
"rim": 0.138,
|
||||
"rim_m": 0.787
|
||||
},
|
||||
"fitted": {
|
||||
"crease": 1.0,
|
||||
"crease_m": 1.0,
|
||||
"rim": 1.0,
|
||||
"rim_m": 0.963
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "at one level Blender builds the rim run and the crease, on both halves, where core.crease_run says, within 1e-4 m",
|
||||
"ok": true,
|
||||
"detail": {
|
||||
"crease": 1.341720156294607e-07,
|
||||
"crease_m": 1.341720156294607e-07,
|
||||
"rim": 1.6729111618262465e-07,
|
||||
"rim_m": 1.6729111618262465e-07
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "a trace doubled back over itself is refused, naming the trace and the span no built run draws",
|
||||
"ok": true,
|
||||
"detail": "Error: traces[1] is not explained: 235 px of the trace, between 126 and 461 px along it, lie more than 5.2 px from the run as built (11.6 px at the 90th of a hundred; up to 15.7 px). Nothing is returned as a fit. The trace draws something this run does not build (an overdrawn or doubled stroke, another edge, a bend the cage has too few points for): redraw it, or give the run more points. A very unsteady hand reads the same as a slight overdraw: if the trace is one clean stroke, ask again with tol over this reading. Nothing changed."
|
||||
},
|
||||
{
|
||||
"name": "an unknown camera is refused naming the trace",
|
||||
"ok": true,
|
||||
"detail": "Error: traces[0]: 'Nobody' is not a camera object."
|
||||
},
|
||||
{
|
||||
"name": "an object that is no shell is refused",
|
||||
"ok": true,
|
||||
"detail": "Error: 'View' is not a shell brokkr_kitbash.shell made (a mesh carrying kit_shell)."
|
||||
},
|
||||
{
|
||||
"name": "a scaled shell is refused",
|
||||
"ok": true,
|
||||
"detail": "Error: 'Plate' is scaled (2.0, 2.0, 2.0): a sheet is in metres of the shell's own frame. Apply or clear the scale."
|
||||
},
|
||||
{
|
||||
"name": "no refusal changed the shell",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "a mirrored free cage's crease, traced on both halves and named {verts}, is fitted within 1 mm of the designed run from a blocking over 0.05 m off: a row for each of its six vertices and no other, every trace explained, nothing written",
|
||||
"ok": true,
|
||||
"detail": {
|
||||
"gap": 0.00042547668113367745,
|
||||
"off": 0.055743395392436126,
|
||||
"traces": [
|
||||
{
|
||||
"unexplained_px": 0.013,
|
||||
"worst_px": 0.022
|
||||
},
|
||||
{
|
||||
"unexplained_px": 0.02,
|
||||
"worst_px": 0.032
|
||||
}
|
||||
],
|
||||
"prior_share": 0.06,
|
||||
"seconds": 0.027
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "brokkr_kitbash.shell takes the fitted free cage, and at one level Blender builds its crease on both halves where core.crease_run says, within 1e-4 m",
|
||||
"ok": true,
|
||||
"detail": {
|
||||
"1": 1.305964704160048e-07,
|
||||
"-1": 1.305964704160048e-07
|
||||
}
|
||||
}
|
||||
],
|
||||
"hostErrors": [],
|
||||
"hostRows": [
|
||||
"brokkr_mesh_polish.audit",
|
||||
"brokkr_mesh_polish.repair",
|
||||
"brokkr_mesh_polish.orient",
|
||||
"brokkr_mesh_polish.delight",
|
||||
"brokkr_mesh_polish.scrub_markings",
|
||||
"brokkr_mesh_polish.cut_parts",
|
||||
"brokkr_mesh_polish.pick",
|
||||
"brokkr_kitbash.place_part",
|
||||
"brokkr_kitbash.set_params",
|
||||
"brokkr_kitbash.describe",
|
||||
"brokkr_kitbash.report",
|
||||
"brokkr_kitbash.attach",
|
||||
"brokkr_kitbash.detach",
|
||||
"brokkr_kitbash.roll",
|
||||
"brokkr_kitbash.aim",
|
||||
"brokkr_kitbash.reach",
|
||||
"brokkr_kitbash.joint",
|
||||
"brokkr_kitbash.slide",
|
||||
"brokkr_kitbash.joints",
|
||||
"brokkr_kitbash.close",
|
||||
"brokkr_kitbash.boolean",
|
||||
"brokkr_kitbash.cut",
|
||||
"brokkr_kitbash.cut_many",
|
||||
"brokkr_kitbash.freeze",
|
||||
"brokkr_kitbash.thaw",
|
||||
"brokkr_kitbash.ribs",
|
||||
"brokkr_kitbash.shell",
|
||||
"brokkr_kitbash.hose",
|
||||
"brokkr_reference.solve_camera",
|
||||
"brokkr_reference.flow_score",
|
||||
"brokkr_reference.fit_shell"
|
||||
],
|
||||
"ok": true
|
||||
}
|
||||
|
|
@ -20,6 +20,7 @@ tolerances round a known truth that no mutant claims. The mutants, each run once
|
|||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import importlib.util
|
||||
import json
|
||||
import math
|
||||
|
|
@ -44,6 +45,10 @@ if np is not None:
|
|||
spec = importlib.util.spec_from_file_location("brokkr_reference_core", SURFACE / "brokkr_reference" / "core.py")
|
||||
core = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(core)
|
||||
spec = importlib.util.spec_from_file_location("brokkr_kitbash_core_for_reference", SURFACE / "brokkr_kitbash" / "core.py")
|
||||
kit = importlib.util.module_from_spec(spec) # the sheet's one parser: fit_sheet takes what it parses
|
||||
sys.modules[spec.name] = kit
|
||||
spec.loader.exec_module(kit)
|
||||
|
||||
BOX = [100.0, 50.0, 1100.0, 800.0]
|
||||
NAMES = [f"p{i}" for i in range(13)]
|
||||
|
|
@ -381,6 +386,337 @@ class FlowTests(unittest.TestCase):
|
|||
self.assertIn(said, str(caught.exception))
|
||||
|
||||
|
||||
FIT_FRAME = [[0.9659258262890683, -0.25881904510252074, 0.0, 0.3], [0.25881904510252074, 0.9659258262890683, 0.0, -0.2], [0.0, 0.0, 1.0, 0.1], [0.0, 0.0, 0.0, 1.0]] # turned 15 degrees about z and moved
|
||||
FIT_VIEWS = ((35, 20, 50), (-60, 40, 85), (150, 10, 35))
|
||||
FIT_K = 10 # cage points in the traced column
|
||||
|
||||
|
||||
def crease(A, w, n=400):
|
||||
"""A crease 2 m long on the +x side of a mirror plane, in the shell's frame: the family the fit was mapped on."""
|
||||
t = np.linspace(0, 1, n)
|
||||
return np.stack([0.4 + A * np.sin(w * t), -1.0 + 2.0 * t, 0.5 + 0.3 * t * t], 1)
|
||||
|
||||
|
||||
def overdrawn(line, start, stop, off, kind):
|
||||
"""A stroke that runs along `line`, and between two shares of it doubles back and over again, each pass `off`
|
||||
of the line's extent further to one side: a trace drawn twice over."""
|
||||
n = len(line)
|
||||
i0, i1 = int(start * (n - 1)), int(stop * (n - 1))
|
||||
v = line[i1] - line[i0]
|
||||
d = np.array([-v[1], v[0]]) / np.linalg.norm(v) * off * np.ptp(line, axis=0).max()
|
||||
forward, back = line[i0:i1 + 1], line[i1:i0 - 1 if i0 > 0 else None:-1]
|
||||
if kind == "mid":
|
||||
return np.vstack([line[:i1 + 1], back + d, forward + 2 * d, line[i1 + 1:]])
|
||||
if kind == "truth-last":
|
||||
return np.vstack([line[:i0], forward + d, back + 2 * d, line[i0:]])
|
||||
return np.vstack([line[:i0], forward + d, back + 2 * d, forward, line[i1 + 1:]])
|
||||
|
||||
|
||||
def strip(column, weight=1.0, last=None):
|
||||
"""A mirrored sheet three points wide whose column 1 is `column`, creased from ring 0 to `last` (the far rim)."""
|
||||
return {"mirror": True, "rim": 1.0, "creases": [{"column": 1, "from": 0, "to": len(column) - 1 if last is None else last, "weight": weight}],
|
||||
"rings": [[[0.0, float(p[1]), float(p[2]) + 0.15], [float(v) for v in p], [float(p[0]) + 0.5, float(p[1]), float(p[2]) - 0.2]] for p in column]}
|
||||
|
||||
|
||||
def blocked(A, w, share):
|
||||
"""(the true crease, a strip whose column stands up to `share` of the crease's 2 m off it)."""
|
||||
truth, t, r = crease(A, w), np.linspace(0, 1, FIT_K), np.random.default_rng(int(A * 100 + w * 10))
|
||||
bump = sum(r.normal(0, 1, 3)[None] * np.sin(np.pi * (j + 1) * t)[:, None] for j in range(2))
|
||||
return truth, strip(core.resampled(truth, FIT_K) + share * 2.0 * bump / np.abs(bump).max())
|
||||
|
||||
|
||||
def fit_views(truth):
|
||||
both = np.vstack([truth, truth * [-1, 1, 1]]) @ np.array(FIT_FRAME)[:3, :3].T + np.array(FIT_FRAME)[:3, 3]
|
||||
return [camera(both, *view) for view in FIT_VIEWS]
|
||||
|
||||
|
||||
def pair_traces(a, b=None):
|
||||
run = {"column": 1, "from": 0, "to": FIT_K - 1}
|
||||
return [{"camera": "View", "run": run, "side": side, "line": np.asarray(line).tolist()} for side, line in ((1, a), (-1, b)) if line is not None]
|
||||
|
||||
|
||||
def fitted(document, traces, cam, **more):
|
||||
return core.fit_sheet(document, kit.sheet(document), FIT_FRAME, traces, [cam] * len(traces), **more)
|
||||
|
||||
|
||||
def off_truth(document, truth):
|
||||
"""The furthest the column's built run stands from the true crease, or the crease's ends from the run."""
|
||||
run = core.resampled(core.crease_run(core.crease_run(np.array(document["rings"])[:, 1])), 400)
|
||||
return max(float(core._off(run, truth).max()), float(core._off(truth[[0, -1]], run).max()))
|
||||
|
||||
|
||||
def hand(line, sigma, rng, corr=30.0, jitter=0.7, tip=6.0):
|
||||
"""`line` as a hand draws it: a wander of `sigma` px that holds over `corr` px, a jitter on every point, and
|
||||
each tip (its 10 px) set off whole by about `tip` px."""
|
||||
s = np.r_[0, np.cumsum(np.linalg.norm(np.diff(line, axis=0), axis=1))]
|
||||
grid = np.arange(0, s[-1] + corr, corr / 2)
|
||||
wander = rng.normal(0, 1, (len(grid), 2))
|
||||
out = line + sigma * np.stack([np.interp(s, grid, wander[:, k]) for k in range(2)], 1) + rng.normal(0, jitter, line.shape)
|
||||
out[s < 10] += rng.normal(0, 1, 2) * tip
|
||||
out[s > s[-1] - 10] += rng.normal(0, 1, 2) * tip
|
||||
return out
|
||||
|
||||
|
||||
def free_strip(points=6):
|
||||
"""A mirrored free cage three columns wide (x 0 on the mirror plane, 0.5, 1) whose middle column is a hard
|
||||
crease, and that column's vertices in order."""
|
||||
verts = [[x, -1 + 2 * i / (points - 1), 0.5 - x * x + 0.1 * math.sin(3 * i / (points - 1)) * (c == 1)] for c, x in enumerate((0.0, 0.5, 1.0)) for i in range(points)]
|
||||
faces = [[c * points + i, c * points + i + 1, c * points + i + 1 + points, c * points + i + points] for c in range(2) for i in range(points - 1)]
|
||||
chain = list(range(points, 2 * points))
|
||||
return {"verts": verts, "faces": faces, "creases": [[a, b, 1.0] for a, b in zip(chain, chain[1:])], "mirror": True, "rim": 1.0}, chain
|
||||
|
||||
|
||||
@unittest.skipIf(np is None, "numpy")
|
||||
class FitTests(unittest.TestCase):
|
||||
"""fit_runs and fit_sheet: a shell's traced runs fitted through cameras, accepted only where the built runs
|
||||
explain the traces. Bounds follow lodur:ruling:deterministic-bound-margin. Mutants, each run once on a copy:
|
||||
F1 no explained check test_an_overdrawn_stroke_is_refused_naming_its_trace
|
||||
F3 the prior left out of S test_one_trace_alone_reads_as_held_by_the_blocking
|
||||
F4 no end terms test_a_mirrored_column_is_recovered_from_a_blocking_well_off
|
||||
F5 a semi-sharp run admitted test_refusals_name_their_field_before_fitting
|
||||
G1 m_per_px along the sight line whole test_a_mirrored_column_is_recovered_from_a_blocking_well_off
|
||||
G2 the gate on the trace's worst point (PART 100) test_hand_traces_are_explained_at_the_default
|
||||
G3 a point on the mirror plane free to leave it test_a_spine_on_the_mirror_plane_stays_on_it
|
||||
G4 a run's last index allowed one past the sheet test_refusals_name_their_field_before_fitting
|
||||
G5 the prior's share not scaled by the diagonal test_one_trace_alone_reads_as_held_by_the_blocking
|
||||
G6 the gate at 1.2 x tol test_an_overdrawn_stroke_is_refused_naming_its_trace
|
||||
G7 a free cage's mirrored half read as the authored test_a_free_cage_is_fitted_by_its_vertex_chains
|
||||
G8 the prior in the Jacobian and not the residual test_one_trace_alone_reads_as_held_by_the_blocking
|
||||
|
||||
core.PART and core.TOL were read from 296 fits kept outside the suite (108 hand traces by `hand`,
|
||||
wander 1, 2 and 4 px; 108 strokes by `overdrawn` 1, 2, 3 and 5% off; the Orchid pair, moved and overdrawn).
|
||||
Read at the PART-th percentile, the traces to accept read 3.76 px at most (the 72 hand traces of wander 1 and
|
||||
2 px; the Orchid pair 0.80) and the least to refuse 7.27 (the Orchid's traces overdrawn 2%; the strokes 3% off
|
||||
7.70): TOL is their geometric mean, separation 1.39 each side. The trace's worst point,
|
||||
which that reading replaces, read 9.20 on the Orchid pair against 9.12 on its least 1% overdraw. What TOL does
|
||||
not separate: 31 of the 36 hand traces of wander 4 px are accepted (they read up to 5.84), 9 of 27 strokes 1%
|
||||
off and 2 of 18 Orchid 1% overdraws are accepted (from 2.57 and 4.25), and of the strokes 2% off, which read
|
||||
from 5.10, 2 of 27 are accepted. A very unsteady hand and a slight overdraw read alike; the report carries the reading.
|
||||
|
||||
Unclaimed, with readings: F6, the Jacobian by differences (time only: tests/live/reference_fit.py's header);
|
||||
the least, in place of the worst, of the traces that draw a point (the 18 pairs' greatest prior_share reads 0.060
|
||||
against 0.080, both under PAIR_FROM_SINGLE; one point's two readings differ up to 4.3 times); the guard on a run
|
||||
seen end on (the reading is dropped either way)."""
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.orchid = json.loads((Path(__file__).resolve().parent / "fixtures" / "orchid_c09_traces.json").read_text(encoding="utf-8"))
|
||||
|
||||
def test_the_projection_derivative_is_the_projections(self):
|
||||
cam, X = camera(cloud(), 35, 20, 50), cloud()
|
||||
u, J = core._drawn(cam, FIT_FRAME, X)
|
||||
self.assertLess(np.abs(u - core.seen(cam, FIT_FRAME, X)).max(), 1e-9)
|
||||
self.assertLess(np.abs(core.seen(cam, FIT_FRAME, X) - core.project(cam, X @ np.array(FIT_FRAME)[:3, :3].T + np.array(FIT_FRAME)[:3, 3])).max(), 1e-9) # seen is project past the frame
|
||||
for c in range(3):
|
||||
step = np.zeros(3)
|
||||
step[c] = 1e-6
|
||||
numeric = (core.seen(cam, FIT_FRAME, X + step) - core.seen(cam, FIT_FRAME, X - step)) / 2e-6
|
||||
self.assertLess(np.abs(numeric - J[:, :, c]).max(), 1e-4 * np.abs(J).max())
|
||||
self.assertIsNone(core._drawn(cam, np.eye(4), np.array([cam["C"]]) - np.array(cam["R"])[2] * -1.0)) # a point behind it
|
||||
|
||||
def families(self):
|
||||
for A, w in ((0.2, 2.5), (0.1, 5.0), (0.4, 1.0)):
|
||||
for share in (0.05, 0.15):
|
||||
truth, document = blocked(A, w, share)
|
||||
for cam in fit_views(truth):
|
||||
yield truth, document, cam
|
||||
|
||||
PAIR_FROM_SINGLE = 0.2 # prior_share: the geometric mean of 0.080, the most any point of the 18 mirrored pairs reads, and 0.503, the least an inner point of the 18 single traces reads: separation 2.5 each side
|
||||
|
||||
def test_a_mirrored_column_is_recovered_from_a_blocking_well_off(self):
|
||||
"""fit-recovers, F4 and G1: each of three views alone, both halves traced, from blockings 0.10 m and 0.30 m
|
||||
off. Shipped: the built run ends within 0.67 mm of the true crease (the 3 mm asked is a tolerance round a
|
||||
known truth) and the worst point of any trace stands 0.196 px off its run. F4 (no end terms): the run stops
|
||||
short of its traces and the worst reads 2.06 px and up: the bound is the geometric mean of 0.196 and 2.06,
|
||||
separation 3.2 each side. Every point reads a prior_share under PAIR_FROM_SINGLE: the pair decides it. G1
|
||||
(the sight line whole, a point's slide along its own run counted in) reads inner points up to 0.95."""
|
||||
worst = 0.0
|
||||
for truth, document, cam in self.families():
|
||||
self.assertGreater(off_truth(document, truth), 0.09)
|
||||
out = fitted(document, pair_traces(core.seen(cam, FIT_FRAME, truth), core.seen(cam, FIT_FRAME, truth * [-1, 1, 1])), cam)
|
||||
worst = max(worst, off_truth(out["sheet"], truth))
|
||||
self.assertLess(max(row["worst_px"] for row in out["traces"]), 0.64)
|
||||
self.assertEqual(len(out["points"]), FIT_K)
|
||||
self.assertLess(max(row["prior_share"] for row in out["points"]), self.PAIR_FROM_SINGLE)
|
||||
self.assertLess(worst, 0.003)
|
||||
|
||||
def test_one_trace_alone_reads_as_held_by_the_blocking(self):
|
||||
"""F3, G5, G8: one half traced in one view decides nothing along the sight line. The same 18 fits with one
|
||||
trace end 17.6 to 355 mm off the truth (G8, the prior left out of the residual, lets the nearest drift to 11.2:
|
||||
the bound is their geometric mean, separation 1.25 each side), and every inner point reads a prior_share over PAIR_FROM_SINGLE
|
||||
(0.503 to 1.0, the sine of the angle its run stands off the sight line; an end seen along its run reads
|
||||
down to 0.005, and its depth across the run is decided). F3 (the prior left out of S) reads 771366 where
|
||||
the ceiling is 1. m_per_px is prior_share x share x the sheet's diagonal (2.77 m here); G5 leaves the
|
||||
diagonal out."""
|
||||
for truth, document, cam in self.families():
|
||||
out = fitted(document, pair_traces(core.seen(cam, FIT_FRAME, truth)), cam)
|
||||
shares = [row["prior_share"] for row in out["points"]]
|
||||
self.assertGreater(min(shares[1:-1]), self.PAIR_FROM_SINGLE)
|
||||
self.assertLessEqual(max(shares), 1.0)
|
||||
self.assertGreater(off_truth(out["sheet"], truth), 0.014)
|
||||
diagonal = float(np.linalg.norm(np.ptp(kit.sheet(document).V, axis=0)))
|
||||
for row in out["points"][1:-1]:
|
||||
self.assertAlmostEqual(row["m_per_px"] / row["prior_share"], 0.1 * diagonal, delta=0.01 * diagonal)
|
||||
|
||||
def test_an_overdrawn_stroke_is_refused_naming_its_trace(self):
|
||||
"""overdraw-refused, F1 and G6: the mirrored half's trace doubled back over part of itself 3% of its extent
|
||||
off. All 27 are refused, naming the trace and the span that no built run draws; the least reads 7.70 px
|
||||
against core.TOL, separation 1.48. F1 returns all 27 as fits, the worst 0.104 m off the truth. Asked with
|
||||
tol 1.1 times its own reading a stroke is accepted, and with tol that reading over 1.1 refused: tol is what
|
||||
the reading is held to (G6 holds it to 1.2 x tol)."""
|
||||
truth, document = blocked(0.2, 2.5, 0.05)
|
||||
least = 1e9
|
||||
for cam in fit_views(truth):
|
||||
a, b = core.seen(cam, FIT_FRAME, truth), core.seen(cam, FIT_FRAME, truth * [-1, 1, 1])
|
||||
for start, stop in ((0.1, 0.3), (0.3, 0.7), (0.6, 1.0)):
|
||||
for kind in ("mid", "truth-last", "truth-first"):
|
||||
with self.assertRaisesRegex(core.ReferenceFitError, r"^traces\[[01]\] is not explained: \d+ px of the trace, between \d+ and \d+ px along it") as caught:
|
||||
fitted(document, pair_traces(a, overdrawn(b, start, stop, 0.03, kind)), cam)
|
||||
self.assertEqual(set(caught.exception.traces[0]), {"unexplained_px", "worst_px"})
|
||||
least = min(least, max(row["unexplained_px"] for row in caught.exception.traces))
|
||||
self.assertGreater(least, core.TOL * 1.2) # lodur:ruling:deterministic-bound-margin's least separation
|
||||
traces = pair_traces(a, overdrawn(b, 0.3, 0.7, 0.03, "mid"))
|
||||
with self.assertRaises(core.ReferenceFitError) as caught:
|
||||
fitted(document, traces, cam)
|
||||
reading = max(row["unexplained_px"] for row in caught.exception.traces)
|
||||
self.assertAlmostEqual(max(row["unexplained_px"] for row in fitted(document, traces, cam, tol=reading * 1.1)["traces"]), reading, delta=0.002)
|
||||
with self.assertRaises(core.ReferenceFitError):
|
||||
fitted(document, traces, cam, tol=reading / 1.1)
|
||||
|
||||
def test_hand_traces_are_explained_at_the_default(self):
|
||||
"""G2: both halves traced by `hand` (wander 2 px, tips 6 px off), each of three views. All three are
|
||||
accepted at core.TOL, reading 2.99 px at most (TOL over 1.74), while the worst point of each stands 6.08 to
|
||||
6.94 px off its run: G2, which holds that point to TOL, refuses all three. The fits end 20 to 64 mm off the
|
||||
true crease, up to 1.3 times TOL x the m_per_px they report: m_per_px is a sensitivity, what one pixel of
|
||||
error on a single point moves, and a wander that holds over 30 px moves more."""
|
||||
truth, document = blocked(0.2, 2.5, 0.05)
|
||||
rng, most = np.random.default_rng(1), 0.0
|
||||
for cam in fit_views(truth):
|
||||
a, b = hand(core.seen(cam, FIT_FRAME, truth), 2.0, rng), hand(core.seen(cam, FIT_FRAME, truth * [-1, 1, 1]), 2.0, rng)
|
||||
out = fitted(document, pair_traces(a, b), cam)
|
||||
self.assertLess(max(row["unexplained_px"] for row in out["traces"]), core.TOL / 1.2)
|
||||
most = max(most, max(row["worst_px"] for row in out["traces"]))
|
||||
self.assertGreater(most, core.TOL * 1.2)
|
||||
|
||||
def test_a_clean_fit_moves_less_than_its_reported_sensitivity(self):
|
||||
"""m_per_px as a sensitivity, on clean strokes only: strokes doubled back 0.2% off pass as explained, and each
|
||||
accepted fit stands within core.TOL x the worst m_per_px it reports of the truth: all 27 are accepted, the
|
||||
worst 8.9 mm off, 0.16 of that. It is no error bound: no mutant claims it, and hand traces end past it
|
||||
(test_hand_traces_are_explained_at_the_default)."""
|
||||
truth, document = blocked(0.2, 2.5, 0.05)
|
||||
accepted, most = 0, 0.0
|
||||
for cam in fit_views(truth):
|
||||
a, b = core.seen(cam, FIT_FRAME, truth), core.seen(cam, FIT_FRAME, truth * [-1, 1, 1])
|
||||
for start, stop in ((0.1, 0.3), (0.3, 0.7), (0.6, 1.0)):
|
||||
for kind in ("mid", "truth-last", "truth-first"):
|
||||
out = fitted(document, pair_traces(a, overdrawn(b, start, stop, 0.002, kind)), cam)
|
||||
accepted += 1
|
||||
most = max(most, off_truth(out["sheet"], truth) / (core.TOL * max(row["m_per_px"] for row in out["points"])))
|
||||
self.assertEqual(accepted, 27)
|
||||
self.assertLess(most, 1.0)
|
||||
|
||||
def test_a_spine_on_the_mirror_plane_stays_on_it(self):
|
||||
"""G3: a mirrored sheet's column 0 is on the mirror plane and has no partner; the plane decides its depth.
|
||||
Traced in one view from a blocking 0.07 m off, its points keep x = 0 and the built run ends 0.15 mm
|
||||
from the true spine, every point reading a prior_share of 0.019 or under. G3 (x free there) leaves the run as far off as a single trace is."""
|
||||
t = np.linspace(0, 1, FIT_K)
|
||||
spine = np.stack([0 * t, -1 + 2 * t, 0.5 + 0.3 * t * t], 1)
|
||||
sheet_ = {"mirror": True, "rim": 1.0, "creases": [{"column": 0, "from": 0, "to": FIT_K - 1, "weight": 1.0}],
|
||||
"rings": [[[0.0, float(p[1]) + 0.05, float(p[2]) + 0.05], [0.4, float(p[1]), float(p[2]) - 0.1], [0.9, float(p[1]), float(p[2]) - 0.3]] for p in spine]}
|
||||
built = core.crease_run(core.crease_run(spine))
|
||||
cam = fit_views(built)[0]
|
||||
out = fitted(sheet_, [{"camera": "View", "run": {"column": 0, "from": 0, "to": FIT_K - 1}, "side": 1, "line": core.seen(cam, FIT_FRAME, built).tolist()}], cam)
|
||||
column = np.array(out["sheet"]["rings"])[:, 0]
|
||||
self.assertEqual(float(np.abs(column[:, 0]).max()), 0.0)
|
||||
self.assertLess(float(core._off(core.resampled(core.crease_run(core.crease_run(column)), 400), built).max()), 0.001)
|
||||
self.assertLess(max(row["prior_share"] for row in out["points"]), self.PAIR_FROM_SINGLE)
|
||||
|
||||
def test_a_free_cage_is_fitted_by_its_vertex_chains(self):
|
||||
"""free-cage, G7: a mirrored free cage's crease, six vertices, both halves traced in one view from a
|
||||
blocking 0.057 m off: the built run ends 0.45 mm from the true one, the six traced vertices are the only
|
||||
ones moved, each with a row naming its vertex and a prior_share under PAIR_FROM_SINGLE (0.036 at most). The
|
||||
mirrored half is the reflections the cage's own parser lists (Sheet.mirror_of); G7 reads it as the authored
|
||||
half and the fit is refused, the second trace unexplained."""
|
||||
truth, chain = free_strip()
|
||||
run = core.crease_run(core.crease_run(np.array(truth["verts"])[chain]))
|
||||
cam = fit_views(run)[0]
|
||||
document, bump = copy.deepcopy(truth), np.random.default_rng(1).normal(0, 0.06, (len(chain), 3))
|
||||
for v, d in zip(chain, bump):
|
||||
document["verts"][v] = [float(x) for x in np.array(truth["verts"][v]) + d]
|
||||
off = lambda sheet_: float(core._off(core.resampled(core.crease_run(core.crease_run(np.array(sheet_["verts"])[chain])), 400), run).max()) # noqa: E731
|
||||
traces = [{"camera": "View", "run": {"verts": chain}, "side": side, "line": core.seen(cam, FIT_FRAME, run * [side, 1, 1]).tolist()} for side in (1, -1)]
|
||||
out = fitted(document, traces, cam)
|
||||
self.assertGreater(off(document), 0.05)
|
||||
self.assertLess(off(out["sheet"]), 0.001)
|
||||
self.assertEqual([row["vertex"] for row in out["points"]], chain)
|
||||
self.assertLess(max(row["prior_share"] for row in out["points"]), self.PAIR_FROM_SINGLE)
|
||||
self.assertTrue(all(out["sheet"]["verts"][v] == document["verts"][v] for v in range(len(document["verts"])) if v not in chain))
|
||||
self.assertTrue(np.array_equal(kit.sheet(document).mirror_of, np.r_[np.arange(18), np.arange(6, 18)])) # the six on the mirror plane are shared, the twelve others reflected after them
|
||||
|
||||
def orchid_strip(self):
|
||||
return strip(np.array(self.orchid["blocking"]))
|
||||
|
||||
def orchid_fit(self, lines):
|
||||
document, run = self.orchid_strip(), {"column": 1, "from": 0, "to": 7}
|
||||
traces = [{"camera": "Concept", "run": run, "side": side, "line": line} for side, line in lines]
|
||||
return core.fit_sheet(document, kit.sheet(document), self.orchid["frame"], traces, [self.orchid["camera"]] * len(traces))
|
||||
|
||||
def test_orchid_c09_hand_traces(self):
|
||||
"""orchid-c09: the inboard edges of two petals traced by hand on one concept view, through a camera solved
|
||||
from hand marks (13 px rms). At the default the pair is explained: its traces read 0.80 and 0.68 px (TOL
|
||||
over 6.5), though the left trace's first 10 px stand up to 9.2 px off the built run, because the two
|
||||
traces' tips are not one point and its mirror image through that camera; the gate on the worst point
|
||||
refused the pair for that. Its points read a prior_share of 0.018 at most; either trace alone reads 0.271
|
||||
and up on every point: the bound is their geometric mean, separation 3.9 each side. The right trace
|
||||
overdrawn 2% of its extent is refused nine ways of nine, reading 7.27 px and up."""
|
||||
left, right, side = self.orchid["left"], self.orchid["right"], self.orchid["left_side"]
|
||||
pair = self.orchid_fit([(side, left), (-side, right)])
|
||||
self.assertLess(max(row["unexplained_px"] for row in pair["traces"]), core.TOL / 1.2)
|
||||
self.assertGreater(pair["traces"][0]["worst_px"], core.TOL * 1.2)
|
||||
self.assertLess(max(row["prior_share"] for row in pair["points"]), 0.07)
|
||||
self.assertEqual(pair["sheet"]["rings"][3][0], self.orchid_strip()["rings"][3][0]) # only the traced column moves
|
||||
for alone in ([(side, left)], [(-side, right)]):
|
||||
self.assertGreater(min(row["prior_share"] for row in self.orchid_fit(alone)["points"]), 0.07)
|
||||
least = 1e9
|
||||
for start, stop in ((0.1, 0.3), (0.3, 0.7), (0.6, 1.0)):
|
||||
for kind in ("mid", "truth-last", "truth-first"):
|
||||
with self.assertRaisesRegex(core.ReferenceFitError, r"^traces\[1\] is not explained") as caught:
|
||||
self.orchid_fit([(side, left), (-side, overdrawn(np.array(right), start, stop, 0.02, kind))])
|
||||
least = min(least, caught.exception.traces[1]["unexplained_px"])
|
||||
self.assertGreater(least, core.TOL * 1.2)
|
||||
|
||||
def test_refusals_name_their_field_before_fitting(self):
|
||||
"""refusals, F5 (which takes the semi-sharp run as far as its end and refuses it there for another cause)."""
|
||||
truth, document = blocked(0.2, 2.5, 0.05)
|
||||
cam = fit_views(truth)[0]
|
||||
a = core.seen(cam, FIT_FRAME, truth)
|
||||
column = np.array(document["rings"])[:, 1]
|
||||
crossed = strip(column)
|
||||
crossed["creases"].append({"ring": 4, "from": 0, "to": 2, "weight": 1.0})
|
||||
big = strip(core.resampled(column, 64))
|
||||
big["rings"] = [[ring[0]] + [[ring[1][0] + 0.01 * j, ring[1][1], ring[1][2]] for j in range(30)] for ring in big["rings"]]
|
||||
whole = {"column": 1, "from": 0, "to": 63}
|
||||
for sheet_, traces, cams, message in (
|
||||
(strip(column, weight=0.6), pair_traces(a), [cam], r"^traces\[0\]: the edge after point 0 of its run has crease weight 0\.6"),
|
||||
(strip(column, last=FIT_K - 2), [dict(pair_traces(a)[0], run={"column": 1, "from": 0, "to": FIT_K - 2})], [cam], r"^traces\[0\]: the last end of its run does not hold: it is a dart"),
|
||||
(strip(column, last=FIT_K - 2), pair_traces(a), [cam], r"^traces\[0\]: the edge after point 8 of its run has crease weight 0\b"),
|
||||
(crossed, pair_traces(a), [cam], r"^traces\[0\]: point 4 of its run is held or pulled by more than the run"),
|
||||
(document, pair_traces(a), [None], r"^traces\[0\]\.camera 'View' is no camera"),
|
||||
(document, [dict(pair_traces(a)[0], line=[[10.0, 20.0]])], [cam], r"^traces\[0\]: its line must be two or more"),
|
||||
(document, [dict(pair_traces(a)[0], side=2)], [cam], r"^traces\[0\]\.side must be 1"),
|
||||
(document, [dict(pair_traces(a)[0], run={"column": 3, "from": 0, "to": 2})], [cam], r"^traces\[0\]\.run must name a column under 3"),
|
||||
(document, [dict(pair_traces(a)[0], run={"ring": 0, "from": 0, "to": 2})], [cam], r"^traces\[0\]: the first end of its run does not hold"),
|
||||
(document, [dict(pair_traces(a)[0], run={"column": 1, "from": 0, "to": FIT_K})], [cam], r"^traces\[0\]\.run must name a column under 3 and from under to, to at most 9$"),
|
||||
(document, [dict(pair_traces(a)[0], run={"ring": 0, "from": 0, "to": 3})], [cam], r"^traces\[0\]\.run must name a ring under 10 and from under to, to at most 2$"),
|
||||
(document, [dict(pair_traces(a)[0], run={"verts": [0, 1]})], [cam], r"^traces\[0\]\.run must be \{ring, from, to\} or \{column, from, to\}: the sheet is a loft"),
|
||||
(free_strip()[0], pair_traces(a), [cam], r"^traces\[0\]\.run must be \{verts: \[v, \.\.\.\]\}, authored vertices under 18 in the run's order: the sheet is a free cage"),
|
||||
(free_strip()[0], [dict(pair_traces(a)[0], run={"verts": [6, 18]})], [cam], r"^traces\[0\]\.run must be \{verts"),
|
||||
(free_strip()[0], [dict(pair_traces(a)[0], run={"verts": [0, 6]})], [cam], r"^traces\[0\]: the first end of its run does not hold"), # a rim run from the mirror plane runs on across it
|
||||
(big, [dict(pair_traces(a)[0], run=whole)], [cam], r"would be about \d+ characters, over the 16000 a receipt carries: nothing was fitted")):
|
||||
with self.assertRaisesRegex(core.ReferenceFitError, message):
|
||||
core.fit_sheet(sheet_, kit.sheet(sheet_), FIT_FRAME, traces, cams)
|
||||
|
||||
|
||||
@unittest.skipIf(np is None, "numpy")
|
||||
class CameraTests(unittest.TestCase):
|
||||
CAM = {"C": [3.0, -7.0, 2.5], "f": 1400.0, "c": [640.0, 395.0], "box": BOX}
|
||||
|
|
@ -444,8 +780,8 @@ class HostFileTests(unittest.TestCase):
|
|||
|
||||
def test_the_row_names_the_operator_and_properties_the_add_on_defines(self):
|
||||
source = (SURFACE / "brokkr_reference" / "__init__.py").read_text(encoding="utf-8")
|
||||
self.assertEqual([row["name"] for row in self.document["actions"]], ["brokkr_reference.solve_camera", "brokkr_reference.flow_score"])
|
||||
self.assertEqual(source.count("bl_idname = "), 2)
|
||||
self.assertEqual([row["name"] for row in self.document["actions"]], ["brokkr_reference.solve_camera", "brokkr_reference.flow_score", "brokkr_reference.fit_shell"])
|
||||
self.assertEqual(source.count("bl_idname = "), 3)
|
||||
for row in self.document["actions"]:
|
||||
self.assertIn(f'bl_idname = "{row["name"]}"', source)
|
||||
self.assertEqual(row.get("result"), "brokkr_mesh_polish_result")
|
||||
|
|
@ -466,6 +802,11 @@ class HostFileTests(unittest.TestCase):
|
|||
for intent, bad in ((flow, {"angle": 0}), (flow, {"lines": ""}), (flow, {"camera_name": "x" * 64})):
|
||||
with self.assertRaises(at.IntentInvalid):
|
||||
at.validate({**intent, **bad}, self.host)
|
||||
fit = {**self.envelope, "action": "brokkr_reference.fit_shell", "object_name": "Plate", "traces": "[{}]"}
|
||||
self.assertEqual((at.validate(fit, self.host)["share"], at.validate(fit, self.host)["tol"]), (0.1, core.TOL))
|
||||
for bad in ({"tol": 0}, {"share": 11}, {"traces": ""}, {"object_name": "x" * 64}):
|
||||
with self.assertRaises(at.IntentInvalid):
|
||||
at.validate({**fit, **bad}, self.host)
|
||||
|
||||
|
||||
class OwnershipTests(unittest.TestCase):
|
||||
|
|
@ -481,6 +822,14 @@ class OwnershipTests(unittest.TestCase):
|
|||
if path.is_file():
|
||||
self.assertIsNone(re.search(r"concepts\.json|PIL|Image\.open|centre_plate|silhouette|polygon_mask|knotted", path.read_text(encoding="utf-8")), path.name)
|
||||
|
||||
def test_fit_shell_never_writes_the_request_and_nothing_here_searches_a_correspondence(self):
|
||||
"""The cut's negative patterns: brokkr_kitbash.shell is the cage's one writer, and no point's depth is
|
||||
decided by matching trace points to each other."""
|
||||
for path in (SURFACE / "brokkr_reference").glob("*.py"):
|
||||
text = path.read_text(encoding="utf-8")
|
||||
self.assertIsNone(re.search(r"def pair|_smoothest|cage_through|on_plane", text), path.name)
|
||||
self.assertIsNone(re.search(r"SHELL\] *=|kit_shell\"\] *=|\.data\.vertices|foreach_set|from_pydata", text), path.name)
|
||||
|
||||
def test_no_other_package_names_this_one(self):
|
||||
for package in ("brokkr_kitbash", "brokkr_rig", "brokkr_bridge", "brokkr_mesh_polish"):
|
||||
for path in (SURFACE / package).rglob("*.py"):
|
||||
|
|
|
|||
Loading…
Reference in a new issue