Paladin (sheet 27), second pass: a kit skeleton whose every joint is a pin with a record (bipedkit.py; kit parts hipbeam and trunk; feet.paladin_hoof under a cross ankle; 35 joints, all with limits); thighs, shins, pauldrons, upper arms and the left forearm as free-cage plates of 2N + 1 vertices (platecage.py), 16 of 71 blocked from edges traced on the sheet and passed through brokkr_reference's fit, the rest mirrored or derived from them as base plates, blocks and lames; pauldrons with sloped shield faces; the cameras solved on the kit's joints with no horizon held; surface.Skin detail pass; paint.apply("paladin"); plates and before/after sheets

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-12-03 07:57:54 +01:00
commit e68895113b
19 changed files with 3210 additions and 594 deletions

View file

@ -0,0 +1,121 @@
"""A biped whose every joint is a kit pin with a joint record. Runs inside Blender beside mechlib.
mechlib.biped hangs each leg on a slew ring's flange, and a flange is a rigid socket: brokkr_kitbash.joint refuses it,
so that skeleton reports no hip, waist or shoulder. Here every degree of freedom rides a `pivot` socket (the kit's
revolute type), so brokkr_kitbash.joints reports the whole figure and brokkr_kitbash.roll drives it inside limits.
Ruling aetheria-release:ruling:mech-joints-match-concept-mechanically.
The kit (gen_kit.py) holds the two parts this needs beside link, cross and feet.py's foot_core:
hipbeam the root: hip_l, hip_r (fore-and-aft pins: splay) and waist (a vertical pin: the torso's yaw)
trunk base on the waist pin; shoulder_l, shoulder_r (fore-and-aft pins: abduction)
A limb is cross -> link -> link: the cross swings on the root's fore-and-aft pin (splay or abduction) and carries the
upper link on its own cross pin (pitch); the lower link hinges on the upper's clevis (knee or elbow). An ankle is a
second cross (pitch, then roll) under the shin, carrying a feet.py foot by tongue_roll.
record(obj, mechanism, lo, hi, toward) brokkr_kitbash.joint: limits lo..hi degrees about the roll the part stands
at, positive swinging its far end toward a world direction
limb(tag, parent, socket, points, lengths, girth, pin_r, cross, names, limits) -> {cross, upper, lower}
ankle(tag, shin, foot, drop, pin_r, limits) -> the ankle's cross
frame(part) a link's authoring frame in the world: origin on its proximal pin, z up the
link, y forward, x to the mech's right (the kit's own is z down the link)
adopt(host, objects) parent finished world-space objects to a kit part, where they stand
joints(root) the kit's joints report (brokkr.joints version 1) of the tree under root
"""
import json
import bpy
from mathutils import Matrix, Vector
import mechlib as M
TURN = Matrix.Diagonal((-1.0, 1.0, -1.0, 1.0)) # half a turn about y: the kit link's frame to the authoring frame
def record(obj, mechanism, lo, hi, toward=None):
"""Limits lo..hi degrees about the roll the part stands at. With `toward` (a world direction) positive is the
sense that swings the part's far end (its own +z) that way; without, it is the roll's own sense."""
roll = float(obj["kit_roll"])
if toward is not None:
M.update()
before = obj.matrix_world.to_3x3() @ Vector((0, 0, 1))
M.reroll(obj, roll + 2.0)
after = obj.matrix_world.to_3x3() @ Vector((0, 0, 1))
M.reroll(obj, roll)
if (after - before).dot(Vector(toward)) < 0:
lo, hi = -hi, -lo
roll = float(obj["kit_roll"])
a, b = roll + lo, roll + hi
while b > 360.0:
a, b = a - 360.0, b - 360.0
while a < -360.0:
a, b = a + 360.0, b + 360.0
if "FINISHED" not in bpy.ops.brokkr_kitbash.joint(object_name=obj.name, record=json.dumps({"limits": [a, b], "mechanism": mechanism})):
raise SystemExit(f"joint record {obj.name} refused")
obj["bk_rest"] = roll
return obj
def limb(tag, parent, socket, points, lengths, girth, pin_r, cross=(0.3, 0.5), names=("hip_splay", "hip_pitch", "knee"),
limits=((-12, 25), (-60, 40), (-100, 5)), toward=(None, None, None), mat="frame", splay_at=0):
"""points: the world points the cross, the upper link and the lower link each aim their length at (the upper
pin's side of the mid joint, the mid joint, the end joint). lengths (upper, lower); girth [(width, depth)] * 2. The whole limb lies in one
plane through the root pin: `splay_at` says which point that plane is turned to pass through (0 the mid joint, 1 the end)."""
mid, end = (Vector(p) for p in points)
cr = M.attach(M.place("cross", f"{tag}.Cross", mat="machine", drop=cross[0], width=cross[1], pin_r=pin_r), "tongue", parent, socket)
M.aim_roll(cr, (0, 0, 1), (mid, end)[splay_at] - cr.matrix_world.translation) # the limb's plane passes through this point
record(cr, names[0], *limits[0], toward=toward[0])
up = M.attach(M.place("link", f"{tag}.Upper", mat=mat, length=lengths[0], width=girth[0][0], depth=girth[0][1], pin_r=pin_r), "tongue", cr, "clevis")
M.aim_roll(up, (0, 0, 1), mid - up.matrix_world.translation)
record(up, names[1], *limits[1], toward=toward[1])
lo = M.attach(M.place("link", f"{tag}.Lower", mat=mat, length=lengths[1], width=girth[1][0], depth=girth[1][1], pin_r=pin_r), "tongue", up, "clevis")
M.aim_roll(lo, (0, 0, 1), end - lo.matrix_world.translation)
record(lo, names[2], *limits[2], toward=toward[2])
return {"cross": cr, "upper": up, "lower": lo}
def ankle(tag, shin, foot_core, drop, pin_r, width, limits=((-35, 35), (-15, 15))):
cr = M.attach(M.place("cross", f"{tag}.Ankle", mat="machine", drop=drop, width=width, pin_r=pin_r), "tongue", shin, "clevis")
M.aim_roll(cr, (0, 0, 1), (0, 0, -1))
record(cr, "ankle_pitch", *limits[0])
M.attach(foot_core, "tongue_roll", cr, "clevis")
M.aim_roll(foot_core, (0, 0, 1), (0, 0, -1))
record(foot_core, "ankle_roll", *limits[1])
return cr
def frame(part):
M.update()
return part.matrix_world @ TURN
def adopt(host, objects):
M.update()
inv = host.matrix_world.inverted()
for o in objects:
if o.parent is None and o is not host:
world = o.matrix_world.copy()
o.parent = host
o.matrix_parent_inverse = Matrix.Identity(4)
o.matrix_basis = inv @ world
M.update()
class Adopt:
"""with Adopt(host): everything made inside, left without a parent, is parented to the kit part where it stands."""
def __init__(self, host):
self.host = host
def __enter__(self):
self.before = set(bpy.data.objects)
return self
def __exit__(self, *exc):
if exc[0] is None:
adopt(self.host, [o for o in bpy.data.objects if o not in self.before and not o.get("stage")])
def joints(root):
bpy.ops.brokkr_kitbash.joints(object_name=root.name)
return json.loads(getattr(bpy.context.window_manager, "brokkr_mesh_polish_result"))

View file

