Seraph round 9: the hero and rear cameras solved from the marked joints; the chest's centre plate lifted from the operator's two lines through the solved camera; flow lines scored on built edges
camsolve.py solves place, turn and focal length of a concept view from marked joints against a build's (pseudo-Huber, leave-one-out model choice, the torso's turn as one more unknown). mechlib stands that camera in the scene (solved_view) and reads the creases and contours it sees on the evaluated build (built_edges). fitshell.py lifts a mirrored pair of traced lines to one 3D crease and places the shell's rings on it; compare.py scores her strokes against built edges and re-scores rounds 7 and 8 the same way. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
parent
6dbba84296
commit
3f45b67f6b
10 changed files with 1374 additions and 199 deletions
271
surfaces/blender/experiments/mechs/camsolve.py
Normal file
271
surfaces/blender/experiments/mechs/camsolve.py
Normal file
|
|
@ -0,0 +1,271 @@
|
|||
"""The camera of a concept view, solved from marked points. Plain Python and numpy; no Blender, no Pillow.
|
||||
|
||||
A concept sheet draws a view through some camera nobody wrote down. Given points whose place in the world is known
|
||||
(a build's joints, mechlib.joint_points) and where the sheet draws each (concepts.json "skeleton": the marked
|
||||
joints), solve() finds the pinhole camera that draws them there: where it stands, how it is turned, and its focal
|
||||
length, all at once (PnP with the focal length unknown), by Levenberg-Marquardt from a grid of starts round the
|
||||
figure. With six or more points that are not all in one plane the answer is determined; in a view that is square-on
|
||||
to a flat set of points (a rear view of a standing figure) distance and focal length trade against each other, and
|
||||
solve() says so: "lens_range" is the span of lenses whose error is within a tenth of the best.
|
||||
|
||||
world x to the mech's right, y forward, z up, metres
|
||||
pixels the sheet's, at the "unit" width the points were marked in; v down
|
||||
camera looks down its own -z, y up (Blender's); "R" turns world to camera; "f" is in pixels; "c" is the
|
||||
principal point, at the middle of the view's box unless the model solves it (MODELS).
|
||||
misses are weighed by a pseudo-Huber loss (SOFT pixels): a build poses some joints elsewhere than the concept
|
||||
does, and those should not turn the camera.
|
||||
|
||||
solve(world, pixels, box, model="auto") the camera, as a dict that goes to JSON
|
||||
project(cam, points) pixels of world points
|
||||
ray(cam, pixel) (origin, unit direction) of a pixel's line of sight, in the world
|
||||
lift(cam, pixel, plane_point, plane_normal) where that line of sight meets a plane: a traced 2D point made 3D
|
||||
blender(cam, width) (matrix_world rows, lens, shift_x, shift_y, resolution) for a 36 mm
|
||||
sensor fitted to the frame's width, the frame being the view's box
|
||||
python camsolve.py <mech> <MECH_OUT>/<mech>/<mech>_skeleton.json solves the hero and rear views, prints them
|
||||
|
||||
Used by seraph.py (the hero and rear renders stand at the solved cameras, so a pixel of the concept is the same
|
||||
pixel of ours), fitshell.py (traced lines lifted and built creases projected) and compare.py (the scores)."""
|
||||
import json
|
||||
import math
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
TORSO = tuple(k + s for k in ("shoulder", "elbow", "wrist") for s in ("_l", "_r")) # a biped's joints that turn with its torso on the waist ring
|
||||
|
||||
|
||||
def _rotation(yaw, pitch, roll):
|
||||
"""World to camera for a camera whose line of sight is turned `yaw` about the world's z from looking along +y,
|
||||
pitched up by `pitch`, and rolled about its line of sight."""
|
||||
cy, sy, cp, sp, cr, sr = math.cos(yaw), math.sin(yaw), math.cos(pitch), math.sin(pitch), math.cos(roll), math.sin(roll)
|
||||
look = np.array([-sy * cp, cy * cp, sp])
|
||||
right = np.array([cy, sy, 0.0])
|
||||
up = np.cross(right, look)
|
||||
r, u = cr * right + sr * up, -sr * right + cr * up
|
||||
return np.stack([r, u, -look])
|
||||
|
||||
|
||||
def project(cam, points):
|
||||
"""Pixels (n, 2) of world points (n, 3). A point behind the camera comes back far off the frame."""
|
||||
q = (np.asarray(points, float) - np.asarray(cam["C"], float)) @ np.asarray(cam["R"], float).T
|
||||
z = np.where(q[:, 2] < -1e-6, -q[:, 2], 1e-6)
|
||||
return np.stack([cam["c"][0] + cam["f"] * q[:, 0] / z, cam["c"][1] - cam["f"] * q[:, 1] / z], 1)
|
||||
|
||||
|
||||
def ray(cam, pixel):
|
||||
d = np.array([(pixel[0] - cam["c"][0]) / cam["f"], -(pixel[1] - cam["c"][1]) / cam["f"], -1.0]) @ np.asarray(cam["R"], float)
|
||||
return np.asarray(cam["C"], float), d / np.linalg.norm(d)
|
||||
|
||||
|
||||
def lift(cam, pixel, plane_point, plane_normal):
|
||||
o, d = ray(cam, pixel)
|
||||
n = np.asarray(plane_normal, float)
|
||||
return o + d * (((np.asarray(plane_point, float) - o) @ n) / (d @ n))
|
||||
|
||||
|
||||
def lm(residual, p, rounds=80):
|
||||
"""Levenberg-Marquardt on a residual function, its Jacobian by differences. Returns (p, residual)."""
|
||||
p = np.array(p, float)
|
||||
r = residual(p)
|
||||
lam = 1e-3
|
||||
for _ in range(rounds):
|
||||
J = np.empty((len(r), len(p)))
|
||||
for k in range(len(p)):
|
||||
h = 1e-6 * max(1.0, abs(p[k]))
|
||||
q = p.copy()
|
||||
q[k] += h
|
||||
J[:, k] = (residual(q) - r) / h
|
||||
A, g = J.T @ J, J.T @ r
|
||||
for _ in range(12):
|
||||
try:
|
||||
step = np.linalg.solve(A + lam * np.diag(np.diag(A) + 1e-12), -g)
|
||||
except np.linalg.LinAlgError:
|
||||
lam *= 10
|
||||
continue
|
||||
r2 = residual(p + step)
|
||||
if r2 @ r2 < r @ r:
|
||||
gain = (r @ r - r2 @ r2) / max(r @ r, 1e-30)
|
||||
p, r, lam = p + step, r2, lam / 3
|
||||
break
|
||||
lam *= 4
|
||||
else:
|
||||
break
|
||||
if gain < 1e-12:
|
||||
break
|
||||
return p, r
|
||||
|
||||
|
||||
SOFT = 10.0 # pixels at the marked unit: about the error of a joint marked by hand; a joint the build poses elsewhere than the concept misses by several times that
|
||||
MODELS = {"upright": (), "rolled": ("roll",), "free": ("roll", "centre"), "square": ("square",)} # what a model solves beyond place, yaw, pitch and focal length; "square" holds the yaw instead, looking along the world's y
|
||||
|
||||
|
||||
def _fit(W, P, c0, model, f_fixed=None, near=None, turned=None, pivot=(0.0, 0.0)):
|
||||
"""The best camera of a model over a grid of starts, or from the one start `near` (the parameter vector of a
|
||||
solve of nearly the same points): (rms pixels, parameter vector, camera, the points as solved). `turned` marks
|
||||
the points that turn together about the vertical through `pivot` (x, y) by one more unknown angle."""
|
||||
extra = MODELS[model]
|
||||
turned = np.zeros(len(W), bool) if turned is None else np.asarray(turned, bool)
|
||||
twist = bool(turned.any())
|
||||
centre, size = W.mean(0), np.ptp(W, axis=0).max()
|
||||
px = np.ptp(P, axis=0).max()
|
||||
|
||||
def split(p):
|
||||
p = list(p)
|
||||
C, yaw, pitch = p[:3], p[3], p[4]
|
||||
del p[:5]
|
||||
if "square" in extra:
|
||||
yaw = math.pi * round(yaw0 / math.pi)
|
||||
roll = p.pop(0) if "roll" in extra else 0.0
|
||||
f = f_fixed if f_fixed is not None else math.exp(p.pop(0))
|
||||
c = [p.pop(0), p.pop(0)] if "centre" in extra else c0
|
||||
return {"C": np.array(C), "R": _rotation(yaw, pitch, roll), "f": f, "c": np.array(c, float)}, (p.pop(0) if twist else 0.0)
|
||||
|
||||
yaw0 = math.pi if near is None else near[3]
|
||||
|
||||
def moved(angle):
|
||||
X = W.copy()
|
||||
if twist:
|
||||
c, s = math.cos(angle), math.sin(angle)
|
||||
d = W[turned, :2] - np.array(pivot)
|
||||
X[turned, 0], X[turned, 1] = pivot[0] + c * d[:, 0] - s * d[:, 1], pivot[1] + s * d[:, 0] + c * d[:, 1]
|
||||
return X
|
||||
|
||||
def residual(p):
|
||||
cam, angle = split(p)
|
||||
r = project(cam, moved(angle)) - P
|
||||
n = np.maximum(np.hypot(r[:, 0], r[:, 1]), 1e-9) # pseudo-Huber: a miss far past SOFT pixels pulls as its distance, not its square
|
||||
return (r * (np.sqrt(2 * SOFT * SOFT * (np.sqrt(1 + (n / SOFT) ** 2) - 1)) / n)[:, None]).ravel()
|
||||
starts = []
|
||||
if near is not None:
|
||||
starts.append(near)
|
||||
else:
|
||||
for az in ((0, 180) if "square" in extra else range(-180, 180, 45)):
|
||||
for dist in (1.5, 6.0):
|
||||
a = math.radians(az)
|
||||
d = dist * size
|
||||
starts.append([centre[0] - d * math.sin(a), centre[1] + d * math.cos(a), centre[2], a + math.pi, 0.0] + [0.0] * ("roll" in extra) + ([] if f_fixed is not None else [math.log(px * d / size)])
|
||||
+ (list(c0) if "centre" in extra else []) + [0.0] * twist)
|
||||
best = None
|
||||
for start in starts:
|
||||
yaw0 = start[3]
|
||||
p, r = lm(residual, start)
|
||||
p[3] = yaw0 if "square" in extra else p[3]
|
||||
if best is None or r @ r < best[0] - 1e-9:
|
||||
best = (float(r @ r), p)
|
||||
cam, angle = split(best[1])
|
||||
miss = project(cam, moved(angle)) - P
|
||||
return math.sqrt((miss * miss).sum() / len(W)), best[1], cam, moved(angle), angle
|
||||
|
||||
|
||||
def _left_out(W, P, c0, model, near, turned, pivot):
|
||||
"""Leave-one-out: each point predicted by the camera solved without it; the rms of those misses, pixels."""
|
||||
miss = []
|
||||
for k in range(len(W)):
|
||||
keep = np.arange(len(W)) != k
|
||||
start = near if turned[keep].any() or not turned.any() else near[:-1]
|
||||
_, _, cam, _, angle = _fit(W[keep], P[keep], c0, model, near=start, turned=turned[keep], pivot=pivot)
|
||||
one = _turn(W[k], angle, pivot) if turned[k] else W[k]
|
||||
miss.append(np.linalg.norm(project(cam, one[None])[0] - P[k]))
|
||||
return float(np.sqrt(np.mean(np.square(miss))))
|
||||
|
||||
|
||||
def _turn(point, angle, pivot):
|
||||
c, s = math.cos(angle), math.sin(angle)
|
||||
x, y = point[0] - pivot[0], point[1] - pivot[1]
|
||||
return np.array([pivot[0] + c * x - s * y, pivot[1] + s * x + c * y, point[2]])
|
||||
|
||||
|
||||
def solve(world, pixels, box, model="auto", unit=None, height_px=None, turned=(), pivot=(0.0, 0.0)):
|
||||
"""world {name: [x, y, z]}, pixels {name: [u, v]}: the camera that draws the names both hold. `box` is the
|
||||
view's box on the sheet [u0, v0, u1, v1]. `model` is one of MODELS: "upright" holds the camera level and its
|
||||
centre at the middle of the box, "rolled" lets it roll, "free" solves the centre too (a view cropped off-axis);
|
||||
"auto" takes whichever of those predicts left-out points best, since a freer model always fits the marked ones
|
||||
closer. "square" is for a view the sheet draws square-on from far off (a rear elevation): there the points lie
|
||||
nearly in one plane across the line of sight, a turn of the camera and a narrower figure draw the same picture,
|
||||
and the solve would spend the turn on the build's error in width; so the camera looks straight along y.
|
||||
`turned` names points that turn as one about the vertical through `pivot` (a torso on its waist ring): the
|
||||
angle is solved with the camera, and "twist" is how far they turn from where they were given.
|
||||
Returns {"C", "R", "f", "c", "box", "unit", "names", "rms" (pixels, per point), "rms_h" (of `height_px`, the
|
||||
figure's height in the view), "worst" (name, pixels), "left_out" (the leave-one-out rms), "model", "tried",
|
||||
"lens" (mm, on a 36 mm sensor across the box's width), "lens_range" (the lenses whose error is within a tenth of
|
||||
the best), "azimuth", "elevation" (degrees: where the camera stands round the points' middle, as mechlib.shot
|
||||
counts them), "distance", "roll", "twist" (degrees), "residuals" {name: [du, dv]}}."""
|
||||
names = [k for k in pixels if k in world]
|
||||
if len(names) < 6:
|
||||
raise ValueError(f"camsolve: {len(names)} points; six are needed")
|
||||
W, P = np.array([world[k] for k in names], float), np.array([pixels[k] for k in names], float)
|
||||
T = np.array([k in turned for k in names])
|
||||
c0 = [(box[0] + box[2]) / 2, (box[1] + box[3]) / 2]
|
||||
tried = {}
|
||||
for m in (("upright", "rolled", "free") if model == "auto" else (model,)):
|
||||
rms, p, cam, X, angle = _fit(W, P, c0, m, turned=T, pivot=pivot)
|
||||
tried[m] = (rms, p, cam, X, angle, _left_out(W, P, c0, m, p, T, pivot))
|
||||
kind = min(tried, key=lambda k: tried[k][5])
|
||||
rms, p, cam, X, angle, left = tried[kind]
|
||||
width = box[2] - box[0]
|
||||
lens = lambda f: f * 36.0 / width # noqa: E731
|
||||
span, at = [cam["f"]], 5 + ("roll" in MODELS[kind])
|
||||
for way in (-1, 1): # walk the lens out each way from the best, each solve started at the last
|
||||
q = np.delete(p, at)
|
||||
for step in range(1, 21):
|
||||
f = cam["f"] * math.exp(0.1 * way * step)
|
||||
r_f, q = _fit(W, P, c0, kind, f_fixed=f, near=q, turned=T, pivot=pivot)[:2]
|
||||
if r_f > 1.1 * rms + 1e-9:
|
||||
break
|
||||
span.append(f)
|
||||
off = cam["C"] - X.mean(0)
|
||||
res = project(cam, X) - P
|
||||
worst = int(np.argmax(np.linalg.norm(res, axis=1)))
|
||||
return {"C": [float(v) for v in cam["C"]], "R": [[float(v) for v in row] for row in cam["R"]], "f": float(cam["f"]), "c": [float(v) for v in cam["c"]],
|
||||
"box": list(box), "unit": unit, "names": names, "rms": float(rms), "rms_h": float(rms / height_px) if height_px else None,
|
||||
"median": float(np.median(np.linalg.norm(res, axis=1))), "worst": [names[worst], float(np.linalg.norm(res[worst]))], "left_out": left, "model": kind,
|
||||
"tried": {k: {"rms": float(v[0]), "left_out": v[5], "lens": float(lens(v[2]["f"]))} for k, v in tried.items()},
|
||||
"lens": float(lens(cam["f"])), "lens_range": [float(lens(min(span))), float(lens(max(span)))],
|
||||
"azimuth": float(math.degrees(math.atan2(-off[0], off[1]))), "elevation": float(math.degrees(math.atan2(off[2], math.hypot(off[0], off[1])))),
|
||||
"distance": float(np.linalg.norm(off)), "roll": float(math.degrees(p[5])) if "roll" in MODELS[kind] else 0.0, "twist": float(math.degrees(angle)),
|
||||
"residuals": {k: [float(v) for v in r] for k, r in zip(names, res)}, "solved": {k: [float(v) for v in x] for k, x in zip(names, X)}}
|
||||
|
||||
|
||||
def blender(cam, width):
|
||||
"""What a Blender camera takes to be this one, the frame being the view's box at `width` pixels across:
|
||||
(matrix_world as rows, lens mm, shift_x, shift_y, (width, height)); the sensor is 36 mm, fitted HORIZONTAL."""
|
||||
R, C = np.asarray(cam["R"], float), np.asarray(cam["C"], float)
|
||||
M = np.eye(4)
|
||||
M[:3, :3], M[:3, 3] = R.T, C
|
||||
u0, v0, u1, v1 = cam["box"]
|
||||
w, h = u1 - u0, v1 - v0
|
||||
return ([[float(v) for v in row] for row in M], cam["f"] * 36.0 / w, ((u0 + u1) / 2 - cam["c"][0]) / w, (cam["c"][1] - (v0 + v1) / 2) / w, (int(width), int(round(width * h / w))))
|
||||
|
||||
|
||||
def in_frame(cam, pixels, width):
|
||||
"""Sheet pixels as pixels of the frame blender() renders at `width`."""
|
||||
k = width / (cam["box"][2] - cam["box"][0])
|
||||
return (np.asarray(pixels, float) - np.array(cam["box"][:2], float)) * k
|
||||
|
||||
|
||||
def views(mech, built, turned=TORSO):
|
||||
"""The hero and rear cameras of concepts.json[mech] against a build's joints (`built`: <mech>_skeleton.json's
|
||||
"world"). {"hero": camera, "rear": camera}."""
|
||||
sk = json.loads((HERE / "concepts.json").read_text(encoding="utf-8"))[mech]["skeleton"]
|
||||
out = {}
|
||||
for tag, view in sk["views"].items():
|
||||
square = tag in ("rear", "front")
|
||||
out[tag] = solve(built, view["joints"], view["box"], model="square" if square else "auto", unit=sk["unit"], height_px=view["ground"] - view["top"], turned=() if square else turned, pivot=built["waist"][:2])
|
||||
return out
|
||||
|
||||
|
||||
def report(tag, cam):
|
||||
lines = [f"CAMERA {tag}: {len(cam['names'])} points; rms {cam['rms']:.1f} px ({100 * cam['rms_h']:.2f}% of the figure's height), median {cam['median']:.1f} px, worst {cam['worst'][0]} {cam['worst'][1]:.1f} px; left-out rms {cam['left_out']:.1f} px",
|
||||
f" lens {cam['lens']:.0f} mm (within a tenth of the best error: {cam['lens_range'][0]:.0f} to {cam['lens_range'][1]:.0f} mm); azimuth {cam['azimuth']:.1f}, elevation {cam['elevation']:.1f}, {cam['distance']:.1f} m off; eye {cam['C'][2]:.2f} m up; model {cam['model']}: roll {cam['roll']:.1f}, centre ({cam['c'][0]:.0f}, {cam['c'][1]:.0f}); the torso turned {cam['twist']:+.1f} degrees from the build's",
|
||||
" " + "; ".join(f"{k}: rms {v['rms']:.1f}, left-out {v['left_out']:.1f}, lens {v['lens']:.0f}" for k, v in cam["tried"].items())]
|
||||
return lines
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
cams = views(sys.argv[1], json.loads(Path(sys.argv[2]).read_text(encoding="utf-8"))["world"])
|
||||
for tag, cam in cams.items():
|
||||
print("\n".join(report(tag, cam)))
|
||||
for k, (du, dv) in cam["residuals"].items():
|
||||
print(f" {k:11s} {du:+6.1f} {dv:+6.1f}")
|
||||
|
|
@ -18,6 +18,11 @@ with `quick`). Writes, under MECH_OUT/compare/:
|
|||
part built alone at the matched camera | the two masks over each other (concept red, ours
|
||||
blue), with the match score; the scores go to <name>_scores.json, and a
|
||||
<name>_scores_before.json beside it is printed next to them
|
||||
<name>_camera.png the solved hero and rear cameras (camsolve): marked joints against the build's reprojected
|
||||
<name>_chest_head.png the concept's chest crop | the chest alone at the solved hero camera in the same frame, the
|
||||
operator's two lines and the shell's built creases on both
|
||||
<name>_flowlines.png the operator's markup | our hero render with her strokes and our built edges | the scores
|
||||
(fitshell.along), this round beside any earlier rounds named in MECH_PRIOR
|
||||
<name>_hip.png the concept's hero-view hips beside the same region of our hero render
|
||||
|
||||
The match score of a part is the overlap (intersection over union) of two masks: the part's outline traced by hand on
|
||||
|
|
@ -31,6 +36,7 @@ MECH_MATCH_ONLY: only the match sheet and scores, from what part_bench.py has re
|
|||
import json, os, sys
|
||||
import numpy as np
|
||||
import skeleton
|
||||
import fitshell
|
||||
from pathlib import Path
|
||||
from PIL import Image, ImageDraw, ImageFilter, ImageFont
|
||||
|
||||
|
|
@ -260,37 +266,6 @@ def resampled(points, n=60):
|
|||
return np.stack([np.interp(t, d, p[:, 0]), np.interp(t, d, p[:, 1])], 1)
|
||||
|
||||
|
||||
def edge_along(img, points, half):
|
||||
"""How far the picture's edges run along a line: of the gradient energy within `half` pixels either side of the
|
||||
line, the share that lies across it (an edge along the line has its gradient across it). 0.5 is texture with no
|
||||
direction; a plate edge or crease that follows the line the whole way is near 1; steps and edges that cross it
|
||||
pull it under 0.5. Returns (share over the whole line, share per tenth of its length)."""
|
||||
g = np.asarray(img.convert("L").filter(ImageFilter.GaussianBlur(max(1.0, half / 5))), float)
|
||||
gy, gx = np.gradient(g)
|
||||
p = resampled(points, max(20, int(np.hypot(*np.diff(np.asarray(points, float), axis=0).T).sum())))
|
||||
tan = np.gradient(p, axis=0)
|
||||
tan /= np.maximum(np.hypot(tan[:, 0], tan[:, 1])[:, None], 1e-9)
|
||||
nor = np.stack([-tan[:, 1], tan[:, 0]], 1)
|
||||
across, total = np.zeros(len(p)), np.zeros(len(p))
|
||||
for off in range(-half, half + 1):
|
||||
q = np.rint(p + nor * off).astype(int)
|
||||
ok = (q[:, 0] >= 0) & (q[:, 0] < g.shape[1]) & (q[:, 1] >= 0) & (q[:, 1] < g.shape[0])
|
||||
x, y = q[ok, 0], q[ok, 1]
|
||||
across[ok] += (gx[y, x] * nor[ok, 0] + gy[y, x] * nor[ok, 1]) ** 2
|
||||
total[ok] += gx[y, x] ** 2 + gy[y, x] ** 2
|
||||
tenths = [float(a.sum() / max(t.sum(), 1e-9)) for a, t in zip(np.array_split(across, 10), np.array_split(total, 10))]
|
||||
return float(across.sum() / max(total.sum(), 1e-9)), tenths
|
||||
|
||||
|
||||
def sweep(a, b):
|
||||
"""How alike two lines run, each in its own picture: the mean cosine of the angle between their directions at
|
||||
the same fraction of their lengths (1: the same sweep; a straight line against one that zigzags scores low)."""
|
||||
ta, tb = np.gradient(resampled(a), axis=0), np.gradient(resampled(b), axis=0)
|
||||
ta /= np.hypot(ta[:, 0], ta[:, 1])[:, None]
|
||||
tb /= np.hypot(tb[:, 0], tb[:, 1])[:, None]
|
||||
return float(np.abs((ta * tb).sum(1)).mean())
|
||||
|
||||
|
||||
def drawn(img, lines, width=5):
|
||||
img = img.convert("RGB")
|
||||
d = ImageDraw.Draw(img)
|
||||
|
|
@ -299,104 +274,131 @@ def drawn(img, lines, width=5):
|
|||
return img
|
||||
|
||||
|
||||
def edges_on(img, segments, box, color=(0, 230, 255), width=2):
|
||||
"""Built edges (sheet pixels, mechlib.built_edges) drawn on a picture whose frame is `box` of the sheet."""
|
||||
img = img.convert("RGB")
|
||||
d, z = ImageDraw.Draw(img), img.width / (box[2] - box[0])
|
||||
for u0, v0, u1, v1 in segments:
|
||||
d.line(((u0 - box[0]) * z, (v0 - box[1]) * z, (u1 - box[0]) * z, (v1 - box[1]) * z), fill=color, width=width)
|
||||
return img
|
||||
|
||||
|
||||
def chest_head_sheet():
|
||||
"""<name>_chest_head.png: the concept's chest and head beside the chest built alone at the matched camera, the
|
||||
operator's two chest lines drawn on the concept and the shell's own crease runs (part_bench's chest_lines.json)
|
||||
on ours; under them the same pair bare. Returns the two lines' scores."""
|
||||
path = src / "parts" / "chest_lines.json"
|
||||
"""<name>_chest_head.png: the concept's chest and head beside the chest built alone where it stands in the build,
|
||||
seen by the solved hero camera in the same frame (part_bench SOLVED): a pixel of one is the same pixel of the
|
||||
other. On both: the operator's two chest lines (red) and the built edges of the chest's shell the camera sees
|
||||
(cyan; part_bench's chest_edges.json, mechlib.built_edges). Under them the same pair bare. Returns the two lines'
|
||||
scores from the built edges (fitshell.along)."""
|
||||
path = src / "parts" / "chest_edges.json"
|
||||
if "flow" not in spec or not path.exists():
|
||||
return {}
|
||||
kf = sheet.width / spec["flow"]["unit"]
|
||||
box = [v * sheet.width / spec["components"]["unit"] for v in spec["components"]["crops"]["chest"]]
|
||||
zoom = 4
|
||||
concept = sheet.crop(tuple(int(v) for v in box)).resize((int(box[2] - box[0]) * zoom, int(box[3] - box[1]) * zoom), Image.LANCZOS)
|
||||
ours = Image.open(src / "parts" / "chest.png").convert("RGB")
|
||||
kf = spec["skeleton"]["unit"] / spec["flow"]["unit"]
|
||||
ku = sheet.width / spec["skeleton"]["unit"]
|
||||
box = [v * spec["skeleton"]["unit"] / spec["components"]["unit"] for v in spec["components"]["crops"]["chest"]]
|
||||
concept = sheet.crop(tuple(int(v * ku) for v in box)).resize((1060, round(1060 * (box[3] - box[1]) / (box[2] - box[0]))), Image.LANCZOS)
|
||||
ours = Image.open(src / "parts" / "chest.png").convert("RGB").resize(concept.size, Image.LANCZOS)
|
||||
built = json.loads(path.read_text(encoding="utf-8"))
|
||||
out, c_lines, o_lines = {}, [], []
|
||||
shell = [e["seg"] for e in built if e["object"].endswith(".breast")]
|
||||
creases = [e["seg"] for e in built if e["object"].endswith(".breast") and e["kind"] == "crease"]
|
||||
fig = spec["skeleton"]["views"]["hero"]["ground"] - spec["skeleton"]["views"]["hero"]["top"]
|
||||
z = concept.width / (box[2] - box[0])
|
||||
out, lines = {}, []
|
||||
for tag in ("chest_r", "chest_l"):
|
||||
c = [((x * kf - box[0]) * zoom, (y * kf - box[1]) * zoom) for x, y in spec["flow"]["lines"][tag]["points"]]
|
||||
o = built[tag]
|
||||
ec, _ = edge_along(concept, c, max(3, concept.height // 90))
|
||||
eo, tenths = edge_along(ours, o, max(3, ours.height // 90))
|
||||
out[tag] = {"sweep": round(sweep(c, o), 3), "edge_ours": round(eo, 3), "edge_concept": round(ec, 3), "edge_ours_least_tenth": round(min(tenths), 3)}
|
||||
print(f"FLOW {name} {tag} (chest alone): sweep {out[tag]['sweep']:.2f}; edges along the line, ours {eo:.2f} (least tenth {min(tenths):.2f}), concept {ec:.2f}")
|
||||
c_lines.append(c)
|
||||
o_lines.append(o)
|
||||
text = "; ".join(f"{t}: sweep {v['sweep']:.2f}, edge {v['edge_ours']:.2f} (concept {v['edge_concept']:.2f})" for t, v in out.items())
|
||||
top = row([label(fit(drawn(concept, c_lines, 7), 900), "concept: chest and head, the operator's two lines"), label(fit(drawn(ours, o_lines), 900), "ours, the chest shell alone: its crease runs. " + text)], 900)
|
||||
bottom = row([label(fit(concept, 900), "concept"), label(fit(ours, 900), "ours")], 900)
|
||||
line = [(x * kf, y * kf) for x, y in spec["flow"]["lines"][tag]["points"]]
|
||||
out[tag] = fitshell.along(line, shell, fig)
|
||||
print(f"FLOW {name} {tag} (chest alone, built edges at the solved camera): on {out[tag]['on']:.2f}, longest run {out[tag]['run']:.2f}, off {out[tag]['off']:.2f}% H")
|
||||
lines.append([((x - box[0]) * z, (y - box[1]) * z) for x, y in line])
|
||||
text = "; ".join(f"{t}: on {v['on']:.2f}, run {v['run']:.2f}, off {v['off']:.2f}% H" for t, v in out.items())
|
||||
top = row([label(drawn(edges_on(concept, creases, box), lines, 4), "concept: the operator's two lines (red); our shell's built creases (cyan), same camera"),
|
||||
label(drawn(edges_on(ours, creases, box), lines, 4), "ours at the solved hero camera. " + text)], concept.height + 30)
|
||||
bottom = row([label(concept, "concept"), label(ours, "ours, the chest alone where it stands in the build")], concept.height + 30)
|
||||
stack([top, bottom]).save(dst / f"{name}_chest_head.png")
|
||||
return out
|
||||
|
||||
|
||||
def carried(points, along, cj, oj):
|
||||
"""A line of the concept's hero view carried onto ours by the skeleton: each point is held by the bone of `along`
|
||||
(joint names) it lies nearest, as a fraction along the bone and an offset across it in bone lengths, and set
|
||||
down the same way by our bone. A line held by three joints that are not a chain (the chest's: both shoulders
|
||||
and the waist) is carried by the affine map of that triangle instead. cj, oj: {joint: (x, y)} in each picture."""
|
||||
P = np.asarray(points, float)
|
||||
if "waist" in along:
|
||||
A = np.array([[*cj[k], 1.0] for k in along])
|
||||
M = np.linalg.solve(A, np.array([oj[k] for k in along], float))
|
||||
return [tuple(q) for q in np.c_[P, np.ones(len(P))] @ M]
|
||||
out = []
|
||||
for p in P:
|
||||
best = None
|
||||
for i, (ka, kb) in enumerate(zip(along, along[1:])):
|
||||
a, b = np.array(cj[ka], float), np.array(cj[kb], float)
|
||||
t = float((p - a) @ (b - a) / ((b - a) @ (b - a)))
|
||||
tc = t if (i == 0 and t < 0) or (i == len(along) - 2 and t > 1) else min(max(t, 0.0), 1.0)
|
||||
d = float(np.hypot(*(p - (a + tc * (b - a)))))
|
||||
if best is None or d < best[0]:
|
||||
n = np.array([-(b - a)[1], (b - a)[0]]) / np.hypot(*(b - a))
|
||||
best = (d, ka, kb, tc, float((p - a - tc * (b - a)) @ n) / np.hypot(*(b - a)))
|
||||
_, ka, kb, t, off = best
|
||||
a, b = np.array(oj[ka], float), np.array(oj[kb], float)
|
||||
n = np.array([-(b - a)[1], (b - a)[0]]) / np.hypot(*(b - a))
|
||||
out.append(tuple(a + t * (b - a) + off * np.hypot(*(b - a)) * n))
|
||||
return out
|
||||
|
||||
|
||||
def flow_sheet(hero):
|
||||
"""<name>_flowlines.png: the operator's markup (her strokes on the concept and on round 7's build) beside this
|
||||
build's hero view with her concept strokes carried onto it by the skeleton. Per line, into <name>_scores.json
|
||||
"flow": sweep (do the two lines run alike, each in its own picture) and edge (do the picture's edges run along
|
||||
the line; ours is the best of small shifts of the carried line across itself, the concept's is beside it)."""
|
||||
sk_file = src / f"{name}_skeleton.json"
|
||||
if "flow" not in spec or not sk_file.exists():
|
||||
"""<name>_flowlines.png: the operator's markup beside this build's hero render, which stands at the solved hero
|
||||
camera, so her concept strokes are drawn on it where she drew them (red), over the build's own edges as that
|
||||
camera sees them (cyan: creases and contours, <name>_edges_hero.json, mechlib.built_edges). Per line, into
|
||||
<name>_scores.json "flow": fitshell.along of her stroke against those built edges: on (the share of the stroke
|
||||
with a built edge within 1% of the figure's height running its way), run (the longest unbroken share), off (mean
|
||||
distance, % of the height). MECH_PRIOR names earlier rounds' edges, "r7=<dir>,r8=<dir>" (edges.py): they are
|
||||
scored the same way and set beside this round's."""
|
||||
path = src / f"{name}_edges_hero.json"
|
||||
if "flow" not in spec or not path.exists():
|
||||
return {}
|
||||
flow = spec["flow"]
|
||||
kf, ks = sheet.width / flow["unit"], sheet.width / spec["skeleton"]["unit"]
|
||||
cj = {k: (x * ks, y * ks) for k, (x, y) in spec["skeleton"]["views"]["hero"]["joints"].items()}
|
||||
ov = json.loads(sk_file.read_text(encoding="utf-8"))["views"]["hero"]
|
||||
up = hero.width / ov["size"][0]
|
||||
oj = {k: (x * up, y * up) for k, (x, y) in ov["joints"].items()}
|
||||
sil = Image.open(src / f"{name}_sil_hero.png").split()[-1]
|
||||
fig_o = (sil.getbbox()[3] - sil.getbbox()[1]) * up
|
||||
fig_c = (spec["skeleton"]["views"]["hero"]["ground"] - spec["skeleton"]["views"]["hero"]["top"]) * ks
|
||||
out, lines = {}, []
|
||||
for tag, line in flow["lines"].items():
|
||||
c = [(x * kf, y * kf) for x, y in line["points"]]
|
||||
o = carried(c, line["along"], cj, oj)
|
||||
ec, _ = edge_along(sheet, c, max(3, round(0.012 * fig_c)))
|
||||
half = max(3, round(0.012 * fig_o))
|
||||
tan = np.asarray(o[-1], float) - np.asarray(o[0], float)
|
||||
nor = np.array([-tan[1], tan[0]]) / np.hypot(*tan)
|
||||
eo, shift, tenths = max((edge_along(hero, [tuple(np.asarray(q) + nor * d) for q in o], half) + (d,) for d in np.linspace(-0.025, 0.025, 11) * fig_o), key=lambda r: r[0])[::2] + (None,)
|
||||
eo, tenths = edge_along(hero, [tuple(np.asarray(q) + nor * shift) for q in o], half)
|
||||
out[tag] = {"sweep": round(sweep(c, o), 3), "edge_ours": round(eo, 3), "edge_concept": round(ec, 3), "edge_ours_least_tenth": round(min(tenths), 3)}
|
||||
print(f"FLOW {name} {tag}: sweep {out[tag]['sweep']:.2f}; edges along the line, ours {eo:.2f} (least tenth {min(tenths):.2f}), concept {ec:.2f}")
|
||||
lines.append(o)
|
||||
mean = {k: round(float(np.mean([v[k] for v in out.values()])), 3) for k in ("sweep", "edge_ours", "edge_concept")}
|
||||
print(f"FLOW {name} mean: sweep {mean['sweep']:.2f}, edge ours {mean['edge_ours']:.2f}, concept {mean['edge_concept']:.2f}")
|
||||
out["mean"] = mean
|
||||
flow, view = spec["flow"], spec["skeleton"]["views"]["hero"]
|
||||
kf = spec["skeleton"]["unit"] / flow["unit"]
|
||||
fig, box = view["ground"] - view["top"], view["box"]
|
||||
lines = {tag: [(x * kf, y * kf) for x, y in line["points"]] for tag, line in flow["lines"].items()}
|
||||
rounds = {tag: Path(p) / f"{name}_edges_hero.json" for tag, p in (item.split("=", 1) for item in os.environ.get("MECH_PRIOR", "").split(",") if item)}
|
||||
rounds["this"] = path
|
||||
table = {}
|
||||
for tag, p in rounds.items():
|
||||
segs = [e["seg"] for e in json.loads(p.read_text(encoding="utf-8"))]
|
||||
table[tag] = {line: fitshell.along(pts, segs, fig) for line, pts in lines.items()}
|
||||
table[tag]["mean"] = {k: round(float(np.mean([v[k] for v in table[tag].values()])), 3) for k in ("on", "run", "off")}
|
||||
for line in list(lines) + ["mean"]:
|
||||
print(f"FLOW {name} {line:11s} " + " ".join(f"{tag}: on {t[line]['on']:.2f} run {t[line]['run']:.2f} off {t[line]['off']:.2f}" for tag, t in table.items()))
|
||||
segs = [e["seg"] for e in json.loads(path.read_text(encoding="utf-8"))]
|
||||
z = hero.width / (box[2] - box[0])
|
||||
ours = drawn(edges_on(hero, segs, box, width=max(1, hero.width // 800)), [[((x - box[0]) * z, (y - box[1]) * z) for x, y in pts] for pts in lines.values()], max(4, hero.width // 260))
|
||||
try:
|
||||
mono = ImageFont.truetype("consola.ttf", 22)
|
||||
except OSError:
|
||||
mono = font
|
||||
text = Image.new("RGB", (760, H), (24, 24, 24))
|
||||
body = ["her strokes against built edges, at the", "solved hero camera: on / run / off (% H)", "", f"{'':12s}" + "".join(f"{tag:>16s}" for tag in table)]
|
||||
body += [f"{line:12s}" + "".join(f" {t[line]['on']:.2f} {t[line]['run']:.2f} {t[line]['off']:4.2f}" for t in table.values()) for line in list(lines) + ["mean"]]
|
||||
ImageDraw.Draw(text).text((14, 44), chr(10).join(body), fill=(235, 235, 235), font=mono, spacing=8)
|
||||
markup = Image.open(Path(os.environ["MECH_CONCEPTS"]) / flow["markup"]).convert("RGB")
|
||||
box = sil.getbbox()
|
||||
pad = round(0.04 * fig_o)
|
||||
ours = drawn(hero, lines, max(6, hero.width // 110)).crop((max(0, round(box[0] * up) - pad), max(0, round(box[1] * up) - pad), min(hero.width, round(box[2] * up) + pad), min(hero.height, round(box[3] * up) + pad)))
|
||||
row([label(fit(markup, H), "the operator's markup: the concept's lines, and the same lines as round 7 built them"),
|
||||
label(fit(ours, H), f"this build: her concept lines carried onto it by the skeleton. mean sweep {mean['sweep']:.2f}, edge {mean['edge_ours']:.2f} (concept {mean['edge_concept']:.2f})")], H).save(dst / f"{name}_flowlines.png")
|
||||
return out
|
||||
label(fit(ours, H), "this build at the solved hero camera: her concept strokes where she drew them (red), our built edges (cyan)"), text], H).save(dst / f"{name}_flowlines.png")
|
||||
return table
|
||||
|
||||
|
||||
def camera_sheet():
|
||||
"""<name>_camera.png: per solved view (<name>_cameras.json, camsolve), the concept with its marked joints (yellow
|
||||
rings) and the build's joints as the solved camera draws them (cyan dots), a red line from each to its mark;
|
||||
beside it the solve: lens, place, error."""
|
||||
path = src / f"{name}_cameras.json"
|
||||
if not path.exists():
|
||||
return
|
||||
import camsolve
|
||||
cams = json.loads(path.read_text(encoding="utf-8"))
|
||||
ku = sheet.width / spec["skeleton"]["unit"]
|
||||
try:
|
||||
mono = ImageFont.truetype("consola.ttf", 20)
|
||||
except OSError:
|
||||
mono = font
|
||||
panels = []
|
||||
for tag, cam in cams.items():
|
||||
box, zoom = cam["box"], 2
|
||||
img = sheet.crop(tuple(int(v * ku) for v in box))
|
||||
img = img.resize((img.width * zoom, img.height * zoom), Image.LANCZOS)
|
||||
d, z = ImageDraw.Draw(img), ku * zoom
|
||||
marks = spec["skeleton"]["views"][tag]["joints"]
|
||||
for joint, (du, dv) in cam["residuals"].items():
|
||||
mx, my = ((marks[joint][0] - box[0]) * z, (marks[joint][1] - box[1]) * z)
|
||||
px, py = mx + du * z, my + dv * z
|
||||
d.line((mx, my, px, py), fill=(255, 40, 30), width=4)
|
||||
d.ellipse((mx - 11, my - 11, mx + 11, my + 11), outline=(255, 230, 0), width=4)
|
||||
d.ellipse((px - 6, py - 6, px + 6, py + 6), fill=(0, 230, 255), outline=(0, 0, 0))
|
||||
d.text((mx + 14, my - 12), joint, fill=(255, 255, 255), font=font)
|
||||
text = Image.new("RGB", (900, H), (24, 24, 24))
|
||||
body = []
|
||||
for line in camsolve.report(tag, cam):
|
||||
words, cur = line.replace("; ", ";|").replace(", ", ",|").split("|"), ""
|
||||
for w in words:
|
||||
if len(cur) + len(w) > 70:
|
||||
body.append(cur)
|
||||
cur = " "
|
||||
cur += w + " "
|
||||
body.append(cur)
|
||||
body += ["", "miss per joint, pixels at the sheet's 1024 (u, v):"] + [f" {joint:11s} {du:+6.1f} {dv:+6.1f}" for joint, (du, dv) in cam["residuals"].items()]
|
||||
ImageDraw.Draw(text).text((14, 44), chr(10).join(body), fill=(235, 235, 235), font=mono, spacing=7)
|
||||
panels += [label(fit(img, H), f"concept, {tag}: marked joints (yellow), the build's joints through the solved camera (cyan)"), text]
|
||||
row(panels, H).save(dst / f"{name}_camera.png")
|
||||
|
||||
|
||||
def figure(img, mask, n=480):
|
||||
|
|
@ -475,6 +477,7 @@ def interior_sheet(hero, rear):
|
|||
H = 1100
|
||||
if os.environ.get("MECH_CHEST_ONLY"):
|
||||
chest_head_sheet()
|
||||
camera_sheet()
|
||||
sys.exit(0)
|
||||
if os.environ.get("MECH_MATCH_ONLY"): # the scores of what part_bench has rendered, without a build of the whole mech
|
||||
match_sheet(None)
|
||||
|
|
@ -502,6 +505,7 @@ if "icon" in spec:
|
|||
row(panels, H).save(dst / f"{name}_silhouette.png")
|
||||
|
||||
match_sheet(hero)
|
||||
camera_sheet()
|
||||
extra = {"chest_lines": chest_head_sheet(), "flow": flow_sheet(hero), "interior": interior_sheet(hero, rear)}
|
||||
scores_path = dst / f"{name}_scores.json"
|
||||
scores_path.write_text(json.dumps({**json.loads(scores_path.read_text(encoding="utf-8")), **extra}, indent=1), encoding="utf-8")
|
||||
|
|
@ -587,7 +591,7 @@ if "skeleton" in spec and sk_path.exists():
|
|||
panels += [label(fit(concept_img, H), f"concept, {view}: marked skeleton"), label(fit(ours_img, H), f"ours, {view}: the build's joints"), text]
|
||||
row(panels, H).save(dst / f"{name}_proportions.png")
|
||||
|
||||
for f in ("vs_concept", "silhouette", "joints", "proportions", "flowlines", "legs", "interior", "chest_head"):
|
||||
for f in ("vs_concept", "silhouette", "joints", "proportions", "flowlines", "legs", "interior", "chest_head", "camera"):
|
||||
p = dst / f"{name}_{f}.png"
|
||||
if p.exists():
|
||||
im = Image.open(p)
|
||||
|
|
|
|||
|
|
@ -3198,6 +3198,61 @@
|
|||
45
|
||||
]
|
||||
]
|
||||
},
|
||||
"fit": {
|
||||
"note": "Recipes for fitshell.py. chest: the centre plate's edge is the flow lines chest_r and chest_l lifted as a mirrored pair at the solved hero camera (chest_l run on straight by `extend` of its length to give chest_r's top its mirror), up to `crown` (the cowl's top in the chest's frame, from the rear view's height); `stations` rings stand along it, then `close` (steps [dx, dy, dz] from the last lifted point) carries it over the crown to the nape, where no line was drawn; `knots` are [t along the rings, corner half-width, the corner's set-back behind the crease, the flank's depth behind the corner], which the silhouette fit moves toward the traced mask `outline` (masks.parts).",
|
||||
"chest": {
|
||||
"extend": 0.2,
|
||||
"crown": 1.75,
|
||||
"stations": 9,
|
||||
"close": [
|
||||
[
|
||||
-0.2,
|
||||
-0.3,
|
||||
0.3
|
||||
],
|
||||
[
|
||||
-0.38,
|
||||
-0.8,
|
||||
0.38
|
||||
]
|
||||
],
|
||||
"knots": [
|
||||
[
|
||||
0.0,
|
||||
1.05,
|
||||
0.5,
|
||||
1.2
|
||||
],
|
||||
[
|
||||
0.3,
|
||||
1.4,
|
||||
0.45,
|
||||
1.1
|
||||
],
|
||||
[
|
||||
0.45,
|
||||
1.05,
|
||||
0.35,
|
||||
0.6
|
||||
],
|
||||
[
|
||||
0.62,
|
||||
0.95,
|
||||
0.3,
|
||||
0.45
|
||||
],
|
||||
[
|
||||
1.0,
|
||||
0.85,
|
||||
0.3,
|
||||
0.45
|
||||
]
|
||||
],
|
||||
"outline": "chest",
|
||||
"fit_outline": false,
|
||||
"proud": 0.13
|
||||
}
|
||||
}
|
||||
},
|
||||
"_doc_skeleton": "skeleton: joints marked by hand on the sheet (pixels of the sheet scaled to skeleton.unit wide), the mech's own left and right; ground is the soles' line, top the figure's highest point in that view. skeleton.py reads it."
|
||||
|
|
|
|||
19
surfaces/blender/experiments/mechs/edges.py
Normal file
19
surfaces/blender/experiments/mechs/edges.py
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
"""The built edges of a saved build at the cameras solved for it: for scoring an earlier round the way this one is.
|
||||
Runs in Blender: blender --background <build>.blend --python edges.py -- <mech> <its _skeleton.json> <out dir>
|
||||
Writes <out dir>/<mech>_cameras.json and <mech>_edges_hero.json (mechlib.built_edges at camsolve.views)."""
|
||||
import json, sys
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import camsolve
|
||||
import mechlib as M
|
||||
|
||||
mech, skeleton, out = sys.argv[sys.argv.index("--") + 1:]
|
||||
out = Path(out)
|
||||
assert out.is_absolute()
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
cams = camsolve.views(mech, json.loads(Path(skeleton).read_text(encoding="utf-8"))["world"])
|
||||
(out / f"{mech}_cameras.json").write_text(json.dumps(cams, indent=1), encoding="utf-8")
|
||||
print("\n".join(camsolve.report("hero", cams["hero"])))
|
||||
edges = M.built_edges(cams["hero"])
|
||||
(out / f"{mech}_edges_hero.json").write_text(json.dumps(edges), encoding="utf-8")
|
||||
print("EDGES", len(edges))
|
||||
417
surfaces/blender/experiments/mechs/fits.json
Normal file
417
surfaces/blender/experiments/mechs/fits.json
Normal file
|
|
@ -0,0 +1,417 @@
|
|||
{
|
||||
"_doc": "Written by fitshell.py: shells fitted by reprojection through the solved cameras. Do not edit by hand; change the recipe (concepts.json \"fit\") and run it again.",
|
||||
"seraph": {
|
||||
"chest": {
|
||||
"rings": [
|
||||
[
|
||||
[
|
||||
0.0,
|
||||
1.3427,
|
||||
-1.4923
|
||||
],
|
||||
[
|
||||
0.2545,
|
||||
1.3427,
|
||||
-1.4923
|
||||
],
|
||||
[
|
||||
0.3745,
|
||||
1.2127,
|
||||
-1.4923
|
||||
],
|
||||
[
|
||||
1.05,
|
||||
0.8427,
|
||||
-1.4923
|
||||
],
|
||||
[
|
||||
1.11,
|
||||
-0.3573,
|
||||
-1.4923
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
0.0,
|
||||
1.1554,
|
||||
-0.8171
|
||||
],
|
||||
[
|
||||
0.3027,
|
||||
1.1554,
|
||||
-0.8171
|
||||
],
|
||||
[
|
||||
0.4227,
|
||||
1.0254,
|
||||
-0.8171
|
||||
],
|
||||
[
|
||||
1.1667,
|
||||
0.672,
|
||||
-0.8171
|
||||
],
|
||||
[
|
||||
1.2267,
|
||||
-0.4946,
|
||||
-0.8171
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
0.0,
|
||||
0.9712,
|
||||
-0.4119
|
||||
],
|
||||
[
|
||||
0.3619,
|
||||
0.9712,
|
||||
-0.4119
|
||||
],
|
||||
[
|
||||
0.4819,
|
||||
0.8412,
|
||||
-0.4119
|
||||
],
|
||||
[
|
||||
1.2833,
|
||||
0.5046,
|
||||
-0.4119
|
||||
],
|
||||
[
|
||||
1.3433,
|
||||
-0.6288,
|
||||
-0.4119
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
0.0,
|
||||
0.785,
|
||||
-0.0332
|
||||
],
|
||||
[
|
||||
0.4139,
|
||||
0.785,
|
||||
-0.0332
|
||||
],
|
||||
[
|
||||
0.5339,
|
||||
0.655,
|
||||
-0.0332
|
||||
],
|
||||
[
|
||||
1.4,
|
||||
0.335,
|
||||
-0.0332
|
||||
],
|
||||
[
|
||||
1.46,
|
||||
-0.765,
|
||||
-0.0332
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
0.0,
|
||||
0.6,
|
||||
0.272
|
||||
],
|
||||
[
|
||||
0.4704,
|
||||
0.6,
|
||||
0.272
|
||||
],
|
||||
[
|
||||
0.5904,
|
||||
0.47,
|
||||
0.272
|
||||
],
|
||||
[
|
||||
1.1667,
|
||||
0.2167,
|
||||
0.272
|
||||
],
|
||||
[
|
||||
1.2267,
|
||||
-0.55,
|
||||
0.272
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
0.0,
|
||||
0.4162,
|
||||
0.5442
|
||||
],
|
||||
[
|
||||
0.5305,
|
||||
0.4162,
|
||||
0.5442
|
||||
],
|
||||
[
|
||||
0.6505,
|
||||
0.2862,
|
||||
0.5442
|
||||
],
|
||||
[
|
||||
1.0206,
|
||||
0.0809,
|
||||
0.5442
|
||||
],
|
||||
[
|
||||
1.0806,
|
||||
-0.475,
|
||||
0.5442
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
0.0,
|
||||
0.2359,
|
||||
0.7752
|
||||
],
|
||||
[
|
||||
0.6004,
|
||||
0.2359,
|
||||
0.7752
|
||||
],
|
||||
[
|
||||
0.7204,
|
||||
0.1059,
|
||||
0.7752
|
||||
],
|
||||
[
|
||||
0.9618,
|
||||
-0.07,
|
||||
0.7752
|
||||
],
|
||||
[
|
||||
1.0218,
|
||||
-0.5376,
|
||||
0.7752
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
0.0,
|
||||
0.0551,
|
||||
0.9945
|
||||
],
|
||||
[
|
||||
0.6684,
|
||||
0.0551,
|
||||
0.9945
|
||||
],
|
||||
[
|
||||
0.7884,
|
||||
-0.0749,
|
||||
0.9945
|
||||
],
|
||||
[
|
||||
0.9289,
|
||||
-0.2449,
|
||||
0.9945
|
||||
],
|
||||
[
|
||||
0.9889,
|
||||
-0.6949,
|
||||
0.9945
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
0.0,
|
||||
-0.1301,
|
||||
1.2145
|
||||
],
|
||||
[
|
||||
0.7246,
|
||||
-0.1301,
|
||||
1.2145
|
||||
],
|
||||
[
|
||||
0.8446,
|
||||
-0.2601,
|
||||
1.2145
|
||||
],
|
||||
[
|
||||
0.9446,
|
||||
-0.4301,
|
||||
1.2145
|
||||
],
|
||||
[
|
||||
1.0046,
|
||||
-0.8801,
|
||||
1.2145
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
0.0,
|
||||
-0.4301,
|
||||
1.5145
|
||||
],
|
||||
[
|
||||
0.5246,
|
||||
-0.4301,
|
||||
1.5145
|
||||
],
|
||||
[
|
||||
0.6446,
|
||||
-0.5601,
|
||||
1.5145
|
||||
],
|
||||
[
|
||||
0.8763,
|
||||
-0.7301,
|
||||
1.5145
|
||||
],
|
||||
[
|
||||
0.9363,
|
||||
-1.1801,
|
||||
1.5145
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
0.0,
|
||||
-0.9301,
|
||||
1.5945
|
||||
],
|
||||
[
|
||||
0.3446,
|
||||
-0.9301,
|
||||
1.5945
|
||||
],
|
||||
[
|
||||
0.4646,
|
||||
-1.0601,
|
||||
1.5945
|
||||
],
|
||||
[
|
||||
0.85,
|
||||
-1.2301,
|
||||
1.5945
|
||||
],
|
||||
[
|
||||
0.91,
|
||||
-1.6801,
|
||||
1.5945
|
||||
]
|
||||
]
|
||||
],
|
||||
"side": 1,
|
||||
"stations": 9,
|
||||
"crease": [
|
||||
[
|
||||
0.2545,
|
||||
1.3427,
|
||||
-1.4923
|
||||
],
|
||||
[
|
||||
0.3041,
|
||||
1.1558,
|
||||
-0.8508
|
||||
],
|
||||
[
|
||||
0.361,
|
||||
0.971,
|
||||
-0.4152
|
||||
],
|
||||
[
|
||||
0.4145,
|
||||
0.7852,
|
||||
-0.0424
|
||||
],
|
||||
[
|
||||
0.4709,
|
||||
0.6002,
|
||||
0.2679
|
||||
],
|
||||
[
|
||||
0.5317,
|
||||
0.4166,
|
||||
0.539
|
||||
],
|
||||
[
|
||||
0.6002,
|
||||
0.2358,
|
||||
0.7737
|
||||
],
|
||||
[
|
||||
0.667,
|
||||
0.0545,
|
||||
0.9946
|
||||
],
|
||||
[
|
||||
0.7246,
|
||||
-0.1301,
|
||||
1.2145
|
||||
],
|
||||
[
|
||||
0.5246,
|
||||
-0.4301,
|
||||
1.5145
|
||||
],
|
||||
[
|
||||
0.3446,
|
||||
-0.9301,
|
||||
1.5945
|
||||
]
|
||||
],
|
||||
"knots": [
|
||||
[
|
||||
0.0,
|
||||
1.05,
|
||||
0.5,
|
||||
1.2
|
||||
],
|
||||
[
|
||||
0.3,
|
||||
1.4,
|
||||
0.45,
|
||||
1.1
|
||||
],
|
||||
[
|
||||
0.45,
|
||||
1.05,
|
||||
0.35,
|
||||
0.6
|
||||
],
|
||||
[
|
||||
0.62,
|
||||
0.95,
|
||||
0.3,
|
||||
0.45
|
||||
],
|
||||
[
|
||||
1.0,
|
||||
0.85,
|
||||
0.3,
|
||||
0.45
|
||||
]
|
||||
],
|
||||
"outline_overlap": [
|
||||
0.53,
|
||||
0.53
|
||||
],
|
||||
"predicted_miss_px": {
|
||||
"chest_r": 5.59,
|
||||
"chest_l": 4.06
|
||||
},
|
||||
"predicted_miss_h": {
|
||||
"chest_r": 0.0074,
|
||||
"chest_l": 0.0054
|
||||
},
|
||||
"camera": {
|
||||
"lens": 45.03169348345337,
|
||||
"azimuth": 20.31108707243239,
|
||||
"elevation": -14.483718006104139,
|
||||
"distance": 11.09333340014215,
|
||||
"rms": 29.300683475794315,
|
||||
"twist": 20.944682682373656
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
295
surfaces/blender/experiments/mechs/fitshell.py
Normal file
295
surfaces/blender/experiments/mechs/fitshell.py
Normal file
|
|
@ -0,0 +1,295 @@
|
|||
"""A shell fitted by reprojection through a solved camera (camsolve). Plain Python, numpy and Pillow; no Blender.
|
||||
|
||||
A line traced on a concept view is two numbers a point; a shell's crease is three. With the view's camera solved, the
|
||||
third comes from what is known of the part:
|
||||
|
||||
pair(cam, frame, a, b) two traced lines that are one crease and its mirror image on a part symmetric about its
|
||||
frame's x = 0 (the two edges of a chest's centre plate): the crease in the frame's
|
||||
metres. A point of `a` and its mirror on `b` lie on a line through the vanishing point
|
||||
of the frame's x axis; the pair is triangulated as one point seen by the camera and
|
||||
by the camera's mirror image. Each lifted point projects back onto both lines exactly.
|
||||
The lift is as sure as the frame's turn to the camera: seen nearly square-on the two
|
||||
sight lines are nearly parallel, and a degree of turn moves the crease a long way in
|
||||
depth. probe() prints the crease at a spread of turns so the caller can see that.
|
||||
on_plane(cam, frame, line, point, normal) one traced line lifted onto a plane of the frame (an outer face).
|
||||
crease_run(points) where a hard crease of a level-1 subdivision cage actually stands: the run of built
|
||||
edges, which cuts the cage's corners. through(targets) is the cage column whose built
|
||||
run passes through the targets.
|
||||
centre_plate(crease, flank) rings of a mirrored shell whose centre panel is edged by a crease: per crease point a
|
||||
ring [centre, crease, step, corner, rear].
|
||||
silhouette(...) ring parameters moved, one at a time, to raise the overlap of the cage's projected
|
||||
outline with a traced outline (intersection over union, rasterised).
|
||||
along(line, segments, h) the flow score from built geometry: how much of a traced line has a built edge
|
||||
(mechlib.built_edges: creases and contours the camera sees, in the sheet's pixels)
|
||||
running along it. {"on": share of the line with an edge within 1% of the figure's
|
||||
height and 20 degrees of its direction, "off": mean distance to such an edge in % of
|
||||
the height, capped at 5, "run": the longest unbroken share that is on}.
|
||||
|
||||
python fitshell.py <mech> chest fits the chest of <mech>_parts from MECH_OUT/<mech>/<mech>_cameras.json and
|
||||
_frames.json (seraph.py under MECH_SKELETON_ONLY writes both) and writes
|
||||
fits.json[<mech>]["chest"] beside this file; the part reads its rings there.
|
||||
python fitshell.py <mech> probe prints the chest crease lifted at a spread of torso turns."""
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
import camsolve
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
MIRROR = np.diag([-1.0, 1.0, 1.0, 1.0])
|
||||
|
||||
|
||||
def matrix(cam):
|
||||
"""The camera as a 3 x 4 projection: pixels = (P @ [x, y, z, 1])[:2] / its third."""
|
||||
R, C, f, c = np.asarray(cam["R"], float), np.asarray(cam["C"], float), cam["f"], cam["c"]
|
||||
K = np.array([[f, 0, -c[0]], [0, -f, -c[1]], [0, 0, -1.0]])
|
||||
return K @ np.c_[R, -R @ C]
|
||||
|
||||
|
||||
def resampled(points, n):
|
||||
p = np.asarray(points, float)
|
||||
d = np.concatenate([[0], np.cumsum(np.hypot(*np.diff(p, axis=0).T))])
|
||||
t = np.linspace(0, d[-1], n)
|
||||
return np.stack([np.interp(t, d, p[:, k]) for k in range(p.shape[1])], 1)
|
||||
|
||||
|
||||
def extended(points, by):
|
||||
"""A polyline run on straight past both ends by `by` of its length."""
|
||||
p = np.asarray(points, float)
|
||||
length = np.hypot(*np.diff(p, axis=0).T).sum()
|
||||
head, tail = p[0] - p[1], p[-1] - p[-2]
|
||||
return np.vstack([p[0] + head / np.linalg.norm(head) * by * length, p, p[-1] + tail / np.linalg.norm(tail) * by * length])
|
||||
|
||||
|
||||
def pair(cam, frame, a, b, n=24, extend=0.2):
|
||||
"""The crease that lines `a` and `b` (sheet pixels) are the two mirror images of: [[x, y, z], ...] in the
|
||||
frame, x >= 0, in the order of `a`, and the side of the frame `a` is on (+1 or -1). `b` is run on past its ends
|
||||
by `extend` of its length to find mirrors for the ends of `a`; a point of `a` with no mirror is left out."""
|
||||
P = matrix(cam)
|
||||
F = np.asarray(frame, float)
|
||||
P1, P2 = P @ F, P @ F @ MIRROR
|
||||
vp = P1 @ np.array([1.0, 0, 0, 0])
|
||||
A, B = resampled(a, n), resampled(extended(b, extend), 600)
|
||||
out, side = [], 0
|
||||
for q in A:
|
||||
d = (vp[:2] - vp[2] * q) # toward the vanishing point, wherever it is (at infinity too)
|
||||
nrm = np.array([-d[1], d[0]]) / np.linalg.norm(d)
|
||||
s = (B - q) @ nrm
|
||||
k = np.nonzero(np.sign(s[:-1]) != np.sign(s[1:]))[0]
|
||||
if not len(k):
|
||||
continue
|
||||
k = k[0]
|
||||
m = B[k] + s[k] / (s[k] - s[k + 1]) * (B[k + 1] - B[k])
|
||||
M = np.array([q[0] * P1[2] - P1[0], q[1] * P1[2] - P1[1], m[0] * P2[2] - P2[0], m[1] * P2[2] - P2[1]])
|
||||
X = np.linalg.svd(M)[2][-1]
|
||||
X = X[:3] / X[3]
|
||||
side += np.sign(X[0])
|
||||
out.append([abs(X[0]), X[1], X[2]])
|
||||
return out, (1 if side >= 0 else -1)
|
||||
|
||||
|
||||
def on_plane(cam, frame, line, point, normal, n=24):
|
||||
"""A traced line (sheet pixels) lifted onto the plane of the frame through `point` with `normal`: [[x, y, z]]."""
|
||||
F = np.asarray(frame, float)
|
||||
inv = np.linalg.inv(F)
|
||||
p0, nw = F[:3, :3] @ np.asarray(point, float) + F[:3, 3], F[:3, :3] @ np.asarray(normal, float)
|
||||
return [list(inv[:3, :3] @ camsolve.lift(cam, q, p0, nw) + inv[:3, 3]) for q in resampled(line, n)]
|
||||
|
||||
|
||||
def seen(cam, frame, points):
|
||||
"""Sheet pixels of points of a frame."""
|
||||
F = np.asarray(frame, float)
|
||||
return camsolve.project(cam, np.asarray(points, float) @ F[:3, :3].T + F[:3, 3])
|
||||
|
||||
|
||||
def crease_run(points):
|
||||
"""The built edges of a hard crease whose cage column is `points`, after one level of subdivision: each inner
|
||||
cage point moves to (1, 6, 1) / 8 of itself and its neighbours, a new point stands at each middle, the ends
|
||||
stay. A polyline of 2n - 1 points."""
|
||||
p = np.asarray(points, float)
|
||||
v = p.copy()
|
||||
v[1:-1] = (p[:-2] + 6 * p[1:-1] + p[2:]) / 8
|
||||
out = np.empty((2 * len(p) - 1, p.shape[1]))
|
||||
out[0::2], out[1::2] = v, (p[:-1] + p[1:]) / 2
|
||||
return out
|
||||
|
||||
|
||||
def through(targets, rounds=30):
|
||||
"""The cage column whose built crease (crease_run) passes through `targets` at its own points."""
|
||||
t = np.asarray(targets, float)
|
||||
c = t.copy()
|
||||
for _ in range(rounds):
|
||||
c += t - crease_run(c)[0::2]
|
||||
return c
|
||||
|
||||
|
||||
def centre_plate(crease, flank, proud=0.08, step=0.12, rear_out=0.06):
|
||||
"""Rings for the half x >= 0 of a mirrored shell with a centre panel: `crease` is the panel's edge, [[x, y, z]]
|
||||
from the shell's first ring to its last; `flank` gives per ring (corner half-width, how far behind the crease
|
||||
the corner stands, how far behind the corner the rear edge stands). A ring is [centre, crease, step, corner, rear]: the panel is flat
|
||||
across, the step stands `proud` behind it and `step` outboard (the panel's edge is then a ridge the eye
|
||||
follows), the facet beside it runs out and back to the corner, the flank back to the rear edge, `rear_out`
|
||||
further out. A corner narrower than the step leaves a 0.1 m facet."""
|
||||
rings = []
|
||||
for (x, y, z), (hw, back, depth) in zip(crease, flank):
|
||||
sx = x + step
|
||||
hw, back = max(hw, sx + 0.1), max(back, proud + 0.02)
|
||||
rings.append([[0.0, y, z], [x, y, z], [sx, y - proud, z], [hw, y - back, z], [hw + rear_out, y - back - max(depth, 0.1), z]])
|
||||
return rings
|
||||
|
||||
|
||||
def polygon_mask(polygons, box, k):
|
||||
from PIL import Image, ImageDraw
|
||||
img = Image.new("L", (int((box[2] - box[0]) * k), int((box[3] - box[1]) * k)), 0)
|
||||
d = ImageDraw.Draw(img)
|
||||
for poly in polygons:
|
||||
d.polygon([((x - box[0]) * k, (y - box[1]) * k) for x, y in poly], fill=255)
|
||||
return np.asarray(img) > 0
|
||||
|
||||
|
||||
def cage_mask(cam, frame, rings, box, k, mirror=True):
|
||||
"""The outline a cage of rings shows the camera: its quads, and their mirror images, filled."""
|
||||
R = np.asarray(rings, float)
|
||||
quads = []
|
||||
for half in ((1,) if not mirror else (1, -1)):
|
||||
p = seen(cam, frame, (R * [half, 1, 1]).reshape(-1, 3)).reshape(R.shape[0], R.shape[1], 2)
|
||||
quads += [[p[i, j], p[i, j + 1], p[i + 1, j + 1], p[i + 1, j]] for i in range(R.shape[0] - 1) for j in range(R.shape[1] - 1)]
|
||||
return polygon_mask(quads, box, k)
|
||||
|
||||
|
||||
def overlap(a, b):
|
||||
return float((a & b).sum() / max((a | b).sum(), 1))
|
||||
|
||||
|
||||
def knotted(knots, n):
|
||||
"""Rows for n rings from a few knots [[t, a, b, ...]], t from 0 (the first ring) to 1 (the last): each value
|
||||
runs straight between knots, so a fit that moves a knot moves a stretch of rings together and the shell stays fair."""
|
||||
K = np.asarray(knots, float)
|
||||
t = np.linspace(0, 1, n)
|
||||
return [[float(np.interp(ti, K[:, 0], K[:, c])) for c in range(1, K.shape[1])] for ti in t]
|
||||
|
||||
|
||||
def silhouette(make, params, moves, cam, frame, polygons, box, k=3.0, rounds=4):
|
||||
"""Coordinate descent on a list of parameter rows: make(params) gives rings; each `moves` entry (row, index,
|
||||
step, least, most) is tried a step up and a step down, and kept if the cage's outline overlaps the traced
|
||||
`polygons` more; steps halve each round. Returns (params, overlap before, overlap after)."""
|
||||
target = polygon_mask(polygons, box, k)
|
||||
score = lambda q: overlap(cage_mask(cam, frame, make(q), box, k), target) # noqa: E731
|
||||
params = [list(row) for row in params]
|
||||
first = best = score(params)
|
||||
for r in range(rounds):
|
||||
for row, index, step, least, most in moves:
|
||||
for way in (1, -1):
|
||||
trial = [list(q) for q in params]
|
||||
trial[row][index] = min(max(trial[row][index] + way * step / 2 ** r, least), most)
|
||||
s = score(trial)
|
||||
if s > best + 1e-4:
|
||||
params, best = trial, s
|
||||
break
|
||||
return params, first, best
|
||||
|
||||
|
||||
def along(line, segments, height, near=0.01, turn=20.0, cap=0.05):
|
||||
"""How much of a traced line (sheet pixels) the build's edges run along. `segments` are [u0, v0, u1, v1] in the
|
||||
same pixels (mechlib.built_edges), `height` the figure's height there. Per point of the line: the distance to
|
||||
the nearest edge within `turn` degrees of the line's direction. Returns {"on", "off", "run"} (module doc)."""
|
||||
p = resampled(line, 80)
|
||||
tan = np.gradient(p, axis=0)
|
||||
tan /= np.linalg.norm(tan, axis=1)[:, None]
|
||||
S = np.asarray(segments, float).reshape(-1, 4)
|
||||
if not len(S):
|
||||
return {"on": 0.0, "off": 100 * cap, "run": 0.0}
|
||||
a, d = S[:, :2], S[:, 2:] - S[:, :2]
|
||||
length = np.maximum(np.linalg.norm(d, axis=1), 1e-9)
|
||||
u = d / length[:, None]
|
||||
dist = np.empty(len(p))
|
||||
for i, (q, t) in enumerate(zip(p, tan)):
|
||||
ok = np.abs(u @ t) >= math.cos(math.radians(turn))
|
||||
if not ok.any():
|
||||
dist[i] = np.inf
|
||||
continue
|
||||
s = np.clip(((q - a[ok]) * u[ok]).sum(1), 0, length[ok])
|
||||
dist[i] = np.linalg.norm(a[ok] + s[:, None] * u[ok] - q, axis=1).min()
|
||||
on = dist <= near * height
|
||||
run = best = 0
|
||||
for flag in on:
|
||||
run = run + 1 if flag else 0
|
||||
best = max(best, run)
|
||||
return {"on": round(float(on.mean()), 3), "off": round(float(100 * np.minimum(dist / height, cap).mean()), 2), "run": round(best / len(on), 3)}
|
||||
|
||||
|
||||
# --- the chest of a biped: its centre plate's two edges traced as flow lines "chest_r" and "chest_l" -------------------
|
||||
|
||||
def chest_crease(spec, cam, frame, n=24):
|
||||
lines = spec["flow"]["lines"]
|
||||
return pair(cam, frame, lines["chest_r"]["points"], lines["chest_l"]["points"], n)
|
||||
|
||||
|
||||
def turned(frame, degrees, pivot):
|
||||
"""A frame turned about the world's vertical through `pivot` (x, y)."""
|
||||
c, s = math.cos(math.radians(degrees)), math.sin(math.radians(degrees))
|
||||
T = np.eye(4)
|
||||
T[:2, :2] = [[c, -s], [s, c]]
|
||||
T[:2, 3] = np.array(pivot) - T[:2, :2] @ np.array(pivot)
|
||||
return T @ np.asarray(frame, float)
|
||||
|
||||
|
||||
def load(mech):
|
||||
out = Path(os.environ["MECH_OUT"]) / mech
|
||||
spec = json.loads((HERE / "concepts.json").read_text(encoding="utf-8"))[mech]
|
||||
cams = json.loads((out / f"{mech}_cameras.json").read_text(encoding="utf-8"))
|
||||
frames = json.loads((out / f"{mech}_frames.json").read_text(encoding="utf-8"))
|
||||
world = json.loads((out / f"{mech}_skeleton.json").read_text(encoding="utf-8"))["world"]
|
||||
return spec, cams, frames, world
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
mech, what = sys.argv[1], sys.argv[2]
|
||||
spec, cams, frames, world = load(mech)
|
||||
cam, frame = cams["hero"], frames["Chest"]
|
||||
if what == "probe":
|
||||
for deg in (-15, -10, -5, 0, 5, 10, 15, 20):
|
||||
crease, side = chest_crease(spec, cam, turned(frame, deg, world["waist"][:2]), 8)
|
||||
print(f"torso turned {deg:+d} from the build's: " + " ".join(f"({x:.2f} {y:.2f} {z:.2f})" for x, y, z in crease))
|
||||
if what == "chest":
|
||||
recipe = spec["fit"]["chest"]
|
||||
lifted, side = pair(cam, frame, spec["flow"]["lines"]["chest_r"]["points"], spec["flow"]["lines"]["chest_l"]["points"], 32, recipe["extend"])
|
||||
lifted = [p for p in lifted if p[2] <= recipe["crown"]]
|
||||
n = recipe["stations"]
|
||||
targets = resampled(lifted[::-1], n) # sternum first, as the shell's rings run
|
||||
column = through(targets) # the built crease passes through the lifted stations
|
||||
for step in recipe["close"]:
|
||||
targets = np.vstack([targets, targets[n - 1] + np.array(step)])
|
||||
column = np.vstack([column, targets[n:]])
|
||||
box = [v * spec["skeleton"]["unit"] / spec["masks"]["unit"] for v in spec["masks"]["parts"][recipe["outline"]]["crop"]]
|
||||
polygons = spec["masks"]["parts"][recipe["outline"]]["polygons"]
|
||||
make = lambda knots: centre_plate(column, knotted(knots, len(column)), proud=recipe.get("proud", 0.08)) # noqa: E731
|
||||
moves = [(i, c, step, least, most) for i in range(len(recipe["knots"])) for c, step, least, most in ((1, 0.3, 0.5, 1.9), (3, 0.3, 0.2, 1.6))] # the corner's width and the flank's depth move; its set-back barely shows in the outline and stays the recipe's
|
||||
knots, before, after = silhouette(make, recipe["knots"], moves, cam, frame, polygons, box) if recipe.get("fit_outline", True) else (recipe["knots"], None, None)
|
||||
if before is None:
|
||||
target = polygon_mask(polygons, box, 3.0)
|
||||
before = after = overlap(cage_mask(cam, frame, make(knots), box, 3.0), target)
|
||||
rings = make(knots)
|
||||
run = crease_run(column)
|
||||
lines = spec["flow"]["lines"]
|
||||
miss = {}
|
||||
for tag, half in (("chest_r", side), ("chest_l", -side)): # the built run, predicted, against her line: pixels
|
||||
dense = resampled(extended(lines[tag]["points"], 0.01), 400)
|
||||
px = seen(cam, frame, run[: 2 * n - 1] * [half, 1, 1])
|
||||
miss[tag] = float(np.mean([np.linalg.norm(px - q, axis=1).min() for q in dense]))
|
||||
height = spec["skeleton"]["views"]["hero"]["ground"] - spec["skeleton"]["views"]["hero"]["top"]
|
||||
out = {"rings": [[[round(float(v), 4) for v in p] for p in ring] for ring in rings], "side": side, "stations": n,
|
||||
"crease": [[round(float(v), 4) for v in p] for p in targets], "knots": knots, "outline_overlap": [round(before, 3), round(after, 3)],
|
||||
"predicted_miss_px": {k: round(v, 2) for k, v in miss.items()}, "predicted_miss_h": {k: round(v / height, 4) for k, v in miss.items()},
|
||||
"camera": {k: cam[k] for k in ("lens", "azimuth", "elevation", "distance", "rms", "twist")}}
|
||||
path = HERE / "fits.json"
|
||||
doc = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {"_doc": "Written by fitshell.py: shells fitted by reprojection through the solved cameras. Do not edit by hand; change the recipe (concepts.json \"fit\") and run it again."}
|
||||
doc.setdefault(mech, {})["chest"] = out
|
||||
path.write_text(json.dumps(doc, indent=1), encoding="utf-8")
|
||||
print(f"FIT {mech} chest: {len(rings)} rings; outline overlap {before:.3f} to {after:.3f}; her lines miss the built crease, as predicted, by " + ", ".join(f"{k} {v:.1f} px ({100 * v / height:.2f}% H)" for k, v in miss.items()))
|
||||
for ring in rings:
|
||||
print(" ", " ".join("(%.2f %.2f %.2f)" % tuple(p) for p in ring[1:]))
|
||||
|
|
@ -45,6 +45,18 @@ Round 8:
|
|||
recessed_rams(on=) heel lugs on a cross ankle's spider, so the rams stay in plane on a splayed leg.
|
||||
Build["khaki:tag"] a second object of one material in a component, named for what it is, so a
|
||||
scored mask can leave it out.
|
||||
|
||||
Round 9:
|
||||
|
||||
solved_view / shot(solved=) / field_views(solve=True) a concept view's camera solved from its marked joints
|
||||
(camsolve.py) and stood in the scene: renders and masks in the sheet's own pixels. Needs: a camera-match
|
||||
action (points in, camera out), and marks that are not placed by hand.
|
||||
built_edges the creases and contours a camera sees on the evaluated build, in the sheet's
|
||||
pixels: what a flow-line score reads. Needs: the same from a perception action; hidden-line removal per edge
|
||||
piece (an edge is kept or dropped whole, by three samples).
|
||||
fitshell.py traced lines lifted to 3D through the solved camera (a mirrored pair
|
||||
triangulated against its own mirror image), a cage column whose built crease passes through the lifted run,
|
||||
a silhouette descent. Needs: the torso's turn solved, not taken from the build (see its doc).
|
||||
"""
|
||||
import json
|
||||
import math
|
||||
|
|
@ -745,10 +757,11 @@ def shells_sound():
|
|||
for name in sorted(FOLDED):
|
||||
mesh = bmesh.new()
|
||||
mesh.from_mesh(bpy.data.objects[name].evaluated_get(depsgraph).data)
|
||||
loose = sum(1 for edge in mesh.edges if not edge.is_manifold)
|
||||
where = [tuple(round(c, 2) for c in (edge.verts[0].co + edge.verts[1].co) / 2) for edge in mesh.edges if not edge.is_manifold]
|
||||
loose = len(where)
|
||||
mesh.free()
|
||||
folded, unsound = folded + FOLDED[name], unsound + loose
|
||||
print(f"SHELL {name} folded {FOLDED[name]} openEdges {loose}", flush=True)
|
||||
print(f"SHELL {name} folded {FOLDED[name]} openEdges {loose}" + (f" at {where[:12]} (the shell's own frame)" if where else ""), flush=True)
|
||||
print(f"SHELLS {len(FOLDED)} folded {folded} openEdges {unsound}", flush=True)
|
||||
if folded or unsound:
|
||||
raise SystemExit(f"shells: {folded} folded inner faces and {unsound} open edges after cuts; thin the wall where it folds, or move the cut")
|
||||
|
|
@ -1212,23 +1225,45 @@ def stage(samples=96):
|
|||
return rig, cam, centre, radius
|
||||
|
||||
|
||||
def shot(rig, cam, radius, azimuth, elevation, path, size, margin=0.95, lens=70.0, lift=0.0, eye=None):
|
||||
def solved_view(rig, cam, solved, width, box=None):
|
||||
"""Stand the camera where camsolve solved a concept view: its place, turn, lens and centre, the frame being the
|
||||
view's box on the sheet (or `box`, a crop of it in the same pixels) at `width` pixels across. The rig, which
|
||||
carries the lights, turns to the camera's azimuth. A pixel of the render is then the same pixel of the sheet,
|
||||
less the box's corner, times width over the box's width. Returns the frame's (width, height)."""
|
||||
import camsolve
|
||||
rows, lens, shift_x, shift_y, size = camsolve.blender(dict(solved, box=list(box or solved["box"])), width)
|
||||
rig.rotation_euler = (0, 0, math.radians(180 + solved["azimuth"]))
|
||||
update()
|
||||
cam.data.sensor_fit, cam.data.sensor_width, cam.data.lens, cam.data.shift_x, cam.data.shift_y = "HORIZONTAL", 36.0, lens, shift_x, shift_y
|
||||
cam.data.clip_end = max(5000.0, 4 * solved["distance"])
|
||||
cam.matrix_world = Matrix(rows)
|
||||
bpy.context.scene.render.resolution_x, bpy.context.scene.render.resolution_y = size
|
||||
update()
|
||||
return size
|
||||
|
||||
|
||||
def shot(rig, cam, radius, azimuth, elevation, path, size, margin=0.95, lens=70.0, lift=0.0, eye=None, solved=None, box=None):
|
||||
"""azimuth 0 looks at the mech's front (+y) from in front; positive goes round to its left side. The distance
|
||||
fits the scene's bounding sphere, times `margin`, in the narrower of the frame's two angles. `eye` puts the
|
||||
camera at that height above the ground instead of at `elevation`: a short lens and a low eye are how the
|
||||
concept sheets draw their hero views."""
|
||||
concept sheets draw their hero views. `solved` (a camsolve camera) overrides all of that: solved_view(), the
|
||||
frame size[0] pixels across and as tall as the view's box (or `box`) makes it."""
|
||||
scene = bpy.context.scene
|
||||
cam.data.lens = lens
|
||||
el = math.radians(elevation)
|
||||
narrow = min(size) / max(size) * cam.data.sensor_width / 2
|
||||
d = radius * margin / math.sin(math.atan(narrow / lens))
|
||||
cam.location = Vector((0.0, -d * math.cos(el), d * math.sin(el) + lift * radius))
|
||||
if eye is not None:
|
||||
z = eye - rig.location.z
|
||||
cam.location = Vector((0.0, -math.sqrt(max(d * d - z * z, 0.01)), z))
|
||||
cam.rotation_euler = (Vector((0, 0, lift * radius * 0.5)) - cam.location).to_track_quat("-Z", "Y").to_euler()
|
||||
rig.rotation_euler = (0, 0, math.radians(180 + azimuth))
|
||||
scene.render.resolution_x, scene.render.resolution_y = size
|
||||
if solved:
|
||||
solved_view(rig, cam, solved, size[0], box)
|
||||
else:
|
||||
cam.data.sensor_fit, cam.data.shift_x, cam.data.shift_y = "AUTO", 0.0, 0.0
|
||||
cam.data.lens = lens
|
||||
el = math.radians(elevation)
|
||||
narrow = min(size) / max(size) * cam.data.sensor_width / 2
|
||||
d = radius * margin / math.sin(math.atan(narrow / lens))
|
||||
cam.location = Vector((0.0, -d * math.cos(el), d * math.sin(el) + lift * radius))
|
||||
if eye is not None:
|
||||
z = eye - rig.location.z
|
||||
cam.location = Vector((0.0, -math.sqrt(max(d * d - z * z, 0.01)), z))
|
||||
cam.rotation_euler = (Vector((0, 0, lift * radius * 0.5)) - cam.location).to_track_quat("-Z", "Y").to_euler()
|
||||
rig.rotation_euler = (0, 0, math.radians(180 + azimuth))
|
||||
scene.render.resolution_x, scene.render.resolution_y = size
|
||||
scene.render.filepath = str(path)
|
||||
scene.render.image_settings.file_format = "PNG"
|
||||
bpy.ops.render.render(write_still=True)
|
||||
|
|
@ -1919,7 +1954,7 @@ def pod(name, rings, host, cap=0.45, levels=2, mat="khaki", **kw):
|
|||
return shell(name, rings, host, closed=True, thickness=0.0, levels=levels, mat=mat, capped=True, **kw)
|
||||
|
||||
|
||||
def silhouette(rig, cam, radius, azimuth, elevation, path, size, margin=0.95, lens=70.0, eye=None):
|
||||
def silhouette(rig, cam, radius, azimuth, elevation, path, size, margin=0.95, lens=70.0, eye=None, solved=None, box=None):
|
||||
"""The same view as shot(), as a mask: the mech's alpha on a transparent film, the stage hidden, one sample."""
|
||||
scene = bpy.context.scene
|
||||
hidden = [o for o in scene.objects if o.get("stage") and not o.hide_render]
|
||||
|
|
@ -1928,7 +1963,7 @@ def silhouette(rig, cam, radius, azimuth, elevation, path, size, margin=0.95, le
|
|||
o.hide_render = True
|
||||
scene.cycles.samples, scene.cycles.use_denoising, scene.render.film_transparent = 1, False, True
|
||||
scene.render.image_settings.color_mode = "RGBA"
|
||||
shot(rig, cam, radius, azimuth, elevation, path, size, margin, lens, eye=eye)
|
||||
shot(rig, cam, radius, azimuth, elevation, path, size, margin, lens, eye=eye, solved=solved, box=box)
|
||||
scene.cycles.samples, scene.cycles.use_denoising, scene.render.film_transparent, scene.render.image_settings.color_mode = keep
|
||||
for o in hidden:
|
||||
o.hide_render = False
|
||||
|
|
@ -1971,7 +2006,63 @@ def project(cam, points, size):
|
|||
return out
|
||||
|
||||
|
||||
def field_views(name, t0, hero=(30.0, 3.0), rear=(180.0, 6.0), hero_size=(2000, 2400), samples=96, turns=(), closeups=(), joints=None, hero_cam=None, rear_cam=None, masks=None):
|
||||
def built_edges(solved, keep=None, angle=18.0):
|
||||
"""The edges a solved camera (camsolve) sees on the build as it stands, evaluated modifiers and all: creases
|
||||
(two faces meeting at more than `angle` degrees, one of them toward the camera), contours (one face toward the
|
||||
camera, the other away) and open borders, each kept where two of three points along it are not hidden behind
|
||||
anything. Returns [{"object", "kind", "seg": [u0, v0, u1, v1]}] in the sheet's pixels, the camera's unit: the
|
||||
same pixels a line traced on the concept is in. `keep` is a test on an object's name. This is what a flow-line
|
||||
score reads: the built geometry, not a line carried over from the concept."""
|
||||
import camsolve
|
||||
import numpy as np
|
||||
scene, dg = bpy.context.scene, bpy.context.evaluated_depsgraph_get()
|
||||
eye, out, cos_a = np.array(solved["C"]), [], math.cos(math.radians(angle))
|
||||
for obj in scene.objects:
|
||||
if obj.type != "MESH" or obj.get("stage") or obj.hide_render or (keep and not keep(obj.name)):
|
||||
continue
|
||||
ev = obj.evaluated_get(dg)
|
||||
me = ev.to_mesh()
|
||||
nv, ne, nl, nf = len(me.vertices), len(me.edges), len(me.loops), len(me.polygons)
|
||||
if not nf:
|
||||
ev.to_mesh_clear()
|
||||
continue
|
||||
co, ends, loop_edge, totals, normal, centre = np.empty(nv * 3), np.empty(ne * 2, np.int32), np.empty(nl, np.int32), np.empty(nf, np.int32), np.empty(nf * 3), np.empty(nf * 3)
|
||||
me.vertices.foreach_get("co", co)
|
||||
me.edges.foreach_get("vertices", ends)
|
||||
me.loops.foreach_get("edge_index", loop_edge)
|
||||
me.polygons.foreach_get("loop_total", totals)
|
||||
me.polygons.foreach_get("normal", normal)
|
||||
me.polygons.foreach_get("center", centre)
|
||||
ev.to_mesh_clear()
|
||||
world = np.array(obj.matrix_world)
|
||||
turn = np.linalg.inv(world[:3, :3]).T
|
||||
co, centre = co.reshape(-1, 3) @ world[:3, :3].T + world[:3, 3], centre.reshape(-1, 3) @ world[:3, :3].T + world[:3, 3]
|
||||
normal = normal.reshape(-1, 3) @ turn.T
|
||||
normal /= np.maximum(np.linalg.norm(normal, axis=1), 1e-12)[:, None]
|
||||
loop_face = np.repeat(np.arange(nf), totals)
|
||||
order = np.argsort(loop_edge, kind="stable")
|
||||
faces, count = loop_face[order], np.bincount(loop_edge, minlength=ne)
|
||||
first = np.searchsorted(loop_edge[order], np.arange(ne))
|
||||
two = count == 2
|
||||
f0, f1 = faces[np.minimum(first, nl - 1)], faces[np.minimum(first + 1, nl - 1)]
|
||||
toward = ((eye - centre) * normal).sum(1) > 0
|
||||
crease = two & ((normal[f0] * normal[f1]).sum(1) < cos_a) & (toward[f0] | toward[f1])
|
||||
contour = two & (toward[f0] != toward[f1])
|
||||
ends = ends.reshape(-1, 2)
|
||||
for k in np.nonzero(crease | contour | (count == 1))[0]:
|
||||
a, b = co[ends[k, 0]], co[ends[k, 1]]
|
||||
seen = 0
|
||||
for t in (0.2, 0.5, 0.8):
|
||||
p = a + t * (b - a)
|
||||
d = float(np.linalg.norm(p - eye))
|
||||
seen += not scene.ray_cast(dg, Vector(eye), Vector((p - eye) / d), distance=d - 0.03)[0]
|
||||
if seen >= 2:
|
||||
(u0, v0), (u1, v1) = camsolve.project(solved, [a, b])
|
||||
out.append({"object": obj.name, "kind": "contour" if contour[k] else "crease" if crease[k] else "border", "seg": [round(float(v), 2) for v in (u0, v0, u1, v1)]})
|
||||
return out
|
||||
|
||||
|
||||
def field_views(name, t0, hero=(30.0, 3.0), rear=(180.0, 6.0), hero_size=(2000, 2400), samples=96, turns=(), closeups=(), joints=None, hero_cam=None, rear_cam=None, masks=None, solve=False, frames=None):
|
||||
"""The finale. Under MECH_QUICK: hero and rear at 24 samples and 1000 px. Else the .blend, hero and rear
|
||||
at `samples`, and any `turns` azimuths. `closeups` are (tag, object, point in its frame, span, azimuth,
|
||||
elevation): joint close-ups, <name>_joint_<tag>.png. Always: silhouette masks of the hero, rear and straight-front views
|
||||
|
|
@ -1979,6 +2070,11 @@ def field_views(name, t0, hero=(30.0, 3.0), rear=(180.0, 6.0), hero_size=(2000,
|
|||
lens, eye and margin for those views. `joints` (joint_points()) are written, projected into the hero and rear masks' pixels, to
|
||||
<name>_skeleton.json for the proportions sheet. `masks` is {tag: a test on an object's name}: part_mask() of those
|
||||
objects in the hero view, at the hero render's size, occluded by the rest.
|
||||
With `solve` (and `joints`) the hero and rear cameras are solved from the concept's marked joints against the
|
||||
build's (camsolve.views) and written to <name>_cameras.json: masks and renders of those two views then stand at
|
||||
the solved cameras, their frames the views' boxes on the sheet, hero_size[0] wide; and <name>_edges_hero.json,
|
||||
<name>_edges_rear.json hold built_edges() at each. `frames` is {component: its frame in the world}, written to
|
||||
<name>_frames.json for part_bench (a part alone, where it stands, at the solved camera) and fitshell.
|
||||
MECH_SKELETON_ONLY stops after the masks; MECH_HERO_ONLY after the hero render."""
|
||||
quick = os.environ.get("MECH_QUICK")
|
||||
out = Path(os.environ["MECH_OUT"]) / name
|
||||
|
|
@ -1990,10 +2086,22 @@ def field_views(name, t0, hero=(30.0, 3.0), rear=(180.0, 6.0), hero_size=(2000,
|
|||
size = (1000, 1200) if quick else hero_size
|
||||
cams = {"hero": {"lens": 60.0, "margin": 0.86, **(hero_cam or {})}, "rear": {"lens": 60.0, "margin": 0.86, **(rear_cam or {})}, "front": dict(lens=60.0, margin=0.86)}
|
||||
views = {}
|
||||
if frames:
|
||||
(out / f"{name}_frames.json").write_text(json.dumps({k: [list(row) for row in Matrix(v)] for k, v in frames.items()}), encoding="utf-8")
|
||||
if solve and joints:
|
||||
import camsolve
|
||||
solved = camsolve.views(name, {k: list(v) for k, v in joints.items()})
|
||||
(out / f"{name}_cameras.json").write_text(json.dumps(solved, indent=1), encoding="utf-8")
|
||||
for tag, c in solved.items():
|
||||
print("\n".join(camsolve.report(tag, c)), flush=True)
|
||||
cams[tag]["solved"] = c
|
||||
for tag, (az, el) in (("hero", hero), ("rear", rear), ("front", (0.0, 3.0))):
|
||||
silhouette(rig, cam, radius, az, el, out / f"{name}_sil_{tag}.png", (1000, 1200), **cams[tag])
|
||||
mask_size = [bpy.context.scene.render.resolution_x, bpy.context.scene.render.resolution_y]
|
||||
if joints:
|
||||
views[tag] = {"size": [1000, 1200], "joints": project(cam, joints, (1000, 1200))}
|
||||
views[tag] = {"size": mask_size, "joints": project(cam, joints, mask_size)}
|
||||
if "solved" in cams[tag]:
|
||||
(out / f"{name}_edges_{tag}.json").write_text(json.dumps(built_edges(cams[tag]["solved"])), encoding="utf-8")
|
||||
if joints:
|
||||
(out / f"{name}_skeleton.json").write_text(json.dumps({"views": views, "world": {k: [round(c, 3) for c in v] for k, v in joints.items()}}, indent=1), encoding="utf-8")
|
||||
for tag, keep in (masks or {}).items(): # what the hero view shows of a part, past its neighbours: <name>_vis_<tag>.png
|
||||
|
|
|
|||
|
|
@ -2,6 +2,11 @@
|
|||
MECH_PARTS: comma-separated names from <MECH_SET>_parts.PARTS (default all); MECH_SET: the mech (default seraph).
|
||||
Writes MECH_OUT/<mech>/parts/<name>.png, 800 px, for compare.py's components sheet, and for a part in the set's
|
||||
MASKS, <name>_mask.png: its scored objects' outline at the same camera, for compare.py's match score.
|
||||
A part in the set's SOLVED ({part: (component of the assembled build, crop of concepts.json "components")}) is benched
|
||||
where that component stands in the build (<mech>_frames.json) and seen by the solved hero camera
|
||||
(<mech>_cameras.json; both from the mech's own script, MECH_SKELETON_ONLY is enough), the frame being its crop of the
|
||||
sheet: a pixel of the render is that pixel of the crop. Its built edges at that camera go to <name>_edges.json
|
||||
(mechlib.built_edges, sheet pixels).
|
||||
MECH_MASK_ONLY: masks only. MECH_FOLDS: mechlib.shells_sound() on each part (folds and open edges stop the bench)."""
|
||||
import importlib, json, math, os, sys, time
|
||||
from pathlib import Path
|
||||
|
|
@ -17,6 +22,13 @@ out = Path(os.environ["MECH_OUT"]) / mech / "parts"
|
|||
assert out.is_absolute()
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
names = [n for n in os.environ.get("MECH_PARTS", "").split(",") if n] or list(lib.PARTS)
|
||||
solved_parts, root = getattr(lib, "SOLVED", {}), out.parent
|
||||
if solved_parts and (root / f"{mech}_cameras.json").exists():
|
||||
hero_cam = json.loads((root / f"{mech}_cameras.json").read_text(encoding="utf-8"))["hero"]
|
||||
frames = json.loads((root / f"{mech}_frames.json").read_text(encoding="utf-8"))
|
||||
crops = json.loads((Path(__file__).resolve().parent / "concepts.json").read_text(encoding="utf-8"))[mech]["components"]["crops"]
|
||||
else:
|
||||
solved_parts = {}
|
||||
for name in names:
|
||||
t0 = time.time()
|
||||
for obj in list(bpy.data.objects):
|
||||
|
|
@ -26,6 +38,10 @@ for name in names:
|
|||
host = bpy.data.objects.new("Bench", None)
|
||||
bpy.context.scene.collection.objects.link(host)
|
||||
host.matrix_world = Matrix.Translation((0, 0, getattr(lib, "GROUND", {}).get(name, 5.0))) @ Matrix.Rotation(math.radians(pitch), 4, "X")
|
||||
view = {}
|
||||
if name in solved_parts:
|
||||
host.matrix_world = Matrix(frames[solved_parts[name][0]])
|
||||
view = {"solved": hero_cam, "box": crops[solved_parts[name][1]]}
|
||||
build = M.Build(name, host)
|
||||
lib.PARTS[name](build)
|
||||
build.done()
|
||||
|
|
@ -33,13 +49,15 @@ for name in names:
|
|||
rig, cam, centre, radius = M.stage_field(int(os.environ.get("MECH_SAMPLES", "32")))
|
||||
lens = getattr(lib, "LENS", {}).get(name, 85.0)
|
||||
if name in getattr(lib, "MASKS", {}): # the scored outline: the armor the crop's mask traces, alone, at the same camera
|
||||
M.part_mask(rig, cam, radius, az, el, out / f"{name}_mask.png", (800, 800), lib.MASKS[name], margin=margin, lens=lens)
|
||||
M.part_mask(rig, cam, radius, az, el, out / f"{name}_mask.png", (800, 800), lib.MASKS[name], margin=margin, lens=lens, **view)
|
||||
for tag, (az2, el2, margin2, lens2) in getattr(lib, "SECOND", {}).get(name, {}).items(): # a second scored view of the same part
|
||||
M.part_mask(rig, cam, radius, az2, el2, out / f"{tag}_mask.png", (800, 800), lib.MASKS[name], margin=margin2, lens=lens2)
|
||||
if not os.environ.get("MECH_MASK_ONLY"):
|
||||
M.shot(rig, cam, radius, az2, el2, out / f"{tag}.png", (800, 800), margin=margin2, lens=lens2)
|
||||
if not os.environ.get("MECH_MASK_ONLY"):
|
||||
M.shot(rig, cam, radius, az, el, out / f"{name}.png", (800, 800), margin=margin, lens=lens)
|
||||
M.shot(rig, cam, radius, az, el, out / f"{name}.png", (800, 800), margin=margin, lens=lens, **view)
|
||||
if view:
|
||||
(out / f"{name}_edges.json").write_text(json.dumps(M.built_edges(hero_cam)), encoding="utf-8")
|
||||
lines = getattr(lib, "LINES", {}).get(name)
|
||||
if lines: # the flow lines the part carries, as built, in this view's pixels
|
||||
drawn = {line: [M.project(cam, {"p": host.matrix_world @ Vector(p)}, (800, 800))["p"] for p in points] for line, points in lines.items()}
|
||||
|
|
|
|||
|
|
@ -35,7 +35,11 @@ CH = CFG["chassis"]["height"]
|
|||
MIR = Matrix.Diagonal((-1.0, 1.0, 1.0, 1.0))
|
||||
|
||||
|
||||
SEATS = {} # component: (host, to_host), for <name>_frames.json: where each stands in the world once the figure is grounded
|
||||
|
||||
|
||||
def put(name, fn, host, to_host, **kw):
|
||||
SEATS[name] = (host, to_host)
|
||||
build = M.Build(name, host, to_host)
|
||||
fn(build, **kw)
|
||||
if build.to_host is not to_host: # the component mirrors itself (it is drawn for one side)
|
||||
|
|
@ -105,5 +109,5 @@ lo, hi = M.bounds()
|
|||
print("HEIGHT", round(hi.z - lo.z, 2), "WIDTH", round(hi.x - lo.x, 2), "RAMS", {k: len(v["rams"]) for k, v in legs.items()})
|
||||
M.report_skeleton("seraph", body)
|
||||
M.field_views("seraph", t0, hero=(18.0, 3.0), rear=(180.0, 2.0), turns=(90,), samples=64, hero_size=(1600, 1920), joints=M.joint_points(body),
|
||||
hero_cam=dict(lens=45.0, eye=2.4, margin=0.72), rear_cam=dict(lens=70.0, eye=2.0, margin=0.76),
|
||||
solve=True, frames={k: host.matrix_world @ to_host for k, (host, to_host) in SEATS.items()}, # the hero and rear views stand at the cameras solved from the concept's marked joints
|
||||
masks={"hip_exposed": lambda name: name.startswith("Hip") and name.endswith((".gunmetal", ".machine")) or ".HipSlew" in name})
|
||||
|
|
|
|||
|
|
@ -6,7 +6,9 @@ VIEWS: per component (azimuth, elevation, margin, pitch of the part in degrees)
|
|||
The pauldron, chest and thigh plates are brokkr_kitbash.shell sheets (M.shell_action), cut by cut_many and framed by ribs:
|
||||
they are objects on the host, not geometry in the Build. Their rings are placed by fit.py from outlines traced on the
|
||||
sheet (concepts.json "outlines"), and compare.py scores each against its crop's traced mask (MASKS below)."""
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
from mathutils import Matrix, Vector
|
||||
import fit
|
||||
import mechlib as M
|
||||
|
|
@ -31,6 +33,7 @@ MASKS = {"pauldron": ARMOR, "chest": lambda name: name.endswith(".breast"), "thi
|
|||
"knee": lambda name: True, "foot": lambda name: True}
|
||||
MIRROR = Matrix.Diagonal((-1.0, 1.0, 1.0, 1.0))
|
||||
SECOND = {"pauldron": {"pauldron_rear": (180, -12, 0.85, 200.0)}} # a part's second scored view: {mask tag: (azimuth, elevation, margin, lens)}; the rear view's camera stands far off
|
||||
SOLVED = {"chest": ("Chest", "chest")} # parts benched where they stand in the build and seen by the solved hero camera: {part: (component of seraph.py, crop of concepts.json "components")}
|
||||
FRAMES = {"pauldron": (-118, -14, 0.6, ("pauldron.gunmetal", "pauldron.shield"))} # (azimuth, elevation, margin, objects hidden): a second bench view, from inboard and below, of the frame a plate stands on
|
||||
|
||||
|
||||
|
|
@ -297,84 +300,65 @@ def block_sheet(front, back):
|
|||
*({"point": [i, j], "weight": 1.0} for i in (1, 2) for j in (1, 2))]} # a closed loop of creases rounds into a disc unless its corners are pinned
|
||||
|
||||
|
||||
LINES = {} # per component, the flow lines it carries as built: {line: [[x, y, z], ...]} in the component's frame (part_bench and seraph.py project them)
|
||||
LINES = {} # per component, flow lines given as points of its frame, for part_bench to project. The chest no longer exports any: its lines are measured on the built edges (mechlib.built_edges)
|
||||
FITS = json.loads((Path(__file__).resolve().parent / "fits.json").read_text(encoding="utf-8"))["seraph"] # shells fitted by fitshell.py through the solved hero camera
|
||||
|
||||
|
||||
def chest(b, torso=True):
|
||||
"""CHEST AND HEAD, one hunched shell. Origin 0.09 m above the shoulders' axis, on the centre plane; the breast's
|
||||
lower edge is z = -0.7, the cowl's crown z = 1.78. One brokkr_kitbash.shell, mirrored: rings from the sternum up
|
||||
the breast's front (placed by fit.wrap from the crop's traced outline), back up the upper slope to the rim of the
|
||||
cockpit's recess, across a shelf, up the cowl's face, which overhangs it, and over a low dome to the back of the
|
||||
head. The centre panel's two creases run the whole way, sternum to crown, and stand on the operator's two chest
|
||||
lines (fit.band, images/33.webp): LINES["chest"] holds them as built. Every facet is planar. Cut into it: the
|
||||
cockpit's slit through the cowl's face, a hatch on the upper slope, a break under the number, a ring mark. In
|
||||
the slit a dark face with two slanted amber eyes. Either side a collar plate rising to the shoulder with a
|
||||
sensor box on it (objects of their own: the crop's traced mask is the shell). On the mech's left a boxed
|
||||
pectoral block standing proud; five vent teeth under the front edge; a sternum block; the dark abdomen column
|
||||
with three lames and a ribbed hose each side. `torso` False: the cowl, shelf and face alone (the cockpit inset)."""
|
||||
"""CHEST AND HEAD, one hunched shell. Origin 0.09 m above the shoulders' axis, on the centre plane. One
|
||||
brokkr_kitbash.shell, mirrored, whose rings fitshell.py placed (fits.json "chest"): the centre plate's edge is
|
||||
the operator's two chest lines (images/33.webp) lifted as a mirrored pair through the solved hero camera, a
|
||||
long arc from the low sternum (z -1.5, 1.34 m forward) back and up to the cowl (z 1.2, behind the shoulders'
|
||||
axis), then over the crown to the nape; the plate stands 0.08 m proud of the facets beside it, so its edge is
|
||||
a ridge from sternum to crown; the breast's facets run out and back to a corner and a flank. Cut into it: the
|
||||
head's recess under the cowl, a hatch, a break under the number, a ring mark. In the recess a dark head with
|
||||
two slanted amber eyes. Either side a collar plate rising to the shoulder with a sensor box on it (objects of
|
||||
their own: the crop's traced mask is the shell). On the mech's left breast a boxed pectoral block standing
|
||||
proud; five vent teeth under the front edge; a sternum block; the dark abdomen column with a ribbed hose each
|
||||
side. `torso` False: the cowl and the head alone (the cockpit inset)."""
|
||||
k, d = b["khaki"], b["gunmetal"]
|
||||
front, side, az, el = fit.load("seraph", "chest.breast")
|
||||
rings = fit.wrap(front, side, az, el, [(-0.7, 1.25, -0.4), (-0.3, 1.15), 0.1, 0.45, (0.75, 0.94), (0.95, 0.8, 0.88)], flat=0.42, chamfer=0.3, flare=0.06)
|
||||
rings = [[list(p) for p in ring] for ring in FITS["chest"]["rings"]]
|
||||
if not torso:
|
||||
rings = rings[4:]
|
||||
# the cowl: (z, the centre's y, the corner's x and y, the side's rear x and y)
|
||||
for z, yc, cx, cy, fx, fy in ((1.2, 0.47, 0.7, 0.47, 0.84, -0.4), (1.6, 0.1, 0.56, 0.02, 0.7, -0.5), (1.76, -0.4, 0.46, -0.45, 0.58, -0.75), (1.68, -0.95, 0.44, -0.98, 0.57, -1.05)):
|
||||
rings.append([[0.0, yc, z], [0.3, yc, z], [cx, cy, z], [fx, fy, z]])
|
||||
half = fit.band("seraph", "chest_r", "chest_l", "chest.breast")
|
||||
v = [fit.seen(ring[0], az, el)[1] for ring in rings]
|
||||
crown = max(range(len(v)), key=lambda i: v[i])
|
||||
for i, ring in enumerate(rings): # the crease column stands on the two lines, which run from 0.2 to 0.92 of the shell's height in the view; the panel stands 0.07 m proud of the facet beside it
|
||||
t = (v[min(i, crown)] - v[0]) / (v[crown] - v[0]) if torso else 0.6 + 0.4 * min(i, crown) / max(crown, 1)
|
||||
ring[1][0] = half((t - 0.2) / 0.72)
|
||||
out = Vector(ring[2]) - Vector(ring[1])
|
||||
proud = 0.09 * min(1.0, (len(rings) - 5 - i) / 2) # the panel's step dies out at the recess's rim
|
||||
ring.insert(2, list(Vector(ring[1]) + out.normalized() * 0.14 + Vector((0, -proud, 0)) if proud > 0 else Vector(ring[1]) + out * (0.3 if proud == 0 else 0.5)))
|
||||
LINES[b.name.lower() if b.name.lower() in ("chest", "cockpit") else "chest"] = {"chest_r": [list(r[1]) for r in rings[:-2]], "chest_l": [[-r[1][0], r[1][1], r[1][2]] for r in rings[:-2]]}
|
||||
rings = rings[5:]
|
||||
shell = {"mirror": True, "flip": True, "rings": rings, "creases": fit.creased(rings, skip_rings=(len(rings) - 2,))} # the crown is left round: a hard ring there folds the wall
|
||||
name = b.name + ".breast"
|
||||
M.shell_action(name, shell, b, "khaki", thickness=0.07, levels=1, bevel=0.014)
|
||||
cuts = [{"name": name + ".slit", "part": "box", "params": "width=1.04; height=0.16; depth=0.05", "origin": [0, 3, 1.08], "direction": [0, -1, 0]}] # a recess in the cowl's face; the visor stands in it
|
||||
slope = Vector((0, 0.79, 0.62)) # the plate's normal under the cowl
|
||||
cuts = [{"name": name + ".recess", "part": "box", "params": "width=1.0; height=0.4; depth=0.05", "origin": list(Vector((0, 0.2, 0.8)) + 2 * slope), "direction": list(-slope)}] # the head's recess, through the wall: the dark gap the sheet draws between breast and cowl
|
||||
if torso:
|
||||
cuts += [{"name": name + ".hatch", "part": "box", "params": "width=0.3; height=0.22; depth=0.03", "origin": [0, 3, 0.7], "direction": [0, -1, 0]},
|
||||
{"name": name + ".break", "part": "slab", "params": "gap=0.025; length=0.36; depth=0.03", "origin": [0, 3, -0.4], "direction": [0, -1, 0], "up": [1, 0, 0]},
|
||||
{"name": name + ".mark", "part": "cyl", "params": "r=0.075; depth=0.025", "origin": [0.62, 3, 0.05], "direction": [0, -1, 0]}]
|
||||
cuts += [{"name": name + ".hatch", "part": "box", "params": "width=0.3; height=0.22; depth=0.03", "origin": [0, 3, -0.1], "direction": [0, -1, -0.3]},
|
||||
{"name": name + ".break", "part": "slab", "params": "gap=0.025; length=0.36; depth=0.03", "origin": [0, 3, -1.1], "direction": [0, -1, 0], "up": [1, 0, 0]}]
|
||||
M.cuts_action(name, cuts)
|
||||
visor = F((0, 0.5, 1.08), (0, 1, 0.32), (0, 0, 1)) # the dark visor in the recess, two slanted amber eyes on it
|
||||
d.box(visor @ T((0, 0, -0.03)), (1.0, 0.2, 0.06))
|
||||
head = F((0, 0.02, 0.74), tuple(slope), (0, 0, 1)) # the dark head in the recess, two slanted amber eyes on it
|
||||
d.box(head @ T((0, 0, -0.14)), (1.6, 0.46, 0.2))
|
||||
for s in (-1, 1):
|
||||
b[amber()].box(visor @ T((s * 0.26, 0, 0.0)) @ RZ(-10 * s), (0.3, 0.05, 0.02))
|
||||
b[amber()].box(head @ T((s * 0.3, 0, -0.03)) @ RZ(-10 * s), (0.34, 0.06, 0.02))
|
||||
if not torso:
|
||||
return
|
||||
collar = b["khaki:collar"]
|
||||
collar.hull([(0.52, -0.9, 0.7), (0.4, -1.25, 0.7), (0.5, -0.9, 1.62), (0.36, -1.2, 1.5)], mirror=True) # the nape: the cowl is open behind
|
||||
collar.hull([(0.8, -1.2, 0.7), (0.5, -1.7, 0.7), (0.8, -1.3, 1.5), (0.5, -1.85, 1.45)], mirror=True) # the nape: the cowl is open behind
|
||||
for s in (-1, 1): # a collar plate rising to each shoulder, a sensor box on it
|
||||
collar.hull([(s * 0.84, 0.4, 1.02), (s * 1.75, 0.3, 1.18), (s * 1.75, -0.7, 1.26), (s * 0.84, -0.72, 1.12),
|
||||
(s * 0.84, 0.62, 0.6), (s * 1.9, 0.42, 0.62), (s * 1.9, -0.75, 0.62), (s * 0.84, -0.75, 0.6)])
|
||||
collar.hull([(s * (1.42 + dx), -0.3 + dy, 1.2 + dz) for dx, dy, dz in ((-0.22, -0.26, -0.15), (0.22, -0.26, -0.15), (-0.22, 0.26, -0.15), (0.22, 0.26, -0.15), (-0.2, -0.24, 0.6), (0.2, -0.24, 0.6), (-0.2, 0.2, 0.55), (0.2, 0.2, 0.55))])
|
||||
d.box(T((s * 1.42, -0.07, 1.52)), (0.26, 0.06, 0.26))
|
||||
yf = rings[1][0][1]
|
||||
hw = rings[1][3][0]
|
||||
block = b.name + ".pectoral" # the left pectoral block
|
||||
M.shell_action(block, block_sheet([[(-hw - 0.08, yf + 0.16, -0.3), (-hw - 0.7, yf - 0.2, -0.32)], [(-hw - 0.1, yf + 0.1, 0.26), (-hw - 0.7, yf - 0.26, 0.24)]],
|
||||
[[(-hw, yf - 0.2, -0.42), (-hw - 0.86, yf - 0.7, -0.44)], [(-hw - 0.02, yf - 0.3, 0.38), (-hw - 0.86, yf - 0.8, 0.36)]]), b, "khaki", thickness=0.08, levels=1, bevel=0.012)
|
||||
y0 = rings[0][0][1]
|
||||
collar.hull([(s * 0.9, -0.1, 0.62), (s * 1.8, -0.2, 0.7), (s * 1.8, -0.95, 0.78), (s * 0.9, -0.95, 0.7),
|
||||
(s * 0.9, 0.1, 0.3), (s * 1.9, 0.0, 0.32), (s * 1.9, -1.0, 0.32), (s * 0.9, -1.0, 0.3)]) # low and behind the breast's top edge: the sheet shows the shoulder ring past it
|
||||
collar.hull([(s * (1.5 + dx), -0.65 + dy, 0.75 + dz) for dx, dy, dz in ((-0.2, -0.24, -0.1), (0.2, -0.24, -0.1), (-0.2, 0.24, -0.1), (0.2, 0.24, -0.1), (-0.18, -0.22, 0.75), (0.18, -0.22, 0.75), (-0.18, 0.18, 0.7), (0.18, 0.18, 0.7))])
|
||||
d.box(T((s * 1.5, -0.44, 1.2)), (0.24, 0.06, 0.24))
|
||||
left = lambda i, t: Vector((-1, 1, 1)) * Vector(rings[i][2]).lerp(Vector(rings[i][3]), t) # noqa: E731 a point of the left breast's facet: ring i, t from the step (0) to the corner (1)
|
||||
out = (left(1, 0.5) - left(3, 0.5)).cross(left(1, 1.0) - left(1, 0.0)).normalized()
|
||||
out = out if out.y > 0 else -out
|
||||
block = b.name + ".pectoral" # the left pectoral block, on the facet's outer half
|
||||
M.shell_action(block, block_sheet([[left(1, 0.5) + out * 0.2, left(1, 0.98) + out * 0.2], [left(3, 0.5) + out * 0.2, left(3, 0.92) + out * 0.2]],
|
||||
[[left(1, 0.38) - out * 0.02, left(1, 1.1) - out * 0.12], [left(3, 0.38) - out * 0.02, left(3, 1.04) - out * 0.12]]), b, "khaki", thickness=0.05, levels=1, bevel=0.012)
|
||||
(_, y0, z0), w0 = rings[0][0], rings[0][1][0]
|
||||
for j in range(5):
|
||||
k.box(T((-0.44 + 0.22 * j, y0 - 0.1, -0.78)), (0.13, 0.12, 0.14))
|
||||
d.box(T((0, y0 - 0.18, -0.78)), (1.1, 0.1, 0.12))
|
||||
sternum = lambda x0, y_0, z0, x1, y1, z1: {"mirror": True, "flip": True, "rings": [ # noqa: E731 a hung block: a front face and a flank each side
|
||||
[[0, y1, z1], [x1, y1, z1], [x1, 0.5, z1]], [[0, y_0, z0], [x0, y_0, z0], [x0, 0.5, z0]]], "creases": [{"column": 1, "from": 0, "to": 1, "weight": 1.0}]}
|
||||
w0 = rings[0][1][0]
|
||||
M.shell_action(b.name + ".sternum", sternum(w0 + 0.2, y0 - 0.1, -0.7, w0 + 0.12, y0 - 0.2, -1.12), b, "khaki", thickness=0.12, levels=1, bevel=0.012) # its edges carry the centre panel's creases on down
|
||||
k.box(T((-0.44 + 0.22 * j, y0 - 0.1, z0 - 0.08)), (0.13, 0.12, 0.14))
|
||||
d.box(T((0, y0 - 0.18, z0 - 0.08)), (1.1, 0.1, 0.12))
|
||||
sternum = lambda x0, y_0, z_0, x1, y1, z1: {"mirror": True, "flip": True, "rings": [ # noqa: E731 a hung block: a front face and a flank each side
|
||||
[[0, y1, z1], [x1, y1, z1], [x1, 0.5, z1]], [[0, y_0, z_0], [x0, y_0, z_0], [x0, 0.5, z_0]]], "creases": [{"column": 1, "from": 0, "to": 1, "weight": 1.0}]}
|
||||
M.shell_action(b.name + ".sternum", sternum(w0 + 0.14, y0 - 0.1, z0, w0 + 0.08, y0 - 0.22, z0 - 0.42), b, "khaki", thickness=0.12, levels=1, bevel=0.012) # its edges carry the centre plate's edges on down
|
||||
d.hull([(0.6, -0.5, -0.4), (0.6, 0.75, -0.4), (0.45, -0.4, -2.3), (0.45, 0.6, -2.3)], mirror=True) # the abdomen column
|
||||
for j in range(3):
|
||||
z = -1.36 - 0.3 * j
|
||||
lame = {"mirror": True, "flip": True, "rings": [[[0, 0.86 - 0.05 * j, z - 0.24], [0.32 - 0.03 * j, 0.86 - 0.05 * j, z - 0.24], [0.32 - 0.03 * j, 0.5, z - 0.26]],
|
||||
[[0, 0.92 - 0.05 * j, z + 0.02], [0.36 - 0.03 * j, 0.92 - 0.05 * j, z + 0.02], [0.36 - 0.03 * j, 0.5, z]]],
|
||||
"creases": [{"column": 1, "from": 0, "to": 1, "weight": 1.0}]}
|
||||
M.shell_action(f"{b.name}.lame{j}", lame, b, "khaki", thickness=0.06, levels=1, bevel=0.01)
|
||||
for s in (-1, 1):
|
||||
corrugated(d, [(s * 0.95, 0.7, -0.5), (s * 0.85, 0.9, -0.95), (s * 0.62, 0.86, -1.5), (s * 0.5, 0.66, -2.0)], 0.13)
|
||||
corrugated(d, [(s * 1.25, 0.5, -0.5), (s * 1.1, 0.62, -1.1), (s * 0.7, 0.5, -1.9)], 0.09)
|
||||
corrugated(d, [(s * 0.9, 0.6, z0 + 0.1), (s * 0.85, 0.88, z0 - 0.25), (s * 0.62, 0.84, z0 - 0.5), (s * 0.5, 0.64, z0 - 0.72)], 0.13)
|
||||
corrugated(d, [(s * 1.15, 0.4, z0 + 0.1), (s * 1.0, 0.6, z0 - 0.3), (s * 0.7, 0.5, z0 - 0.6)], 0.09)
|
||||
|
||||
|
||||
def pauldron(b, arm=False):
|
||||
|
|
|
|||
Loading…
Reference in a new issue