@ -0,0 +1,731 @@
"""Articulated feet for the mech builds, one per concept sheet (23 to 31 and 34): toes of one to three segments, each
on its own hinge, splay hinges where the toes fan, heel spurs and rear toes, toe rams, stepped armour over the
segments. Ruling aetheria-release:ruling:mech-toes-articulated.
Who owns what. The joints are the kit's: a foot is a tree of kit parts (kit mech: foot_core, toe_knuckle, link, toe)
seated on pivot sockets, and every hinge carries a kit joint record (brokkr_kitbash.joint: limits, a mechanism label
toe_pitch or toe_splay), so brokkr_kitbash.joints reports the foot and a walk drives it with brokkr_kitbash.roll.
The rams are ram core's (brokkr_kitbash/ram.py): seats come from ram.search over a grid on the two parts' backs,
its clearance gate reading the dress through ram.Signed, and the mechanism record it writes is kept on the driven part as the JSON property feet_ram, in the driving part's frame.
The armour, housings, hinge barrels and soles are this module's: jointlib.Link geometry authored in the frame of the
kit part that carries it and parented to it, so it follows any pose. Rams are drawn at the pose (Foot.draw_rams).
A foot is a drop-in for the kit's foot, talon and trident: its root is a foot_core, which takes (width, length, drop,
pin_r), stands on the ankle pin by `tongue` (or `tongue_roll` under a cross ankle) and carries their instep and heel
sockets. mechlib.leg and humanoid seat a foot with attach(foot, "tongue", shin, "clevis"); every function here takes
the shin and that socket and does the same (shin None: the caller seats Foot.core, as under a cross ankle).
feet_dropin.py checks both against the kit's talon.
Foot(name, dims, toes, shin, socket) the kit tree at rest: flat on the ground, toes fanned as the concept plants them
T(at, yaw, segs, ...) one toe: where its splay pin stands on the core, its heading, its segments
Foot.armour / housing / mass / pbox / drums dress, in the part's frame (the core's in plan coordinates)
Foot.ram(i, j, bore) a ram across a pitch joint, seated at done() clear of all the dress
Foot.level(pitch) the ankle: the core nose down by pitch degrees
Foot.drive(roll, strike, splay, curl) the walk's four inputs, written to the kit joints inside their limits
Foot.done() objects made, rams drawn; Foot.report() is the kit's joints report and the rams
FEET the concept feet, registered by @concept with their crop and view
Conventions: a pitch joint's roll is positive lifting the toe. A toe's authored yaw is its heading when planted
(degrees from the foot's front toward the core's +x); `splay` is how far it closes inward from there. Plan
coordinates are (x, y, height above the ground) in the core's frame.
"""
import json
import math
import bpy
import numpy as np
from mathutils import Matrix, Vector
import jointlib as J
import mechlib as M
from jointlib import X, Y, Z
TOES = "abcdef"
FEET = {}
_RAM = None
def ramcore():
"""brokkr_kitbash/ram.py of the add-on tree mechlib.setup() enabled."""
global _RAM
if _RAM is None:
from brokkr_kitbash import ram
_RAM = ram
return _RAM
def concept(sheet, number, crop, view=(40.0, 14.0), variant=None, dims=None):
"""Register a concept foot: the sheet's name and number, its crop of the sheet (pixels), the catalog view
(azimuth, elevation), a parameter variant for the catalog and its default (width, length, drop, pin_r)."""
def wrap(fn):
FEET[fn.__name__] = {"fn": fn, "sheet": sheet, "number": number, "crop": crop, "view": view, "variant": variant or {}, "dims": dims}
return fn
return wrap
def T(at, yaw=0.0, segs=(), role="front", splay=0.0, lim=None, fall=None, reach=None, pad=None):
"""One toe. at: its splay pin on the core (x, y); yaw: its heading planted; segs: (length, width, depth) per
segment, root first; role: front or rear; splay: degrees it closes inward on a splay hinge (0: a fixed seat);
lim: (lo, hi) degrees about rest per pitch joint; fall: the share of the drop to the ground each segment but
the last takes (the last lies flat)."""
return {"at": at, "yaw": yaw, "dims": [tuple(s) for s in segs], "role": role, "splay": splay, "lim": lim, "fall": fall, "reach": reach, "pad": pad}
class Dress(J.Link):
"""Geometry in one kit part's own frame, parented to it."""
def __init__(self, foot, part):
super().__init__(foot, part.name)
self.part = part
def make(self, bevel):
made = []
for (mat, tag), geo in self.geos.items():
if not len(geo.bm.verts):
continue
armour = mat in J.ARMOR
obj = geo.to_object(f"{self.part.name}.{mat}.{tag}", mat, self.part, 12.0 if armour else 38.0)
obj["tag"], obj["mat"] = tag, mat
if armour: # faceted: a bevel's faces would be shaded round across a smooth hull
obj.data.polygons.foreach_set("use_smooth", [False] * len(obj.data.polygons))
if armour and bevel:
mod = obj.modifiers.new("Bevel", "BEVEL")
mod.width, mod.segments, mod.limit_method, mod.angle_limit = bevel, 1, "ANGLE", math.radians(18)
made.append(obj)
self.geos = {}
return made
class _Fit:
"""A ram core Fit as jointlib._draw_ram reads one."""
def __init__(self, fit):
self.fit, self.ram, self.axis, self.barrel = fit, fit.ram, tuple(fit.m.axis), fit.barrel
def at(self, degrees):
ram = ramcore()
p = ram.pose(self.fit.m, degrees)
return {"base": p.base[0], "eye": p.eye[0], "dir": p.u[0], "length": float(p.L[0]), "extension": float(ram.extension(self.fit.m, self.ram, degrees)[0])}
class Foot:
def __init__(self, name, dims, toes, shin=None, socket="clevis", toe_pin=None, toe_h=None, plate="olive", plate2="olive_light", pad=None):
self.name, self.dims = name, dims
self.w, self.l, self.d, self.pin = dims
self.tp = tp = toe_pin or 0.42 * self.pin
self.pad = pad if pad is not None else 0.04 * self.d
self.plate, self.plate2 = plate, plate2
self.dress, self.joints, self.drives, self.rams, self.notes, self.asked = {}, {}, [], [], [], []
self.objects, self.ram_objects, self.clashes = [], [], []
if len(toes) > len(TOES):
raise ValueError(f"{name}: a foot_core carries {len(TOES)} toes, got {len(toes)}")
if toe_h is None: # a one-segment front toe lies flat: the pins stand just above the ground
first = next((t for t in toes if t["role"] == "front"), toes[0])
toe_h = 1.0 - (first["dims"][-1][2] / 2 + self.pad + 1.6 * tp) / self.d if len(first["dims"]) == 1 else 0.5
self.toe_h = toe_h = max(0.15, min(0.95, toe_h))
pins = {f"t{TOES[i]}{c}": t["at"][j] for i, t in enumerate(toes) for j, c in enumerate("xy")}
self.core = M.place("foot_core", name, mat="gunmetal", width=self.w, length=self.l, drop=self.d, pin_r=self.pin, toe_pin_r=tp, toe_h=toe_h, **pins)
if shin is not None:
M.attach(self.core, "tongue", shin, socket, 0.0)
self.hk = self.d * (1.0 - toe_h) - 1.6 * tp # the first pitch pins' height above the ground
self.toes = [self._toe(i, dict(t)) for i, t in enumerate(toes)]
# -- the kit tree -----------------------------------------------------------------------------------------
def _joint(self, name, obj, kind, rest, lo, hi):
bpy.ops.brokkr_kitbash.joint(object_name=obj.name, record=json.dumps({"limits": [lo, hi], "mechanism": f"toe_{kind}"}))
self.joints[name] = {"obj": obj, "kind": kind, "rest": rest, "lo": lo, "hi": hi}
def _toe(self, i, t):
tp, key, dims = self.tp, TOES[i], t["dims"]
n, pad = len(dims), t["pad"] if t["pad"] is not None else self.pad
t["pad"], t["i"] = pad, i
t["reach"] = reach = t["reach"] or 2.6 * tp
x, yaw = t["at"][0], t["yaw"]
side = 1 if x > 1e-6 else -1 if x < -1e-6 else 0
t["out"] = out = side if abs((yaw + 180.0) % 360.0 - 180.0) < 90.0 else -side
kn = M.place("toe_knuckle", f"{self.name}.Toe{i}.Knuckle", mat="gunmetal", pin_r=tp, reach=reach, width=dims[0][1])
if t["splay"] and out:
M.attach(kn, "splay", self.core, f"toe_{key}", -yaw)
closed = -(yaw - out * t["splay"])
self._joint(f"toe{i}.splay", kn, "splay", -yaw, min(-yaw, closed), max(-yaw, closed))
else:
t["splay"] = 0.0
M.attach(kn, "seat", self.core, f"seat_{key}", -yaw)
t["knuckle"] = kn
last = dims[-1]
if n == 1: # one segment: it slopes until its tip's sole meets the ground
lo_a, hi_a = -0.6, 1.2
for _ in range(40):
a = (lo_a + hi_a) / 2
if self.hk - 0.92 * last[0] * math.sin(a) - (last[2] / 2 + pad) * math.cos(a) > 0:
lo_a = a
else:
hi_a = a
alphas = [a]
else: # the last lies flat; the others share the drop to it
drop = self.hk - (last[2] / 2 + pad)
fall = t["fall"] or [d[0] for d in dims[:-1]]
alphas = [math.asin(max(-0.9, min(0.9, f / sum(fall) * drop / d[0]))) for f, d in zip(fall, dims[:-1])] + [0.0]
t["alphas"] = alphas
rest = [-math.degrees(alphas[0])] + [math.degrees(alphas[k - 1] - alphas[k]) for k in range(1, n)]
lim = t["lim"] or [(-10.0, 30.0)] * (n - 1) + [(-12.0, 48.0)]
t["rest"], t["lim"], t["segs"] = rest, lim, []
parent = kn
for k, (length, width, depth) in enumerate(dims):
seg = M.place("toe" if k == n - 1 else "link", f"{self.name}.Toe{i}.Seg{k}", mat="gunmetal", length=length, width=width, depth=depth, pin_r=tp)
M.attach(seg, "tongue", parent, "clevis", rest[k])
self._joint(f"toe{i}.pitch{k}", seg, "pitch", rest[k], rest[k] + lim[k][0], rest[k] + lim[k][1])
t["segs"].append(seg)
parent = seg
return t
def set(self, name, value):
"""Write a joint, `value` degrees from rest, held inside its limits. Returns what was written."""
j = self.joints[name]
roll = max(j["lo"], min(j["hi"], j["rest"] + value))
M.reroll(j["obj"], roll)
return roll - j["rest"]
def level(self, pitch=0.0):
"""Turn the core about the ankle pin until its sole faces down, then `pitch` degrees nose down."""
M.update()
fwd = self.core.matrix_world.to_3x3() @ Y
fwd.z = 0.0
fwd.normalize()
a = math.radians(pitch)
return M.aim_roll(self.core, (0, 0, 1), -Z * math.cos(a) - fwd * math.sin(a))
def drive(self, roll=0.0, strike=0.0, splay=1.0, curl=0.0):
"""The walk's inputs, in degrees. roll: toe roll at push-off, the heel risen that far over toes that stay
on the ground (the last pitch joint takes most, the one before it the rest). strike: the heel-first
landing, the core nose up that far: the rear toes stay flat and the front toes cock up. splay: 0 closed
to 1 fanned. curl: every toe's first joint, positive lifting. The caller pitches the core (level)."""
for t in self.toes:
n, i = len(t["segs"]), t["i"]
add = [0.0] * n
if t["role"] == "front":
share = (1.0,) if n == 1 else (0.3, 0.7) if n == 2 else (0.0,) * (n - 2) + (0.35, 0.65)
for k in range(n):
add[k] += roll * share[k]
add[0] += 0.5 * strike
else:
add[-1] += strike
add[0] -= 0.25 * roll
add[0] += curl
for k in range(n):
self.set(f"toe{i}.pitch{k}", add[k])
if t["splay"]:
self.set(f"toe{i}.splay", t["out"] * t["splay"] * (1.0 - splay))
if self.objects:
self.draw_rams()
# -- dress ------------------------------------------------------------------------------------------------
def on(self, part):
if part.name not in self.dress:
self.dress[part.name] = Dress(self, part)
return self.dress[part.name]
def plan(self, x, y, h):
return Vector((x, y, self.d - h))
def mass(self, mat, points, mirror=True, tag="body"):
"""A faceted block on the core: the hull of plan points (and their mirrors)."""
self.on(self.core).hull(mat, [self.plan(*p) for p in points], mirror, tag)
def pbox(self, mat, centre, size, ch=0.0, yaw=0.0, tag="body"):
"""A block on the core, in plan coordinates: size is (x, y, height), its top rim chamfered."""
rot = Matrix.Rotation(math.radians(-yaw), 4, "Z") @ Matrix.Rotation(math.pi, 4, "X")
self.on(self.core).box(mat, self.plan(*centre), size, ch, rot, tag)
def drums(self, r, x, width, cap=0.8, bolts=8, mat="machine"):
"""The ankle's drums: a disc on the ankle pin either side of the core, capped."""
core = self.on(self.core)
for s in (-1, 1):
core.cyl(mat, (s * x, 0, 0), r, width)
if cap:
core.cap(mat, (s * (x + width / 2), 0, 0), r * cap, X * s, bolts=bolts)
def top_at(self, i, k, z):
"""The height of toe i's segment k armour above its pin axis at z along it."""
(z_r, y_r), (z_f, y_f) = self.toes[i]["line"][k]
return y_r + (y_f - y_r) * max(0.0, min(1.0, (z - z_r) / max(z_f - z_r, 1e-6))) + self.toes[i].get("plate", 0.0)
def armour(self, i, tops, widen=1.3, cap="block", tab=False, plate=0.0, mat=None, mat2=None, nose=0.35, tip=(0.6, 0.35), ch=None, barrel=0.9, treads=3,
sole="rubber", over=0.0):
"""Armour over toe i: per segment a faceted block from its sole to tops[k] = (rear, front) heights above
the pin axis, its end faces raked back from each hinge by half the joint's travel so two blocks close on
each other at the limit and no sooner (the first block's rear face is raked the same, which clears a
housing raked like it; against an instep mass above the pins it is not checked); a hinge barrel with bolted caps on every pin; an applique plate of
thickness `plate` on each back, a second step on its rear half; a sole pad with tread bars. The last
segment ends in a cap: block (a chamfered nose), claw (tapering to tip = (width, height) fractions) or
hoof (a block drawn in at the nose). tab: a steel wear tab let into the nose. over: the cap past the pin."""
t = self.toes[i]
n, mat, mat2 = len(t["segs"]), mat or self.plate, mat2 or self.plate2
t["line"], t["wa"], t["plate"] = [], [], 0.0
for k, seg in enumerate(t["segs"]):
length, width, depth = t["dims"][k]
wa, half = width * widen, width * widen / 2
c = ch if ch is not None else 0.1 * wa
dr, (top_r, top_f), (lo, hi) = self.on(seg), tops[k], t["lim"][k]
gap = 0.03 * length
rt, rb = math.tan(math.radians(hi) / 2), math.tan(math.radians(-lo) / 2)
z0 = gap
pts = [(half, -depth / 2, z0 + rb * depth / 2), (half, 0, z0), (half, top_r - c, z0 + rt * (top_r - c)), (half - c, top_r, z0 + rt * top_r)]
rear = (z0 + rt * top_r, top_r)
if k < n - 1:
lo2, hi2 = t["lim"][k + 1]
ft, fb, z1 = math.tan(math.radians(hi2) / 2), math.tan(math.radians(-lo2) / 2), length - gap
pts += [(half, -depth / 2, z1 - fb * depth / 2), (half, 0, z1), (half, top_f - c, z1 - ft * (top_f - c)), (half - c, top_f, z1 - ft * top_f)]
front = (z1 - ft * top_f, top_f)
else:
z1 = length * (1.0 + over)
zn = z1 - nose * length
if cap == "claw":
tw, th = tip[0] * half, -depth / 2 + tip[1] * (top_f + depth / 2)
pts += [(half, -depth / 2, zn), (half, top_f - c, zn), (half - c, top_f, zn), (tw, -depth / 2, z1), (tw, th - 0.3 * c, z1), (tw - 0.3 * c, th, z1)]
else:
nh = -depth / 2 + 0.5 * (top_f + depth / 2)
nw = half * (0.82 if cap == "hoof" else 1.0)
pts += [(half, -depth / 2, zn), (nw, -depth / 2, z1), (nw, nh - c, z1), (nw - c, nh, z1), (half, top_f - c, zn), (half - c, top_f, zn)]
if cap == "hoof":
pts += [(nw * 0.86, -depth / 2, z1 + 0.05 * length), (nw * 0.86, nh * 0.4 - depth * 0.3, z1 + 0.05 * length)]
front = (zn, top_f)
if tab:
dr.box("steel", (0, -depth / 2 + 0.16 * (top_f + depth / 2), z1 - 0.02 * length), (0.3 * wa, 0.3 * (top_f + depth / 2), 0.12 * length), tag="trim")
dr.box("gunmetal", (0, -depth / 2 + 0.42 * (top_f + depth / 2), z1 - 0.07 * length), (0.2 * wa, 0.08 * (top_f + depth / 2), 0.1 * length), tag="trim")
dr.hull(mat, pts, mirror=True)
t["line"].append((rear, front))
t["wa"].append(wa)
if plate:
t["plate"] = 0.0
span = front[0] - rear[0]
for z_a, z_b, thick, inset in ((rear[0] + 0.1 * span, front[0] - 0.08 * span, plate, 0.08), (rear[0] + 0.1 * span, rear[0] + 0.5 * span, 2.0 * plate, 0.16)):
px = half - c - inset * wa
y_a, y_b = self.top_at(i, k, z_a), self.top_at(i, k, z_b)
dr.hull(mat2, [(px, y_a - 0.01, z_a), (px, y_a + thick, z_a + 0.3 * thick), (px, y_b - 0.01, z_b), (px, y_b + thick, z_b - 0.3 * thick)], mirror=True, tag="trim")
t["plate"] = 2.0 * plate # what a ram's seat stands above
z_s0, z_s1 = z0 + 0.06 * length, (front[0] if k == n - 1 else z1) - 0.04 * length
pad = t["pad"]
if sole:
dr.g(sole, "trim").box(Matrix.Translation((0, -depth / 2 - 0.45 * pad, (z_s0 + z_s1) / 2)), (wa * 0.9, 0.9 * pad, z_s1 - z_s0))
for m in range(treads):
z_t = z_s0 + (z_s1 - z_s0) * (m + 0.5) / treads
dr.g("gunmetal", "trim").box(Matrix.Translation((0, -depth / 2 - 0.9 * pad, z_t)), (wa * 0.96, 0.22 * pad, 0.16 * (z_s1 - z_s0) / treads + 0.01))
if barrel:
r = barrel * 0.5 * min(depth, t["dims"][k - 1][2] if k else depth)
dr.cyl("machine", (0, 0, 0), r, wa * 1.03)
for s in (-1, 1):
dr.cap("machine", (s * wa * 0.515, 0, 0), r * 0.82, X * s, steps=((1.0, 0.16), (0.7, 0.26), (0.36, 0.34)), bolts=6)
def housing(self, i, horn=0.0, mat=None, widen=None, back=2.4):
"""Toe i's root: a block over its knuckle, from the pin's seat (or `horn` above it, where a ram's base
stands) to the toe's sole line, and on a splay hinge the pin's cap."""
t = self.toes[i]
tp, dr = self.tp, self.on(t["knuckle"])
wa = (widen * t["dims"][0][1]) if widen else t.get("wa", [t["dims"][0][1] * 1.3])[0]
half, c = wa / 2, 0.1 * wa
y_b, y_f = -(back + 3.0 * horn / max(wa, 1e-6)) * tp, t["reach"] - 0.2 * tp
z_t, z_b = -horn, 1.6 * tp + 0.42 * t["dims"][0][2]
lean = 0.45 * horn
dr.hull(mat or self.plate, [(half, y_b, z_t + c), (half - c, y_b, z_t), (half, y_f - lean, z_t + c), (half - c, y_f - lean, z_t), (half, y_f, min(z_t + c + 1.2 * lean, z_b)),
(half, y_b, z_b), (half, y_f, z_b)], mirror=True)
t["horn"] = horn
if t["splay"]:
dr.cyl("machine", (0, 0, z_t - 0.2 * tp), 2.4 * tp, 0.5 * tp, Z, 20, "trim")
dr.cyl("steel", (0, 0, z_t - 0.55 * tp), 1.1 * tp, 0.3 * tp, Z, 6, "trim")
def ram(self, i, j, bore, **how):
"""Ask for a ram across toe i's pitch joint j. It is seated when the foot is done, against all the dress
there is by then (_seat takes the rest: x, boot, mat, high, along, back, min_arm)."""
self.asked.append(dict(how, i=i, j=j, bore=bore))
def _shells(self, part, into):
"""The closed shells of a part's dress as authored so far, their vertices carried through `into`: what ram
core's distance oracle (ram.Signed) reads. Clevis seats are left out: a ram's own pins stand in them."""
out = []
dr = self.dress.get(part.name)
for (mat, tag), geo in (dr.geos.items() if dr else ()):
if tag == "seat":
continue
bm = geo.bm
bm.faces.ensure_lookup_table()
bm.faces.index_update()
seen = set()
for start in bm.faces:
if start.index in seen:
continue
island, stack = [], [start]
seen.add(start.index)
while stack:
face = stack.pop()
island.append(face)
for edge in face.edges:
for other in edge.link_faces:
if other.index not in seen:
seen.add(other.index)
stack.append(other)
verts = {}
faces = [[verts.setdefault(v, len(verts)) for v in face.verts] for face in island]
out.append((np.array([list(into @ v.co) for v in verts]), faces))
return out
def _seat(self, i, j, bore, x=0.0, boot=False, mat="machine", high=(2.2, 3.4, 5.0), along=(0.3, 0.9), back=(0.15, 1.3), min_arm=None, tail=0.0):
"""A ram across toe i's pitch joint j, seated by ram core's search: its base on the part before the joint
(the knuckle's housing and horn for j = 0, the segment's back otherwise), its eye on the segment's back,
both from a grid `high` bores above the armour, and clear over the joint's whole range of the dress of
the two parts and of the core (ram.Signed over their shells; the core as it stands at the planted splay).
`tail` (in bores) mounts the ram on a trunnion that far ahead of its barrel's back end, which leaves a short
span more barrel. The record is kept on the driven segment (feet_ram); a ram that finds no seat is reported
and not drawn."""
ram, t = ramcore(), self.toes[i]
parent, child = (t["knuckle"] if j == 0 else t["segs"][j - 1]), t["segs"][j]
socket = M.local_sockets(parent)["clevis"]
rest0 = socket @ M.FLIP @ M.local_sockets(child)["tongue"].inverted() # the child at roll 0, in the parent's frame
pivot, axis = socket.translation.copy(), socket.to_3x3() @ Z
fwd, up = rest0.to_3x3() @ Z, rest0.to_3x3() @ Y
length = t["dims"][j][0]
steps = lambda a, b, n: [a + (b - a) * q / (n - 1) for q in range(n)]
seats_b = [rest0 @ Vector((0, self.top_at(i, j, z) + h * bore, z)) + axis * x for z in steps(along[0] * length, along[1] * length, 6) for h in high]
if j == 0:
base, run = t.get("horn", 0.0) + 1.6 * self.tp, t["reach"] + 2.4 * self.tp
seats_a = [pivot - fwd * s + up * (base + h * bore) + axis * x for s in steps(back[0] * run, back[1] * run, 6) for h in high]
else:
run = t["dims"][j - 1][0]
seats_a = [pivot - fwd * s + up * (self.top_at(i, j - 1, run - s) + h * bore) + axis * x for s in steps(back[0] * run, back[1] * run, 6) for h in high]
joint = self.joints[f"toe{i}.pitch{j}"]
name = f"toe{i}.ram{j}"
M.update()
shells = {"before": self._shells(parent, Matrix.Identity(4)), "segment": self._shells(child, rest0),
"core": self._shells(self.core, parent.matrix_world.inverted() @ self.core.matrix_world)}
parts = {"before": "parent", "segment": "child", "core": "parent"}
def touch(m, body):
"""The zones about the ram's two pins: within three bores of its base pin the barrel and rod may stand
beside the part the base's clevis stands on, and within three of the eye beside the segment's back (depth
0: beside, never inside), no wider than the ram is long."""
r = min(3.0 * body.bore, 0.45 * float(np.linalg.norm(m.b - m.a)))
return {member: [("before", "a", r, 0.0), ("segment", "b", r, 0.0)] for member in ("barrel", "rod")}
for scale in (1.0, 0.8, 0.64): # a slimmer ram is shorter closed: tried when the bore asked for finds no seat
body = ram.Ram(bore * scale, min_arm=min_arm, tail=tail * bore * scale)
oracle = ram.Signed(shells, cap=body.reach())
found = ram.search("direct", {"pivot": list(pivot), "axis": list(axis), "lo": joint["lo"], "hi": joint["hi"]}, body, {"a": [list(p) for p in seats_a], "b": [list(p) for p in seats_b]},
world=lambda m: (parts, touch(m, body), oracle))
print(f"RAM {self.name}.{name} bore {bore * scale:.4f}: {found.report()}", flush=True)
if found.found:
break
entry = {"name": name, "ok": bool(found.found), "text": f"bore {body.bore:.4f}: {found.report()}", "parent": parent, "child": child, "boot": boot, "mat": mat}
self.drives.append(entry)
if not found.found:
return None
fit = found.best
child["feet_ram"] = json.dumps(ram.record(fit.m, body))
entry["fit"] = _Fit(fit)
a, b = Vector(fit.m.a), rest0.inverted() @ Vector(fit.m.b)
bore = body.bore
self.on(parent).seat(a, -up, bore, axis, reach=(high[0] + 1.6) * bore)
self.on(child).seat(b, -Y, bore, X, reach=(high[0] + 1.6) * bore)
return fit
def draw_rams(self):
"""The rams at the joints' rolls as they stand: last pose's are removed, each is drawn from its record."""
for obj in self.ram_objects:
if obj in self.objects:
self.objects.remove(obj)
bpy.data.objects.remove(obj, do_unlink=True)
self.ram_objects = []
for entry in self.drives:
if entry["ok"]:
dr = Dress(self, entry["parent"])
J._draw_ram(dr, entry["fit"], float(entry["child"]["kit_roll"]), Vector((0, 0, 0)), entry["boot"], entry["mat"])
made = dr.make(0.0)
for obj in made:
obj["tag"] = "ram" if obj["tag"] == "ram" else "eye"
self.ram_objects += made
self.objects += self.ram_objects
M.update()
def done(self):
for ask in self.asked:
self._seat(**ask)
self.asked = []
bevel = 0.005 * self.w
for dr in self.dress.values():
self.objects += dr.make(bevel)
self.draw_rams()
return self
def check(self):
"""Mesh overlaps between each ram (barrel and rod) and the armour, at the pose as it stands."""
self.clashes = J.Rig._clashes(self)
return self.clashes
def report(self):
"""The kit's joints report of the foot, and each ram's fit."""
bpy.ops.brokkr_kitbash.joints(object_name=self.core.name)
kit = json.loads(getattr(bpy.context.window_manager, "brokkr_mesh_polish_result"))
return {"foot": self.name, "dims": list(self.dims), "toes": len(self.toes), "segments": sum(len(t["segs"]) for t in self.toes),
"splay_hinges": sum(1 for t in self.toes if t["splay"]), "joints": kit,
"rams": [{"name": e["name"], "ok": e["ok"], "fit": e["text"]} for e in self.drives], "notes": self.notes}
# --- the concept feet ----------------------------------------------------------------------------------------------
@concept("KESTREL", 29, (775, 745, 908, 988), view=(52.0, 12.0), variant={"length": 2.3, "claw": 0.26, "splay": 26.0}, dims=(1.0, 1.9, 0.46, 0.07))
def kestrel_talons(name, shin=None, socket="clevis", width=1.0, length=1.9, drop=0.46, pin_r=0.07, claw=0.34, splay=16.0, rams=True):
"""KESTREL, FOOT (FRONT) and FOOT (REAR): two long talons, each a root block, a stepped mid plate and a long
tapering claw on three pitch pins, fanned on splay pins either side of a bare ankle drum in a yoke; two short
rear toes angled out behind; a booted ram from each talon's root horn to its first plate and a second from
that plate to the next."""
w, l, d = width, length, drop
front = [(0.19 * l, 0.3 * w, 0.46 * d), (0.2 * l, 0.28 * w, 0.4 * d), (claw * l, 0.27 * w, 0.34 * d)]
rear = [(0.17 * l, 0.24 * w, 0.44 * d)]
f = Foot(name, (w, l, d, pin_r), [T((s * 0.25 * w, 0.06 * l), s * 9.0, front, splay=splay, fall=(0.75, 0.25)) for s in (-1, 1)]
+ [T((s * 0.22 * w, -0.1 * l), s * 152.0, rear, role="rear", splay=splay * 0.6, lim=[(-14.0, 30.0)]) for s in (-1, 1)], shin, socket, toe_h=0.42)
for i in (0, 1):
f.armour(i, [(0.42 * d, 0.34 * d), (0.3 * d, 0.25 * d), (0.22 * d, 0.16 * d)], widen=1.25, cap="claw", plate=0.03 * d + 0.006, nose=0.6, tip=(0.5, 0.34), treads=2)
f.housing(i, horn=0.3 * d)
if rams:
f.ram(i, 0, 0.02 * w, boot=True)
f.ram(i, 1, 0.016 * w)
for i in (2, 3):
f.armour(i, [(0.28 * d, 0.16 * d)], widen=1.3, cap="block", plate=0.02 * d + 0.005, nose=0.3, treads=2)
f.housing(i)
f.drums(0.36 * d, 0.2 * w, 0.14 * w, cap=0.78)
core = f.on(f.core)
core.cyl("gunmetal", (0, 0, 0), 0.27 * d, 0.3 * w)
for x in (-0.08 * w, 0.0, 0.08 * w):
core.cyl("machine", (x, 0, 0), 0.3 * d, 0.025 * w)
f.mass("gunmetal", [(0.2 * w, -0.14 * l, 0.58 * d), (0.2 * w, 0.1 * l, 0.58 * d), (0.3 * w, -0.14 * l, 0.3 * d), (0.3 * w, 0.1 * l, 0.3 * d)])
f.mass(f.plate, [(0.16 * w, 0.02 * l, 0.62 * d), (0.16 * w, 0.14 * l, 0.5 * d), (0.12 * w, 0.02 * l, 0.74 * d), (0.12 * w, 0.12 * l, 0.66 * d), (0.16 * w, 0.02 * l, 0.5 * d), (0.16 * w, 0.14 * l, 0.44 * d)])
return f
def _heavy(f, drum=0.42, drum_x=0.36, drum_w=0.16, top=0.95, back=-0.16, front=0.2, half=0.34, nose=0.55, mat=None):
"""The instep of a heavy foot: a faceted mass from the ankle's column down over the toes' roots, a stepped
plate on its slope, and the ankle's drums."""
w, l, d = f.w, f.l, f.d
base = 1.0 - f.toe_h - 0.04
f.mass(mat or f.plate, [(half * w, back * l, base * d), (half * w, front * l, base * d), (half * w, back * l, 0.7 * d), (0.8 * half * w, back * 0.8 * l, top * d),
(0.7 * half * w, 0.05 * l, top * d), (0.9 * half * w, front * l, nose * d)])
# the ankle's housing between the drums, and three plates stepping down its front
f.mass(mat or f.plate, [(0.5 * half * w, back * 0.7 * l, top * d), (0.42 * half * w, back * 0.5 * l, (top + 0.34) * d), (0.42 * half * w, 0.03 * l, (top + 0.34) * d),
(0.5 * half * w, 0.09 * l, top * d)])
for k in range(3):
y, h = (0.07 + 0.3 * (front - 0.07) * k) * l, (top + 0.12 - (top + 0.12 - nose) * k / 2.4) * d
f.pbox(f.plate2, (0, y, h), ((0.56 + 0.12 * k) * half * 2 * w * 0.8, 0.3 * (front - 0.04) * l, 0.1 * d), 0.025 * d, tag="trim")
f.drums(drum * d, drum_x * w, drum_w * w)
@concept("walker", 23, (700, 770, 1010, 950), view=(12.0, 12.0), variant={"outrigger": 0.3, "splay": 30.0}, dims=(1.5, 1.9, 0.6, 0.09))
def walker_slabs(name, shin=None, socket="clevis", width=1.5, length=1.9, drop=0.6, pin_r=0.09, outrigger=0.22, splay=18.0, rams=True):
"""walker (23), the hero view's two feet: two wide slab toes, each an upper plate sloping down from the instep
and a blunt toe block with a wear tab let into its nose; a ram on each slab's inner edge, from the upper
plate to the toe block, either side of the centre line; a wedge outrigger fanned out on a splay pin either side; and
behind, a tall tapered heel pylon on its own pin."""
w, l, d = width, length, drop
slab = [(0.25 * l, 0.36 * w, 0.4 * d), (0.24 * l, 0.36 * w, 0.42 * d)]
f = Foot(name, (w, l, d, pin_r), [T((s * 0.23 * w, 0.08 * l), s * 5.0, slab) for s in (-1, 1)]
+ [T((s * 0.44 * w, -0.03 * l), s * 62.0, [(outrigger * l, 0.2 * w, 0.4 * d)], splay=splay, lim=[(-14.0, 28.0)]) for s in (-1, 1)]
+ [T((0, -0.17 * l), 180.0, [(0.21 * l, 0.36 * w, 0.44 * d)], role="rear", lim=[(-12.0, 26.0)])], shin, socket, toe_h=0.5)
for i in (0, 1):
f.armour(i, [(0.52 * d, 0.36 * d), (0.3 * d, 0.3 * d)], widen=1.22, cap="block", tab=True, plate=0.03 * d, nose=0.34)
f.housing(i)
if rams:
f.ram(i, 1, 0.024 * w, x=(0.1 if i == 0 else -0.1) * w, tail=2.5)
for i in (2, 3):
f.armour(i, [(0.62 * d, 0.3 * d)], widen=1.3, cap="block", nose=0.3, plate=0.025 * d)
f.housing(i, horn=0.2 * d)
f.armour(4, [(1.15 * d, 0.5 * d)], widen=1.15, cap="block", nose=0.2, plate=0.03 * d)
f.housing(4)
_heavy(f, drum=0.36, drum_x=0.33, drum_w=0.12, top=0.9, half=0.3, front=0.16)
core = f.on(f.core)
for x in (-0.04 * w, 0.04 * w): # the linkage between the slabs
core.box("gunmetal", f.plan(x, 0.2 * l, 0.36 * d), (0.03 * w, 0.2 * l, 0.3 * d))
core.cyl("machine", f.plan(0, 0.27 * l, 0.42 * d), 0.07 * d, 0.14 * w)
return f
@concept("BREAKER", 24, (505, 785, 755, 985), view=(40.0, 14.0), variant={"toe": 0.3, "width": 1.7}, dims=(1.45, 1.6, 0.6, 0.09))
def breaker_sections(name, shin=None, socket="clevis", width=1.45, length=1.6, drop=0.6, pin_r=0.09, toe=0.23):
"""BREAKER, FOOT DETAIL (multi-section design): a stepped instep slab over two broad front toes, each a sloped
plate and a square toe block on two pins; a short block toe at each front corner; two heel blocks behind;
the ankle's disc on the side. No ram shows: the toes' drives are under the instep."""
w, l, d = width, length, drop
f = Foot(name, (w, l, d, pin_r), [T((s * 0.22 * w, 0.1 * l), s * 5.0, [(0.25 * l, 0.36 * w, 0.42 * d), (toe * l, 0.36 * w, 0.44 * d)]) for s in (-1, 1)]
+ [T((s * 0.46 * w, 0.0), s * 38.0, [(0.21 * l, 0.22 * w, 0.44 * d)], lim=[(-10.0, 30.0)]) for s in (-1, 1)]
+ [T((s * 0.25 * w, -0.17 * l), s * 166.0, [(0.19 * l, 0.34 * w, 0.44 * d)], role="rear", lim=[(-12.0, 24.0)]) for s in (-1, 1)], shin, socket, toe_h=0.5)
for i in (0, 1):
f.armour(i, [(0.56 * d, 0.36 * d), (0.32 * d, 0.3 * d)], widen=1.2, cap="block", plate=0.035 * d, nose=0.3)
f.housing(i)
for i in (2, 3, 4, 5):
f.armour(i, [(0.42 * d, 0.3 * d)], widen=1.25, cap="block", plate=0.03 * d, nose=0.32)
f.housing(i)
_heavy(f, drum=0.4, drum_x=0.4, drum_w=0.14, top=1.0, half=0.36, front=0.2, nose=0.62)
f.pbox(f.plate2, (0, 0.1 * l, 0.82 * d), (0.5 * w, 0.2 * l, 0.1 * d), 0.03 * d)
f.pbox(f.plate, (0, 0.17 * l, 0.68 * d), (0.56 * w, 0.14 * l, 0.1 * d), 0.03 * d)
return f
@concept("MCR-3", 25, (280, 500, 480, 595), view=(48.0, 10.0), variant={"toes": 2, "heel": 0.3}, dims=(1.3, 1.6, 0.55, 0.085))
def mcr3_wedges(name, shin=None, socket="clevis", width=1.3, length=1.6, drop=0.55, pin_r=0.085, toes=3, heel=0.24):
"""MCR-3, the hero and side views and ANKLE (ACTUATOR): a rotary actuator's drum on each side of the ankle
over a wedge instep; chamfered wedge toes on two pins each, three across the front (`toes` 2: a pair), and
one long heel toe sloping back to the ground, so the foot stands as the side view's A."""
w, l, d = width, length, drop
seg = lambda k: [(0.22 * l, k * w, 0.42 * d), (0.2 * l, k * w, 0.4 * d)]
front = [T((0, 0.1 * l), 0.0, seg(0.28))] if toes == 3 else []
x = 0.33 if toes == 3 else 0.2
front += [T((s * x * w, 0.06 * l), s * 13.0, seg(0.27)) for s in (-1, 1)]
f = Foot(name, (w, l, d, pin_r), front + [T((0, -0.12 * l), 180.0, [(heel * l, 0.42 * w, 0.46 * d)], role="rear", lim=[(-12.0, 26.0)])], shin, socket, toe_h=0.42)
for i in range(len(front)):
f.armour(i, [(0.5 * d, 0.34 * d), (0.3 * d, 0.24 * d)], widen=1.18, cap="block", plate=0.03 * d, nose=0.5)
f.housing(i)
f.armour(len(front), [(0.56 * d, 0.26 * d)], widen=1.15, cap="block", plate=0.03 * d, nose=0.4)
f.housing(len(front))
_heavy(f, drum=0.5, drum_x=0.3, drum_w=0.2, top=0.9, half=0.27, front=0.16, nose=0.6)
return f
@concept("R-3", 26, (845, 725, 1015, 925), view=(20.0, 22.0), variant={"rear": 2, "splay": 34.0}, dims=(0.42, 0.62, 0.2, 0.035))
def r3_tripod(name, shin=None, socket="clevis", width=0.42, length=0.62, drop=0.2, pin_r=0.035, rear=1, splay=24.0, rams=True):
"""R-3, FOOT DESIGN (three-toed stability): a tripod. Two long front toes of three stepped segments fan out
on splay pins from under a twin-disc ankle, a ram from each one's first segment to its second; behind, one
shorter toe of two segments (`rear` 2: the inset's pair, angled out)."""
w, l, d = width, length, drop
front = [(0.26 * l, 0.26 * w, 0.44 * d), (0.22 * l, 0.25 * w, 0.4 * d), (0.2 * l, 0.24 * w, 0.36 * d)]
back = [(0.2 * l, 0.25 * w, 0.44 * d), (0.2 * l, 0.24 * w, 0.38 * d)]
rears = [T((0, -0.1 * l), 180.0, back, role="rear")] if rear == 1 else [T((s * 0.17 * w, -0.08 * l), s * 148.0, back, role="rear", splay=0.5 * splay) for s in (-1, 1)]
f = Foot(name, (w, l, d, pin_r), [T((s * 0.2 * w, 0.07 * l), s * splay, front, splay=0.6 * splay, fall=(0.7, 0.3)) for s in (-1, 1)] + rears, shin, socket, toe_h=0.3, pad=0.05 * d)
for i in (0, 1):
f.armour(i, [(0.44 * d, 0.36 * d), (0.34 * d, 0.3 * d), (0.28 * d, 0.2 * d)], widen=1.3, cap="block", plate=0.04 * d, nose=0.4)
f.housing(i, horn=0.3 * d)
if rams:
f.ram(i, 1, 0.03 * w, tail=2.5)
for i in range(2, len(f.toes)):
f.armour(i, [(0.42 * d, 0.34 * d), (0.3 * d, 0.2 * d)], widen=1.3, cap="block", plate=0.04 * d, nose=0.4)
f.housing(i, horn=0.2 * d)
f.drums(0.46 * d, 0.3 * w, 0.14 * w, cap=0.8, bolts=6)
core = f.on(f.core)
core.cyl("gunmetal", (0, 0, 0), 0.32 * d, 0.5 * w)
f.mass("gunmetal", [(0.24 * w, -0.1 * l, 0.72 * d), (0.24 * w, 0.1 * l, 0.72 * d), (0.3 * w, -0.12 * l, 0.5 * d), (0.3 * w, 0.12 * l, 0.5 * d)])
return f
@concept("PALADIN", 27, (815, 740, 1012, 928), view=(-34.0, 16.0), variant={"lames": 2, "length": 2.4}, dims=(1.6, 2.0, 0.7, 0.1))
def paladin_hoof(name, shin=None, socket="clevis", width=1.6, length=2.0, drop=0.7, pin_r=0.1, lames=3):
"""PALADIN, FOOT & ANKLE: the instep steps down the centre in `lames` short plates, each on its own pin, to a
narrow centre toe; a heavy two-segment toe with a deep cap either side of it; two heel blocks angled out
behind; the ankle's drums under a boxed instep."""
w, l, d = width, length, drop
centre = [(0.46 / lames * l, 0.3 * w, (0.42 - 0.03 * k) * d) for k in range(lames)]
f = Foot(name, (w, l, d, pin_r), [T((0, 0.13 * l), 0.0, centre)]
+ [T((s * 0.34 * w, 0.05 * l), s * 12.0, [(0.24 * l, 0.3 * w, 0.46 * d), (0.2 * l, 0.3 * w, 0.44 * d)]) for s in (-1, 1)]
+ [T((s * 0.3 * w, -0.15 * l), s * 150.0, [(0.21 * l, 0.3 * w, 0.46 * d)], role="rear", lim=[(-12.0, 24.0)]) for s in (-1, 1)], shin, socket, toe_h=0.46,
plate="khaki", plate2="olive_light")
f.armour(0, [((0.52 - 0.1 * k) * d, (0.44 - 0.1 * k) * d) for k in range(lames)], widen=1.2, cap="block", plate=0.035 * d, nose=0.4)
f.housing(0)
for i in (1, 2):
f.armour(i, [(0.6 * d, 0.42 * d), (0.38 * d, 0.3 * d)], widen=1.25, cap="hoof", plate=0.035 * d, nose=0.36)
f.housing(i)
for i in (3, 4):
f.armour(i, [(0.5 * d, 0.32 * d)], widen=1.25, cap="hoof", plate=0.03 * d, nose=0.34)
f.housing(i)
_heavy(f, drum=0.4, drum_x=0.4, drum_w=0.14, top=1.0, half=0.36, front=0.18, nose=0.66)
f.pbox(f.plate2, (0, 0.06 * l, 0.92 * d), (0.4 * w, 0.2 * l, 0.12 * d), 0.03 * d)
return f
@concept("CHIMERA (28)", 28, (460, 630, 680, 715), view=(-30.0, 9.0), variant={"toes": 2, "width": 1.9}, dims=(1.7, 2.1, 0.7, 0.1))
def chimera_slabs(name, shin=None, socket="clevis", width=1.7, length=2.1, drop=0.7, pin_r=0.1, toes=3):
"""CHIMERA (sheet 28), the hero view's feet: broad slab toes abreast, each a long sloped plate and a square
cap on two pins, under a low instep with the ankle's drum outboard; one wide heel block behind."""
w, l, d = width, length, drop
xs = (-0.36, 0.0, 0.36) if toes == 3 else (-0.24, 0.24)
f = Foot(name, (w, l, d, pin_r), [T((x * w, (0.1 if x else 0.13) * l), x * 22.0, [(0.26 * l, (0.3 if toes == 3 else 0.4) * w, 0.4 * d), (0.2 * l, (0.3 if toes == 3 else 0.4) * w, 0.42 * d)]) for x in xs]
+ [T((0, -0.17 * l), 180.0, [(0.2 * l, 0.56 * w, 0.44 * d)], role="rear", lim=[(-12.0, 24.0)])], shin, socket, toe_h=0.5)
for i in range(toes):
f.armour(i, [(0.5 * d, 0.34 * d), (0.3 * d, 0.3 * d)], widen=1.16, cap="block", plate=0.035 * d, nose=0.28)
f.housing(i)
f.armour(toes, [(0.46 * d, 0.3 * d)], widen=1.1, cap="block", plate=0.03 * d, nose=0.3)
f.housing(toes)
_heavy(f, drum=0.42, drum_x=0.42, drum_w=0.14, top=0.92, half=0.38, front=0.2, nose=0.6)
return f
@concept("SERAPH", 30, (605, 812, 818, 992), view=(34.0, 13.0), variant={"toe": 0.28, "skirt": False}, dims=(1.5, 2.2, 0.62, 0.12))
def seraph_caps(name, shin=None, socket="clevis", width=1.5, length=2.2, drop=0.62, pin_r=0.12, toe=0.21, skirt=True, rams=True):
"""SERAPH, FOOT DETAIL: two big toes, each a wedge plate off the instep and a deep toe cap with a skirt of
sole plates round its rim, on two pins; between them the instep's ribbed strut, a booted ram driving a narrow
centre toe; a short block toe on a splay pin at each side behind the ankle's drum; a heel block."""
w, l, d = width, length, drop
f = Foot(name, (w, l, d, pin_r), [T((s * 0.27 * w, 0.1 * l), s * 6.0, [(0.24 * l, 0.36 * w, 0.42 * d), (toe * l, 0.36 * w, 0.44 * d)]) for s in (-1, 1)]
+ [T((0, 0.17 * l), 0.0, [(0.22 * l, 0.13 * w, 0.3 * d)], lim=[(-12.0, 36.0)])]
+ [T((s * 0.45 * w, -0.05 * l), s * 78.0, [(0.15 * l, 0.26 * w, 0.42 * d)], splay=12.0, lim=[(-10.0, 26.0)]) for s in (-1, 1)]
+ [T((0, -0.19 * l), 180.0, [(0.16 * l, 0.52 * w, 0.42 * d)], role="rear", lim=[(-12.0, 24.0)])], shin, socket, toe_h=0.5, plate="khaki", plate2="olive_light")
for i in (0, 1):
f.armour(i, [(0.6 * d, 0.38 * d), (0.36 * d, 0.3 * d)], widen=1.2, cap="block", plate=0.035 * d, nose=0.36)
f.housing(i)
if skirt: # the cap's rim: sole plates round the nose
dr, (ln, wd, dp) = f.on(f.toes[i]["segs"][1]), f.toes[i]["dims"][1]
for x in (-0.4, 0.0, 0.4):
dr.box(f.plate2, (x * wd, -0.3 * dp, ln * 1.0), (0.34 * wd, 0.36 * dp, 0.06 * ln), tag="trim")
for s in (-1, 1):
dr.box(f.plate2, (s * 0.61 * wd, -0.3 * dp, 0.6 * ln), (0.04 * wd, 0.36 * dp, 0.5 * ln), tag="trim")
f.armour(2, [(0.2 * d, 0.16 * d)], widen=1.2, cap="block", nose=0.3, barrel=0.8, mat="gunmetal")
f.housing(2, horn=0.5 * d, mat="gunmetal")
if rams:
f.ram(2, 0, 0.034 * w, boot=True)
for i in (3, 4):
f.armour(i, [(0.44 * d, 0.3 * d)], widen=1.2, cap="block", plate=0.03 * d, nose=0.34)
f.housing(i, horn=0.1 * d)
f.armour(5, [(0.44 * d, 0.3 * d)], widen=1.1, cap="block", plate=0.03 * d, nose=0.3)
f.housing(5)
_heavy(f, drum=0.46, drum_x=0.36, drum_w=0.16, top=1.0, half=0.32, front=0.12, nose=0.7)
return f
@concept("SPECTRE", 31, (815, 718, 1017, 928), view=(6.0, 14.0), variant={"splay": 52.0, "spur": 0.36}, dims=(1.3, 1.6, 0.5, 0.07))
def spectre_shocks(name, shin=None, socket="clevis", width=1.3, length=1.6, drop=0.5, pin_r=0.07, splay=38.0, spur=0.26, rams=True):
"""SPECTRE, FOOT DETAIL (multi-surface foot, shock absorption system): three toes, the centre one ahead and
one fanned out on a splay pin either side, each a shrouded root and a toe plate with a wear tab on two pins,
and each hung on a booted damper from the horn of its root to its plate; a spur on its own pin behind."""
w, l, d = width, length, drop
seg = [(0.2 * l, 0.26 * w, 0.4 * d), (0.23 * l, 0.26 * w, 0.36 * d)]
f = Foot(name, (w, l, d, pin_r), [T((0, 0.1 * l), 0.0, seg)] + [T((s * 0.3 * w, 0.02 * l), s * splay, seg, splay=0.6 * splay) for s in (-1, 1)]
+ [T((0, -0.12 * l), 180.0, [(spur * l, 0.22 * w, 0.38 * d)], role="rear", lim=[(-14.0, 30.0)])], shin, socket, toe_h=0.36)
for i in (0, 1, 2):
f.armour(i, [(0.46 * d, 0.34 * d), (0.3 * d, 0.24 * d)], widen=1.25, cap="block", tab=True, plate=0.035 * d, nose=0.36)
f.housing(i, horn=0.34 * d)
if rams:
f.ram(i, 0, 0.024 * w, boot=True)
f.armour(3, [(0.4 * d, 0.2 * d)], widen=1.25, cap="claw", plate=0.03 * d, nose=0.5, tip=(0.6, 0.4))
f.housing(3, horn=0.1 * d)
f.drums(0.36 * d, 0.2 * w, 0.12 * w)
f.mass(f.plate, [(0.2 * w, -0.12 * l, 0.6 * d), (0.2 * w, 0.1 * l, 0.6 * d), (0.16 * w, -0.1 * l, 0.98 * d), (0.14 * w, 0.06 * l, 0.98 * d), (0.2 * w, 0.13 * l, 0.72 * d)])
return f
@concept("CHIMERA (34)", 34, (725, 628, 872, 812), view=(-52.0, 12.0), variant={"hoof": 0.3, "width": 1.9}, dims=(1.6, 1.9, 0.8, 0.1))
def chimera_hooves(name, shin=None, socket="clevis", width=1.6, length=1.9, drop=0.8, pin_r=0.1, hoof=0.2):
"""CHIMERA (sheet 34), LEG DETAIL (RIGHT) and (LEFT): three hooves abreast, each a sloped plate and a drawn-in
hoof on two pins; a block toe at each rear corner and a heel block; a tall stepped instep with the ankle's drum
cluster. No toe ram: the leg detail's twin struts are the ankle's, and a ram from the instep to a hoof found
no seat clear of the drums (ram core, 324 candidates)."""
w, l, d = width, length, drop
f = Foot(name, (w, l, d, pin_r), [T((x * w, (0.1 if x else 0.13) * l), x * 26.0, [(0.2 * l, 0.3 * w, 0.4 * d), (hoof * l, 0.3 * w, 0.4 * d)]) for x in (-0.34, 0.0, 0.34)]
+ [T((s * 0.38 * w, -0.1 * l), s * 132.0, [(0.2 * l, 0.26 * w, 0.4 * d)], role="rear", lim=[(-10.0, 24.0)]) for s in (-1, 1)]
+ [T((0, -0.2 * l), 180.0, [(0.19 * l, 0.5 * w, 0.4 * d)], role="rear", lim=[(-12.0, 24.0)])], shin, socket, toe_h=0.52)
for i in (0, 1, 2):
f.armour(i, [(0.46 * d, 0.34 * d), (0.3 * d, 0.26 * d)], widen=1.2, cap="hoof", plate=0.03 * d, nose=0.4)
f.housing(i)
for i in (3, 4, 5):
f.armour(i, [(0.36 * d, 0.24 * d)], widen=1.15, cap="block", plate=0.03 * d, nose=0.3)
f.housing(i)
_heavy(f, drum=0.36, drum_x=0.4, drum_w=0.14, top=1.0, half=0.36, front=0.2, nose=0.6)
f.pbox(f.plate2, (0, 0.08 * l, 0.9 * d), (0.46 * w, 0.2 * l, 0.1 * d), 0.03 * d)
f.pbox(f.plate, (0, 0.16 * l, 0.72 * d), (0.52 * w, 0.14 * l, 0.1 * d), 0.03 * d)
for s in (-1, 1):
f.on(f.core).cyl("machine", (s * 0.44 * w, -0.12 * l, 0.2 * d), 0.2 * d, 0.1 * w)
return f

View file

@ -0,0 +1,151 @@
"""Builds the feet library's feet alone on a shin stub and renders them. Environment:
FEET: comma-separated names of feet.FEET (default all). FEET_MODE: catalog (each foot planted, from its concept's
side, and its parameter variant), motion (each foot at heel strike, flat plant and toe-off, side by side), step
(FEET_STEP frames of one foot rolling through a step, to MECH_OUT/feet/step_<name>/f%04d.png). FEET_FAST: EEVEE
in place of Cycles. FEET_NOVAR: no variants. FEET_SAMPLES: Cycles samples (default 48). Writes MECH_OUT/feet/<name>.png, <name>_var.png,
<name>_motion.png and feet_report.json (the kit's joints report and the rams of every foot built)."""
import json, math, os, sys, time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import mechlib as M
from mathutils import Matrix, Vector
import bpy
import numpy as np
M.setup()
M.cache_kits()
import feet
OUT = Path(os.environ["MECH_OUT"]) / "feet"
assert OUT.is_absolute()
OUT.mkdir(parents=True, exist_ok=True)
MODE, FAST = os.environ.get("FEET_MODE", "catalog"), bool(os.environ.get("FEET_FAST"))
NAMES = [n for n in os.environ.get("FEET", "").split(",") if n] or list(feet.FEET)
SAMPLES = int(os.environ.get("FEET_SAMPLES", "48"))
POSES = {"heel strike": dict(pitch=-14.0, strike=14.0, splay=0.0, lean=-16.0), "flat plant": dict(pitch=0.0, splay=1.0, lean=0.0),
"toe-off": dict(pitch=38.0, roll=38.0, splay=0.35, lean=30.0)}
def clear():
for obj in list(bpy.data.objects):
bpy.data.objects.remove(obj, do_unlink=True)
def stand(name, tag, y=0.0, pose=None, **params):
"""A foot of the library on a shin stub at y, posed, its lowest point on the ground. Returns the Foot."""
entry = feet.FEET[name]
w, l, d, pin = (params.get(k, v) for k, v in zip(("width", "length", "drop", "pin_r"), entry["dims"]))
pose = dict(pose or POSES["flat plant"])
shin_len = 1.0 * d + 0.12 * l
shin = M.place("link", f"{tag}.Shin", mat="gunmetal", length=shin_len, width=min(0.3 * w, 1.0), depth=min(0.22 * w, 0.9), pin_r=pin)
lean = pose.pop("lean", 0.0)
shin.matrix_world = Matrix.Translation((0, y, 2.0 * d)) @ Matrix.Rotation(math.radians(-lean), 4, "X") @ Matrix.Rotation(math.pi, 4, "Y") @ Matrix.Translation((0, 0, -shin_len))
M.update()
t1 = time.time()
foot = entry["fn"](tag, shin, "clevis", **params)
print("BUILT", tag, round(time.time() - t1, 1), "s", flush=True)
foot.level(pose.pop("pitch", 0.0))
foot.done()
foot.drive(**pose)
M.update()
shin.matrix_world = Matrix.Translation((0, 0, -lowest(foot))) @ shin.matrix_world
M.update()
return foot
def lowest(foot):
"""The least z of the foot's own vertices as it stands (a bounding box of a tilted part reaches below it)."""
M.update()
low = 1e9
for obj in [foot.core] + list(foot.core.children_recursive):
if obj.type == "MESH" and len(obj.data.vertices):
co = np.empty(len(obj.data.vertices) * 3)
obj.data.vertices.foreach_get("co", co)
m = np.array(obj.matrix_world)
low = min(low, float((co.reshape(-1, 3) @ m[2, :3] + m[2, 3]).min()))
return low
def stage():
rig, cam, centre, radius = M.stage(SAMPLES)
scene = bpy.context.scene
if FAST:
scene.render.engine = "BLENDER_EEVEE"
scene.eevee.taa_render_samples = 16
return rig, cam, radius
report, t_all = {}, time.time()
for name in NAMES:
entry, t0 = feet.FEET[name], time.time()
az, el = entry["view"]
if MODE == "catalog":
for suffix, params in (("", {}), ("_var", entry["variant"])):
if suffix and (not params or os.environ.get("FEET_NOVAR")):
continue
clear()
foot = stand(name, name, **params)
if not suffix:
report[name] = dict(foot.report(), clashes=foot.check(), sheet=entry["sheet"], doc=" ".join(entry["fn"].__doc__.split()), variant=entry["variant"])
rig, cam, radius = stage()
M.shot(rig, cam, radius, az, el, OUT / f"{name}{suffix}.png", (900, 760), margin=0.7, lens=85.0)
elif MODE == "motion":
clear()
gap = 1.55 * max(entry["dims"][0], entry["dims"][1])
clashes = {}
for k, (label, pose) in enumerate(POSES.items()):
foot = stand(name, f"{name}{k}", y=(k - 1) * gap, pose=pose)
clashes[label] = foot.check()
report[name] = {"clashes": clashes}
rig, cam, radius = stage()
M.shot(rig, cam, radius, -68.0, 10.0, OUT / f"{name}_motion.png", (1800, 620), margin=0.4, lens=110.0)
elif MODE == "step":
clear()
w, l, d, pin = entry["dims"]
frames, out = int(os.environ.get("FEET_STEP", "48")), OUT / f"step_{name}"
out.mkdir(parents=True, exist_ok=True)
shin_len = 1.0 * d + 0.12 * l
shin = M.place("link", "Step.Shin", mat="gunmetal", length=shin_len, width=min(0.3 * w, 1.0), depth=min(0.22 * w, 0.9), pin_r=pin)
base = Matrix.Rotation(math.pi, 4, "Y") @ Matrix.Translation((0, 0, -shin_len))
shin.matrix_world = Matrix.Translation((0, 0, 2.0 * d)) @ base
M.update()
foot = entry["fn"]("Step", shin, "clevis")
foot.level(0.0)
foot.done()
anchor = foot.toes[0]["segs"][-1]
foot.drive(splay=1.0)
at = anchor.matrix_world.translation
shin.matrix_world = Matrix.Translation((-at.x, 0.25 * l - at.y, -lowest(foot))) @ shin.matrix_world
rig, cam, radius = stage()
mix = lambda a, b, u: a + (b - a) * (u * u * (3 - 2 * u))
log = []
for k in range(frames):
t = k / (frames - 1)
if t < 0.18: # heel strike rolling down to the plant
u = t / 0.18
pitch, strike, roll, splay, lean, lift = mix(-14, 0, u), mix(14, 0, u), 0.0, mix(0, 1, u), mix(-16, -8, u), 0.0
elif t < 0.5: # planted, the shin passing over
u = (t - 0.18) / 0.32
pitch, strike, roll, splay, lean, lift = 0.0, 0.0, 0.0, 1.0, mix(-8, 14, u), 0.0
elif t < 0.82: # the heel rises, the toes roll
u = (t - 0.5) / 0.32
pitch, strike, roll, splay, lean, lift = mix(0, 44, u), 0.0, mix(0, 44, u), mix(1, 0.3, u), mix(14, 36, u), 0.0
else: # the foot leaves the ground and the toes fall back
u = (t - 0.82) / 0.18
pitch, strike, roll, splay, lean, lift = mix(44, 26, u), 0.0, mix(44, 6, u), mix(0.3, 0.0, u), mix(36, 28, u), mix(0, 0.9 * d, u)
shin.matrix_world = Matrix.Translation((0, 0, 3.0 * d)) @ Matrix.Rotation(math.radians(-lean), 4, "X") @ base
M.update()
foot.level(pitch)
wrote = foot.drive(roll=roll, strike=strike, splay=splay)
M.update()
at = anchor.matrix_world.translation # the talon's last pin stays where it is planted
shin.matrix_world = Matrix.Translation((-at.x, 0.25 * l - at.y + (0.5 * lift if lift else 0.0), 0)) @ shin.matrix_world
shin.matrix_world = Matrix.Translation((0, 0, lift - lowest(foot))) @ shin.matrix_world
M.update()
log.append({"frame": k, "pitch": round(pitch, 1), "roll": round(roll, 1), "strike": round(strike, 1), "splay": round(splay, 2),
"joints": {n: round(float(j["obj"]["kit_roll"]) - j["rest"], 1) for n, j in foot.joints.items()}})
M.shot(rig, cam, radius * 1.3, -62.0, 11.0, out / f"f{k:04d}.png", (960, 600), margin=0.85, lens=95.0, lift=0.12)
report[name] = {"frames": log}
print("FOOT", name, MODE, "s", round(time.time() - t0, 1), flush=True)
(OUT / f"feet_report_{MODE}.json").write_text(json.dumps(report, indent=1, default=str), encoding="utf-8")
print("DONE", MODE, len(NAMES), "feet", round(time.time() - t_all, 1), "s")

View file

@ -0,0 +1,65 @@
"""Checks that a feet library foot seats where the kit's talon does: on a shin's clevis by `tongue`, as mechlib.leg
and humanoid seat a foot, and under a cross ankle's clevis by `tongue_roll`, as mechlib.ankle_cross does; that the
instep and heel sockets recessed_rams and the foot dress read are there; and that the kit reports its joints and
refuses a roll outside a toe's limits. Prints DROPIN lines and exits 1 on a miss."""
import json, math, sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import mechlib as M
from mathutils import Matrix, Vector
import bpy
M.setup()
M.cache_kits()
import feet
bad = 0
w, l, d, pin = 1.5, 2.2, 0.62, 0.12
shin = M.place("link", "Shin", length=2.4, width=0.8, depth=0.8, pin_r=pin)
shin.matrix_world = Matrix.Translation((0, 0, 4)) @ Matrix.Rotation(math.pi, 4, "Y") @ Matrix.Translation((0, 0, -2.4))
M.update()
talon = M.attach(M.place("talon", "Talon", width=w, length=l, drop=d, pin_r=pin), "tongue", shin, "clevis", 0.0)
M.level_foot(talon)
pin_at = talon.matrix_world.translation.copy()
talon_sockets = set(M.local_sockets(talon))
bpy.ops.brokkr_kitbash.detach(object_name=talon.name)
bpy.data.objects.remove(talon, do_unlink=True)
foot = feet.seraph_caps("Foot", shin, "clevis", width=w, length=l, drop=d, pin_r=pin)
foot.level(0.0)
foot.done()
M.update()
miss = (foot.core.matrix_world.translation - pin_at).length
down = foot.core.matrix_world.to_3x3() @ Vector((0, 0, 1))
print("DROPIN tongue on the shin's clevis: ankle pin", round(miss, 6), "m from the talon's; sole normal", tuple(round(v, 3) for v in down))
bad += miss > 1e-5 or down.z > -0.999
lacking = talon_sockets - set(M.local_sockets(foot.core))
print("DROPIN the talon's sockets the foot_core lacks:", sorted(lacking) or "none")
bad += bool(lacking)
report = foot.report()
rows = report["joints"]["joints"]
print("DROPIN kit joints report:", report["joints"]["schema"], len(rows), "rows;", sorted({r["mechanism"] for r in rows}))
bad += len(rows) != len(foot.joints)
seg = foot.joints["toe0.pitch1"]
before = float(seg["obj"]["kit_roll"])
try:
bpy.ops.brokkr_kitbash.roll(object_name=seg["obj"].name, roll=seg["hi"] + 20.0)
refused = False
except RuntimeError as error:
refused = True
print("DROPIN a roll 20 past the limit is refused:", str(error).strip().splitlines()[-1][:160])
print("DROPIN roll after the refused write:", float(seg["obj"]["kit_roll"]), "was", before)
bad += (not refused) or abs(float(seg["obj"]["kit_roll"]) - before) > 1e-6
wrote = foot.set("toe0.pitch1", 30.0)
print("DROPIN brokkr_kitbash.roll inside the limits wrote", round(wrote, 3), "from rest; ram record on the centre toe:", "feet_ram" in foot.toes[2]["segs"][0])
bad += abs(wrote - 30.0) > 1e-6
# under a cross ankle, as Seraph stands
cross = M.attach(M.place("cross", "Cross", drop=0.3, width=0.6, pin_r=pin), "tongue", M.place("link", "Shin2", length=2.4, width=0.8, depth=0.8, pin_r=pin), "clevis", 0.0)
second = feet.kestrel_talons("Foot2", None, width=1.0, length=1.9, drop=0.46, pin_r=pin)
M.attach(second.core, "tongue_roll", cross, "clevis")
second.done()
M.update()
gap = (second.core.matrix_world.translation - M.sockets(cross)["clevis"].translation).length
print("DROPIN tongue_roll under a cross's clevis: pin", round(gap, 6), "m off; toes followed:", all(t["segs"][0].parent is not None for t in second.toes))
bad += gap > 1e-5
print("DROPIN", "FAILED" if bad else "OK")
sys.exit(1 if bad else 0)

View file

@ -0,0 +1,104 @@
"""The feet library's two sheets, from feet_bench.py's renders. Plain Python (Pillow), no Blender.
usage: python feet_sheets.py MECH_OUT: where feet/ is and where the sheets go; MECH_CONCEPTS: the concept sheets.
catalog_feet.png: per foot, its concept crop, the foot planted, its parameter variant, and its name, parameters,
joints and rams (feet_report_catalog.json). feet_motion.png: per foot, heel strike, flat plant and toe-off."""
import ast, json, os, textwrap
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont
HERE = Path(__file__).resolve().parent
OUT, CONCEPTS = Path(os.environ["MECH_OUT"]), Path(os.environ["MECH_CONCEPTS"])
assert OUT.is_absolute()
SRC = OUT / "feet"
try:
FONT, BOLD, MONO = ImageFont.truetype("arial.ttf", 19), ImageFont.truetype("arialbd.ttf", 26), ImageFont.truetype("consola.ttf", 17)
except OSError:
FONT = BOLD = MONO = ImageFont.load_default()
BG = (22, 22, 22)
def registry():
"""feet.FEET as the source declares it, read without Blender: each @concept call and its function's signature."""
out = {}
for node in ast.parse((HERE / "feet.py").read_text(encoding="utf-8")).body:
if isinstance(node, ast.FunctionDef) and node.decorator_list and getattr(node.decorator_list[0].func, "id", "") == "concept":
call = node.decorator_list[0]
args = [ast.literal_eval(a) for a in call.args]
names = [a.arg for a in node.args.args]
defaults = [ast.literal_eval(d) for d in node.args.defaults]
params = dict(zip(names[len(names) - len(defaults):], defaults))
out[node.name] = {"sheet": args[0], "number": args[1], "crop": args[2], "params": {k: v for k, v in params.items() if k not in ("shin", "socket")},
"doc": " ".join(ast.get_docstring(node).split())}
return out
def fit(img, w, h):
s = min(w / img.width, h / img.height)
img = img.resize((max(1, round(img.width * s)), max(1, round(img.height * s))), Image.LANCZOS)
cell = Image.new("RGB", (w, h), BG)
cell.paste(img, ((w - img.width) // 2, (h - img.height) // 2))
return cell
def caption(cell, text):
d = ImageDraw.Draw(cell)
d.rectangle((0, 0, d.textlength(text, font=FONT) + 16, 28), fill=(0, 0, 0))
d.text((8, 3), text, font=FONT, fill=(235, 235, 235))
return cell
def catalog():
reg = registry()
report = json.loads((SRC / "feet_report_catalog.json").read_text(encoding="utf-8")) if (SRC / "feet_report_catalog.json").exists() else {}
cw, ch, tw = 470, 400, 640
names = [n for n in reg if (SRC / f"{n}.png").exists()]
sheet = Image.new("RGB", (3 * cw + tw + 5 * 8, len(names) * (ch + 8) + 8), BG)
for row, name in enumerate(names):
e, y = reg[name], 8 + row * (ch + 8)
crop = Image.open(CONCEPTS / f"{e['number']}.webp").convert("RGB").crop(tuple(e["crop"]))
sheet.paste(caption(fit(crop, cw, ch), f"concept {e['number']}: {e['sheet']}"), (8, y))
sheet.paste(caption(fit(Image.open(SRC / f"{name}.png").convert("RGB"), cw, ch), "built, planted"), (16 + cw, y))
rep = report.get(name, {})
var = SRC / f"{name}_var.png"
if var.exists():
vt = ", ".join(f"{k}={v}" for k, v in rep.get("variant", {}).items()) or "variant"
sheet.paste(caption(fit(Image.open(var).convert("RGB"), cw, ch), vt), (24 + 2 * cw, y))
d = ImageDraw.Draw(sheet)
x = 32 + 3 * cw
d.text((x, y + 4), f"feet.{name}", font=BOLD, fill=(240, 240, 240))
lines = textwrap.wrap(", ".join(f"{k}={v}" for k, v in e["params"].items()), 60)
joints = rep.get("joints", {}).get("joints", [])
if rep:
pitch = sum(1 for j in joints if j.get("mechanism") == "toe_pitch")
splay = sum(1 for j in joints if j.get("mechanism") == "toe_splay")
rams = rep.get("rams", [])
lines += ["", f"{rep['toes']} toes, {rep['segments']} segments; kit joints: {pitch} pitch, {splay} splay",
f"rams seated by ram core: {sum(1 for r in rams if r['ok'])} of {len(rams)}" + (f"; ram/armour overlaps: {len(rep.get('clashes', []))}" if rams else "")]
for k, line in enumerate(lines):
d.text((x, y + 42 + 21 * k), line, font=MONO, fill=(170, 210, 170) if k < len(lines) - (3 if rep else 0) else (210, 200, 150))
for k, line in enumerate(textwrap.wrap(e["doc"], 66)[:11]):
d.text((x, y + 42 + 21 * len(lines) + 12 + 22 * k), line, font=FONT, fill=(200, 200, 200))
sheet.save(OUT / "catalog_feet.png")
print("WROTE", OUT / "catalog_feet.png", sheet.size, len(names), "feet")
def motion():
reg = registry()
names = [n for n in reg if (SRC / f"{n}_motion.png").exists()]
w, h = 1800, 620
sheet = Image.new("RGB", (w + 16, len(names) * (h + 8) + 8), BG)
for row, name in enumerate(names):
y = 8 + row * (h + 8)
strip = Image.open(SRC / f"{name}_motion.png").convert("RGB")
d = ImageDraw.Draw(strip)
d.rectangle((0, 0, w, 34), fill=(0, 0, 0))
d.text((10, 3), f"feet.{name} ({reg[name]['sheet']})", font=BOLD, fill=(240, 240, 240))
for k, text in enumerate(("heel strike: nose up 14, rear toes flat, toes closed", "flat plant: toes fanned", "toe-off: heel up 38, toes rolled and left on the ground")):
d.text((w * (2 * k + 1) // 6 - d.textlength(text, font=FONT) // 2, h - 30), text, font=FONT, fill=(20, 20, 20))
sheet.paste(strip, (8, y))
sheet.save(OUT / "feet_motion.png")
print("WROTE", OUT / "feet_motion.png", sheet.size, len(names), "feet")
catalog()
motion()

View file

@ -2,7 +2,8 @@
import json, sys
from pathlib import Path
SURFACE = Path(__file__).resolve().parents[2]
import os
SURFACE = Path(os.environ["BROKKR_SURFACE"]) if os.environ.get("BROKKR_SURFACE") else Path(__file__).resolve().parents[2] # the add-on tree the kit is written into
sys.path.insert(0, str(SURFACE))
@ -51,7 +52,7 @@ parts = []
parts.append({
"name": "link", "doc": "Limb girder along +z: a tongue on a pin axis (x) at z=0, a clevis at z=length, side plates, web, ribs and bolt rows. Pin sockets lie on the centre plane, so links of any width hinge centred.",
"params": [P("length", 0.3, 5.0, 1.2), P("width", 0.08, 1.0, 0.3, "x extent"), P("depth", 0.08, 1.0, 0.3, "y extent"), P("pin_r", 0.015, 0.2, 0.05)],
"params": [P("length", 0.08, 5.0, 1.2), P("width", 0.04, 1.2, 0.3, "x extent"), P("depth", 0.03, 1.0, 0.3, "y extent"), P("pin_r", 0.008, 0.2, 0.05)],
"bevel": "0.02*min(width,depth)",
"shapes": [
xtube("1.6*pin_r", "0.6*width", "-0.3*width", 0, 0, 32),
@ -385,6 +386,83 @@ parts.append({
],
"sockets": [S("mount", "mount", "0.8*r", [0, 0, 0], "-z", "+y"), S("cap", "mount", "0.6*r", [0, 0, "t"], "+z", "+y")]})
# --- articulated feet (feet.py): a core on the ankle pin, a knuckle per toe on a vertical splay pin, toe segments on pitch pins
TOES = "abcdef"
parts.append({
"name": "foot_core", "doc": "The carriage of an articulated foot on an ankle pin (x) at z=0, the ground at z=drop, +y the front: hub, column and a deck with six vertical toe pins under it at (tNx, tNy), each a splay hinge (toe_N, a pivot: the roll is the toe's yaw) and a fixed seat (seat_N, a mount) on one frame. A pin left at 0, 0 stands inside the column. Takes the sockets of the kit's other feet (tongue, tongue_roll, instep, heel), so it seats where they do.",
"params": [P("width", 0.1, 3.0, 0.6), P("length", 0.2, 4.0, 1.0), P("drop", 0.1, 1.5, 0.36), P("pin_r", 0.015, 0.25, 0.05), P("toe_pin_r", 0.008, 0.2, 0.03, "every toe pin's radius"),
P("toe_h", 0.15, 0.95, 0.6, "the toe pins' seat plane, as a fraction of drop below the ankle pin")]
+ [P(f"t{k}{c}", -3.0, 3.0, 0.0, f"toe pin {k}: {c} in the core's frame") for k in TOES for c in "xy"],
"bevel": "0.02*width",
"shapes": [
xtube("1.6*pin_r", "0.6*width", "-0.3*width", 0, 0, 32),
box(["0.6*width", "3.4*pin_r", "toe_h*drop"], [0, 0, "0.5*toe_h*drop"]),
box(["0.7*width", "0.4*length", "0.3*toe_h*drop"], [0, "0.04*length", "0.85*toe_h*drop"]),
] + [ztube("1.9*toe_pin_r", "0.2*toe_h*drop", f"t{k}x", f"t{k}y", "0.8*toe_h*drop", 16) for k in TOES],
"sockets": [S("tongue", "pivot", "2*pin_r", [0, 0, 0], "+x", "+z"),
S("instep", "mount", "0.3*width", [0, "0.22*length", "0.7*drop"], "-z", "+y"), S("heel", "mount", "0.3*width", [0, "-0.36*length", "0.72*drop"], "-z", "+y")]
+ [S(f"{name}{sfx}", "mount", "0.4*width", [f"{sign}0.27*width", y, z], "-z", "+y") for name, y, z in (("instep", "0.22*length", "0.7*drop"), ("heel", "-0.3*length", "0.72*drop"))
for sfx, sign in (("_l", "-"), ("_r", ""))]
+ [S("tongue_roll", "pivot", "2*pin_r", [0, 0, 0], "+y", "+z")]
+ [S(f"toe_{k}", "pivot", "2*toe_pin_r", [f"t{k}x", f"t{k}y", "toe_h*drop"], "+z", "+y") for k in TOES]
+ [S(f"seat_{k}", "mount", "2*toe_pin_r", [f"t{k}x", f"t{k}y", "toe_h*drop"], "+z", "+y") for k in TOES]})
parts.append({
"name": "toe_knuckle", "doc": "A toe's root, z down and +y along the toe: a bush on a vertical pin at the origin (splay, a pivot whose roll is the toe's yaw; seat, the same frame as a fixed mount) and, `reach` ahead and 1.6 pin_r below, a clevis on a pin along x for the toe's first segment (its roll is the toe's pitch, positive lifting the toe).",
"params": [P("pin_r", 0.008, 0.2, 0.03), P("reach", 0.02, 1.5, 0.1), P("width", 0.04, 1.2, 0.2, "the toe's width")],
"bevel": "0.1*pin_r",
"shapes": [
ztube("1.9*pin_r", "0.4*pin_r", 0, 0, 0, 16),
box(["width", "3.8*pin_r", "2.4*pin_r"], [0, 0, "1.6*pin_r"]),
rep(2, ["0.86*width", 0, 0], box(["0.14*width", "reach", "2.4*pin_r"], ["-0.43*width", "0.5*reach", "1.6*pin_r"])),
rep(2, ["0.86*width", 0, 0], xtube("1.9*pin_r", "0.14*width", "-0.5*width", "reach", "1.6*pin_r", 24)),
xtube("pin_r", "1.2*width", "-0.6*width", "reach", "1.6*pin_r"),
rep(2, ["1.24*width", 0, 0], xtube("1.5*pin_r", "0.08*width", "-0.66*width", "reach", "1.6*pin_r", 6, False)),
],
"sockets": [S("splay", "pivot", "2*pin_r", [0, 0, 0], "-z", "+y"), S("seat", "mount", "2*pin_r", [0, 0, 0], "-z", "+y"),
S("clevis", "pivot", "2*pin_r", [0, "reach", "1.6*pin_r"], "-x", "+y")]})
parts.append({
"name": "toe", "doc": "A toe's last segment along +z: a tongue on a pin axis (x) at z=0 and a beam to z=length, +y its back (the armour's side), -y its sole. No clevis: nothing hinges beyond it.",
"params": [P("length", 0.08, 3.0, 0.4), P("width", 0.04, 1.2, 0.2), P("depth", 0.03, 1.0, 0.16), P("pin_r", 0.008, 0.2, 0.03)],
"bevel": "0.02*min(width,depth)",
"shapes": [
xtube("1.6*pin_r", "0.6*width", "-0.3*width", 0, 0, 32),
box(["0.6*width", "min(depth,3.2*pin_r)", "0.5*length"], [0, 0, "0.25*length"]),
box(["0.5*width", "0.5*depth", "0.5*length"], [0, 0, "0.45*length"]),
],
"sockets": [S("tongue", "pivot", "2*pin_r", [0, 0, 0], "+x", "+z"), S("top", "mount", "0.5*width", [0, "0.4*depth", "0.6*length"], "+y", "+z"),
S("sole", "mount", "0.5*width", [0, "-0.4*depth", "0.6*length"], "-y", "+z")]})
# --- a biped whose every joint is a pin (bipedkit.py): a hip beam and a trunk whose limb sockets are pivots
parts.append({
"name": "hipbeam", "doc": "The root of a pinned biped (bipedkit.py): a beam along the hip axis (x) with a fore-and-aft pin at each end (hip_l, hip_r: a pivot along +y, the leg's splay) and a vertical pin on a boss on top (waist: a pivot about +z, the torso's yaw). Every limb socket is a pivot, so each connection carries a joint record.",
"params": [P("span", 0.3, 5.0, 2.0, "between the two hip pins"), P("depth", 0.1, 2.5, 0.8), P("height", 0.1, 2.0, 0.7), P("pin_r", 0.015, 0.25, 0.1), P("waist_r", 0.05, 1.5, 0.5), P("waist_z", 0.1, 3.0, 0.8, "the waist pin's seat above the hip axis")],
"bevel": "0.02*height",
"shapes": [
box(["span", "depth", "height"], [0, 0, 0]),
rep(2, ["span", 0, 0], ytube("2.2*pin_r", "1.1*depth", "-0.5*span", "-0.55*depth", 0, 24)),
ztube("waist_r", "waist_z-0.3*height", 0, 0, "0.3*height", 32),
ztube("1.15*waist_r", "0.12*waist_z", 0, 0, "0.88*waist_z", 32),
],
"sockets": [S("hip_l", "pivot", "2*pin_r", ["-0.5*span", 0, 0], "+y", "+z"), S("hip_r", "pivot", "2*pin_r", ["0.5*span", 0, 0], "+y", "+z"),
S("waist", "pivot", "2*waist_r", [0, 0, "waist_z"], "+z", "+y"),
S("front", "mount", "0.5*height", [0, "0.5*depth", 0], "+y", "+z"), S("back", "mount", "0.5*height", [0, "-0.5*depth", 0], "-y", "+z")]})
parts.append({
"name": "trunk", "doc": "The torso's spine of a pinned biped (bipedkit.py): a vertical pin at z=0 (base: a pivot, its roll the torso's yaw on a hipbeam's waist), a column to a shoulder beam at (sy, sz) with a fore-and-aft pin at each end (shoulder_l, shoulder_r at +-sx: a pivot along +y, the arm's abduction).",
"params": [P("waist_r", 0.05, 1.5, 0.5), P("pin_r", 0.015, 0.25, 0.1), P("sx", 0.2, 5.0, 2.0, "half the span between the shoulder pins"), P("sy", -3.0, 3.0, 0.0), P("sz", 0.3, 6.0, 2.0), P("depth", 0.1, 3.0, 0.8)],
"bevel": "0.02*depth",
"shapes": [
ztube("waist_r", "0.12*sz", 0, 0, 0, 32),
box(["1.2*waist_r", "depth", "sz"], [0, "0.5*sy", "0.5*sz"]),
box(["2*sx", "0.7*depth", "0.7*depth"], [0, "sy", "sz"]),
rep(2, ["2*sx", 0, 0], ytube("2.2*pin_r", "0.9*depth", "-sx", "sy-0.45*depth", "sz", 24)),
],
"sockets": [S("base", "pivot", "2*waist_r", [0, 0, 0], "-z", "+y"),
S("shoulder_l", "pivot", "2*pin_r", ["-sx", "sy", "sz"], "+y", "+z"), S("shoulder_r", "pivot", "2*pin_r", ["sx", "sy", "sz"], "+y", "+z"),
S("top", "mount", "waist_r", [0, "sy", "sz+0.35*depth"], "+z", "+y")]})
talon = next(p for p in parts if p["name"] == "talon")
trident = json.loads(json.dumps(talon))
trident["name"], trident["doc"] = "trident", "A three-toed foot on an ankle pin (x) at z=0: the talon with a middle toe and a short heel."
@ -392,7 +470,7 @@ trident["shapes"] += [box(["0.26*width", "0.62*length", "0.46*drop"], [0, "0.5*l
parts.append(trident)
kit = {"schema": "brokkr.kit.v0", "kit": "mech", "doc": "Mech-scale structure for the armor-shell experiment: girders, yokes, slew rings, rams, lugs, feet, hull frames, guns.",
"socketTypes": {"flange": {"match": "equal", "doc": "bolted pipe or duct face; size is the bore diameter"}, "mount": {"match": "fits", "doc": "flat seat; size is the free diameter around the socket"}, "pivot": {"match": "equal", "doc": "pin joint on the pin's centre plane; size is the pin diameter"}},
"socketTypes": {"flange": {"match": "equal", "doc": "bolted pipe or duct face; size is the bore diameter"}, "mount": {"match": "fits", "doc": "flat seat; size is the free diameter around the socket"}, "pivot": {"match": "equal", "dof": "revolute", "doc": "pin joint on the pin's centre plane; size is the pin diameter; the child turns about the socket's z"}},
"parts": parts}
out = SURFACE / "brokkr_kitbash" / "kits" / "mech.v0.json"
out.write_text(json.dumps(kit, indent=1), encoding="utf-8")

View file

@ -38,6 +38,9 @@ Round 4 (massing first, then attachment, then layering), none of it a Brokkr act
silhouette / closeup / field_views, compare.py masks, joint close-ups and the comparison sheets. Needs: a
concept outline that is not traced by hand (concepts.json).
cache_kits each checked kit kept for the session. Needs: core.load_kit to keep a kit
by its file's modification time (it checks the whole file at every call of every action).
Round 8:
canted_hip / lay(cant=True) the legs' splay: the hip's slew ring on a wedge, its axis tipped by the lean of
@ -99,6 +102,15 @@ def setup():
materials()
def cache_kits():
"""Keep each checked kit for the session. core.load_kit reads and checks the whole kit file at every call, and
every kit action calls it several times: 183 calls and 23 of the 27 seconds of one 13-part foot. A kit file
edited after this is not read again."""
import functools
if not hasattr(KB.core.load_kit, "cache_info"):
KB.core.load_kit = functools.lru_cache(maxsize=None)(KB.core.load_kit)
def material(name, color, metallic=0.0, rough=0.5, emission=None, coat=0.0):
mat = bpy.data.materials.new(name)
mat.use_nodes = True
@ -711,8 +723,9 @@ def _turn_and_stretch(name, to_host):
def shell_action(name, sheet, build, mat, thickness=0.05, offset=-1.0, levels=3, bevel=0.0):
"""A faceted, hollow plate by brokkr_kitbash.shell on a Build's host: `sheet` is its document ({rings, closed,
mirror, creases, rim, flip}) in the component's frame. The shell is parented to build.host and stands where
"""A faceted, hollow plate by brokkr_kitbash.shell on a Build's host: `sheet` is its document, a loft ({rings,
closed, mirror, creases, rim, flip}) or a free cage ({verts, faces, creases, corners, poles, mirror, rim, flip}),
in the component's frame. The shell is parented to build.host and stands where
Build.done puts a Geo: the turn and move of build.to_host are the object's matrix, and its sizes and mirror are
written into the ring points, since the kitbash actions cut and rib only an unscaled object. A mirror reverses
`flip`, so the wall stays on the plate's inside; on a sheet that is itself mirrored about x it changes nothing. A
@ -724,16 +737,20 @@ def shell_action(name, sheet, build, mat, thickness=0.05, offset=-1.0, levels=3,
turn, stretch = _turn_and_stretch(name, Matrix.Identity(4) if build.to_host is None else Matrix(build.to_host))
sx, sy, sz = (stretch[k][k] for k in range(3))
sheet = dict(sheet)
if sheet.get("mirror"):
sheet["rings"] = [[[abs(sx) * p[0], sy * p[1], sz * p[2]] for p in ring] for ring in sheet["rings"]] # the cage is its own mirror image about x
mx = abs(sx) if sheet.get("mirror") else sx # a mirrored cage is its own mirror image about x
if "verts" in sheet:
sheet["verts"] = [[mx * p[0], sy * p[1], sz * p[2]] for p in sheet["verts"]]
else:
sheet["rings"] = [[[sx * p[0], sy * p[1], sz * p[2]] for p in ring] for ring in sheet["rings"]]
if sx < 0:
sheet["flip"] = not sheet.get("flip", False)
sheet["rings"] = [[[mx * p[0], sy * p[1], sz * p[2]] for p in ring] for ring in sheet["rings"]]
if mx < 0:
sheet["flip"] = not sheet.get("flip", False)
result = bpy.ops.brokkr_kitbash.shell(object_name=name, sheet=json.dumps(sheet), thickness=thickness, offset=offset, levels=levels, bevel=bevel, count_folds=True)
if "FINISHED" not in result:
raise SystemExit(f"shell {name}: {result}")
FOLDED[name] = json.loads(getattr(bpy.context.window_manager, KB.RESULT))["folded"]
report = json.loads(getattr(bpy.context.window_manager, KB.RESULT))
FOLDED[name] = report["folded"]
if "verts" in sheet:
print("CAGE", name, json.dumps({key: report[key] for key in ("cageVerts", "cageFaces", "triangles", "creases", "poles", "closed", "subdividedFaces", "facing")}), flush=True)
if FOLDED[name]:
print(f"FOLD {name}: {FOLDED[name]} inner faces of the wall fold at thickness {thickness:g}, levels {levels}", flush=True)
obj = bpy.data.objects[name]
@ -747,6 +764,44 @@ def shell_action(name, sheet, build, mat, thickness=0.05, offset=-1.0, levels=3,
return obj
def cage_wire(shell, width=0.012):
"""Three objects drawn over a shell, children of it, for a picture of its cage: the cage's uncreased edges as dark
rods, its creased edges (the rim's included, where the rim carries a weight) as thicker red ones, and a yellow
ball on each pole (a vertex whose valence is not 4 off the boundary, or not 2 or 3 on it). Read from the cage mesh
and its crease_edge attribute as brokkr_kitbash.shell wrote them. Returns the objects, for the caller to remove."""
cage = shell.data
weights = cage.attributes["crease_edge"].data
made = []
for label, color, creased, depth in (("edges", (0.01, 0.01, 0.01), False, width), ("creases", (1.0, 0.02, 0.02), True, 1.6 * width)):
curve = bpy.data.curves.new(f"{shell.name}.wire.{label}", "CURVE")
curve.dimensions, curve.bevel_depth, curve.bevel_resolution = "3D", depth, 2
for edge in cage.edges:
if (weights[edge.index].value > 0) == creased:
spline = curve.splines.new("POLY")
spline.points.add(1)
for point, v in zip(spline.points, edge.vertices):
point.co = (*cage.vertices[v].co, 1.0)
made.append((bpy.data.objects.new(curve.name, curve), color))
bm = bmesh.new()
bm.from_mesh(cage)
balls = bmesh.new()
for v in bm.verts:
if len(v.link_edges) not in ((2, 3) if v.is_boundary else (4,)):
bmesh.ops.create_icosphere(balls, subdivisions=2, radius=3.0 * width, matrix=Matrix.Translation(v.co))
bm.free()
mesh = bpy.data.meshes.new(f"{shell.name}.wire.poles")
balls.to_mesh(mesh)
balls.free()
made.append((bpy.data.objects.new(mesh.name, mesh), (1.0, 0.8, 0.0)))
for obj, color in made:
paint = bpy.data.materials.get("wire." + obj.name.rsplit(".", 1)[-1]) or material("wire." + obj.name.rsplit(".", 1)[-1], color, 0.0, 0.6, emission=(color, 1.5))
obj.data.materials.append(paint)
obj.parent = shell
bpy.context.scene.collection.objects.link(obj)
update()
return [obj for obj, _ in made]
def shells_sound():
"""Every shell shell_action made, as built: the folded inner faces the action counted, and the edges of its whole
evaluated stack (wall, cuts, bevel) that do not join exactly two faces. Prints a line a shell and the totals,
@ -1282,7 +1337,7 @@ def turntable(rig, cam, radius, out_dir, prefix, views=8, size=(1100, 1100), ele
# --- limbs -------------------------------------------------------------------------------------------------------
SIDE_SOCKETS = {"link": {"front": ("front_a", "front_b"), "back": ("back_a", "back_b")}, "thigh": {"front": ("front_a", "front_b"), "back": ("back_a", "back_b")}, "yoke": {"front": ("front",), "back": ("back",)},
"wrist": {"front": ("front",), "back": ("back",)}, "foot": {"front": ("instep",), "back": ("heel",)}, "talon": {"front": ("instep",), "back": ("heel",)}, "trident": {"front": ("instep",), "back": ("heel",)}}
"wrist": {"front": ("front",), "back": ("back",)}, "foot": {"front": ("instep",), "back": ("heel",)}, "talon": {"front": ("instep",), "back": ("heel",)}, "trident": {"front": ("instep",), "back": ("heel",)}, "foot_core": {"front": ("instep",), "back": ("heel",)}}
def occupied(part, socket):
@ -1848,7 +1903,7 @@ def canted_hip(tag, saddle, sock, slew, r, cant, sx):
# --- joint designs: one axis each, each a helper -------------------------------------------------------------------
TWIN = {sfx: {kind: {"front": tuple(n + sfx for n in v["front"]), "back": tuple(n + sfx for n in v["back"])} for kind, v in SIDE_SOCKETS.items() if kind in ("link", "thigh", "talon", "foot", "trident")}
TWIN = {sfx: {kind: {"front": tuple(n + sfx for n in v["front"]), "back": tuple(n + sfx for n in v["back"])} for kind, v in SIDE_SOCKETS.items() if kind in ("link", "thigh", "talon", "foot", "trident", "foot_core")}
for sfx in ("_l", "_r")}

View file

@ -0,0 +1,317 @@
"""Field paint for the mech experiments: one Cycles node group, MechPaint, and the materials that set its inputs.
Render only, from geometry alone: no UVs, no bakes, no image textures, so it costs no texture memory. It needs
bpy and nothing else of this folder, so any track can drop it beside its build.
The hook, after a mech is built and before it is rendered:
import paint; paint.apply("seraph")
apply(preset, ground=0.0, objects=None, scale=1.0, **overrides) swaps, by material name, every armour paint for
the preset's paint, every bare-metal material for its metal, every marking for its worn stencil; it leaves glass,
rubber, glows and pits alone; called again with another preset it repaints. Returns {old material name: new material}. `ground` is the world height of the
soles (mud and wet are measured from it); `scale` multiplies every noise frequency (a mech half as tall wants 2).
An override is any MechPaint input by its lower-case name with underscores, e.g. apply("mcr3", wear=1.4); it
reaches the armour and the markings, not the bare metal (material() tunes one role alone).
PRESETS seraph (cleaner, warm drab: 30.webp), mcr3 (grey drab, middling wear: 25.webp),
breaker (dark, heavy wear, mud to the knee: 24.webp), paladin (27.webp), kestrel (29.webp).
material(name, role="armour", preset="seraph", **overrides)
one material of a preset: role is armour, metal, mark or hazard.
group() the MechPaint node group (built once per file). Its layers, bottom up:
base paint Base Color, toned per plate by Object Info's Random and Geometry's Random Per Island (value,
and a little hue and saturation: Tone Variation), mottled by two world-space noises (Mottle).
cover a marking's own colour over the paint (Cover Color, Cover); Cover Wear opens it, by Alpha, to
the plate under the decal, in specks and in patches.
cavity grime Ambient Occlusion (4 samples, 0.45 m) darkens recesses, seams and the undersides of overhangs,
and a thin film lies in patches on open faces (Grime, Grime Color).
streaks noise stretched along world Z, on faces that stand upright, stronger where AO says something
hangs over them: dark runs and paler washed ones (Streaks).
dust pale dust on faces that look up (Dust).
edge wear the Bevel node's rounded normal leaves the true one near an edge; where the edge is exposed
(AO) and a noise passes a threshold, the paint is chipped to Chip Color with a ring of
Primer Color round it; scuffs on open faces (Wear).
mud and wet by height over Ground Z: wet darkening and gloss below Wet Top, mud thick below Mud Top and
in splashes to twice that (Mud, Wet).
Every noise reads the world position, so a pattern runs unbroken across neighbouring plates and under a decal;
that also means it swims if the mech moves: this is paint for stills.
"""
import bpy
GROUP = "MechPaint"
# name: (socket type, default). The order is the group's input order.
INPUTS = {
"Base Color": ("NodeSocketColor", (0.05, 0.044, 0.032, 1.0)),
"Roughness": ("NodeSocketFloat", 0.62),
"Metallic": ("NodeSocketFloat", 0.0),
"Tone Variation": ("NodeSocketFloat", 0.3),
"Mottle": ("NodeSocketFloat", 1.0),
"Cover Color": ("NodeSocketColor", (0.2, 0.19, 0.165, 1.0)),
"Cover": ("NodeSocketFloat", 0.0),
"Cover Wear": ("NodeSocketFloat", 0.5),
"Grime": ("NodeSocketFloat", 1.0),
"Grime Color": ("NodeSocketColor", (0.02, 0.017, 0.013, 1.0)),
"Streaks": ("NodeSocketFloat", 1.0),
"Dust": ("NodeSocketFloat", 0.5),
"Dust Color": ("NodeSocketColor", (0.17, 0.155, 0.125, 1.0)),
"Wear": ("NodeSocketFloat", 1.0),
"Chip Color": ("NodeSocketColor", (0.016, 0.015, 0.014, 1.0)),
"Chip Metallic": ("NodeSocketFloat", 0.85),
"Primer Color": ("NodeSocketColor", (0.1, 0.092, 0.074, 1.0)),
"Mud": ("NodeSocketFloat", 1.0),
"Mud Top": ("NodeSocketFloat", 1.4),
"Mud Color": ("NodeSocketColor", (0.026, 0.019, 0.013, 1.0)),
"Wet": ("NodeSocketFloat", 0.6),
"Wet Top": ("NodeSocketFloat", 3.0),
"Ground Z": ("NodeSocketFloat", 0.0),
"Scale": ("NodeSocketFloat", 1.0),
}
OUTPUTS = {"Color": "NodeSocketColor", "Metallic": "NodeSocketFloat", "Roughness": "NodeSocketFloat", "Normal": "NodeSocketVector", "Alpha": "NodeSocketFloat"}
_METAL = {"base_color": (0.03, 0.03, 0.03), "metallic": 0.75, "roughness": 0.5, "tone_variation": 0.3, "chip_color": (0.11, 0.11, 0.11), "chip_metallic": 1.0, "primer_color": (0.03, 0.03, 0.03),
"dust": 0.8, "grime": 1.2}
PRESETS = {
# SERAPH, 30.webp: a warm grey drab, the cleanest of the sheets; small chips, light streaks, mud on the feet only.
"seraph": {"armour": {"base_color": (0.066, 0.056, 0.038), "wear": 0.85, "grime": 0.8, "streaks": 0.8, "dust": 0.6, "mud": 0.8, "mud_top": 1.2, "wet_top": 2.0},
"metal": {**_METAL, "wear": 0.6, "mud": 0.8, "mud_top": 1.2},
"mark": {"cover_color": (0.22, 0.21, 0.18), "cover_wear": 0.55}},
# MCR-3, 25.webp: greyer and darker, every plate chipped along its edges, streaked, dirty to the shin.
"mcr3": {"armour": {"base_color": (0.048, 0.044, 0.034), "wear": 1.0, "grime": 1.0, "streaks": 1.0, "dust": 0.45, "mud": 1.0, "mud_top": 1.4, "wet_top": 2.4, "tone_variation": 0.32},
"metal": {**_METAL, "wear": 0.9},
"mark": {"cover_color": (0.2, 0.195, 0.175), "cover_wear": 0.5}},
# BREAKER, 24.webp: the same drab two stops down, the heaviest wear on any sheet, mud to the knee.
"breaker": {"armour": {"base_color": (0.03, 0.028, 0.021), "wear": 1.5, "grime": 1.3, "streaks": 1.3, "dust": 0.35, "mud": 1.3, "mud_top": 2.2, "wet_top": 4.0, "tone_variation": 0.35,
"primer_color": (0.12, 0.11, 0.09)},
"metal": {**_METAL, "wear": 1.3, "grime": 1.5, "mud": 1.3, "mud_top": 2.2},
"mark": {"cover_color": (0.19, 0.18, 0.15), "cover_wear": 0.75}},
# PALADIN, 27.webp: an olive greener than SERAPH's, middling wear.
"paladin": {"armour": {"base_color": (0.05, 0.052, 0.033), "wear": 0.9, "grime": 0.9, "streaks": 0.9},
"metal": {**_METAL, "wear": 0.8},
"mark": {"cover_wear": 0.5}},
# KESTREL, 29.webp: a light grey-green scout paint, thin wear, long streaks.
"kestrel": {"armour": {"base_color": (0.06, 0.062, 0.048), "wear": 0.8, "grime": 0.9, "streaks": 1.2, "mud_top": 1.0},
"metal": {**_METAL, "wear": 0.7},
"mark": {"cover_wear": 0.5}},
}
ROLES = {
"armour": {"khaki", "olive", "olive_light", "plate_olive", "plate_white", "plate_grey", "plate_sand", "drab", "drab_fit", "drab_dark", "drab_dark_fit"},
"metal": {"gunmetal", "frame", "machine", "structure", "plate_dark"},
"mark": {"stencil", "marking", "marking_fresh"},
"hazard": {"hazard", "accent_yellow"},
}
HAZARD = {"cover_color": (0.32, 0.2, 0.025), "cover_wear": 0.7}
class _Net:
"""Node wiring shorthand: a value is a socket or a constant."""
def __init__(self, tree):
self.tree, self.nodes, self.links = tree, tree.nodes, tree.links
def put(self, socket, value):
if value is None:
return
if hasattr(value, "is_linked"):
self.links.new(value, socket)
elif isinstance(value, (int, float)):
socket.default_value = float(value)
else:
socket.default_value = tuple(value) if len(value) == len(socket.default_value) else (*value, 1.0)
def math(self, op, a, b=None, c=None, clamp=False):
node = self.nodes.new("ShaderNodeMath")
node.operation, node.use_clamp = op, clamp
for socket, value in zip(node.inputs, (a, b, c)):
self.put(socket, value)
return node.outputs[0]
def mul(self, *values, clamp=False):
out = values[0]
for v in values[1:]:
out = self.math("MULTIPLY", out, v, clamp=clamp)
return out
def ramp(self, value, lo, hi, to=(0.0, 1.0)):
"""lo maps to to[0], hi to to[1], clamped; lo may exceed hi. lo and hi may be sockets."""
node = self.nodes.new("ShaderNodeMapRange")
for socket, v in zip(node.inputs, (value, lo, hi, to[0], to[1])):
self.put(socket, v)
return node.outputs[0]
def mix(self, a, b, fac, blend="MIX"):
node = self.nodes.new("ShaderNodeMix")
node.data_type, node.blend_type = "RGBA", blend
self.put(node.inputs[0], fac)
self.put(node.inputs[6], a)
self.put(node.inputs[7], b)
return node.outputs[2]
def vec(self, op, a, b=None, scale=None):
node = self.nodes.new("ShaderNodeVectorMath")
node.operation = op
self.put(node.inputs[0], a)
self.put(node.inputs[1], b)
self.put(node.inputs[3], scale)
return node.outputs["Value" if op == "DOT_PRODUCT" else "Vector"]
def noise(self, vector, scale, detail=4.0, rough=0.55, distortion=0.0):
node = self.nodes.new("ShaderNodeTexNoise")
node.inputs["Scale"].default_value, node.inputs["Detail"].default_value = scale, detail
node.inputs["Roughness"].default_value, node.inputs["Distortion"].default_value = rough, distortion
self.links.new(vector, node.inputs["Vector"])
return node.outputs[0]
def group():
"""The MechPaint node group; built on first call, then the one in the file."""
if GROUP in bpy.data.node_groups:
return bpy.data.node_groups[GROUP]
tree = bpy.data.node_groups.new(GROUP, "ShaderNodeTree")
for name, (kind, default) in INPUTS.items():
s = tree.interface.new_socket(name, in_out="INPUT", socket_type=kind)
s.default_value = default
for name, kind in OUTPUTS.items():
tree.interface.new_socket(name, in_out="OUTPUT", socket_type=kind)
n = _Net(tree)
gin, gout = tree.nodes.new("NodeGroupInput"), tree.nodes.new("NodeGroupOutput")
G = gin.outputs
geo, info = tree.nodes.new("ShaderNodeNewGeometry"), tree.nodes.new("ShaderNodeObjectInfo")
pos = n.vec("SCALE", geo.outputs["Position"], scale=G["Scale"])
xyz = tree.nodes.new("ShaderNodeSeparateXYZ")
tree.links.new(geo.outputs["Position"], xyz.inputs[0])
nrm = tree.nodes.new("ShaderNodeSeparateXYZ")
tree.links.new(geo.outputs["Normal"], nrm.inputs[0])
up = nrm.outputs["Z"]
height = n.math("SUBTRACT", xyz.outputs["Z"], G["Ground Z"])
# base paint: one tone per plate, mottled
rand = n.math("FRACT", n.math("ADD", info.outputs["Random"], n.math("MULTIPLY", geo.outputs["Random Per Island"], 0.7)))
rand2 = n.math("FRACT", n.math("MULTIPLY_ADD", rand, 7.31, 0.37))
hsv = tree.nodes.new("ShaderNodeHueSaturation")
tree.links.new(G["Base Color"], hsv.inputs["Color"])
n.put(hsv.inputs["Hue"], n.math("MULTIPLY_ADD", n.math("SUBTRACT", rand2, 0.5), n.math("MULTIPLY", G["Tone Variation"], 0.2), 0.5))
n.put(hsv.inputs["Saturation"], n.math("MULTIPLY_ADD", n.math("SUBTRACT", rand2, 0.5), G["Tone Variation"], 1.0))
n.put(hsv.inputs["Value"], n.math("MULTIPLY_ADD", n.math("MULTIPLY_ADD", rand, 2.0, -1.0), G["Tone Variation"], 1.0))
blotch, speck = n.noise(pos, 0.9, 5.0, 0.6), n.noise(pos, 28.0, 3.0, 0.6)
shade = n.math("ADD", n.math("ADD", n.ramp(blotch, 0.3, 0.7, (-0.3, 0.3)), n.ramp(speck, 0.3, 0.7, (-0.2, 0.2))), n.ramp(n.noise(pos, 6.0, 5.0, 0.7), 0.3, 0.7, (-0.22, 0.22)))
col = n.vec("SCALE", hsv.outputs["Color"], scale=n.math("MULTIPLY_ADD", shade, G["Mottle"], 1.0))
# a marking's own colour over it, worn through by Alpha
col = n.mix(col, n.vec("SCALE", G["Cover Color"], scale=n.ramp(n.noise(pos, 7.0, 4.0), 0.3, 0.7, (0.6, 1.05))), G["Cover"])
fine_lo, patch_lo = n.ramp(G["Cover Wear"], 0.0, 1.0, (0.7, 0.46)), n.ramp(G["Cover Wear"], 0.0, 1.0, (0.82, 0.46))
gone = n.math("MAXIMUM", n.ramp(n.noise(pos, 38.0, 3.0, 0.6, 1.2), fine_lo, n.math("ADD", fine_lo, 0.03)), n.ramp(n.noise(pos, 4.5, 5.0), patch_lo, n.math("ADD", patch_lo, 0.05)))
alpha = n.math("SUBTRACT", 1.0, n.mul(gone, n.math("MINIMUM", G["Cover"], 1.0)), clamp=True)
# cavity grime
ao = tree.nodes.new("ShaderNodeAmbientOcclusion")
ao.samples, ao.inputs["Distance"].default_value = 4, 0.45
occ = ao.outputs["AO"]
cavity = n.mul(n.ramp(occ, 0.93, 0.5), n.ramp(n.noise(pos, 5.0, 6.0, 0.7), 0.3, 0.6, (0.5, 1.0)), G["Grime"], clamp=True)
film = n.mul(n.ramp(n.noise(pos, 2.3, 7.0, 0.7), 0.5, 0.68), 0.5, G["Grime"])
grime = n.math("MAXIMUM", cavity, film)
col = n.mix(col, G["Grime Color"], n.math("MINIMUM", grime, 0.85))
# streaks down the upright faces
stretch = n.vec("MULTIPLY", pos, (13.0, 13.0, 0.5))
upright = n.ramp(n.math("ABSOLUTE", up), 0.8, 0.35)
under = n.ramp(occ, 0.98, 0.7, (0.45, 1.0))
broken = n.ramp(n.noise(pos, 1.4, 3.0), 0.35, 0.55, (0.15, 1.0))
dark_run = n.mul(n.ramp(n.noise(stretch, 1.0, 3.0, 0.5), 0.5, 0.66), upright, under, broken, G["Streaks"], clamp=True)
pale_run = n.mul(n.ramp(n.noise(n.vec("ADD", stretch, (31.0, 17.0, 5.0)), 1.0, 2.0, 0.5), 0.6, 0.74), upright, 0.32, G["Streaks"], clamp=True)
col = n.mix(col, G["Dust Color"], pale_run)
col = n.mix(col, G["Grime Color"], n.math("MULTIPLY", dark_run, 0.85))
# dust on what looks up
dust = n.mul(n.ramp(up, 0.45, 0.95), n.ramp(n.noise(pos, 3.0, 6.0, 0.7), 0.25, 0.7, (0.25, 1.0)), G["Dust"], 0.6, clamp=True)
col = n.mix(col, G["Dust Color"], dust)
# edge wear: chips to metal with a primer ring, scuffs on open faces
bevel = tree.nodes.new("ShaderNodeBevel")
bevel.samples, bevel.inputs["Radius"].default_value = 4, 0.14
edge = n.ramp(n.vec("DOT_PRODUCT", bevel.outputs["Normal"], geo.outputs["Normal"]), 0.9995, 0.98)
exposed = n.ramp(occ, 0.45, 0.85)
chip_noise = n.math("ADD", n.ramp(n.noise(pos, 5.0, 7.0, 0.72), 0.3, 0.7, (0.0, 0.6)), n.ramp(n.noise(pos, 45.0, 2.0), 0.3, 0.7, (-0.05, 0.05))) # 0 to 0.6, about evenly
level = n.math("ADD", chip_noise, n.mul(edge, exposed, G["Wear"], 0.5))
scuff = n.mul(n.ramp(n.noise(pos, 4.0, 9.0, 0.82), 0.66, 0.69), n.ramp(G["Wear"], 0.0, 1.5, (0.0, 1.0)))
metal = n.math("MAXIMUM", n.ramp(level, 0.74, 0.77), n.math("MULTIPLY", scuff, 0.85))
primer = n.math("MAXIMUM", n.ramp(level, 0.7, 0.73), scuff)
col = n.mix(col, G["Primer Color"], n.math("MULTIPLY", primer, 0.75))
col = n.mix(col, G["Chip Color"], metal)
# wet, then mud, from the ground up
wet = n.mul(n.ramp(height, G["Wet Top"], 0.0), G["Wet"], clamp=True)
col = n.vec("SCALE", col, scale=n.math("MULTIPLY_ADD", wet, -0.5, 1.0))
mud_noise = n.noise(pos, 3.2, 7.0, 0.7)
thick = n.mul(n.ramp(height, G["Mud Top"], 0.0), n.ramp(mud_noise, 0.35, 0.62, (0.1, 1.5)), n.ramp(occ, 0.95, 0.5, (0.7, 1.6)), G["Mud"])
splash = n.mul(n.ramp(n.noise(pos, 11.0, 4.0, 0.6), 0.62, 0.66), n.ramp(height, n.math("MULTIPLY", G["Mud Top"], 2.2), n.math("MULTIPLY", G["Mud Top"], 0.4)), G["Mud"], 0.85)
mud = n.math("MAXIMUM", n.ramp(thick, 0.2, 0.5), splash, clamp=True)
col = n.mix(col, n.vec("SCALE", G["Mud Color"], scale=n.ramp(mud_noise, 0.3, 0.7, (0.7, 1.3))), mud)
tree.links.new(col, gout.inputs["Color"])
tree.links.new(n.mul(n.math("MAXIMUM", G["Metallic"], n.math("MULTIPLY", metal, G["Chip Metallic"])), n.math("SUBTRACT", 1.0, mud), n.math("SUBTRACT", 1.0, n.math("MULTIPLY", grime, 0.7))), gout.inputs["Metallic"])
rough = n.math("ADD", G["Roughness"], n.math("ADD", n.math("MULTIPLY", grime, 0.25), n.math("MULTIPLY", metal, -0.22)))
rough = n.math("ADD", rough, n.math("MULTIPLY", wet, -0.12))
rough = n.math("ADD", rough, n.math("MULTIPLY", mud, 0.12), clamp=True)
tree.links.new(rough, gout.inputs["Roughness"])
bump = tree.nodes.new("ShaderNodeBump")
bump.inputs["Strength"].default_value, bump.inputs["Distance"].default_value = 0.35, 0.006
relief = n.math("ADD", n.math("MULTIPLY", speck, 0.25), n.math("ADD", n.math("MULTIPLY", metal, -1.0), n.mul(mud, mud_noise, 3.0)))
tree.links.new(relief, bump.inputs["Height"])
tree.links.new(bump.outputs["Normal"], gout.inputs["Normal"])
tree.links.new(alpha, gout.inputs["Alpha"])
return tree
def _input_name(key):
for name in INPUTS:
if name.lower().replace(" ", "_") == key:
return name
raise KeyError(f"MechPaint has no input {key!r}; it has " + ", ".join(k.lower().replace(" ", "_") for k in INPUTS))
def material(name, role="armour", preset="seraph", **overrides):
"""One MechPaint material: the preset's values for `role` (armour, metal, mark, hazard), then `overrides`."""
p = PRESETS[preset]
values = dict(p["armour"])
if role == "metal":
values = {**{k: v for k, v in values.items() if k in ("mud", "mud_top", "wet_top", "streaks")}, **p["metal"]}
elif role in ("mark", "hazard"):
values.update({"cover": 1.0, **(HAZARD if role == "hazard" else p["mark"])})
values.update(overrides)
mat = bpy.data.materials.get(name) or bpy.data.materials.new(name)
mat.use_nodes = True
nodes, links = mat.node_tree.nodes, mat.node_tree.links
nodes.clear()
out, bsdf, grp = nodes.new("ShaderNodeOutputMaterial"), nodes.new("ShaderNodeBsdfPrincipled"), nodes.new("ShaderNodeGroup")
grp.node_tree = group()
for key, value in values.items():
socket = grp.inputs[_input_name(key)]
socket.default_value = value if isinstance(value, (int, float)) else (*value, 1.0)
for a, b in (("Color", "Base Color"), ("Metallic", "Metallic"), ("Roughness", "Roughness"), ("Normal", "Normal")) + ((("Alpha", "Alpha"),) if role in ("mark", "hazard") else ()):
links.new(grp.outputs[a], bsdf.inputs[b])
bsdf.inputs["Specular IOR Level"].default_value = 0.35 # a matt paint under a bright sky: the default sheen greys every dark plate
links.new(bsdf.outputs[0], out.inputs[0])
key = "cover_color" if role in ("mark", "hazard") else "base_color"
base = values.get(key, INPUTS[_input_name(key)][1])
mat.diffuse_color = (*base[:3], 1.0)
mat["paint_role"] = role
return mat
def apply(preset="seraph", ground=0.0, objects=None, scale=1.0, roles=None, **overrides):
"""Repaint a built mech: see the module header. `roles` adds or moves material names, {name: role}."""
role_of = {name: role for role, names in ROLES.items() for name in names}
role_of.update(roles or {})
made, swapped = {}, {}
for obj in objects or bpy.context.scene.objects:
if obj.type not in {"MESH", "CURVE", "FONT"} or obj.get("stage"):
continue
for slot in obj.material_slots:
role = slot.material and (slot.material.get("paint_role") or role_of.get(slot.material.name)) # a painted mech can be repainted
if not role:
continue
if role not in made:
made[role] = material(f"paint_{preset}_{role}", role, preset, ground_z=ground, scale=scale, **({} if role == "metal" else overrides))
swapped[slot.material.name] = made[role]
slot.material = made[role]
return swapped

View file

@ -0,0 +1,58 @@
"""Render a saved mech .blend at a solved camera with the paint it was saved with, then with paint.apply():
the proof renders for paint.py.
blender --background --python paint_render.py -- <mech.blend> <cameras.json> <stem> <preset> [width] [samples] [crops]
cameras.json camsolve cameras, {"hero": ...}, at the build's scale
crops JSON, {tag: [x0, y0, x1, y1]} in the concept sheet's pixels: extra renders of the hero view cropped
Writes, under MECH_OUT: <stem>_old.png, <stem>_new.png, <stem>_new_<tag>.png (and <stem>_old_<tag>.png with
PAINT_OLD_CROPS set). PAINT_ONLY=new skips the old paint. A .blend without a stage gets mechlib.stage_field().
PAINT_VARIANTS=seraph,breaker,... instead renders the first crop once per preset, <stem>_variant_<preset>.png: the
presets' catalog (paint_sheets.py lays them out).
"""
import json, os, sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import bpy
import mechlib as M
import paint
args = sys.argv[sys.argv.index("--") + 1:]
blend, cams_path, stem, preset = args[:4]
width = int(args[4]) if len(args) > 4 else 1100
samples = int(args[5]) if len(args) > 5 else 64
crops = json.loads(args[6]) if len(args) > 6 else {}
OUT = Path(os.environ["MECH_OUT"])
assert OUT.is_absolute()
bpy.ops.wm.open_mainfile(filepath=blend)
scene = bpy.context.scene
M.MATS.update({m.name: m for m in bpy.data.materials})
if "Rig" in bpy.data.objects and scene.camera:
rig, cam = bpy.data.objects["Rig"], scene.camera
M.gpu(scene)
else:
if "mud" not in M.MATS:
M.mud_ground()
rig, cam, _, _ = M.stage_field(samples)
scene.cycles.samples, scene.cycles.use_denoising = samples, True
hero = json.loads(Path(cams_path).read_text(encoding="utf-8"))["hero"]
only = os.environ.get("PAINT_ONLY")
def shots(tag):
M.shot(rig, cam, 0, 0, 0, OUT / f"{stem}_{tag}.png", (width, width), solved=hero)
if tag == "new" or os.environ.get("PAINT_OLD_CROPS"):
for name, box in crops.items():
M.shot(rig, cam, 0, 0, 0, OUT / f"{stem}_{tag}_{name}.png", (min(width, 900), 0), solved=hero, box=box)
if os.environ.get("PAINT_VARIANTS"):
name, box = next(iter(crops.items()))
for p in os.environ["PAINT_VARIANTS"].split(","):
paint.apply(p)
M.shot(rig, cam, 0, 0, 0, OUT / f"{stem}_variant_{p}.png", (width, 0), solved=hero, box=box)
raise SystemExit(0)
if only != "new":
shots("old")
overrides = json.loads(os.environ.get("PAINT_OVERRIDES", "{}"))
print("PAINTED", {k: v.name for k, v in paint.apply(preset, **overrides).items()}, flush=True)
shots("new")

View file

@ -0,0 +1,73 @@
"""The paint track's two sheets, from paint_render.py's renders (plain Python, PIL):
paint_compare.png per mech: the concept's hero view, the build in its old paint, the build after paint.apply()
paint_variants.png the presets, each on the MCR-3 from chest to knee (paint_render.py under PAINT_VARIANTS)
paint_closeups.png per mech, chest, knee and foot: the concept's inset, the concept's hero view cropped to the
part, the old paint cropped the same, the new paint rendered at that crop
python paint_sheets.py MECH_OUT holds the renders and takes the sheets; MECH_CONCEPTS holds the concept sheets.
"""
import os
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont
OUT, CONCEPTS = Path(os.environ["MECH_OUT"]), Path(os.environ["MECH_CONCEPTS"])
# stem, title, concept sheet, the hero view's box on it, the old hero render, {part: (inset box, hero crop box)}
MECHS = (
("seraph", "SERAPH (30.webp), preset seraph", "30.webp", (0, 0, 700, 810), os.environ["PAINT_OLD_SERAPH"],
{"chest": ((703, 453, 857, 598), (200, 90, 520, 300)), "knee": ((436, 815, 598, 998), (400, 330, 600, 530)), "foot": ((606, 815, 818, 998), (400, 620, 660, 810))}),
("mcr3", "MCR-3 (25.webp), preset mcr3", "25.webp", (40, 0, 500, 600), os.environ["PAINT_OLD_MCR3"],
{"chest": ((5, 607, 203, 798), (200, 60, 400, 220)), "knee": ((208, 805, 363, 1010), (290, 310, 430, 450)), "foot": ((369, 805, 543, 1010), (280, 490, 480, 590))}),
)
BG, INK = (24, 25, 27), (225, 225, 220)
def font(size):
try:
return ImageFont.truetype("arial.ttf", size)
except OSError:
return ImageFont.load_default()
def fit(im, w, h):
"""im scaled to fit w x h, centred on the background."""
k = min(w / im.width, h / im.height)
im = im.resize((max(1, round(im.width * k)), max(1, round(im.height * k))), Image.LANCZOS)
cell = Image.new("RGB", (w, h), BG)
cell.paste(im, ((w - im.width) // 2, (h - im.height) // 2))
return cell
def grid(rows, cell, heads, path, pad=10, head=34):
"""rows: [(row label, [images])]; heads: the column titles."""
w, h = cell
cols = len(heads)
sheet = Image.new("RGB", (pad + cols * (w + pad), head + len(rows) * (h + pad + 26) + pad), BG)
d = ImageDraw.Draw(sheet)
for c, t in enumerate(heads):
d.text((pad + c * (w + pad), 8), t, INK, font(20))
for r, (label, ims) in enumerate(rows):
y = head + r * (h + pad + 26)
d.text((pad, y + 2), label, INK, font(17))
for c, im in enumerate(ims):
sheet.paste(fit(im, w, h), (pad + c * (w + pad), y + 24))
sheet.save(path)
print("WROTE", path, sheet.size)
compare, close = [], []
for stem, title, sheet_name, box, old_path, parts in MECHS:
concept = Image.open(CONCEPTS / sheet_name).convert("RGB")
old, new = Image.open(old_path).convert("RGB"), Image.open(OUT / f"{stem}_new.png").convert("RGB")
compare.append((title, [concept.crop(box), old, new]))
k = old.width / (box[2] - box[0])
for part, (inset, crop) in parts.items():
local = [round((crop[i] - box[i % 2]) * k) for i in range(4)]
close.append((f"{title}: {part}", [concept.crop(inset), concept.crop(crop), old.crop(local), Image.open(OUT / f"{stem}_new_{part}.png").convert("RGB")]))
grid(compare, (760, 900), ("concept, hero view", "old paint (the build as its track rendered it)", "new paint: paint.apply()"), OUT / "paint_compare.png")
grid(close, (560, 440), ("concept inset", "concept hero, cropped", "old paint, same crop", "new paint, rendered at the crop"), OUT / "paint_closeups.png")
variants = sorted(OUT.glob("mcr3_variant_*.png"))
if variants:
order = ["seraph", "kestrel", "paladin", "mcr3", "breaker"]
variants.sort(key=lambda f: order.index(f.stem.split("_variant_")[1]))
grid([("paint.apply(preset) on the MCR-3 build, cleanest to most worn", [Image.open(f).convert("RGB") for f in variants])], (460, 740), [f.stem.split("_variant_")[1] for f in variants], OUT / "paint_variants.png")

View file

@ -1,20 +1,23 @@
"""PALADIN: concept sheet images/27.webp, built on the method of Seraph's clean rebuild and the walker's: the
character line first, then mass as solids checked against the silhouettes, then plates.
"""PALADIN: concept sheet images/27.webp, second pass (aetheria-release:ruling:second-passes-all-mechs).
The character line is the chest's belt (paladin_form.BELT): the knuckle where the glacis under the turret breaks to
the hull's upright band, a chevron in plan with the amber lamp at its stem, carried outboard by the pauldrons'
knuckles and repeated above by the turret's visor band.
the hull's upright band, a chevron in plan with the amber lamp at its stem. The first pass built it first and it
landed; the hull, turret and their plates are kept from it (paladin_body.py).
PALADIN_STAGE: line (the hull, the turret and the pauldrons alone, plated: the belt and nothing else), volume (the
whole figure as solids, no plate), full (default). MECH_QUICK renders by Workbench. Writes under MECH_OUT/paladin/:
<stage>_<view>.png and <stage>_sil_<view>.png for the hero, rear and side views at the solved cameras
(paladin_cameras.json: the sheet's own pixels), <stage>_character.png (the hero camera cropped to the belt),
<stage>_edges_hero.json (mechlib.built_edges), <stage>_turn_*.png, component close-ups (full), paladin_report.json.
What this pass rebuilds (paladin_limbs.py):
the skeleton kit parts, every joint a pin with a joint record and limits (bipedkit.py): waist, per leg hip
splay, hip pitch, knee, ankle pitch, ankle roll and feet.paladin_hoof's toes; per arm shoulder
abduction, shoulder pitch, elbow. brokkr_kitbash.joints reports it (paladin_joints.json).
the cameras solved on the kit's joints as they stand, no horizon held (paladin_form.solve)
the plates thighs, shins, pauldrons, upper arms and the left forearm as free cages, the big ones fitted to
edges traced on the sheet (platecage.py over brokkr_reference's fit), layered base / shield /
block and lame; the detail pass by surface.Skin; then paint.apply("paladin").
The skeleton is paladin_form.JOINTS: every part is built on those points, so the cameras are solved from them before
anything is built (python paladin_form.py solve). The legs and arms are not kit parts: the joints are drawn as the
sheet draws them (hip drums, the library's kneecap on its bisector ring, ankle discs, the library's waist slew
ring), but nothing here turns on a kit socket, and brokkr_kitbash's joint records have nothing to read."""
PALADIN_STAGE: skeleton (the kit and the first pass's hull alone), full (default). MECH_QUICK renders by Workbench.
Writes under MECH_OUT/paladin/: <stage>_<view>.png and <stage>_sil_<view>.png for the hero, rear and side views at
the solved cameras (the sheet's own pixels), <stage>_character.png, <stage>_edges_hero.json (mechlib.built_edges),
<stage>_turn_*.png, component close-ups, paladin_report_<stage>.json (cameras, cages, fits, joints, the detail
pass), paladin_joints.json, paladin.blend."""
import json, math, os, sys, time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
@ -27,54 +30,62 @@ import bpy
t0 = time.time()
M.setup()
import addon_utils
if addon_utils.enable("brokkr_reference", default_set=True) is None:
raise SystemExit("brokkr_reference could not be enabled")
import bipedkit as BK
import paladin_limbs as PL
import platecage as PC
import surface
surface.materials()
M.material("lamp_amber", (0.02, 0.02, 0.02), 0.0, 0.2, emission=((1.0, 0.5, 0.05), 12.0))
F, T = M.frame_at, Matrix.Translation
STAGES = ("line", "volume", "full")
STAGE = os.environ.get("PALADIN_STAGE", "full")
AT = STAGES.index(STAGE)
FULL = STAGE == "full"
QUICK = bool(os.environ.get("MECH_QUICK"))
OUT = Path(os.environ["MECH_OUT"]) / "paladin"
assert OUT.is_absolute()
OUT.mkdir(parents=True, exist_ok=True)
FR = T(PF.WAIST)
PLATED = STAGE != "volume"
# --- the character line first: the hull, the turret, the pauldrons ------------------------------------------------------
torso = PB.torso_mass(FR)
turret = PB.turret_mass(FR)
pauldrons = {sx: PB.pauldron_mass(FR, sx) for sx in (-1, 1)}
slot = PB.visor_cut(FR)
PB.torso_plates(torso, plates=PLATED)
PB.turret_plates(turret, [slot], plates=PLATED)
for sx, pm in pauldrons.items():
PB.pauldron_plates(pm, sx, plates=PLATED)
if PLATED:
def adopt_named(host, *keys):
BK.adopt(host, [o for o in bpy.data.objects if o.parent is None and not o.get("stage") and not o.get("kit_part") and any(k in o.name for k in keys)])
# --- the skeleton, then the cameras on it ---------------------------------------------------------------------------
kits = PL.skeleton()
points = PL.joint_points()
print("JOINT POINTS " + ", ".join(f"{k} ({p[0]:.2f}, {p[1]:.2f}, {p[2]:.2f})" for k, p in points.items()), flush=True)
cams = PF.solve(points)
PL.CAMS.update(cams)
trunk, pelvis = kits["trunk"], kits["pelvis"]
M.update()
FR = trunk.matrix_world.copy()
print("skeleton s", round(time.time() - t0, 1), "waist", tuple(round(v, 3) for v in FR.translation), flush=True)
# --- the character line: the hull and the turret, as the first pass built them ------------------------------------------
with BK.Adopt(trunk):
torso = PB.torso_mass(FR)
turret = PB.turret_mass(FR)
slot = PB.visor_cut(FR)
PB.torso_plates(torso)
PB.turret_plates(turret, [slot])
MS.carve(turret, [slot])
PB.visor(FR)
PB.hatch(FR)
print("line s", round(time.time() - t0, 1), flush=True)
if AT >= 1:
import jointlib as J
import joints
import weapons_missile, weapons_rotary, weapons_sensor
PB.mast(FR)
PB.exchangers(FR)
PB.abdomen(FR)
for sx in (-1, 1):
PB.shoulder(FR, sx)
PB.upper_arm(sx)
PB.hip(sx)
PB.thigh(sx, plates=PLATED)
PB.knee(sx)
PB.shin(sx, plates=PLATED)
PB.foot(sx)
PB.pelvis()
rig = J.Rig("Waist", T((0, PF.WAIST[1] - 0.1, PF.WAIST[2] - 0.35)), -50.0, 50.0)
joints.slew_waist(rig, 0.0, r=0.8, torso=(1.3, 1.0, 0.3))
rig.done()
PB.forearm_left(plates=PLATED)
PB.put("Gatling", PB.aim(PF.JOINTS["elbow_r"], PF.JOINTS["muzzle_r"]), weapons_rotary.paladin_gatling, size="M")
PL.pauldron_core(FR, sx)
crowns, shoulders = {}, {}
if FULL:
for sx in (-1, 1):
PL.pauldron_shields(FR, sx, shoulders)
for sx in (-1, 1):
PL.pauldron_layers(FR, sx, shoulders)
PB.put("Battery", FR @ T((3.1, 0.45, 3.62)), weapons_missile.paladin_battery, size="M", cols=6, rows=4)
PB.put("EW", FR @ T((-3.1, 0.25, 2.95)), weapons_sensor.paladin_ew_module, size="M", dome=False, optic=False)
b = PB.put("EWLow", FR @ T((-3.1, 1.45, 2.55))) # the EW inset's lower case, forward on the pauldron's roof
@ -83,34 +94,92 @@ if AT >= 1:
for x in (-0.36, 0.0, 0.36):
b["glass"].box(T((x, 0.525, -0.3)), (0.26, 0.02, 0.26))
b.done()
print("volume s", round(time.time() - t0, 1), flush=True)
if FULL:
wy, wz = FR.translation.y, FR.translation.z
PB.mark("Mark07.band", "07", (1.15 + 1.8, wy + 1.47 + 2.4, wz + 1.5), (-0.61, -0.79, 0.0), 0.36)
PB.mark("Mark7.band", "7", (-1.15 - 1.8, wy + 1.47 + 2.4, wz + 1.5), (0.61, -0.79, 0.0), 0.34)
print("upper s", round(time.time() - t0, 1), flush=True)
if AT >= 2:
wy, wz = PF.WAIST[1], PF.WAIST[2]
PB.mark("Mark07.band", "07", (1.15 + 1.8, wy + 1.47 + 2.4, wz + 1.5), (-0.61, -0.79, 0.0), 0.36)
PB.mark("Mark07.pauldron", "07", (2.95, 6.0, wz + PF.PAULDRON_AT[2] + 0.55), (0, -1, 0), 0.42)
PB.mark("Mark07.thigh", "07", (-1.85, 6.0, 4.9), (0, -1, 0), 0.42)
PB.mark("Mark7.band", "7", (-1.15 - 1.8, wy + 1.47 + 2.4, wz + 1.5), (0.61, -0.79, 0.0), 0.34)
PB.triangle("Tri.thigh", (1.85, 6.0, 4.9), (0, -1, 0), 0.5)
PB.triangle("Tri.shin", (-1.8, 6.0, 2.5), (0, -1, 0), 0.34)
PB.triangle("Tri.pauldron", (-2.95, 6.0, wz + PF.PAULDRON_AT[2] + 0.5), (0, -1, 0), 0.4)
# --- the lower body ----------------------------------------------------------------------------------------------------
with BK.Adopt(pelvis):
PB.pelvis()
for sx in (-1, 1):
PB.hip(sx)
for s, sx in (("L", -1), ("R", 1)):
PL.leg_cores(s, sx)
if FULL:
for s, sx in (("L", -1), ("R", 1)):
PL.leg_shields(s, sx, crowns)
for s, sx in (("L", -1), ("R", 1)):
PL.leg_layers(s, sx, crowns)
PL.knee(s)
adopt_named(kits["legs"][s]["upper"], f"Thigh{s}")
adopt_named(kits["legs"][s]["lower"], f"Shin{s}")
print("legs s", round(time.time() - t0, 1), flush=True)
# --- the arms ----------------------------------------------------------------------------------------------------------
if FULL:
for s, sx in (("L", -1), ("R", 1)):
PL.upper_arm(s, sx)
adopt_named(kits["arms"][s]["upper"], f"UpperArm{s}")
PL.forearm_left(crowns)
adopt_named(kits["arms"]["L"]["lower"], "ForearmL", "HandL", "Emitter")
fr = kits["arms"]["R"]["lower"]
M.update()
elbow = fr.matrix_world.translation.copy()
PB.put("Gatling", PB.aim(elbow, fr.matrix_world @ Vector((0, 0, 1.0))), weapons_rotary.paladin_gatling, size="M")
adopt_named(fr, "Gatling")
print("arms s", round(time.time() - t0, 1), flush=True)
# --- the joints, as the kit reports them ----------------------------------------------------------------------------------
joints = BK.joints(pelvis)
rows = joints["joints"]
by_mech = {}
for row in rows:
by_mech[row["mechanism"]] = by_mech.get(row["mechanism"], 0) + 1
unlimited = [row["part"] for row in rows if row.get("limits") is None and row.get("min") is None]
knee = kits["legs"]["L"]["lower"]
try:
bpy.ops.brokkr_kitbash.roll(object_name=knee.name, roll=float(knee["kit_roll"]) + 170.0)
refused = False
M.reroll(knee, float(knee["bk_rest"]))
except RuntimeError as error:
refused = True
print("JOINTS a roll 170 past the knee's rest is refused:", str(error).strip().splitlines()[-1][:160], flush=True)
print("JOINTS", joints["schema"], "version", joints["version"], len(rows), "rows,", joints["rigid"], "rigid;", json.dumps(by_mech), "without limits:", unlimited or "none", flush=True)
(OUT / "paladin_joints.json").write_text(json.dumps(joints, indent=1), encoding="utf-8")
M.update()
lo, hi = M.bounds()
print("HEIGHT", round(hi.z - lo.z, 2), "LOW", round(lo.z, 2), "WIDTH", round(hi.x - lo.x, 2), "DEPTH", round(lo.y, 2), round(hi.y, 2), "stage", STAGE, "frozen", len(PB.FROZEN), "build s", round(time.time() - t0, 1), flush=True)
M.tops()
summary = PC.summary()
print("CAGES", json.dumps(summary), flush=True)
print("DETAIL", PL.DRESSED[0], "features placed,", len(PL.DRESS_FAILED), "failed", flush=True)
for line in PL.DRESS_FAILED:
print(" DETAIL FAILED", line, flush=True)
# --- the solved cameras, the views, the edges ---------------------------------------------------------------------------
if os.environ.get("PALADIN_BUILD_ONLY"):
raise SystemExit(0)
# --- paint, the solved cameras, the views, the edges -----------------------------------------------------------------------
import camsolve
cams = PF.cameras()
report = {"stage": STAGE, "height": round(hi.z - lo.z, 2), "width": round(hi.x - lo.x, 2), "frozen": len(PB.FROZEN), "cameras": {}}
import paint
if not os.environ.get("PALADIN_NO_PAINT"):
paint.apply("paladin", ground=0.0)
report = {"stage": STAGE, "height": round(hi.z - lo.z, 2), "width": round(hi.x - lo.x, 2), "frozen": len(PB.FROZEN), "cameras": {}, "cages": summary,
"plates": {k: {a: b for a, b in v.items() if a != "crown"} for k, v in PC.PLATES.items()}, "joints": {"rows": len(rows), "rigid": joints["rigid"], "by_mechanism": by_mech,
"without_limits": unlimited, "over_limit_roll_refused": refused},
"detail": {"placed": PL.DRESSED[0], "failed": PL.DRESS_FAILED}, "joint_points": {k: [round(c, 3) for c in p] for k, p in points.items()}}
for tag, cam in cams.items():
report["cameras"][tag] = {k: cam[k] for k in ("rms", "left_out", "lens", "lens_range", "azimuth", "elevation", "distance", "model", "worst")}
report["cameras"][tag]["projected"] = {k: [float(c) for c in camsolve.project(cam, [PF.world(k)])[0]] for k in PF.VIEWS[tag]["marks"]}
report["cameras"][tag]["eye_z"] = cam["C"][2]
report["cameras"][tag]["projected"] = {k: [float(c) for c in camsolve.project(cam, [points.get(k, PF.world(k))])[0]] for k in PF.VIEWS[tag]["marks"]}
(OUT / f"paladin_report_{STAGE}.json").write_text(json.dumps(report, indent=1), encoding="utf-8")
rig, cam, centre, radius = M.stage_field(8 if QUICK else int(os.environ.get("MECH_SAMPLES", 48)))
scene = bpy.context.scene
K = 3
PARTS_ONLY = bool(os.environ.get("PALADIN_PARTS_ONLY")) # the turns and close-ups alone: a rerun after the GPU ran out under them
PARTS_ONLY = bool(os.environ.get("PALADIN_PARTS_ONLY"))
for tag in ([] if PARTS_ONLY else cams):
box = cams[tag]["box"]
w = int(box[2] - box[0]) * K
@ -126,22 +195,23 @@ elif QUICK:
M.preview(rig, cam, cams["hero"], OUT / f"{STAGE}_character.png", 1328, CHARACTER)
else:
M.shot(rig, cam, radius, 0, 0, OUT / f"{STAGE}_character.png", (1328, 800), solved=cams["hero"], box=CHARACTER)
if PLATED and not PARTS_ONLY and not os.environ.get("PALADIN_NO_EDGES"):
if FULL and not PARTS_ONLY and not os.environ.get("PALADIN_NO_EDGES"):
armour = lambda name: not name.endswith((".machine", ".steel", ".rubber", ".glass", ".glow", ".glow_blue", ".lamp_amber")) and not name.startswith(("Mark", "Tri.")) # noqa: E731
(OUT / f"{STAGE}_edges_hero.json").write_text(json.dumps(M.built_edges(cams["hero"], keep=armour)), encoding="utf-8")
print("edges s", round(time.time() - t0, 1), flush=True)
for az in (() if PARTS_ONLY else (35, 90, 180) if not QUICK else (35, 180)):
M.shot(rig, cam, radius, az, 6.0, OUT / f"{STAGE}_turn_{az:03d}.png", (900, 900) if QUICK else (1100, 1100), margin=0.8, lens=85.0)
if STAGE == "full":
wz = PF.WAIST[2]
# the sheet's insets, each from about where the inset looks: (name, target, span, azimuth, elevation)
wy = PF.WAIST[1]
for az in (() if PARTS_ONLY and not os.environ.get("PALADIN_TURNS") else (35, 90, 180, -35) if not QUICK else (35, 90, 180)):
M.shot(rig, cam, radius, az, 6.0, OUT / f"{STAGE}_turn_{az % 360:03d}.png", (900, 900) if QUICK else (1100, 1100), margin=0.8, lens=85.0)
if FULL and not os.environ.get("PALADIN_NO_PARTS"):
wy, wz = FR.translation.y, FR.translation.z
P = {k: Vector(v) for k, v in points.items()}
# the sheet's insets, each from about where the inset looks, and the rebuilt plates: (name, target, span, azimuth, elevation)
shots = [("cockpit", (0, wy + 1.2, wz + 2.3), 4.2, -25, 8), ("battery", (2.95, wy + 0.6, wz + 3.5), 4.0, 28, -6), ("ew", (-2.9, wy + 0.6, wz + 3.2), 4.0, -30, 4), ("exchangers", (0, wy - 2.0, wz + 2.0), 5.6, 180, 0),
("gatling", tuple((Vector(PF.JOINTS["elbow_r"]) + Vector(PF.JOINTS["muzzle_r"])) / 2), 4.8, 40, 6), ("hand", PF.JOINTS["wrist_l"], 3.6, -40, 4),
("pelvis", (0, 0.8, 5.5), 4.2, 0, 0), ("knee", PF.JOINTS["knee_l"], 3.6, -55, 4), ("foot", (-1.85, 0.6, 0.6), 4.2, -40, 14)]
("gatling", tuple((P["elbow_r"] + P["muzzle_r"]) / 2), 4.8, 40, 6), ("hand", tuple(P["wrist_l"]), 3.6, -40, 4),
("pelvis", (0, 0.8, 5.5), 4.2, 0, 0), ("knee", tuple(P["knee_l"]), 3.6, -55, 4), ("foot", (P["ankle_l"].x, 0.6, 0.6), 4.2, -40, 14),
("pauldron_r", (3.1, wy + 0.3, wz + 1.9), 4.4, 38, 4), ("pauldron_side", (3.1, wy + 0.3, wz + 1.9), 4.4, 90, 2), ("pauldron_rear", (-3.1, wy + 0.3, wz + 1.9), 4.4, 150, 6),
("thigh_r", tuple((P["hip_r"] + P["knee_r"]) / 2), 3.8, 25, 2), ("shin_r", tuple((P["knee_r"] + P["ankle_r"]) / 2), 3.8, 25, 2),
("leg_side", tuple(P["knee_r"]), 6.4, 90, 2), ("forearm_l", tuple((P["elbow_l"] + P["wrist_l"]) / 2), 3.4, -30, 4)]
for name, target, span, az, el in shots:
M.closeup(rig, cam, Vector(target), 0.42 * span, az, el, OUT / f"part_{name}.png", (700, 620))
bpy.ops.wm.save_as_mainfile(filepath=str(OUT / "paladin.blend"))
if not PARTS_ONLY:
(OUT / f"paladin_report_{STAGE}.json").write_text(json.dumps(report, indent=1), encoding="utf-8")
print("total s", round(time.time() - t0, 1))

View file

@ -10,9 +10,9 @@ Tools here, each used by more than one part:
sided(points, sx) points written with x outboard, for a side
mark(...) / triangle(...) a stencil seated on whatever a ray hits
Parts, in the order paladin.py builds them (the character line first): torso_mass, turret_mass, pauldron_mass;
torso_plates, turret_plates, visor, pauldron_plates; mast, shoulder, exchangers, abdomen, pelvis, hip, thigh, knee,
shin, foot, upper_arm, forearm_left.
Parts kept from the first pass, where the character line landed: torso_mass, turret_mass, torso_plates,
turret_plates, visor, hatch, mast, shoulder, exchangers, abdomen, pelvis, hip. The skeleton, the pauldrons and the
limbs' armour are the second pass's: paladin_limbs.py.
"""
import math
@ -214,27 +214,6 @@ def turret_mass(frame, mat=P):
return mass("Turret.mass", both(pts), frame @ T(t["at"]), mat)
def pauldron_profile():
p = PF.PAULDRON
return [(-p["crown"][0], p["crown"][1]), (-0.1, p["crown"][1] + 0.05), (-p["knuckle"][0], p["knuckle"][1]), (-p["foot"][0], p["foot"][1]), (-p["inner_foot"][0], p["inner_foot"][1]), (-1.0, 0.2)]
def pauldron_frame(frame, sx):
at = PF.PAULDRON_AT
return frame @ T((-sx * at[0], at[1], at[2]))
def pauldron_mass(frame, sx, mat=P):
"""A pauldron: the profile (outboard, up) drawn fore and aft, the ends drawn in. Its knuckle stands outboard at
the belt's height; the roof falls to it from the crown, the skirt is cut back under it."""
p, prof = PF.PAULDRON, pauldron_profile()
hy, nose = p["half_y"], p["nose"]
pts = []
for y, k in ((hy, 0.8), (hy - nose, 1.0), (-hy + nose, 1.0), (-hy, 0.8)):
pts += [(u * k, y, z * k + (0.1 if k < 1 else 0.0)) for u, z in prof]
return mass(f"Pauldron{'L' if sx < 0 else 'R'}.mass", sided(pts, sx), pauldron_frame(frame, sx), mat)
def torso_plates(solid, cutters=(), plates=True):
"""The hull's plates, cut along the hull's own creases (facets): the glacis plates stand furthest proud and end
on the belt, the band's plates stand under it, so the knuckle is a step; the stem between the band's halves
@ -288,20 +267,6 @@ def visor(frame):
return b.done()
def pauldron_plates(solid, sx, cutters=(), plates=True):
p = PF.PAULDRON
yb = p["half_y"] - p["nose"]
kz = p["knuckle"][1]
specs = [("Roof", band("z", kz + 0.02) + band("y", -yb + 0.03, yb - 0.03) + out(sx, -0.6), 0.14, 0.16, 0.05),
("Inner", band("y", -yb + 0.03, yb - 0.03) + out(sx, None, -0.64), 0.03, 0.1, 0.03),
("Skirt", band("z", None, kz - 0.03) + band("y", -yb + 0.03, yb - 0.03) + out(sx, -0.6), 0.05, 0.14, 0.04),
("FrontUp", band("y", yb + 0.02) + band("z", kz + 0.12), 0.16, 0.16, 0.05),
("FrontLow", band("y", yb + 0.02) + band("z", None, kz + 0.08), 0.08, 0.16, 0.05),
("RearUp", band("y", None, -yb - 0.02) + band("z", kz + 0.12), 0.12, 0.14, 0.04),
("RearLow", band("y", None, -yb - 0.02) + band("z", None, kz + 0.08), 0.06, 0.14, 0.04)]
return armour(f"Pauldron{'L' if sx < 0 else 'R'}", solid, specs, cutters, plates=plates)
# --- the rest of the upper body ----------------------------------------------------------------------------------------
def hatch(frame):
@ -413,7 +378,7 @@ def pelvis():
"""PELVIS & HIP ASSEMBLY inset: the hip beam; in front a long shield (the codpiece) under a centre block, a
hexagonal wing plate a side; a seat plate behind."""
hz = PF.JOINTS["hip_r"][2]
b = put("Pelvis", T((0, PF.JOINTS["hip_r"][1] + 0.05, hz)))
b = put("PelvisArmour", T((0, PF.JOINTS["hip_r"][1] + 0.05, hz)))
g, k = b["gunmetal"], b["khaki"]
g.hull([(0.95, 0.6, 0.45), (0.95, -0.6, 0.45), (0.95, 0.7, -0.35), (0.95, -0.65, -0.35), (0.6, 0.75, 0.6), (0.6, -0.7, 0.6), (0.55, 0.6, -0.75), (0.55, -0.5, -0.75)], mirror=True)
k.hull([(0.5, 0.78, 0.25), (0.42, 0.74, -1.0), (0.28, 0.76, -1.3), (0.4, 1.05, 0.1), (0.34, 1.12, -0.85), (0.22, 1.0, -1.2), (0.3, 0.95, 0.4)], mirror=True) # the codpiece
@ -430,151 +395,18 @@ def hip(sx):
"""PELVIS & HIP ASSEMBLY inset: the black ribbed drum between the hip beam and the thigh, on the hip's axis."""
j = PF.JOINTS["hip_r"]
b = put(f"Hip{'L' if sx < 0 else 'R'}", F((sx * 0.9, j[1], j[2]), (sx, 0, 0), UP))
prof, n, L = [(0.0, 0.0), (0.56, 0.0)], 6, 0.75
prof, n, L = [(0.0, 0.0), (0.56, 0.0)], 5, 0.5
for i in range(n):
a = L * i / n
prof += [(0.56, a + 0.02), (0.6, a + 0.05), (0.56, a + 0.08), (0.48, a + 0.1)]
prof += [(0.5, L), (0.0, L)]
b["rubber"].lathe(Matrix.Identity(4), prof, 32)
b["machine"].lathe(T((0, 0, L)), [(0.0, 0.0), (0.4, 0.0), (0.4, 0.5), (0.0, 0.5)], 24)
return b.done()
def thigh_points(sx):
t = PF.THIGH_SHIELD
top, bot = t["top"], t["bottom"]
outline = [(-0.42, top - 0.4), (-0.1, top), (0.62, top), (0.92, top - 0.5), (0.92, bot + 0.55), (0.55, bot), (-0.25, bot), (-0.42, bot + 0.5)]
cu, cz = 0.22, 0.5 * (top + bot)
pts = []
for y, k in ((0.88, 0.8), (0.6, 1.0), (-0.4, 1.0), (-0.62, 0.78)):
pts += [(cu + (u - cu) * k, y, cz + (z - cz) * k) for u, z in outline]
return sided(pts, sx)
def thigh(sx, plates=True):
"""Hero and rear views: the thigh as one deep hexagonal block from above the hip's axis down to the knee: a
front shield in two plates (the upper carries the mark), an outer plate, a rear plate; its inner face open."""
s = "L" if sx < 0 else "R"
H_, K_ = (Vector(PF.JOINTS[f"{k}_{s.lower()}"]) for k in ("hip", "knee"))
frame = limb(H_, K_)
solid = mass(f"Thigh{s}.mass", thigh_points(sx), frame)
t = PF.THIGH_SHIELD
mid = 0.5 * (t["top"] + t["bottom"]) + 0.35
specs = [("FrontUp", band("y", 0.62) + band("z", mid + 0.02), 0.15, 0.16, 0.05),
("FrontLow", band("y", 0.62) + band("z", None, mid - 0.02), 0.08, 0.16, 0.05),
("Outer", out(sx, 0.55) + band("y", -0.38, 0.58), 0.10, 0.14, 0.05),
("Top", band("z", t["top"] - 0.45) + band("y", -0.38, 0.58) + out(sx, None, 0.51), 0.05, 0.1, 0.04),
("Rear", band("y", None, -0.42), 0.10, 0.14, 0.05)]
armour(f"Thigh{s}", solid, specs, plates=plates)
b = put(f"Thigh{s}.frame", frame)
L = (H_ - K_).length
b["gunmetal"].box(T((0, 0, -0.5 * L)), (0.6, 0.7, L))
b.done()
return frame
def knee(sx):
"""KNEE & LEG DETAIL inset: the joints library's kneecap_bisector, at this knee's bend: the kneecap on its own
ring at half the bend, the pin's disc at the side."""
import jointlib as J
import joints
s = "l" if sx < 0 else "r"
H_, K_, A_ = (Vector(PF.JOINTS[f"{k}_{s}"]) for k in ("hip", "knee", "ankle"))
frame = limb(H_, K_)
frame.translation = K_
down = frame.to_3x3().inverted() @ (A_ - K_).normalized()
angle = math.degrees(math.atan2(down.y, -down.z))
rig = J.Rig(f"Knee{s.upper()}", frame, -95.0, 0.0)
joints.kneecap_bisector(rig, angle, r=0.5, cap=(1.15, 1.25), disc=0.34)
objs = rig.done()
for o in objs: # the bench's limb stubs are this build's thigh and shin
if o.get("link") in ("root", "shin") and o.get("mat") == "khaki":
bpy.data.objects.remove(o, do_unlink=True)
print(f"KNEE {s}: bend {angle:.1f}", flush=True)
return angle
def shin(sx, plates=True):
"""Hero view and KNEE & LEG DETAIL: the shin as a block that widens to mid-height, a guard rising over the
knee at its top; front in two plates, an outer and an inner plate; behind, open to the calf's rams."""
s = "L" if sx < 0 else "R"
K_, A_ = (Vector(PF.JOINTS[f"{k}_{s.lower()}"]) for k in ("knee", "ankle"))
frame = limb(K_, A_)
L = (K_ - A_).length
hw = 0.5 * PF.SHIN["width"]
outline = [(-0.6 * hw, -0.45), (0.0, -0.2), (0.6 * hw, -0.45), (hw, -0.5 * L), (0.8 * hw, -L + 0.3), (-0.8 * hw, -L + 0.3), (-hw, -0.5 * L)]
cz = -0.55 * L
pts = []
for y, k in ((0.82, 0.78), (0.55, 1.0), (-0.3, 1.0), (-0.55, 0.8)):
pts += [(u * k, y, cz + (z - cz) * k) for u, z in outline]
solid = mass(f"Shin{s}.mass", sided(pts, sx), frame)
specs = [("FrontUp", band("y", 0.58) + band("z", cz + 0.25), 0.14, 0.16, 0.05),
("FrontLow", band("y", 0.58) + band("z", None, cz + 0.21), 0.07, 0.16, 0.05),
("Outer", out(sx, 0.3) + band("y", -0.28, 0.54), 0.09, 0.14, 0.05),
("Inner", out(sx, None, -0.3) + band("y", -0.28, 0.54), 0.06, 0.12, 0.04)]
armour(f"Shin{s}", solid, specs, plates=plates)
b = put(f"Shin{s}.frame", frame)
g = b["gunmetal"]
g.box(T((0, -0.1, -0.5 * L)), (0.6, 0.7, L))
for x in (-0.3, 0.3):
g.rod((x, -0.62, -0.55), (x, -0.7, -L + 0.45), 0.11, 12)
b["steel"].rod((x, -0.7, -L + 0.45), (x, -0.62, -L + 0.05), 0.06, 12)
g.cylinder(F((x, -0.6, -0.5), (1, 0, 0)), 0.14, 0.2, 12)
b["khaki"].hull([(0.4, -0.5, -0.9), (0.4, -0.5, -1.7), (0.3, -0.78, -1.05), (0.3, -0.78, -1.55)], mirror=True)
b.done()
return frame
def foot(sx):
"""FOOT & ANKLE inset: the ankle's disc on its pin; a block over it; three heavy toes fanned forward, each a
faceted wedge with a dark stepped tip; two shorter blocks behind."""
s = "L" if sx < 0 else "R"
A_ = Vector(PF.JOINTS[f"ankle_{s.lower()}"])
b = put(f"Foot{s}", T((A_.x, A_.y, 0.0)))
g, k = b["gunmetal"], b["khaki"]
az = A_.z
g.lathe(F((-0.72, 0, az), (1, 0, 0), UP), [(0, 0), (0.42, 0), (0.46, 0.06), (0.46, 1.38), (0.42, 1.44), (0, 1.44)], 28)
for x in (-0.78, 0.78):
b["machine"].cylinder(F((x, 0, az), (1, 0, 0), UP), 0.3, 0.08, 20)
k.hull([(0.6, 0.75, 0.4), (0.6, -0.55, 0.4), (0.48, 0.55, az + 0.25), (0.48, -0.4, az + 0.15), (0.66, 0.5, 0.75), (0.66, -0.45, 0.7), (0.3, 0.9, 0.7)], mirror=True)
g.box(T((0, 0, 0.3)), (1.3, 1.5, 0.5))
tw, tl, th = PF.FOOT["toe"]
for i, a in enumerate((-36.0, 0.0, 36.0)):
to = Matrix.Rotation(math.radians(-a), 4, "Z") @ T((0, 0.5, 0))
hw = 0.5 * tw
k.hull([to @ Vector(q) for q in both([(hw, 0.0, 0.05), (hw, 0.0, th + 0.12), (hw + 0.05, 0.6 * tl, 0.0), (hw + 0.02, 0.62 * tl, th), (hw * 0.5, 0.3 * tl, th + 0.2),
(hw - 0.02, tl, 0.0), (hw - 0.06, tl, 0.55 * th), (hw * 0.6, 0.8 * tl, 0.85 * th)])])
g.hull([to @ Vector(q) for q in both([(hw - 0.06, tl - 0.05, 0.0), (hw - 0.1, tl - 0.05, 0.4 * th), (hw - 0.1, tl + 0.2, 0.0), (hw - 0.14, tl + 0.18, 0.24 * th)])])
hw_, hl, hh = PF.FOOT["heel"]
for a in (142.0, -142.0):
to = Matrix.Rotation(math.radians(-a), 4, "Z") @ T((0, 0.45, 0))
hw = 0.5 * hw_
k.hull([to @ Vector(q) for q in both([(hw, 0.0, 0.05), (hw, 0.0, hh + 0.1), (hw + 0.04, 0.6 * hl, 0.0), (hw, 0.6 * hl, hh), (hw - 0.04, hl, 0.0), (hw - 0.08, hl, 0.5 * hh)])])
b["machine"].lathe(T((0, 0, L)), [(0.0, 0.0), (0.4, 0.0), (0.4, 0.25), (0.0, 0.25)], 24)
return b.done()
# --- the arms ------------------------------------------------------------------------------------------------------------
def upper_arm(sx):
"""Hero view: a short dark upper arm hanging from under the pauldron, a khaki block on its outer face, the
elbow's disc on its pin."""
s = "l" if sx < 0 else "r"
S_, E_ = Vector(PF.JOINTS[f"shoulder_{s}"]), Vector(PF.JOINTS[f"elbow_{s}"])
frame = limb(S_, E_)
L = (S_ - E_).length
b = put(f"UpperArm{s.upper()}", frame)
g, k = b["gunmetal"], b["khaki"]
g.box(T((0, 0, -0.5 * L)), (0.62, 0.72, L))
for i in range(4):
g.box(T((0, 0, -0.25 - 0.22 * i)), (0.74, 0.84, 0.08))
k.hull(sided([(0.34, 0.42, -0.25), (0.34, -0.42, -0.25), (0.5, 0.3, -0.5), (0.5, -0.3, -0.5), (0.36, 0.42, -L + 0.3), (0.36, -0.42, -L + 0.3), (0.52, 0.28, -L + 0.5), (0.52, -0.28, -L + 0.5)], sx))
k.hull(sided([(-0.3, 0.38, -0.3), (0.3, 0.38, -0.3), (-0.3, 0.38, -L + 0.4), (0.3, 0.38, -L + 0.4), (-0.2, 0.52, -0.45), (0.2, 0.52, -0.45), (-0.2, 0.52, -L + 0.55), (0.2, 0.52, -L + 0.55)], sx))
g.lathe(F((-0.5, 0, -L), (1, 0, 0), UP), [(0, 0), (0.4, 0), (0.44, 0.05), (0.44, 0.95), (0.4, 1.0), (0, 1.0)], 24)
for x in (-0.54, 0.54):
b["machine"].cylinder(F((x, 0, -L), (1, 0, 0), UP), 0.28, 0.08, 16)
return b.done()
def aim(a, b):
"""A weapon's frame at a: its y along a to b, its z as near up as that leaves."""
a, b = Vector(a), Vector(b)
@ -586,33 +418,3 @@ def aim(a, b):
return m
def forearm_left(plates=True):
"""LEFT FOREARM - MANIPULATOR & ENERGY inset and the hero view: a slab-sided housing from the elbow to the
wrist; under its end the open hand (the joints library's hand), beside the hand the emitter (the weapons
library's paladin_energy_emitter, class S)."""
import jointlib as J
import hands
import weapons_energy
E_, W_ = Vector(PF.JOINTS["elbow_l"]), Vector(PF.JOINTS["wrist_l"])
frame = limb(E_, W_)
L = (E_ - W_).length
pts = []
for z, k in ((-0.15, 0.7), (-0.5, 1.0), (-L + 0.2, 1.0), (-L - 0.1, 0.75)):
pts += [(u * k, y * k, z) for u, y in ((-0.38, 0.45), (0.38, 0.45), (0.46, 0.0), (0.38, -0.45), (-0.38, -0.45), (-0.46, 0.0))]
solid = mass("ForearmL.mass", pts, frame)
specs = [("Outer", out(-1, 0.16) + band("z", -L + 0.25, -0.52), 0.1, 0.14, 0.05),
("Inner", out(-1, None, -0.16) + band("z", -L + 0.25, -0.52), 0.05, 0.12, 0.04),
("Front", band("y", 0.3) + band("x", -0.14, 0.14) + band("z", -L + 0.25, -0.52), 0.12, 0.12, 0.04),
("Cuff", band("z", None, -L + 0.2), 0.08, 0.14, 0.05),
("Collar", band("z", -0.48), 0.06, 0.12, 0.04)]
armour("ForearmL", solid, specs, plates=plates)
z, y = frame.to_3x3() @ Vector((0, 0, 1)), frame.to_3x3() @ Vector((1, 0, 0)) # the hand hangs down the forearm, its palm inboard
m = Matrix((y.cross(z), y, z)).transposed().to_4x4()
m.translation = W_ - z * 0.25
rig = J.Rig("HandL", m @ Matrix.Scale(1.55, 4), 0.0, 100.0)
hands.hand(rig, 30.0, plate="khaki")
rig.done()
side = frame.to_3x3() @ Vector((-1, 0, 0))
at = aim(E_ + side * 0.8 - z * 0.7, W_ + side * 0.8 - z * 0.7)
put("Emitter", at, weapons_energy.paladin_energy_emitter, size="S")
return frame

View file

@ -1,31 +1,31 @@
{
"hero": {
"C": [
4.024342939500392,
38.96685007436571,
1.9072178575925234
3.166359458844853,
18.291375677273702,
5.974887522617769
],
"R": [
[
-0.9746981483315451,
0.22352328962396972,
0.0009266254563114965
-0.9954714736026896,
0.08115547119873885,
0.049500855929980235
],
[
0.0974752331937773,
0.42131371199054596,
0.9016614303620656
0.07193169063267664,
0.30264152317512244,
0.9503862058831489
],
[
0.2011519290309593,
0.878938049628315,
-0.43244167972421166
0.06214802592210706,
0.9496430371169752,
-0.3071086532959184
]
],
"f": 1428.1556207875658,
"f": 662.9901734726185,
"c": [
379.2795454742095,
-289.172779334783
130.21617396138112,
-8.096494835726665
],
"box": [
0,
@ -53,181 +53,168 @@
"battery",
"ew"
],
"rms": 12.503824875395983,
"rms": 9.413614568560101,
"rms_h": null,
"median": 7.83707312791194,
"median": 7.4647894656702825,
"worst": [
"elbow_l",
30.972341608815473
19.36849184371895
],
"left_out": 17.207337978826192,
"left_out": 13.546097215308682,
"model": "free",
"tried": {
"upright": {
"rms": 15.620297640257816,
"left_out": 21.32540120099779,
"lens": 139.66883100426915
},
"rolled": {
"rms": 14.974012248700662,
"left_out": 21.67274860559036,
"lens": 174.4086105155622
},
"free": {
"rms": 12.503824875395983,
"left_out": 17.207337978826192,
"lens": 146.06137030781923
"rms": 9.413614568560101,
"left_out": 13.546097215308682,
"lens": 67.80581319606326
}
},
"lens": 146.06137030781923,
"lens": 67.80581319606326,
"lens_range": [
80.16017960876972,
723.4467030862105
41.12630461015983,
136.54413990580977
],
"azimuth": -6.025446714065794,
"elevation": -6.334591543633486,
"distance": 38.43252799014191,
"roll": 0.05888208961534556,
"azimuth": -10.104611030137775,
"elevation": -0.12256320906206657,
"distance": 17.599576618585676,
"roll": 2.9815558772044812,
"twist": 0.0,
"horizon": [
396.0,
395.77762721408243
],
"horizon": null,
"residuals": {
"waist": [
-0.7279500592247814,
10.954405924411674
-3.100717515024485,
6.381766019638803
],
"hip_r": [
-14.087693857534646,
6.480680858183348
-10.256880225845975,
0.9729426056547652
],
"hip_l": [
-8.969456183648958,
6.292667085251026
-13.07068570514491,
3.691232271909911
],
"knee_r": [
-11.94390550338153,
1.864668154700496
-6.339914052849252,
-1.9474494517313587
],
"knee_l": [
6.506306031792747,
-4.368946902045934
7.746245524091705,
-3.5552398613211267
],
"ankle_r": [
9.421799212615383,
5.448228592607904
7.461552097820487,
-0.21982278838351021
],
"ankle_l": [
-3.858671269852721,
-0.13678529235318138
2.8160587292839523,
-1.3535641217711145
],
"shoulder_r": [
7.255114183885269,
0.3298125139336321
11.805185100441605,
-3.2455920283938298
],
"shoulder_l": [
14.999336444676885,
9.44639582387498
1.046440049782234,
9.554762163579198
],
"elbow_r": [
-0.2876535584446174,
1.0137284095269479
4.71273710348197,
1.4689589230843296
],
"elbow_l": [
28.309971424260993,
-12.563099247028504
19.308119933805187,
-1.5280644364692932
],
"muzzle_r": [
11.583559472405625,
-14.306762221664428
1.3420282081170853,
4.007007253591951
],
"wrist_l": [
-2.972803838292407,
-6.219218603053434
-12.603986027967153,
3.3310554026264754
],
"lamp": [
-6.6003118702379595,
-0.4639766611508094
-2.7950268769504873,
-2.8742058071375
],
"visor": [
-0.12394333878961561,
-5.5928067596090045
-1.3709524519653087,
-9.044443439272825
],
"battery": [
-0.2828812432254608,
-2.53789760560727
-0.8858298796588429,
-6.693660239902719
],
"ew": [
-5.878745342355387,
2.455803712783336
-2.4872678960809935,
1.5042317151004738
]
},
"solved": {
"waist": [
0.0,
0.25,
6.65
0.05000000074505806,
6.53479528427124
],
"hip_r": [
1.55,
0.05,
5.55
1.5047065019607544,
0.05000000074505806,
5.368373394012451
],
"hip_l": [
-1.55,
0.05,
5.55
-1.4852867126464844,
0.05000000074505806,
5.3662800788879395
],
"knee_r": [
1.75,
0.8,
3.7
1.7371020317077637,
0.8613621592521667,
3.599395275115967
],
"knee_l": [
-1.75,
0.8,
3.7
-1.635337233543396,
0.8573893308639526,
3.5866150856018066
],
"ankle_r": [
1.85,
0.05,
1.15
2.078731060028076,
0.14072352647781372,
0.9989395141601562
],
"ankle_l": [
-1.85,
0.05,
1.15
-1.8535141944885254,
0.04823189973831177,
0.9989395141601562
],
"shoulder_r": [
2.95,
0.5,
8.55
2.863720417022705,
0.30000001192092896,
8.469656944274902
],
"shoulder_l": [
-2.95,
0.5,
8.55
-2.8101675510406494,
0.30000001192092896,
8.46491813659668
],
"elbow_r": [
3.2,
0.6,
6.95
3.138875722885132,
0.6650422811508179,
6.677023887634277
],
"elbow_l": [
-3.0,
0.45,
7.05
-2.85483455657959,
0.4345642030239105,
6.620359420776367
],
"muzzle_r": [
3.35,
3.4,
4.15
3.5504469871520996,
3.397095203399658,
3.9956448078155518
],
"wrist_l": [
-3.3,
1.1,
5.1
-2.898378849029541,
1.1876097917556763,
4.8221588134765625
],
"lamp": [
0.0,
@ -249,35 +236,105 @@
2.21,
8.9
]
},
"shift": {
"waist": [
-3.100717515024485,
6.381766019638803
],
"hip_r": [
-10.256880225845975,
0.9729426056547652
],
"hip_l": [
-13.07068570514491,
3.691232271909911
],
"knee_r": [
-6.339914052849252,
-1.9474494517313587
],
"knee_l": [
7.746245524091705,
-3.5552398613211267
],
"ankle_r": [
7.461552097820487,
-0.21982278838351021
],
"ankle_l": [
2.8160587292839523,
-1.3535641217711145
],
"shoulder_r": [
11.805185100441605,
-3.2455920283938298
],
"shoulder_l": [
1.046440049782234,
9.554762163579198
],
"elbow_r": [
4.71273710348197,
1.4689589230843296
],
"elbow_l": [
19.308119933805187,
-1.5280644364692932
],
"muzzle_r": [
1.3420282081170853,
4.007007253591951
],
"wrist_l": [
-12.603986027967153,
3.3310554026264754
],
"lamp": [
-2.7950268769504873,
-2.8742058071375
],
"visor": [
-1.3709524519653087,
-9.044443439272825
],
"battery": [
-0.8858298796588429,
-6.693660239902719
],
"ew": [
-2.4872678960809935,
1.5042317151004738
]
}
},
"rear": {
"C": [
-17.06059734781936,
-37.309086271769914,
0.715664445415914
-22.074827146253003,
-40.54367537122909,
4.880872134117224
],
"R": [
[
0.7356762718996472,
-0.6720362795693844,
-0.08454384605857931
0.8803045809036056,
-0.470549824446539,
0.06038797523893856
],
[
-0.27147792296738843,
-0.4069104178950268,
0.8721947312096122
-0.054618671581600865,
0.02591956697507224,
0.998170815423135
],
[
-0.6205482739522763,
-0.6187011804991445,
-0.4817973525703684
-0.47125433213370943,
-0.8819926523283265,
-0.002883692781031549
]
],
"f": 1430.5298684287816,
"f": 2046.1791620298611,
"c": [
1056.1924449945607,
-386.7474563803904
521.0,
255.0
],
"box": [
352,
@ -302,164 +359,151 @@
"exch_l",
"exch_r"
],
"rms": 9.746732432371452,
"rms": 9.603166421099951,
"rms_h": null,
"median": 6.53279172590044,
"median": 5.674771611102115,
"worst": [
"elbow_r",
28.07216576153325
"shoulder_l",
21.09784099516896
],
"left_out": 14.292032696765954,
"model": "free",
"left_out": 12.230909619477266,
"model": "rolled",
"tried": {
"upright": {
"rms": 13.276686056223102,
"left_out": 16.982547497203164,
"lens": 246.9705786290606
},
"rolled": {
"rms": 12.192924736224214,
"left_out": 17.820335764607425,
"lens": 340.6074547222906
},
"free": {
"rms": 9.746732432371452,
"left_out": 14.292032696765954,
"lens": 152.36412799833175
"rms": 9.603166421099951,
"left_out": 12.230909619477266,
"lens": 217.93624210968937
}
},
"lens": 152.36412799833175,
"lens": 217.93624210968937,
"lens_range": [
83.61920636880411,
306.82367527801887
88.60626379968123,
1610.343118938627
],
"azimuth": 155.81890740538992,
"elevation": -7.0357865844790135,
"distance": 41.420948778771255,
"roll": -5.536515103731178,
"azimuth": 151.70861369186903,
"elevation": -0.935858080298556,
"distance": 46.24815059602102,
"roll": 3.4620969055706596,
"twist": 0.0,
"horizon": [
396.0,
396.11660431497694
],
"horizon": null,
"residuals": {
"waist": [
-7.232530105321189,
1.0106966144215903
-8.911205650679335,
1.697783424377036
],
"hip_l": [
-1.170900270320658,
0.14134995309314036
-3.578893315444759,
3.4697989247594876
],
"hip_r": [
0.943316560457788,
0.45027252368879545
-3.500524984522599,
11.057610694004495
],
"knee_l": [
10.132840505881177,
3.314762215229507
10.538458494388635,
-2.7939850294227426
],
"knee_r": [
1.3475874092439426,
-1.494090960722474
-4.937838229702379,
2.5747254576348837
],
"ankle_l": [
0.936318915695665,
7.785132694588469
5.73944830811655,
-0.6897855336575276
],
"ankle_r": [
-8.093061030221179,
-5.4247614212619055
-3.4193736194986286,
1.2470608122366684
],
"shoulder_l": [
-8.63320802916644,
-3.653120531304353
-11.699948465380373,
-17.556483149106924
],
"shoulder_r": [
-1.9833802668287035,
6.623709784568632
-0.6299309441021705,
2.6063469363401452
],
"elbow_l": [
3.447491235632924,
-3.761308019024227
-0.19853304887158174,
2.847328239716802
],
"elbow_r": [
14.431603509560318,
-24.07852384773298
9.596606710618062,
-12.948588344128666
],
"wrist_l": [
-0.35430721475154314,
-2.768112637974582
8.851240867757099,
-5.913554093983862
],
"exch_l": [
1.9816922216643889,
5.823347500832654
-1.5916923900402935,
0.5415528787390826
],
"exch_r": [
1.5775138889416667,
1.4725583657973402
4.060345373902237,
0.20381792846441726
]
},
"solved": {
"waist": [
0.0,
0.25,
6.65
0.05000000074505806,
6.53479528427124
],
"hip_l": [
-1.55,
0.05,
5.55
-1.4852867126464844,
0.05000000074505806,
5.3662800788879395
],
"hip_r": [
1.55,
0.05,
5.55
1.5047065019607544,
0.05000000074505806,
5.368373394012451
],
"knee_l": [
-1.75,
0.8,
3.7
-1.635337233543396,
0.8573893308639526,
3.5866150856018066
],
"knee_r": [
1.75,
0.8,
3.7
1.7371020317077637,
0.8613621592521667,
3.599395275115967
],
"ankle_l": [
-1.85,
0.05,
1.15
-1.8535141944885254,
0.04823189973831177,
0.9989395141601562
],
"ankle_r": [
1.85,
0.05,
1.15
2.078731060028076,
0.14072352647781372,
0.9989395141601562
],
"shoulder_l": [
-2.95,
0.5,
8.55
-2.8101675510406494,
0.30000001192092896,
8.46491813659668
],
"shoulder_r": [
2.95,
0.5,
8.55
2.863720417022705,
0.30000001192092896,
8.469656944274902
],
"elbow_l": [
-3.0,
0.45,
7.05
-2.85483455657959,
0.4345642030239105,
6.620359420776367
],
"elbow_r": [
3.2,
0.6,
6.95
3.138875722885132,
0.6650422811508179,
6.677023887634277
],
"wrist_l": [
-3.3,
1.1,
5.1
-2.898378849029541,
1.1876097917556763,
4.8221588134765625
],
"exch_l": [
-1.15,
@ -471,13 +515,71 @@
-1.25,
8.7
]
},
"shift": {
"waist": [
-8.911205650679335,
1.697783424377036
],
"hip_l": [
-3.578893315444759,
3.4697989247594876
],
"hip_r": [
-3.500524984522599,
11.057610694004495
],
"knee_l": [
10.538458494388635,
-2.7939850294227426
],
"knee_r": [
-4.937838229702379,
2.5747254576348837
],
"ankle_l": [
5.73944830811655,
-0.6897855336575276
],
"ankle_r": [
-3.4193736194986286,
1.2470608122366684
],
"shoulder_l": [
-11.699948465380373,
-17.556483149106924
],
"shoulder_r": [
-0.6299309441021705,
2.6063469363401452
],
"elbow_l": [
-0.19853304887158174,
2.847328239716802
],
"elbow_r": [
9.596606710618062,
-12.948588344128666
],
"wrist_l": [
8.851240867757099,
-5.913554093983862
],
"exch_l": [
-1.5916923900402935,
0.5415528787390826
],
"exch_r": [
4.060345373902237,
0.20381792846441726
]
}
},
"side": {
"C": [
87.84896913275175,
1.1078440594982277,
1.5121479421322626
74.22580229606024,
1.0919442264947585,
3.1052411455157483
],
"R": [
[
@ -486,17 +588,17 @@
0.0
],
[
0.04269467483038552,
-1.3071474217917174e-17,
0.9990881666505352
0.027200224236332445,
-8.327666886778697e-18,
0.9996300054527641
],
[
0.9990881666505352,
-3.0588253133864385e-16,
-0.04269467483038552
0.9996300054527641,
-3.060484216273447e-16,
-0.027200224236332445
]
],
"f": 3533.3698454010014,
"f": 2919.7828838468417,
"c": [
787.5,
255.0
@ -507,69 +609,106 @@
885.0,
510.0
],
"lens": 652.3144329971079,
"lens": 539.0368400948015,
"lens_band": [
131.7000126597741,
89.10219037814785,
4000.0
],
"lens_at_bound": null,
"rms": 14.094214065791983,
"median": 13.798717017990711,
"lens_determined": false,
"planarity": 0.3792378668671132,
"rms": 15.8801286379222,
"median": 13.848808444460836,
"worst": [
"waist",
19.58426841132626
"elbow_r",
24.03494207571549
],
"left_out": 22.521663328055052,
"left_out": 25.247651332661736,
"model": "square",
"tried": {
"square": {
"rms": 14.094214065791983,
"left_out": 22.521663328055052,
"lens": 652.3144329971079
"rms": 15.8801286379222,
"left_out": 25.247651332661736,
"lens": 539.0368400948015
}
},
"azimuth": -90.06986790263996,
"elevation": -3.1181641567690845,
"distance": 85.9512858974804,
"azimuth": -90.07727618296836,
"elevation": -2.358974238205676,
"distance": 72.22846781616647,
"roll": 0.0,
"twist": 0.0,
"plane": null,
"residuals": {
"shoulder_r": [
-4.731279891913459,
3.5896813767305105
-11.848260728081755,
5.248677637534826
],
"elbow_r": [
8.340597978301957,
12.218021141215786
11.983137802181659,
20.834655000669528
],
"muzzle_r": [
13.307399580006859,
-10.363655441629703
12.734387859403796,
-8.351368649987421
],
"knee_r": [
-10.131262607705366,
6.141266354327968
-6.7893631168664115,
4.532995703460642
],
"ankle_r": [
-9.010277146131102,
-9.097108713927128
-4.040646791703807,
-10.179161373212764
],
"battery": [
5.868489342415273,
-3.650411055520294
6.257884854915687,
-4.439089414332955
],
"waist": [
-11.94870437287966,
-15.516830636969587
-18.45012009212894,
-15.388857171879096
],
"lamp": [
10.377988705854591,
14.39636356282466
9.775359156122022,
11.030673462786325
]
},
"lens_range": [
131.7000126597741,
89.10219037814785,
4000.0
]
],
"shift": {
"shoulder_r": [
-11.848260728081755,
5.248677637534826
],
"elbow_r": [
11.983137802181659,
20.834655000669528
],
"muzzle_r": [
12.734387859403796,
-8.351368649987421
],
"knee_r": [
-6.7893631168664115,
4.532995703460642
],
"ankle_r": [
-4.040646791703807,
-10.179161373212764
],
"battery": [
6.257884854915687,
-4.439089414332955
],
"waist": [
-18.45012009212894,
-15.388857171879096
],
"lamp": [
9.775359156122022,
11.030673462786325
]
}
}
}

View file

@ -1,17 +1,24 @@
"""PALADIN as numbers (concept sheet images/27.webp): the skeleton, the marks on the sheet's three views, the solved
cameras, the masses and where they split into plates. Plain Python and numpy; no Blender, no Pillow. paladin.py
builds from it, paladin_sheets.py scores against it.
python paladin_form.py solve solves the hero, rear and side cameras from JOINTS, LANDMARKS and VIEWS' marks
(camsolve, the horizon held) and writes paladin_cameras.json beside this file
"""PALADIN as numbers (concept sheet images/27.webp): the skeleton's targets, the marks on the sheet's three views,
the solved cameras, the character line, and the plate edges traced on the views. Plain Python and numpy; no Blender,
no Pillow. paladin.py builds from it, paladin_sheets.py scores against it.
Frames. World: x to the mech's right, y forward, z up, metres, origin on the ground under the hips' middle. Torso:
the same axes at WAIST (the slew ring's top). The sheet's pixels are the 1024-wide sheet's own.
the same axes at WAIST (the waist pin's top). The sheet's pixels are the 1024-wide sheet's own.
The skeleton is kit parts (bipedkit.py): JOINTS are the targets its limbs are aimed at, and the joints the cameras
are solved on are read back from the kit as it stands (solve(points)), not from this table. The targets were posed
on the marks: each limb joint moved, across the line of sight only, to where the hero, rear and side marks' sight
lines pass nearest (work/pose_probe.py); the hips and shoulders, which one rigid body carries, are kept symmetric.
The cameras are solved free of any horizon. The first pass held the hero camera's horizon on the row of the
soldiers' heads, which stood the eye 1.9 m up and drew the figure from under; the marks alone stand it about
5.5 m up, level with the hips, as the sheet draws it (the feet seen from above, the pauldrons' roofs not seen).
The character line (BELT) is the chest's knuckle: the hard edge where the sloped glacis under the turret breaks to
the hull's upright band, a shallow chevron in plan with the amber lamp at its stem, carried outboard by the
pauldrons' own knuckles at the same height and repeated above by the turret's visor band. It was built first, and
every mass above the waist is fitted round it.
the hull's upright band, a shallow chevron in plan with the amber lamp at its stem.
TRACES are plate edges read off the sheet at 8x under a 10 px grid (work/grid.py), a pixel a corner, to about
2 px; corners another plate hides are guessed and named in HIDDEN.
"""
import json
import math
@ -21,18 +28,22 @@ from pathlib import Path
HERE = Path(__file__).resolve().parent
HEIGHT = 11.0 # to the battery's top; the antennas stand above it
WAIST = (0.0, 0.25, 6.65) # the torso stands a little forward of the hips (side view: the battery's middle between knee and ankle)
WAIST = (0.0, 0.25, 6.65)
# The skeleton, world. hip is the thigh's head on the hip drum's axis; muzzle_r the gatling's muzzle.
# Targets, world. hip: the thigh's pitch pin; muzzle_r the gatling's muzzle.
JOINTS = {
"waist": (0.0, 0.25, 6.65),
"hip_r": (1.55, 0.05, 5.55), "hip_l": (-1.55, 0.05, 5.55),
"knee_r": (1.75, 0.80, 3.70), "knee_l": (-1.75, 0.80, 3.70),
"ankle_r": (1.85, 0.05, 1.15), "ankle_l": (-1.85, 0.05, 1.15),
"shoulder_r": (2.95, 0.5, 8.55), "shoulder_l": (-2.95, 0.5, 8.55),
"elbow_r": (3.20, 0.6, 6.95), "elbow_l": (-3.0, 0.45, 7.05),
"muzzle_r": (3.35, 3.4, 4.15), "wrist_l": (-3.3, 1.1, 5.1),
"hip_r": (1.5, 0.05, 5.5), "hip_l": (-1.5, 0.05, 5.5),
"knee_r": (1.6, 0.95, 3.7), "knee_l": (-1.68, 0.95, 3.7),
"ankle_r": (2.12, 0.0, 1.0), "ankle_l": (-1.88, -0.05, 1.0),
"shoulder_r": (2.9, 0.5, 8.65), "shoulder_l": (-2.9, 0.5, 8.65),
"elbow_r": (3.12, 0.64, 6.8), "elbow_l": (-2.85, 0.42, 6.82),
"muzzle_r": (3.4, 3.32, 4.05), "wrist_l": (-3.25, 1.1, 5.04),
}
# The kit skeleton (bipedkit): where the root's pins stand and how long the links are; both sides alike. hip_z is
# where the root is first stood: skeleton() sets it down until the soles stand on the ground.
KIT = {"hip_span": 2.9, "hip_z": 6.1, "waist_z": 0.75, "hip_drop": 0.42, "pin_r": 0.11, "thigh": 1.96, "shin": 2.72, "ankle_drop": 0.3, "foot": (1.6, 2.0, 0.7),
"shoulder_sx": 2.8, "shoulder_sz": 2.35, "shoulder_sy": 0.25, "shoulder_drop": 0.42, "arm_pin_r": 0.09, "upper_arm": 1.85, "forearm_l": 1.95, "forearm_r": 1.3}
# Landmarks that are not joints, world: they hold the cameras where the joints are nearly in one plane.
LANDMARKS = {
"lamp": (0.0, 0.25 + 2.3, 6.65 + 1.25), # the amber lamp on the belt's stem
@ -41,7 +52,6 @@ LANDMARKS = {
"ew": (-3.1, 0.25 + 1.96, 6.65 + 2.25), # the middle of the EW module's lower face
"exch_l": (-1.15, 0.25 - 1.5, 8.7), "exch_r": (1.15, 0.25 - 1.5, 8.7), # the middles of the heat exchangers' grilles
}
HORIZON = 396 # the sheet row the soldiers' heads stand on, in all three views: the cameras' eye is a soldier's
VIEWS = {
"hero": {"box": [0, 0, 352, 510], "label": "FRONT 3/4",
"marks": {"waist": (197, 181), "hip_r": (146, 230), "hip_l": (262, 233), "knee_r": (132, 312), "knee_l": (256, 320),
@ -57,6 +67,28 @@ VIEWS = {
"battery": (800, 38), "waist": (765, 215), "lamp": (835, 135)}},
}
# --- plate edges traced on the views: {plate: (view, [(u, v) a crown corner, ...])} ------------------------------------
TRACES = {
"ThighR.Shield": ("hero", [(130, 219), (159, 222), (170, 240), (170, 274), (160, 292), (122, 281), (123, 248)]),
"ThighR.Outer": ("hero", [(120, 189), (133, 187), (129, 218), (108, 262), (96, 262), (104, 225)]),
"ThighL.Shield": ("hero", [(255, 243), (263, 236), (276, 238), (298, 288), (294, 296), (268, 292), (256, 262)]),
"ThighL.Inner": ("hero", [(246, 250), (256, 262), (266, 292), (250, 300), (236, 268)]),
"ShinR.Upper": ("hero", [(119, 289), (150, 293), (151, 322), (128, 327), (113, 313)]),
"ShinR.Lower": ("hero", [(113, 328), (150, 326), (147, 360), (139, 397), (111, 400)]),
"ShinR.Outer": ("hero", [(72, 330), (88, 318), (100, 330), (100, 385), (80, 388)]),
"ShinL.Upper": ("hero", [(281, 301), (298, 300), (305, 331), (284, 336)]),
"ShinL.Lower": ("hero", [(284, 338), (305, 333), (296, 356), (272, 350)]),
"ShinL.Inner": ("hero", [(262, 318), (280, 305), (283, 336), (270, 348)]),
"PauldronR.Front": ("hero", [(85, 71), (101, 58), (120, 59), (121, 112), (108, 126), (87, 108)]),
"PauldronR.Outer": ("hero", [(84, 73), (87, 108), (72, 123), (47, 110), (45, 103)]),
"PauldronL.Front": ("hero", [(286, 73), (301, 76), (326, 116), (331, 130), (318, 146), (291, 134)]),
"PauldronL.Rear": ("rear", [(451, 63), (478, 38), (491, 46), (493, 118), (478, 133), (452, 104)]),
"ForearmL.Front": ("hero", [(297, 206), (315, 203), (338, 244), (323, 253)]),
"ForearmL.Outer": ("hero", [(314, 185), (324, 186), (348, 240), (340, 247)]),
}
HIDDEN = {"ThighR.Shield": "its lower edge runs under the knee guard", "ThighR.Outer": "its lower corners stand behind the shield", "ThighL.Inner": "its upper corner is in the hip's shadow",
"ShinR.Lower": "its foot is behind the ankle block", "PauldronR.Outer": "its rear edge is the silhouette", "ShinL.Inner": "dark on dark: read to about 4 px"}
# --- the character line ------------------------------------------------------------------------------------------
# The belt, torso frame: (x, y) of the knuckle's right half from the stem outboard and round the flank, and its z.
# The belt, torso frame: the knuckle's right half from the stem outboard and round the flank. It is not level: it
@ -73,10 +105,6 @@ KEEL = [(0.8, [(0.0, 1.3), (1.0, 0.9), (1.2, 0.0), (1.0, -0.6), (0.0, -0.8)])]
# The belt as the sheet's hero view draws it (the sheet's pixels), right end to stem to left end: the traced line.
BELT_TRACE = [(122, 75), (183, 101), (216, 129), (270, 106)]
VISOR_TRACE = [(169, 73), (205, 80), (250, 76)] # the visor band's lower lip
PAULDRON_TRACE = {"r": [(48, 56), (38, 88), (62, 122), (108, 98)], # the right pauldron's knuckle: outer top, outer corner, lower tip, inner
"l": [(268, 70), (318, 74), (338, 140), (296, 124)]}
THIGH_TRACE = {"r": [(128, 196), (166, 215), (172, 262), (150, 290), (100, 276), (96, 215)]} # the right thigh shield's outline
# --- masses --------------------------------------------------------------------------------------------------------
# The turret: a low cap of clipped corners on the deck, the visor band across its brow. Torso frame.
TURRET = {"at": (0.0, 0.25, 2.56), "half": 1.3, "front": 1.3, "rear": 0.85, "height": 0.62, "clip": 0.45, "crown": 0.78}
@ -86,9 +114,6 @@ PAULDRON_AT = (-3.1, 0.3, 1.85)
PAULDRON = {"half_y": 1.35, "crown": (0.95, 1.25), "knuckle": (-1.0, -0.15), "foot": (-0.55, -1.05), "inner_foot": (0.75, -0.9), "nose": 0.3}
EXCHANGER = {"x": 1.15, "y": -1.15, "z": (0.75, 3.3), "width": 1.25, "depth": 0.7}
# The legs' armour, each in a frame along its link (z up the link, y forward, x outboard), lengths in metres.
THIGH_SHIELD = {"width": 1.75, "top": 0.7, "bottom": -2.0, "t": 0.4} # rises above the hip's axis, as the hero view has it
SHIN = {"width": 1.45, "depth": 1.5}
FOOT = {"toes": 3, "toe": (0.62, 1.15, 0.62), "heel": (0.55, 0.8, 0.5)}
def world(name):
@ -99,29 +124,36 @@ def cameras():
return json.loads((HERE / "paladin_cameras.json").read_text(encoding="utf-8"))
def solve():
"""The three cameras, by camsolve (this branch's solver) and not brokkr_reference.core: every view holds soldiers
standing at different depths whose heads lie on one row of the sheet (HORIZON), so the camera stands at a
soldier's eye height, and only camsolve can hold a horizon. Without it the hero camera came out 5.5 m up and
drew the feet from above."""
def solve(points=None, write=True):
"""The three cameras from the marks and `points` (world, by name: the kit's joints as they stand, the landmarks;
JOINTS and LANDMARKS where absent). Hero and rear by camsolve with no horizon held (the free model, or the better of upright and
rolled where the free one stands the eye under the ground); the side view square-on
along x by brokkr_reference.core. Each camera also carries "shift": per marked name, how far the point as built
is drawn from its mark (du, dv): what a trace near that joint is moved by before it is fitted."""
import camsolve
W_all = {k: list(v) for k, v in (JOINTS | LANDMARKS).items()}
W_all.update({k: [float(c) for c in v] for k, v in (points or {}).items()})
out = {}
for tag, view in VIEWS.items():
names = list(view["marks"])
W, Px = {k: list(world(k)) for k in names}, {k: list(view["marks"][k]) for k in names}
if tag == "side": # square-on along x: camsolve's square looks along y only, brokkr_reference's along any axis
W, Px = {k: W_all[k] for k in names}, {k: list(view["marks"][k]) for k in names}
if tag == "side":
surface = Path(os.environ["BROKKR_SURFACE"]) if os.environ.get("BROKKR_SURFACE") else HERE.parents[1]
sys.path.insert(0, str(surface / "brokkr_reference")) # core.py alone: the package's __init__ wants bpy
import core
cam = core.solve(W, Px, view["box"], model="square")
cam["lens_range"] = cam["lens_band"]
else:
cam = camsolve.solve(W, Px, view["box"], horizon=HORIZON)
cam = camsolve.solve(W, Px, view["box"], model="free")
if cam["C"][2] < 1.0: # a free centre can trade the eye's height away: this one stood under the ground
tried = [camsolve.solve(W, Px, view["box"], model=m) for m in ("upright", "rolled")]
cam = min([c for c in tried if c["C"][2] >= 1.0] or tried, key=lambda c: c["rms"])
cam["shift"] = {k: [float(v) for v in r] for k, r in cam["residuals"].items()}
out[tag] = cam
print(f"CAMERA {tag}: {cam['model']}, lens {cam['lens']:.0f} mm (range {cam['lens_range'][0]:.0f}..{cam['lens_range'][1]:.0f}), azimuth {cam['azimuth']:.1f}, elevation {cam['elevation']:.1f}, "
f"distance {cam['distance']:.1f} m, eye {cam['C'][2]:.2f} m up, rms {cam['rms']:.1f} px, left-out {cam['left_out']:.1f} px, worst {cam['worst'][0]} {cam['worst'][1]:.1f}")
print(" " + ", ".join(f"{k} {r[0]:+.0f},{r[1]:+.0f}" for k, r in cam["residuals"].items()))
(HERE / "paladin_cameras.json").write_text(json.dumps(out, indent=1), encoding="utf-8")
f"distance {cam['distance']:.1f} m, eye {cam['C'][2]:.2f} m up, rms {cam['rms']:.1f} px, left-out {cam['left_out']:.1f} px, worst {cam['worst'][0]} {cam['worst'][1]:.1f}", flush=True)
if write:
(HERE / "paladin_cameras.json").write_text(json.dumps(out, indent=1), encoding="utf-8")
return out

View file

@ -0,0 +1,522 @@
"""PALADIN's second pass (concept sheet images/27.webp): the kit skeleton and the sculpted plates. Runs inside Blender.
The skeleton is kit parts whose every joint is a pin with a record (skeleton(), over bipedkit.py and feet.py's
paladin_hoof). Everything else is built in the world on the kit's frames and parented to the kit part that carries
it (bipedkit.Adopt / adopt), so the build follows brokkr_kitbash.roll.
The limbs' and pauldrons' armour is sculpted plates: free cages of 2N + 1 vertices (platecage.py). The big ones are
blocked by lifting their traced edges (paladin_form.TRACES) onto a plane of the limb and fitted to those traces by
brokkr_reference's fit (plate(trace=...)); a plate the sheet hides on one side is the other side's fitted crown
mirrored (PC.mirrored); the plates under and on them are derived from the fitted crowns (PC.grown, PC.patch), so they
layer as the sheet layers them: a base plate standing back under each shield, blocks and lames proud of it. The
detail pass is surface.Skin on those shells (dress()), after which each shell is frozen.
Tools here, each used by more than one part:
plate(name, frame, ...) one free-cage plate: traced and fitted, or from a crown
on_plane(point, normal, pts) / extent(crown) a crown authored in a plane; a crown's span in its own plane
dress(name, steps) surface.Skin on a plate, features placed in its crown's plane
bolts / inset / port / slots / numeral / line / dings feature makers for dress()
tri_on(name, size) / stowage(b, frame, size)
Parts: skeleton; pauldron_core, pauldron_shields, pauldron_layers; leg_cores, leg_shields, leg_layers, knee;
upper_arm, forearm_left.
"""
import math
import bpy
import numpy as np
from mathutils import Matrix, Vector
import bipedkit as BK
import mechlib as M
import paladin_form as PF
import platecage as PC
from paladin_body import CORE, UP, F, T, aim, freeze, mass, put, sided, triangle
CAMS = {} # the solved cameras, set by paladin.py once the skeleton stands
KITS = {} # the skeleton's parts, by name
DRESS_FAILED = []
DRESSED = [0]
def skeleton():
"""The kit tree: hipbeam; per leg a cross (hip_splay), a thigh link (hip_pitch), a shin link (knee), an ankle
cross (ankle_pitch, ankle_roll) and feet.paladin_hoof (its toes' pitch pins); trunk on the waist pin
(waist_yaw); per arm a cross (shoulder_abduct), an upper arm (shoulder_pitch) and a forearm (elbow). Every
connection is a pivot with limits. The right shin is re-solved (brokkr_kitbash.reach) so both ankle pins stand
at one height, and the root is set down so the soles stand on z = 0."""
import feet
M.cache_kits()
k, J = PF.KIT, PF.JOINTS
pel = M.place("hipbeam", "Pelvis", mat="gunmetal", span=k["hip_span"], depth=1.0, height=0.7, pin_r=k["pin_r"], waist_r=0.8, waist_z=k["waist_z"])
pel.matrix_world = T((0.0, J["hip_r"][1], k["hip_z"]))
M.update()
legs, feet_ = {}, {}
fw, fl, fd = k["foot"]
for s, sx in (("L", -1), ("R", 1)):
leg = BK.limb(f"Leg{s}", pel, f"hip_{s.lower()}", (J[f"knee_{s.lower()}"], J[f"ankle_{s.lower()}"]), (k["thigh"], k["shin"]), [(0.6, 0.7), (0.55, 0.6)], k["pin_r"],
cross=(k["hip_drop"], 0.7), names=("hip_splay", "hip_pitch", "knee"), limits=((-8, 30), (-40, 70), (-5, 100)),
toward=((sx, 0, 0), (0, 1, 0), (0, -1, 0)), mat="gunmetal", splay_at=1)
if legs:
want = M.sockets(legs["L"]["lower"])["clevis"].translation.z
bpy.ops.brokkr_kitbash.reach(object_name=leg["lower"].name, socket="clevis", height=want, direction_x=0.0, direction_y=0.0, direction_z=1.0)
M.update()
BK.record(leg["lower"], "knee", -5, 100, toward=(0, -1, 0))
foot = feet.paladin_hoof(f"Foot{s}", None, width=fw, length=fl, drop=fd, pin_r=k["pin_r"])
leg["ankle"] = BK.ankle(f"Leg{s}", leg["lower"], foot.core, k["ankle_drop"], k["pin_r"], 0.7)
foot.done()
legs[s], feet_[s] = leg, foot
M.update()
sole = min((f.core.matrix_world @ Vector((0, 0, fd))).z for f in feet_.values())
pel.matrix_world = T((0.0, J["hip_r"][1], k["hip_z"] - sole))
M.update()
trunk = M.attach(M.place("trunk", "Trunk", mat="gunmetal", waist_r=0.8, pin_r=k["arm_pin_r"], sx=k["shoulder_sx"], sy=k["shoulder_sy"], sz=k["shoulder_sz"], depth=0.9), "base", pel, "waist", 0.0)
BK.record(trunk, "waist_yaw", -50, 50)
arms = {}
for s, sx in (("L", -1), ("R", 1)):
end = J["wrist_l"] if sx < 0 else J["muzzle_r"]
arms[s] = BK.limb(f"Arm{s}", trunk, f"shoulder_{s.lower()}", (J[f"elbow_{s.lower()}"], end), (k["upper_arm"], k["forearm_l"] if sx < 0 else k["forearm_r"]), [(0.5, 0.6), (0.45, 0.5)],
k["arm_pin_r"], cross=(k["shoulder_drop"], 0.6), names=("shoulder_abduct", "shoulder_pitch", "elbow"), limits=((-10, 70), (-60, 150), (-5, 120)),
toward=((sx, 0, 0), (0, 1, 0), (0, 1, 0)), mat="gunmetal")
KITS.update(pelvis=pel, trunk=trunk, legs=legs, arms=arms, feet=feet_)
return KITS
def joint_points():
"""The kit's joints as they stand, world, named as paladin_form names them: what the cameras are solved on."""
M.update()
out = {"waist": KITS["trunk"].matrix_world.translation.copy()}
for s in ("L", "R"):
leg, arm, t = KITS["legs"][s], KITS["arms"][s], s.lower()
out[f"hip_{t}"] = leg["upper"].matrix_world.translation.copy()
out[f"knee_{t}"] = leg["lower"].matrix_world.translation.copy()
out[f"ankle_{t}"] = M.sockets(leg["lower"])["clevis"].translation
out[f"shoulder_{t}"] = arm["upper"].matrix_world.translation.copy()
out[f"elbow_{t}"] = arm["lower"].matrix_world.translation.copy()
out["wrist_l"] = M.sockets(KITS["arms"]["L"]["lower"])["clevis"].translation
reach = (Vector(PF.JOINTS["muzzle_r"]) - Vector(PF.JOINTS["elbow_r"])).length
out["muzzle_r"] = KITS["arms"]["R"]["lower"].matrix_world @ Vector((0, 0, reach))
return {name: tuple(p) for name, p in out.items()}
# --- plates --------------------------------------------------------------------------------------------------------
def plate(name, frame, trace=None, point=None, normal=None, crown=None, near=(), **kw):
"""One free-cage plate at `frame` (a kit part's authoring frame, world). With `trace` (a key of
paladin_form.TRACES) the crown is blocked by lifting the traced polygon onto the plane (point, normal) of the
frame and fitted to the trace; `near` names the marked joints whose miss at the solved camera the trace is
moved by first, so the plate sits on the limb as built. Otherwise `crown` is the crown, facing `normal`.
Returns the crown as built (frame coordinates)."""
if trace is not None:
view, line = PF.TRACES[trace]
cam = CAMS[view]
misses = [cam["shift"][j] for j in near if j in cam["shift"]]
shift = tuple(np.mean(misses, axis=0)) if misses else (0.0, 0.0)
crown = PC.lift(cam, frame, line, point, normal, shift)
Fm = np.asarray(frame)
sight = PC._unit(np.asarray(cam["C"]) - (Fm[:3, :3] @ crown.mean(0) + Fm[:3, 3]))
square = float(sight @ (Fm[:3, :3] @ PC._unit(normal)))
if square < 0.4:
raise SystemExit(f"plate {name}: its blocking plane stands {math.degrees(math.acos(max(-1.0, square))):.0f} degrees off square-on to the {view} camera; a trace lifted onto it "
"stretches past 2.5 times. Turn the plane to the face the view shows, or author the crown.")
PC.shell(name, crown, frame, facing=normal, trace=line, cam=cam, view=view, shift=shift, **kw)
else:
PC.shell(name, crown, frame, facing=normal, **kw)
return np.array(PC.PLATES[name]["crown"])
def on_plane(point, normal, pts):
"""2D points (across, up: as seen from outside) on the plane through `point` facing `normal`."""
n = PC._unit(normal)
up = np.array([0.0, 0.0, 1.0]) if abs(n[2]) < 0.9 else np.array([0.0, 1.0, 0.0])
e2 = PC._unit(up - n * (up @ n))
e1 = np.cross(e2, n)
return np.array([np.asarray(point, float) + e1 * x + e2 * y for x, y in pts])
def extent(crown):
"""(x0, x1, y0, y1) of a crown in its own plane's coordinates (PC.basis)."""
c, e1, e2, n = PC.basis(crown)
xs, ys = [(np.asarray(p) - c) @ e1 for p in crown], [(np.asarray(p) - c) @ e2 for p in crown]
return min(xs), max(xs), min(ys), max(ys)
def dress(name, steps):
"""The detail pass on one plate: surface.Skin on the shell, each step(skin, at) placing features at plane
coordinates of the plate's crown (at(x, y, roll) is a frame on the skin there). A step that misses is listed
in DRESS_FAILED and left out. The shell is frozen afterwards."""
import surface as S
obj = bpy.data.objects.get(name)
if obj is None:
DRESS_FAILED.append(f"{name}: no such plate")
return
if steps:
crown = np.array(PC.PLATES[name]["crown"])
c, e1, e2, n = PC.basis(crown)
skin = S.Skin(obj)
def at(x, y, roll=0.0):
return skin.at(tuple(c + e1 * x + e2 * y + n * 0.4), tuple(-n), up=tuple(e2), roll=roll)
at.crown, at.c, at.e1, at.e2 = crown, c, e1, e2
for label, step in steps:
try:
step(skin, at)
DRESSED[0] += 1
except Exception as error:
DRESS_FAILED.append(f"{name} {label}: {type(error).__name__} {str(error)[:120]}")
try:
skin.prune()
skin.commit()
except BaseException as error:
DRESS_FAILED.append(f"{name} commit: {type(error).__name__} {str(error)[:120]}")
freeze(obj)
def bolts(inset_=0.07, spacing=0.26, r=0.02, sides=None):
"""A bolt row inside each of the crown's sides (or those named)."""
def step(skin, at):
import surface as S
P, c = at.crown, at.c
frames = []
for i in range(len(P)):
if sides is not None and i not in sides:
continue
a, b = P[i], P[(i + 1) % len(P)]
a, b = a + PC._unit(c - a) * inset_ * 1.6, b + PC._unit(c - b) * inset_ * 1.6
count = max(2, int(np.linalg.norm(b - a) / spacing) + 1)
for t in np.linspace(0.0, 1.0, count)[: count - 1]:
q = a + (b - a) * t - c
frames.append(at(q @ at.e1, q @ at.e2))
S.bolt_row(skin, frames, r=r)
return ("bolts", step)
def inset(x, y, size, **kw):
import surface as S
return ("inset", lambda skin, at: S.inset(skin, at(x, y), size, **kw))
def port(x, y, r=0.07):
import surface as S
return ("port", lambda skin, at: S.access_port(skin, at(x, y), r))
def slots(x, y, count=3, pitch=0.09, width=0.3, height=0.04):
import surface as S
return ("slots", lambda skin, at: S.vent_slots(skin, [at(x, y + (i - (count - 1) / 2) * pitch) for i in range(count)], width, height))
def numeral(x, y, text, height):
import surface as S
return (text, lambda skin, at: S.numeral(skin, at(x, y), text, height, "marking"))
def line(x0, y0, x1, y1):
import surface as S
def step(skin, at):
a, b = at.c + at.e1 * x0 + at.e2 * y0, at.c + at.e1 * x1 + at.e2 * y1
n = np.cross(at.e1, at.e2)
S.panel_line(skin, ("line", tuple(a + n * 0.4), tuple(b + n * 0.4), tuple(-n)), gap=0.022)
return ("line", step)
def dings(seed=1):
import surface as S
return ("dings", lambda skin, at: S.edge_dings(skin, ("rim", 0), count=5, seed=seed))
def tri_on(name, size):
"""The sheet's hollow triangle on a plate's face: a ray down the crown's normal at its middle (the world)."""
obj = bpy.data.objects[name]
c, e1, e2, n = PC.basis(np.array(PC.PLATES[name]["crown"]))
w = obj.matrix_world
return triangle(f"Tri.{name}", w @ Vector(c + n * 0.4), w.to_3x3() @ Vector(-n), size)
def stowage(b, frame, size, mat="khaki"):
"""A strapped stowage box on a frame (z out of the face): the box, a lid step, two straps, a latch."""
w, h, d = size
b[mat].prism(frame, M.rect(w, h, 0.03), d, 0.02)
b[mat].prism(frame @ T((0, 0.04 * h, d)), M.rect(0.92 * w, 0.8 * h, 0.03), 0.025, 0.012)
for x in (-0.28, 0.28):
b["gunmetal"].box(frame @ T((x * w, 0, 0.5 * d + 0.02)), (0.06 * w, 1.04 * h, d + 0.04))
b["machine"].box(frame @ T((0, -0.5 * h, 0.6 * d)), (0.16 * w, 0.03, 0.08))
# --- pauldrons -------------------------------------------------------------------------------------------------------
def pauldron_frame(frame, sx):
at = PF.PAULDRON_AT
return frame @ T((-sx * at[0], at[1], at[2]))
def pauldron_core(frame, sx):
"""The pauldron's dark body under its shields: a faceted hood, its roof falling outboard, its front and rear
faces leaning back to the roof, its foot cut back under the knuckle."""
pts = [(-0.9, 1.0, 1.15), (-0.9, -1.0, 1.15), (0.45, 0.95, 0.72), (0.45, -0.95, 0.72), (0.86, 1.0, -0.1), (0.86, -1.0, -0.1), (0.5, 0.8, -0.95), (0.5, -0.8, -0.95),
(-0.8, 0.85, -0.85), (-0.8, -0.85, -0.85), (0.0, 1.22, 0.1), (0.0, -1.22, 0.1), (-0.9, 1.1, 0.2), (-0.9, -1.1, 0.2)]
return mass(f"Pauldron{'L' if sx < 0 else 'R'}.core", sided(pts, sx), pauldron_frame(frame, sx), CORE)
def pauldron_shields(frame, sx, crowns):
"""The traced shields of one pauldron: the front shield (both sides, hero), the right's front-outboard facet (hero), the
left's rear shield (rear view). Each stands on a sloped plane of the pauldron: the front leans back 17 degrees,
the outboard facet is turned 50 degrees out from it, the rear leans forward. The side shield, which no view but
the square-on side shows, is authored (pauldron_layers): it leans in 20 degrees to the roof."""
s, t = ("L", "l") if sx < 0 else ("R", "r")
Fp = pauldron_frame(frame, sx)
near = (f"shoulder_{t}",)
crowns[s, "Front"] = plate(f"Pauldron{s}.Front", Fp, f"Pauldron{s}.Front", (0, 1.34, 0.1), (sx * 0.22, 1, 0.3), near=near, flare=0.08, drop=0.09, dome=0.03, soft=(3,), thickness=0.015)
if sx > 0:
crowns[s, "Outer"] = plate("PauldronR.Outer", Fp, "PauldronR.Outer", (sx * 0.72, 1.0, 0.0), (sx * 0.75, 0.6, 0.3), near=near, flare=0.08, drop=0.09, dome=0.03, soft=(2,), thickness=0.015)
else:
crowns[s, "Rear"] = plate("PauldronL.Rear", Fp, "PauldronL.Rear", (0, -1.34, 0.1), (sx * 0.2, -1, 0.3), near=near, flare=0.08, drop=0.09, dome=0.03, soft=(3,), thickness=0.015)
def pauldron_layers(frame, sx, crowns):
"""The rest of a pauldron, layered on the shields: the shield the sheet hides on this side from the other side's
fitted crown mirrored; a base plate standing back under each shield and larger than it; the roof, a sloped plate
of its own; lames stepping down under the outer shield; a block and a sunk box on the front shield; bolts."""
s, o = ("L", "R") if sx < 0 else ("R", "L")
Fp = pauldron_frame(frame, sx)
for face in ("Outer", "Rear"):
if (s, face) not in crowns:
crowns[s, face] = plate(f"Pauldron{s}.{face}", Fp, crown=PC.mirrored(crowns[o, face]), normal=(sx * 0.75, 0.6, 0.3) if face == "Outer" else (sx * 0.2, -1, 0.3),
flare=0.08, drop=0.09, dome=0.03, thickness=0.015)
side = on_plane((sx * 0.98, -0.1, 0.05), (sx, -0.05, 0.36), [(-0.95 * sx, 0.72), (-1.0 * sx, -0.2), (-0.45 * sx, -0.95), (0.5 * sx, -0.95), (0.85 * sx, -0.1), (0.7 * sx, 0.72)])
crowns[s, "Side"] = plate(f"Pauldron{s}.Side", Fp, crown=side, normal=(sx, -0.05, 0.36), flare=0.08, drop=0.09, dome=0.04, soft=(2,), thickness=0.015)
for face in ("Front", "Outer", "Rear", "Side"):
cr = crowns[s, face]
plate(f"Pauldron{s}.{face}Base", Fp, crown=PC.grown(cr, 1.13, 0.13, (0.0, 0.04)), normal=PC.basis(cr)[3], flare=0.05, drop=0.08, dome=0.0, soft=(0, 2), thickness=0.015)
roof = sided([(-0.92, -1.08, 1.3), (0.5, -1.0, 0.9), (0.5, 1.0, 0.9), (-0.92, 1.08, 1.3)], sx)
crowns[s, "Roof"] = plate(f"Pauldron{s}.Roof", Fp, crown=roof, normal=(sx * 0.3, 0, 1), flare=0.07, drop=0.08, dome=0.03, thickness=0.015)
x0, x1, y0, y1 = extent(crowns[s, "Side"])
for i in range(2): # lames stepping down under the side shield's foot
plate(f"Pauldron{s}.Lame{i}", Fp, crown=PC.patch(crowns[s, "Side"], (0.0, y0 - 0.1 - 0.3 * i), (0.7 * (x1 - x0) - 0.2 * i, 0.34), -0.1 - 0.07 * i, cut=0.08),
normal=PC.basis(crowns[s, "Side"])[3], flare=0.04, drop=0.05, dome=0.0, soft=(0,), thickness=0.015)
fx0, fx1, fy0, fy1 = extent(crowns[s, "Front"])
plate(f"Pauldron{s}.Block", Fp, crown=PC.patch(crowns[s, "Front"], (0.0, fy1 - 0.3), (0.5 * (fx1 - fx0), 0.36), 0.06, cut=0.06), normal=PC.basis(crowns[s, "Front"])[3],
flare=0.035, drop=0.05, dome=0.0, thickness=0.015)
mid, low = 0.5 * (fy0 + fy1), fy0 + 0.42
dress(f"Pauldron{s}.Front", [bolts(0.08, 0.3), inset(0.05, low, (0.42, 0.26)), line(fx0 + 0.1, mid - 0.2, fx1 - 0.1, mid - 0.2)] + ([numeral(0.0, mid + 0.02, "07", 0.34)] if sx > 0 else []))
dress(f"Pauldron{s}.Outer", [bolts(0.08, 0.34), dings(3)])
dress(f"Pauldron{s}.Side", [bolts(0.08, 0.34), slots(0.0, 0.5 * (y0 + y1) - 0.15, 3, 0.1, 0.4, 0.04), port(0.0, 0.5 * (y0 + y1) + 0.35, 0.08)])
dress(f"Pauldron{s}.Rear", [bolts(0.08, 0.34), port(0.1, 0.1, 0.08), line(-0.4, -0.3, 0.4, -0.3)])
dress(f"Pauldron{s}.Roof", [bolts(0.08, 0.4), inset(0.0, 0.0, (0.5, 0.3))])
for name in (f"Pauldron{s}.FrontBase", f"Pauldron{s}.OuterBase", f"Pauldron{s}.RearBase", f"Pauldron{s}.SideBase", f"Pauldron{s}.Lame0", f"Pauldron{s}.Lame1", f"Pauldron{s}.Block"):
dress(name, [bolts(0.05, 0.3, 0.014)] if "Lame" in name or "Block" in name else [])
if sx < 0:
tri_on("PauldronL.Front", 0.4)
b = put(f"Pauldron{s}.fittings", Fp) # a grab rail along the roof's inner edge
g = b["gunmetal"]
g.rod((-sx * 0.8, -0.8, 1.42), (-sx * 0.8, 0.8, 1.42), 0.03, 8)
for y in (-0.8, 0.0, 0.8):
g.rod((-sx * 0.8, y, 1.25), (-sx * 0.8, y, 1.42), 0.03, 8)
b.done()
# --- legs ------------------------------------------------------------------------------------------------------------
def leg_frames(s):
leg = KITS["legs"][s]
return BK.frame(leg["upper"]), BK.frame(leg["lower"])
def leg_cores(s, sx):
"""The legs' dark bodies round the kit's girders: a deep hexagonal thigh block from above the hip's pin to the
knee, the shin a block that widens to mid-height; the calf's two rams behind; a stowage box on the calf."""
Ft, Fs = leg_frames(s)
Lt, Ls = PF.KIT["thigh"], PF.KIT["shin"]
b = put(f"Thigh{s}.core", Ft)
sec = [(-0.56, 0.6), (0.56, 0.6), (0.72, 0.0), (0.56, -0.54), (-0.56, -0.54), (-0.72, 0.0)]
b[CORE].hull([(x * k, y * k, z) for z, k in ((0.5, 0.7), (0.15, 1.0), (-Lt + 0.5, 1.0), (-Lt + 0.15, 0.72)) for x, y in sec])
for z in (-0.5, -0.95, -1.4): # ribs showing between the plates
b["machine"].box(T((0, 0, z)), (1.1, 1.0, 0.06))
with BK.Adopt(KITS["legs"][s]["upper"]):
b.done()
b = put(f"Shin{s}.core", Fs)
sec = [(-0.5, 0.54), (0.5, 0.54), (0.64, 0.0), (0.5, -0.5), (-0.5, -0.5), (-0.64, 0.0)]
b[CORE].hull([(x * k, y * k, z) for z, k in ((-0.35, 0.75), (-0.8, 1.0), (-Ls + 0.75, 0.95), (-Ls + 0.4, 0.7)) for x, y in sec])
g = b["gunmetal"]
for x in (-0.3, 0.3):
g.rod((x, -0.6, -0.6), (x, -0.68, -Ls + 0.9), 0.11, 12)
b["steel"].rod((x, -0.68, -Ls + 0.9), (x, -0.6, -Ls + 0.3), 0.06, 12)
g.cylinder(F((x, -0.58, -0.55), (1, 0, 0)), 0.14, 0.2, 12)
stowage(b, F((0, -0.5, -1.25), (0, -1, 0), UP), (0.62, 0.5, 0.2))
for z in (-1.0, -1.6):
b["machine"].box(T((0, 0, z)), (0.98, 0.9, 0.06))
with BK.Adopt(KITS["legs"][s]["lower"]):
b.done()
def leg_shields(s, sx, crowns):
"""The traced plates of one leg (hero view): the thigh's front shield; the right thigh's outer plate and the
left's inner; the plate over the knee (Shin.Upper: the sheet draws it centred on the knee) and the shin's front plate under it
(Shin.Lower; on the left leg the sheet shows only a short plate under the knee, the greave being in shadow); the
right shin's front-outboard plate and the left's inner."""
t = s.lower()
Ft, Fs = leg_frames(s)
hip, knee, ankle = f"hip_{t}", f"knee_{t}", f"ankle_{t}"
crowns[s, "Shield"] = plate(f"Thigh{s}.Shield", Ft, f"Thigh{s}.Shield", (0, 0.86, -0.9), (sx * 0.12, 1, 0.08), near=(hip, knee), flare=0.09, drop=0.1, dome=0.04, soft=(4,) if sx > 0 else (3,),
thickness=0.015)
if sx > 0:
crowns[s, "Outer"] = plate("ThighR.Outer", Ft, "ThighR.Outer", (sx * 0.62, 0.5, -0.6), (sx * 0.7, 0.7, 0.1), near=(hip, knee), flare=0.07, drop=0.08, dome=0.03, soft=(3,), thickness=0.015)
crowns[s, "ShinOuter"] = plate("ShinR.Outer", Fs, "ShinR.Outer", (sx * 0.6, 0.35, -1.5), (sx * 0.7, 0.7, 0), near=(knee, ankle), flare=0.06, drop=0.08, dome=0.03, soft=(3,), thickness=0.015)
else:
crowns[s, "Inner"] = plate("ThighL.Inner", Ft, "ThighL.Inner", (-sx * 0.74, 0.25, -1.0), (-sx, 0.55, 0), near=(hip, knee), flare=0.06, drop=0.08, dome=0.03, soft=(2,), thickness=0.015)
crowns[s, "ShinInner"] = plate("ShinL.Inner", Fs, "ShinL.Inner", (-sx * 0.64, 0.1, -1.2), (-sx, 0.5, 0), near=(knee, ankle), flare=0.06, drop=0.08, dome=0.03, soft=(2,), thickness=0.015)
crowns[s, "Upper"] = plate(f"Shin{s}.Upper", Fs, f"Shin{s}.Upper", (0, 0.86, -0.1), (sx * 0.1, 1, 0.1), near=(knee,), flare=0.07, drop=0.09, dome=0.04, soft=(2,), thickness=0.015)
crowns[s, "Lower"] = plate(f"Shin{s}.Lower", Fs, f"Shin{s}.Lower", (0, 0.7, -1.4), (sx * 0.1, 1, -0.08), near=(knee, ankle) if sx > 0 else (knee,), flare=0.07, drop=0.09, dome=0.03, soft=(0,), thickness=0.015)
def leg_layers(s, sx, crowns):
"""The rest of a leg's armour, layered on the fitted plates: the side plate the sheet hides, mirrored from the
other leg's; a base plate under each shield; on the thigh's shield the block over its head and a lame across its
foot; the left shin's greave; rear plates; stowage; bolts, sunk panels, slots and marks."""
o = "R" if s == "L" else "L"
Ft, Fs = leg_frames(s)
for key, F_, pre, n in (("Outer", Ft, "Thigh", (sx * 0.7, 0.7, 0.1)), ("Inner", Ft, "Thigh", (-sx, 0.55, 0)), ("ShinOuter", Fs, "Shin", (sx * 0.7, 0.7, 0)), ("ShinInner", Fs, "Shin", (-sx, 0.5, 0))):
if (s, key) not in crowns:
crowns[s, key] = plate(f"{pre}{s}.{key.replace('Shin', '')}", F_, crown=PC.mirrored(crowns[o, key]), normal=n, flare=0.06, drop=0.08, dome=0.03, thickness=0.015)
sh = crowns[s, "Shield"]
n = PC.basis(sh)[3]
x0, x1, y0, y1 = extent(sh)
plate(f"Thigh{s}.ShieldBase", Ft, crown=PC.grown(sh, 1.12, 0.15, (0.0, 0.06)), normal=n, flare=0.06, drop=0.09, dome=0.0, soft=(1, 4), thickness=0.015)
plate(f"Thigh{s}.Block", Ft, crown=PC.patch(sh, (0.04, y1 - 0.08), (0.52, 0.46), 0.09, cut=0.07), normal=n, flare=0.04, drop=0.07, dome=0.0, thickness=0.015)
plate(f"Thigh{s}.Lame", Ft, crown=PC.patch(sh, (0.0, y0 + 0.2), (0.8 * (x1 - x0), 0.3), 0.05, cut=0.06), normal=n, flare=0.04, drop=0.05, dome=0.0, soft=(0,), thickness=0.015)
plate(f"Thigh{s}.OuterBase", Ft, crown=PC.grown(crowns[s, "Outer"], 1.1, 0.1), normal=PC.basis(crowns[s, "Outer"])[3], flare=0.05, drop=0.07, dome=0.0, soft=(0, 3), thickness=0.015)
plate(f"Thigh{s}.Rear", Ft, crown=on_plane((0, -0.66, -0.85), (0, -1, 0.05), [(-0.5, 0.7), (-0.62, 0.2), (-0.5, -0.75), (0.5, -0.75), (0.62, 0.2), (0.5, 0.7)]), normal=(0, -1, 0.05),
flare=0.07, drop=0.09, dome=0.03, soft=(2,), thickness=0.015)
plate(f"Thigh{s}.Cap", Ft, crown=on_plane((0, 0.05, 0.58), (0, 0.25, 1), [(-0.5, -0.4), (0.5, -0.4), (0.56, 0.2), (0.3, 0.46), (-0.3, 0.46), (-0.56, 0.2)]), normal=(0, 0.25, 1),
flare=0.06, drop=0.08, dome=0.02, thickness=0.015)
up, lo = crowns[s, "Upper"], crowns[s, "Lower"]
nu = PC.basis(up)[3]
plate(f"Shin{s}.UpperBase", Fs, crown=PC.grown(up, 1.12, 0.13), normal=nu, flare=0.05, drop=0.08, dome=0.0, soft=(0, 2), thickness=0.015)
ux0, ux1, uy0, uy1 = extent(up)
if sx < 0: # the left shin's greave is in shadow on the sheet: the right's fitted crown, mirrored
crowns[s, "Greave"] = plate("ShinL.Greave", Fs, crown=PC.mirrored(crowns["R", "Lower"]), normal=(sx * 0.1, 1, -0.08), flare=0.07, drop=0.09, dome=0.03, soft=(0,), thickness=0.015)
lx0, lx1, ly0, ly1 = extent(lo)
plate(f"Shin{s}.LowerBase", Fs, crown=PC.grown(lo, 1.1, 0.12), normal=PC.basis(lo)[3], flare=0.05, drop=0.08, dome=0.0, soft=(1, 3), thickness=0.015)
plate(f"Shin{s}.Step", Fs, crown=PC.patch(lo, (0.0, ly0 + 0.2), (0.7 * (lx1 - lx0), 0.3), 0.05, cut=0.05), normal=PC.basis(lo)[3], flare=0.04, drop=0.05, dome=0.0, thickness=0.015)
plate(f"Shin{s}.Calf", Fs, crown=on_plane((0, -0.62, -2.0), (0, -1, -0.1), [(-0.4, 0.3), (-0.5, -0.1), (-0.36, -0.4), (0.36, -0.4), (0.5, -0.1), (0.4, 0.3)]), normal=(0, -1, -0.1),
flare=0.05, drop=0.07, dome=0.02, thickness=0.015)
mid = 0.5 * (y0 + y1)
dress(f"Thigh{s}.Shield", [bolts(0.09, 0.3), line(x0 + 0.12, y0 + 0.42, x1 - 0.12, y0 + 0.42)] + ([numeral(0.0, mid - 0.05, "07", 0.4)] if sx < 0 else []))
dress(f"Thigh{s}.Block", [inset(0.0, 0.0, (0.3, 0.22))])
dress(f"Thigh{s}.Lame", [slots(0.0, 0.0, 1, 0.1, 0.4, 0.05), bolts(0.05, 0.3, 0.014, sides=(0,))])
dress(f"Thigh{s}.Outer", [bolts(0.08, 0.32), port(0.0, 0.25, 0.08), dings(5)])
dress(f"Thigh{s}.Inner", [bolts(0.08, 0.34)])
dress(f"Thigh{s}.Rear", [bolts(0.08, 0.34), inset(0.0, 0.1, (0.5, 0.3)), slots(0.0, -0.45, 2, 0.1, 0.4, 0.04)])
dress(f"Shin{s}.Upper", [bolts(0.08, 0.3), line(ux0 + 0.1, uy0 + 0.25, ux1 - 0.1, uy0 + 0.25)])
dress(f"Shin{s}.Lower", [bolts(0.08, 0.32), inset(0.0, 0.5 * (ly0 + ly1) + 0.15, (0.4, 0.5)), dings(7)])
if sx < 0:
dress("ShinL.Greave", [bolts(0.08, 0.32), inset(0.0, 0.2, (0.4, 0.5)), dings(9)])
dress(f"Shin{s}.Outer", [bolts(0.07, 0.34), slots(0.0, 0.0, 3, 0.1, 0.3, 0.04)])
dress(f"Shin{s}.Inner", [bolts(0.07, 0.34)])
for name in ("Thigh%s.ShieldBase", "Thigh%s.OuterBase", "Thigh%s.Cap", "Shin%s.UpperBase", "Shin%s.LowerBase", "Shin%s.Step", "Shin%s.Calf"):
dress(name % s, [bolts(0.05, 0.32, 0.014)] if "Step" in name or "Cap" in name or "Calf" in name else [])
if sx > 0:
tri_on("ThighR.Shield", 0.5)
else:
tri_on("ShinL.Lower", 0.3)
b = put(f"Thigh{s}.stowage", Ft) # a stowage box and a rail on the thigh's outer side, behind the outer plate
stowage(b, F((sx * 0.7, -0.3, -1.2), (sx, -0.2, 0), UP), (0.5, 0.42, 0.18))
b["gunmetal"].rod((sx * 0.72, -0.05, -0.2), (sx * 0.72, -0.4, -0.2), 0.035, 8)
b.done()
def knee(s):
"""KNEE & LEG DETAIL inset: the joints library's kneecap_bisector at the knee's bend as the kit stands, for
its carrier ring and the pin's disc at the side. Its limb stubs and its cap are left out: the plate over the knee
is the fitted Shin.Upper."""
import jointlib as J
import joints
leg = KITS["legs"][s]
Ft, Fs = leg_frames(s)
frame = Ft.copy()
frame.translation = Fs.translation
down = frame.to_3x3().inverted() @ (Fs.to_3x3() @ Vector((0, 0, -1)))
angle = math.degrees(math.atan2(down.y, -down.z))
rig = J.Rig(f"Knee{s}", frame, -95.0, 0.0)
joints.kneecap_bisector(rig, angle, r=0.5, cap=(1.15, 1.25), disc=0.34)
objs = list(rig.done())
for o in list(objs):
if o.get("mat") == "khaki": # its limb stubs and its cap: the fitted plate over the knee is this build's
objs.remove(o)
bpy.data.objects.remove(o, do_unlink=True)
BK.adopt(leg["lower"], [o for o in objs if o.get("link") == "shin"])
BK.adopt(leg["upper"], [o for o in objs if o.get("link") != "shin"])
print(f"KNEE {s}: bend {angle:.1f}", flush=True)
return angle
# --- arms ------------------------------------------------------------------------------------------------------------
def arm_frames(s):
arm = KITS["arms"][s]
return BK.frame(arm["upper"]), BK.frame(arm["lower"])
def upper_arm(s, sx):
"""Hero view: a short dark upper arm under the pauldron, ribbed; an outer and a front plate on it, each a free
cage, a lame on the outer plate; the elbow's drum on its pin."""
Fu, Ff = arm_frames(s)
L = PF.KIT["upper_arm"]
b = put(f"UpperArm{s}", Fu)
g = b["gunmetal"]
g.box(T((0, 0, -0.5 * L)), (0.66, 0.76, L))
for i in range(5):
g.box(T((0, 0, -0.25 - 0.26 * i)), (0.78, 0.88, 0.08))
g.lathe(F((-0.5, 0, -L), (1, 0, 0), UP), [(0, 0), (0.4, 0), (0.44, 0.05), (0.44, 0.95), (0.4, 1.0), (0, 1.0)], 24)
for x in (-0.54, 0.54):
b["machine"].cylinder(F((x, 0, -L), (1, 0, 0), UP), 0.28, 0.08, 16)
b.done()
out_ = plate(f"UpperArm{s}.Outer", Fu, crown=on_plane((sx * 0.5, 0, -0.85), (sx, 0, 0.05), [(-0.4, 0.5), (-0.46, -0.1), (-0.3, -0.55), (0.3, -0.55), (0.46, -0.1), (0.4, 0.5)]), normal=(sx, 0, 0.05),
flare=0.05, drop=0.07, dome=0.03, soft=(2,), thickness=0.015)
plate(f"UpperArm{s}.Front", Fu, crown=on_plane((0, 0.5, -0.9), (0, 1, 0), [(-0.3, 0.45), (-0.3, -0.5), (0.3, -0.5), (0.3, 0.45)]), normal=(0, 1, 0), flare=0.05, drop=0.07, dome=0.02, thickness=0.015)
plate(f"UpperArm{s}.Lame", Fu, crown=PC.patch(out_, (0.0, -0.3), (0.5, 0.24), 0.05, cut=0.05), normal=PC.basis(out_)[3], flare=0.035, drop=0.05, dome=0.0, thickness=0.015)
dress(f"UpperArm{s}.Outer", [bolts(0.07, 0.28, 0.016), port(0.0, 0.2, 0.06)])
dress(f"UpperArm{s}.Front", [bolts(0.06, 0.3, 0.016)])
dress(f"UpperArm{s}.Lame", [])
def forearm_left(crowns):
"""LEFT FOREARM - MANIPULATOR & ENERGY inset and the hero view: a dark housing from the elbow to the wrist; a
front plate and an outer plate traced on the hero view, three small stepped plates down the front as the sheet
stacks them, an inner plate; under its end the open hand (the joints library's), beside it the emitter (the
weapons library's paladin_energy_emitter, class S)."""
import jointlib as J
import hands
import weapons_energy
Fu, Ff = arm_frames("L")
L = PF.KIT["forearm_l"]
b = put("ForearmL.core", Ff)
sec = [(-0.36, 0.4), (0.36, 0.4), (0.44, 0.0), (0.36, -0.42), (-0.36, -0.42), (-0.44, 0.0)]
b[CORE].hull([(x * k, y * k, z) for z, k in ((-0.15, 0.7), (-0.5, 1.0), (-L + 0.2, 1.0), (-L - 0.05, 0.75)) for x, y in sec])
for z in (-0.7, -1.1, -1.5):
b["machine"].box(T((0, 0, z)), (0.94, 0.9, 0.05))
b.done()
near = ("elbow_l", "wrist_l")
fr = crowns["L", "ForearmFront"] = plate("ForearmL.Front", Ff, "ForearmL.Front", (0, 0.5, -1.0), (0.12, 1, 0.05), near=near, flare=0.05, drop=0.07, dome=0.02, thickness=0.015)
crowns["L", "ForearmOuter"] = plate("ForearmL.Outer", Ff, "ForearmL.Outer", (-0.36, 0.38, -1.0), (-0.6, 0.8, 0), near=near, flare=0.05, drop=0.07, dome=0.02, thickness=0.015)
n = PC.basis(fr)[3]
x0, x1, y0, y1 = extent(fr)
for i in range(3):
y = y1 - 0.25 - i * (y1 - y0 - 0.3) / 3
plate(f"ForearmL.Step{i}", Ff, crown=PC.patch(fr, (0.0, y), (0.72 * (x1 - x0), 0.3), 0.05 + 0.02 * (2 - i), cut=0.05), normal=n, flare=0.035, drop=0.05, dome=0.0, soft=(0,), thickness=0.015)
plate("ForearmL.Inner", Ff, crown=on_plane((0.5, 0.0, -1.05), (1, 0.2, 0), [(-0.36, 0.55), (-0.36, -0.6), (0.36, -0.6), (0.36, 0.55)]), normal=(1, 0.2, 0), flare=0.05, drop=0.07, dome=0.02, thickness=0.015)
dress("ForearmL.Front", [bolts(0.06, 0.28, 0.014)])
dress("ForearmL.Outer", [bolts(0.06, 0.28, 0.014), slots(0.0, 0.0, 3, 0.09, 0.2, 0.035)])
dress("ForearmL.Inner", [bolts(0.06, 0.3, 0.014), port(0.0, 0.1, 0.06)])
for i in range(3):
dress(f"ForearmL.Step{i}", [bolts(0.045, 0.3, 0.012, sides=(0,))])
z, y = Ff.to_3x3() @ Vector((0, 0, 1)), Ff.to_3x3() @ Vector((1, 0, 0)) # the hand hangs down the forearm, its palm inboard
m = Matrix((y.cross(z), y, z)).transposed().to_4x4()
m.translation = Ff @ Vector((0, 0, -L - 0.25))
rig = J.Rig("HandL", m @ Matrix.Scale(1.55, 4), 0.0, 100.0)
hands.hand(rig, 30.0, plate="khaki")
rig.done()
side = Ff.to_3x3() @ Vector((-1, 0, 0))
E_, W_ = Ff.translation, Ff @ Vector((0, 0, -L))
put("Emitter", aim(E_ + side * 0.8 - z * 0.7, W_ + side * 0.8 - z * 0.7), weapons_energy.paladin_energy_emitter, size="S")

View file

@ -5,7 +5,9 @@ Reads MECH_OUT/paladin/ (paladin.py's renders); writes under MECH_OUT/compare/:
paladin_flowlines.png the lines traced on the hero view (red) | our built edges at the same camera (cyan) | scores
paladin_vs_concept.png hero, rear and side: concept | ours | the two laid over each other; the silhouettes' overlap
paladin_character.png the belt, close: concept | ours with the traced belt and our edges | ours
paladin_components.png each inset of the sheet beside our part
paladin_components.png each inset of the sheet beside our part, and the rebuilt plates beside their crops
paladin_plates.png the traced plate edges (red) on the hero and rear views | our edges | each cage's numbers
paladin_before_after.png the first pass (MECH_BEFORE/paladin, its own renders) beside this one, view by view
Scores go to MECH_OUT/paladin/paladin_scores.json."""
import json, os, sys
from pathlib import Path
@ -120,8 +122,11 @@ edges_path = src / f"{stage}_edges_hero.json"
if edges_path.exists():
edges = json.loads(edges_path.read_text(encoding="utf-8"))
segs = [e["seg"] for e in edges]
traces = {"belt": PF.BELT_TRACE, "visor": PF.VISOR_TRACE, "pauldron_r": PF.PAULDRON_TRACE["r"], "pauldron_l": PF.PAULDRON_TRACE["l"], "thigh_r": PF.THIGH_TRACE["r"] + PF.THIGH_TRACE["r"][:1]}
own = {"belt": ("Torso.",), "visor": ("Turret.", "Visor"), "pauldron_r": ("PauldronR.",), "pauldron_l": ("PauldronL.",), "thigh_r": ("ThighR.",)}
traces = {"belt": PF.BELT_TRACE, "visor": PF.VISOR_TRACE}
own = {"belt": ("Torso.",), "visor": ("Turret.", "Visor")}
for name, (view, pts) in PF.TRACES.items():
if view == "hero":
traces[name], own[name] = list(pts) + [pts[0]], (name,)
fl = {}
for k, pts in traces.items():
mine = [e["seg"] for e in edges if e["object"].startswith(own[k])]
@ -131,11 +136,11 @@ if edges_path.exists():
c = fit(sheet.crop(tuple(box)), H)
o = render(f"{stage}_hero.png", size=c.size)
body = ["traced lines against our built edges at the", "solved hero camera (fitshell.along):", "on: share of the line with a built edge", " within 1% of the figure's height,", " running its way", "run: longest unbroken share",
"off: mean distance, % of the height", "own: the part's own edges; all: any edge", "", f"{'line':11s} {'':4s} {'on':>5s} {'run':>5s} {'off':>5s}"]
"off: mean distance, % of the height", "own: the part's own edges; all: any edge", "", f"{'line':16s} {'':4s} {'on':>5s} {'run':>5s} {'off':>5s}"]
for k, v in fl.items():
for which in ("own", "all"):
if v[which]:
body.append(f"{k:11s} {which:4s} {v[which]['on']:5.2f} {v[which]['run']:5.2f} {v[which]['off']:5.2f}")
body.append(f"{k:16s} {which:4s} {v[which]['on']:5.2f} {v[which]['run']:5.2f} {v[which]['off']:5.2f}")
row([label(in_box(c, box, lines=traces.values(), width=4), "sheet 27, hero: the traced lines (red); the belt is the character line"),
label(in_box(o, box, lines=traces.values(), segs=segs, width=4), "ours at the solved hero camera: the traces (red), our built edges (cyan)"), text_panel(body, 560, H + 34)]).save(dst / "paladin_flowlines.png")
cb = [20, 0, 352, 200]
@ -148,10 +153,38 @@ if edges_path.exists():
stack([row([label(in_box(crop, cb, lines=lines, width=5), "sheet 27: the belt and the visor's lip (red)"), label(in_box(ours, cb, lines=lines, segs=torso, width=5), "ours, same camera: the traces (red), the hull's, turret's and pauldrons' edges (cyan). " + note)]),
row([label(crop, "sheet 27"), label(ours, "ours")])]).save(dst / "paladin_character.png")
# the plates: traces, edges, cages
if edges_path.exists() and report.get("plates"):
box = cams["hero"]["box"]
c = fit(sheet.crop(tuple(box)), H)
o = render(f"{stage}_hero.png", size=c.size)
hero_lines = [list(pts) + [pts[0]] for name, (view, pts) in PF.TRACES.items() if view == "hero"]
plate_segs = [e["seg"] for e in edges if e["object"].split(" ")[0] in report["plates"]]
cg = report["cages"]
body = [f"{cg['plates']} free-cage plates, {cg['cage_verts']} cage vertices ({cg['verts_per_plate']} a plate)", f"creased {cg['creased']} of {cg['edges']} edges: {100 * cg['crease_share']:.0f}% (Dexter's hull: 19%)",
f"poles {cg['poles']} (each a plate's centre)", f"fitted {cg['fitted']}, refused {cg['refused']}; worst reading {cg['worst_unexplained_px']} px (tol 5.2)", "",
f"{'traced plate':17s} {'v':>2s} {'cr%':>4s} {'p':>1s} {'unexpl':>6s} {'worst':>5s} {'moved':>6s} {'prior':>9s}"]
for name, pl in report["plates"].items():
f_ = pl["fit"]
if f_ is None:
continue
if "refused" in f_:
body.append(f"{name:17s} {pl['verts']:2d} {100 * pl['crease_share']:4.0f} {pl['poles']:1d} REFUSED")
else:
body.append(f"{name:17s} {pl['verts']:2d} {100 * pl['crease_share']:4.0f} {pl['poles']:1d} {f_['unexplained_px']:6.2f} {f_['worst_px']:5.1f} {f_['moved_m']:6.3f} {f_['prior_share'][0]:4.2f}-{f_['prior_share'][1]:4.2f}")
body += ["", "v: cage vertices; cr%: creased edges; p: poles", "unexpl: 90th percentile px of the trace from", "its built run; moved: m the fit moved a point", "prior: prior_share (near 1: depth is the", "blocking plane's, one view decides none)",
"", f"{sum(1 for p_ in report['plates'].values() if p_['fit'] is None)} more plates are derived from these", "(mirrored, base, block, lame) or authored"]
row([label(in_box(c, box, lines=hero_lines, width=3), "sheet 27, hero: the traced plate edges (red)"), label(in_box(o, box, lines=hero_lines, segs=plate_segs, width=3), "ours: the traces (red), the plates' built edges (cyan)"),
text_panel(body, 760, H + 34)]).save(dst / "paladin_plates.png")
scores["cages"] = cg
# components
INSETS = [("cockpit", (0, 512, 262, 712), "COCKPIT & SENSOR ARRAY"), ("battery", (262, 512, 512, 712), "RIGHT SHOULDER - MISSILE BATTERY"), ("ew", (512, 512, 762, 712), "LEFT SHOULDER - SENSOR / EW MODULE"),
("exchangers", (762, 512, 1024, 712), "DORSAL SPINE & HEAT EXCHANGERS"), ("gatling", (0, 742, 205, 930), "RIGHT FOREARM - BALLISTIC WEAPON"), ("hand", (207, 742, 390, 930), "LEFT FOREARM - MANIPULATOR & ENERGY"),
("pelvis", (392, 742, 633, 930), "PELVIS & HIP ASSEMBLY"), ("knee", (635, 742, 815, 930), "KNEE & LEG DETAIL"), ("foot", (817, 742, 1024, 930), "FOOT & ANKLE")]
("pelvis", (392, 742, 633, 930), "PELVIS & HIP ASSEMBLY"), ("knee", (635, 742, 815, 930), "KNEE & LEG DETAIL"), ("foot", (817, 742, 1024, 930), "FOOT & ANKLE"),
("pauldron_r", (25, 35, 155, 150), "hero: the right pauldron"), ("pauldron_rear", (385, 20, 515, 150), "rear: the left pauldron"), ("pauldron_side", (690, 60, 885, 190), "side: the pauldron"),
("thigh_r", (75, 180, 200, 300), "hero: the right thigh"), ("shin_r", (60, 280, 190, 410), "hero: the right shin"), ("leg_side", (690, 230, 885, 470), "side: the leg"),
("forearm_l", (265, 150, 352, 280), "hero: the left forearm")]
cells = []
for name, box, title in INSETS:
if (src / f"part_{name}.png").exists():
@ -162,6 +195,23 @@ if cells:
cells = [c.crop((0, 0, w, c.height)) if c.width == w else row([c, Image.new("RGB", (w - c.width - 8, c.height), BG)]) for c in cells]
stack([row(cells[i:i + 3]) for i in range(0, len(cells), 3)]).save(dst / "paladin_components.png")
# before and after: the first pass's own renders beside this pass's
before = Path(os.environ.get("MECH_BEFORE", ""))
if os.environ.get("MECH_BEFORE") and (before / "paladin" / "full_hero.png").exists():
def old(stem, size):
img = Image.open(before / "paladin" / stem).convert("RGBA")
return Image.alpha_composite(Image.new("RGBA", img.size, (150, 156, 164, 255)), img).convert("RGB").resize(size, Image.LANCZOS)
rows = []
for tag, cam in cams.items():
box = cam["box"]
c = fit(sheet.crop(tuple(box)), 900)
rows.append([label(c, f"sheet 27, {PF.VIEWS[tag]['label']}"), label(old(f"full_{tag}.png", c.size), "first pass (87fd442), its own solved camera"), label(render(f"{stage}_{tag}.png", size=c.size), "second pass, its solved camera")])
turns = []
for az in ("035", "090", "180"):
if (before / "paladin" / f"full_turn_{az}.png").exists() and (src / f"{stage}_turn_{az}.png").exists():
turns.append(row([label(old(f"full_turn_{az}.png", (760, 760)), f"first pass, turned {int(az)}"), label(render(f"{stage}_turn_{az}.png", size=(760, 760)), f"second pass, turned {int(az)}")], gap=2))
stack([row(rows[0] + rows[2]), row(rows[1]), row(turns)] if turns else [row(rows[0] + rows[2]), row(rows[1])]).save(dst / "paladin_before_after.png")
for tag, cam in cams.items():
box = cam["box"]
size = (int(box[2] - box[0]) * 3, int(box[3] - box[1]) * 3)

View file

@ -7,6 +7,8 @@ where that component stands in the build (<mech>_frames.json) and seen by the so
(<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_CAGE_WIRE: for each free-cage shell of a part (kit_shell with verts), <name>_wire_<shell>.png: that shell alone, as
built, under its cage (mechlib.cage_wire: cage edges dark, creased edges red, poles yellow), from the set's WIRE view.
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
@ -58,6 +60,19 @@ for name in names:
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")
if os.environ.get("MECH_CAGE_WIRE"):
shells = [o for o in bpy.data.objects if o.type == "MESH" and "verts" in json.loads(o.get("kit_shell", "{}")).get("sheet", {})]
shown = [o for o in bpy.data.objects if o.type in ("MESH", "CURVE", "FONT") and not o.hide_render]
for shell in shells:
wires = M.cage_wire(shell)
for o in shown:
o.hide_render = o is not shell and not o.get("stage")
waz, wel, wmargin = getattr(lib, "WIRE", {}).get(name, (az, el, margin))
M.shot(rig, cam, radius, waz, wel, out / f"{name}_wire_{shell.name.split('.')[-1]}.png", (800, 800), margin=wmargin, lens=lens)
for o in wires:
bpy.data.objects.remove(o, do_unlink=True)
for o in shown:
o.hide_render = False
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()}

View file

@ -0,0 +1,23 @@
"""Probe: one free-cage plate under variants of wall thickness, chamfer and pinned corners: folded inner faces and bounds."""
import json, sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import mechlib as M
from mathutils import Matrix
import bpy, numpy as np
M.setup()
import platecage as PC
crown = np.array([(-0.5, 0, 0.6), (-0.62, 0, 0.1), (-0.4, 0, -0.7), (0.4, 0, -0.7), (0.62, 0, 0.1), (0.5, 0, 0.6)])
k = 0
for thickness in (0.07, 0.03, 0.012):
for flare, drop in ((0.08, 0.09), (0.03, 0.09), (0.12, 0.06)):
for pin_skirt in (True, False):
for offset in (-1.0, 0.0):
doc, N, marks = PC.sheet(crown, flare, drop, 0.03, (), (), (0, -1, 0))
if not pin_skirt:
doc["corners"] = [c for c in doc["corners"] if c[0] < N]
name = f"P{k}"; k += 1
bpy.ops.brokkr_kitbash.shell(object_name=name, sheet=json.dumps(doc), thickness=thickness, offset=offset, levels=2, bevel=0.01, count_folds=True)
rep = json.loads(getattr(bpy.context.window_manager, M.KB.RESULT))
lo, hi = M.bounds([bpy.data.objects[name]])
print("PROBE", name, "t", thickness, "flare", flare, "drop", drop, "skirt pinned", pin_skirt, "offset", offset, "folded", rep["folded"], "bounds", [round(v, 2) for v in (*lo, *hi)], flush=True)

View file

@ -0,0 +1,210 @@
"""Armour plates as minimal free cages whose hard runs are fitted to lines traced on a concept view.
Rulings aetheria-release:ruling:minimal-cages-learned-from-operator (the fewest vertices that hold the form, creases
judicious, every pole declared) and mech-concept-fidelity. The arithmetic of the fit is brokkr_reference's
(core.fit_sheet, what the fit_shell action runs); the cage's one writer is brokkr_kitbash.shell (mechlib.shell_action).
numpy and the two add-ons; shell() runs inside Blender.
A plate is its CROWN: the polygon of its raised face, the line a concept draws as the plate's edge. The cage is the
crown ring, a skirt ring flared out and dropped back from it (the chamfered wall), and one centre vertex (the dome):
2N + 1 vertices for an N-sided plate. The crown's sides are creased 1 except those named soft (a side that rolls
over instead of breaking); crown and skirt corners are pinned except those named round. Every crown vertex then has
valence 4; the one pole is the centre, where the dome turns anyway.
lift(cam, frame, line, point, normal, shift) a traced polygon (the view's pixels) as points of `frame` on a plane
of that frame: the blocking. Depth is the plane's, by eye.
sheet(crown, flare, drop, dome, soft, round) the cage document of a crown (frame coordinates), wound to face
`facing`; returns (document, N)
fit(document, n, frame, cam, line, share, tol) core.fit_sheet on the crown's hard runs against the traced polygon,
one trace a run between pinned corners. Returns (crown as fitted,
report) or (None, report with the refusal).
shell(name, crown, frame, ...) fit if a trace is given, rebuild skirt and dome from the fitted
crown, brokkr_kitbash.shell; the numbers go to PLATES
grown(crown, by, back) / patch(crown, at, size, lift, turn) / mirrored(crown)
layering: a plate under a crown, larger and further back; a small
plate on a crown's face; the crown reflected about x = 0
stats(document) verts, faces, edges, creased, crease_share, poles
PLATES: {shell name: {verts, faces, triangles, edges, creased, crease_share, poles, fit: None | {...}}}.
What it gives up: a crown is one planar-ish polygon with a dome, so a plate that wraps a corner is two plates. The
fit moves crown points across the line of sight; along it they stay on the blocking plane (one view, no mirror
partner: prior_share reads near 1 and is reported, not hidden).
"""
import json
import math
import numpy as np
PLATES = {}
HARD = 1.0
def _unit(v):
v = np.asarray(v, float)
return v / max(np.linalg.norm(v), 1e-12)
def newell(P):
P = np.asarray(P, float)
Q = np.roll(P, -1, axis=0)
return _unit(np.cross(P, Q).sum(0))
def lift(cam, frame, line, point, normal, shift=(0.0, 0.0)):
"""Pixels of a view lifted through its camera onto the plane through `point` with `normal`, both of `frame` (a
4x4 that only turns and moves); `shift` is added to the pixels first (the build's joints stand that far from
the marks the camera was solved on). Returns the points in the frame's coordinates."""
F = np.asarray(frame, float)
R, t = F[:3, :3], F[:3, 3]
p0, n = R @ np.asarray(point, float) + t, R @ _unit(normal)
C, Rc = np.asarray(cam["C"], float), np.asarray(cam["R"], float)
out = []
for u, v in line:
d = np.array([(u + shift[0] - cam["c"][0]) / cam["f"], -(v + shift[1] - cam["c"][1]) / cam["f"], -1.0]) @ Rc
w = C + d * (((p0 - C) @ n) / (d @ n))
out.append(R.T @ (w - t))
return np.array(out)
def sheet(crown, flare=0.06, drop=0.06, dome=0.02, soft=(), round_=(), facing=None):
"""The cage of a crown. Vertices: crown 0..N-1, skirt N..2N-1, centre 2N. `facing` is a direction of the frame
the plate's outer face looks along: the crown is reversed if it winds the other way, and soft / round indices
(which name the crown as given: side i runs from point i to i + 1) follow it."""
P = np.asarray(crown, float)
N = len(P)
soft, round_ = set(soft), set(round_)
if facing is not None and newell(P) @ np.asarray(facing, float) < 0:
P = P[::-1].copy()
soft = {(N - 2 - i) % N for i in soft}
round_ = {N - 1 - i for i in round_}
n, c = newell(P), P.mean(0)
out = np.array([_unit((p - c) - n * ((p - c) @ n)) for p in P])
S = P + out * flare - n * drop
centre = c + n * dome
verts = [[round(float(x), 5) for x in p] for p in list(P) + list(S) + [centre]]
faces = [[i, (i + 1) % N, 2 * N] for i in range(N)] + [[N + i, N + (i + 1) % N, (i + 1) % N, i] for i in range(N)]
creases = [[i, (i + 1) % N, HARD] for i in range(N) if i not in soft]
corners = [[i, 1.0] for i in range(N) if i not in round_] + [[N + i, 1.0] for i in range(N) if i not in round_]
poles = [] if N == 4 else [2 * N]
return {"verts": verts, "faces": faces, "creases": creases, "corners": corners, "poles": poles, "rim": 0.0}, N, (soft, round_)
def runs(N, soft, round_):
"""The crown's hard runs: maximal chains of creased sides between pinned corners (a round corner is a run's
inner point; a soft side breaks the chain). [[v, ...]] in crown indices."""
out = []
starts = [i for i in range(N) if i not in round_]
for a in starts:
if a in soft:
continue
chain, i = [a], a
while True:
j = (i + 1) % N
chain.append(j)
if j not in round_ or j in soft or j == a:
break
i = j
if len(set(chain)) == len(chain) and chain[-1] not in round_:
out.append(chain)
return out
def fit(document, N, marks, frame, cam, line, share=0.1, tol=5.2, shift=(0.0, 0.0)):
"""core.fit_sheet on the crown's hard runs. `line` is the traced polygon, one pixel a crown vertex, in the order
the document's crown ended up in. Returns (fitted crown (N, 3) or None, report)."""
from brokkr_kitbash import core as kit
from brokkr_reference import core as ref
soft, round_ = marks
line = [[u + shift[0], v + shift[1]] for u, v in line]
traces = [{"run": {"verts": chain}, "side": 1, "line": [line[v] for v in chain]} for chain in runs(N, soft, round_)]
if not traces:
return None, {"refused": "no hard run between pinned corners"}
try:
out = ref.fit_sheet(document, kit.sheet(document), [list(map(float, row)) for row in np.asarray(frame)], traces, [cam] * len(traces), share=share, tol=tol)
except ref.ReferenceFitError as refusal:
return None, {"refused": str(refusal)[:300], "runs": len(traces)}
moved = [p["moved_m"] for p in out["points"]]
report = {"runs": len(traces), "unexplained_px": round(max(t["unexplained_px"] for t in out["traces"]), 2), "worst_px": round(max(t["worst_px"] for t in out["traces"]), 2),
"moved_m": round(max(moved), 4), "prior_share": [round(min(p["prior_share"] for p in out["points"]), 3), round(max(p["prior_share"] for p in out["points"]), 3)]}
return np.array(out["sheet"]["verts"][:N], float), report
def stats(document):
edges = {}
for f in document["faces"]:
for a, b in zip(f, f[1:] + f[:1]):
edges[(min(a, b), max(a, b))] = edges.get((min(a, b), max(a, b)), 0) + 1
creased = {(min(a, b), max(a, b)) for a, b, w in document.get("creases", []) if w > 0}
return {"verts": len(document["verts"]), "faces": len(document["faces"]), "triangles": sum(1 for f in document["faces"] if len(f) == 3), "edges": len(edges),
"creased": len(creased), "crease_share": round(len(creased) / len(edges), 3), "poles": len(document.get("poles", []))}
def shell(name, crown, frame, mat="khaki", facing=None, flare=0.06, drop=0.07, dome=0.02, soft=(), round_=(), thickness=0.05, levels=2, bevel=0.0,
trace=None, cam=None, view=None, shift=(0.0, 0.0), share=0.1, tol=5.2):
"""One plate, built in the world at `frame` (parent it afterwards). With `trace` (the polygon in the view's
pixels, a point a crown vertex as given) its crown's hard runs are fitted first; a refused fit keeps the blocking
and says so. Returns the object; PLATES[name] holds the numbers, PLATES[name]["crown"] the crown as built."""
import mechlib as M
from mathutils import Matrix
crown = np.asarray(crown, float)
doc, N, marks = sheet(crown, flare, drop, dome, soft, round_, facing)
report = None
if trace is not None:
line = list(trace)
if not np.allclose(np.asarray(doc["verts"][0]), crown[0], atol=1e-4): # the crown was reversed: the trace follows
line = line[::-1]
fitted, report = fit(doc, N, marks, frame, cam, line, share, tol, shift)
report["view"] = view
if fitted is not None:
doc, N, marks = sheet(fitted, flare, drop, dome, marks[0], marks[1], None)
build = M.Build(name, None, Matrix(np.asarray(frame).tolist()))
obj = M.shell_action(name, doc, build, mat, thickness=thickness, levels=levels, bevel=bevel)
PLATES[name] = dict(stats(doc), fit=report, crown=[list(map(float, p)) for p in doc["verts"][:N]])
span = np.ptp(np.asarray(doc["verts"]), axis=0)
print("PLATE", name, "N", N, "span", [round(float(v), 2) for v in span], "centre", [round(float(v), 2) for v in np.mean(doc["verts"], axis=0)], "FIT " + json.dumps(report) if report else "", flush=True)
return obj
# --- layering -------------------------------------------------------------------------------------------------------
def basis(crown):
"""(centre, e1, e2, n) of a crown: n its normal, e2 the frame's z laid in its plane (or y where the plate lies
flat), e1 = e2 x n."""
P = np.asarray(crown, float)
n, c = newell(P), P.mean(0)
up = np.array([0.0, 0.0, 1.0]) if abs(n[2]) < 0.9 else np.array([0.0, 1.0, 0.0])
e2 = _unit(up - n * (up @ n))
return c, np.cross(e2, n), e2, n
def grown(crown, by=1.12, back=0.08, shift=(0.0, 0.0)):
"""The crown scaled about its centre in its own plane, moved `shift` in the plane and `back` behind it: the
plate under a plate."""
c, e1, e2, n = basis(crown)
return np.array([c + (np.asarray(p) - c) * by + e1 * shift[0] + e2 * shift[1] - n * back for p in crown])
def patch(crown, at=(0.0, 0.0), size=(0.3, 0.2), lift_=0.04, turn=0.0, cut=0.0):
"""A small crown on a crown's face: a rectangle `size` centred `at` (plane coordinates: e1 across, e2 up), turned
`turn` degrees, standing `lift_` proud; `cut` clips its two upper corners (a six-sided lame)."""
c, e1, e2, n = basis(crown)
w, h = size[0] / 2, size[1] / 2
pts = [(-w, -h), (w, -h), (w, h), (-w, h)] if not cut else [(-w, -h), (w, -h), (w, h - cut), (w - cut, h), (-w + cut, h), (-w, h - cut)]
a = math.radians(turn)
return np.array([c + e1 * (at[0] + x * math.cos(a) - y * math.sin(a)) + e2 * (at[1] + x * math.sin(a) + y * math.cos(a)) + n * lift_ for x, y in pts])
def mirrored(crown):
return np.array([[-p[0], p[1], p[2]] for p in crown])[::-1]
def summary():
rows = list(PLATES.values())
if not rows:
return {}
edges, creased = sum(r["edges"] for r in rows), sum(r["creased"] for r in rows)
fits = [r["fit"] for r in rows if r["fit"]]
return {"plates": len(rows), "cage_verts": sum(r["verts"] for r in rows), "verts_per_plate": round(sum(r["verts"] for r in rows) / len(rows), 1), "edges": edges, "creased": creased,
"crease_share": round(creased / edges, 3), "poles": sum(r["poles"] for r in rows), "fitted": sum(1 for f in fits if "refused" not in f),
"refused": sum(1 for f in fits if "refused" in f), "worst_unexplained_px": max((f["unexplained_px"] for f in fits if "refused" not in f), default=None)}