Merge pull request 'brokkr_kitbash: a part kit as data, the mechanical kit, and four host actions (cut chassis-kit-format)' (#24) from nibu/chassis-kit-format into main
This commit is contained in:
commit
57c453f0ab
8 changed files with 2421 additions and 0 deletions
222
surfaces/blender/brokkr_kitbash/__init__.py
Normal file
222
surfaces/blender/brokkr_kitbash/__init__.py
Normal file
|
|
@ -0,0 +1,222 @@
|
|||
"""Kitbash parts: place a parametric machine part from a kit, re-parameterise it, and report where its sockets are.
|
||||
|
||||
A host add-on for Brokkr beside brokkr_mesh_polish and brokkr_rig (it imports the polish package's operator base,
|
||||
Refused and mesh_object, and nothing from Brokkr): brokkr_actions.json beside this file lists the operators agents
|
||||
may run (docs/kitbash.md). The kit format, its checks and the geometry are core.py (numpy, tested without
|
||||
Blender); this file is the bpy around it. Every operator writes a JSON report to
|
||||
WindowManager.brokkr_mesh_polish_result, as the polish operators do.
|
||||
|
||||
What a placed part is lives on its object as three ID properties: kit_kit, kit_part and kit_params. The mesh is
|
||||
derived from them (set_params rebuilds it), and socket frames are derived again at every report: nothing else in
|
||||
the scene stores them. Two things would give a part a second owner and are refused: a mesh datablock shared with
|
||||
another object (set_params), and a world transform that scales, mirrors or shears (set_params and report: a
|
||||
part's size is its params). Placement, materials and export are Brokkr's own rows (setObjectTransform, assignMaterial,
|
||||
exportGltf).
|
||||
"""
|
||||
bl_info = {"name": "Brokkr Kitbash", "author": "GameCult", "version": (0, 1, 0), "blender": (4, 2, 0),
|
||||
"category": "Object", "description": "Parametric machine parts from kits, with socket frames; agent-callable through Brokkr."}
|
||||
|
||||
import json
|
||||
import math
|
||||
|
||||
import bpy
|
||||
import numpy as np
|
||||
|
||||
try:
|
||||
from brokkr_mesh_polish import RESULT, PolishOperator, Refused, mesh_object
|
||||
MISSING = None
|
||||
except ImportError as error: # register() says so; the classes below only need something to subclass
|
||||
RESULT, PolishOperator, Refused, mesh_object, MISSING = "brokkr_mesh_polish_result", bpy.types.Operator, RuntimeError, None, error
|
||||
|
||||
from . import core
|
||||
|
||||
KIT, PART, PARAMS = "kit_kit", "kit_part", "kit_params"
|
||||
BEVEL = "Kit Bevel"
|
||||
BEVEL_SEGMENTS, BEVEL_ANGLE = 2, math.radians(30.0)
|
||||
REPORT_LIMIT = 16000 # characters of a result Brokkr copies into a receipt before it truncates
|
||||
|
||||
|
||||
def kit_work(work):
|
||||
"""A KitError from core is this request's refusal."""
|
||||
def wrapped(self, context):
|
||||
try:
|
||||
return work(self, context)
|
||||
except core.KitError as error:
|
||||
raise Refused(str(error)) from None
|
||||
return wrapped
|
||||
|
||||
|
||||
def write_mesh(mesh, built) -> None:
|
||||
"""The built part into an empty mesh datablock: vertices, n-gon faces, and flat shading on every face not marked smooth."""
|
||||
mesh.vertices.add(len(built.V))
|
||||
mesh.vertices.foreach_set("co", built.V.astype(np.float32).ravel())
|
||||
mesh.loops.add(len(built.faces))
|
||||
mesh.loops.foreach_set("vertex_index", built.faces)
|
||||
mesh.polygons.add(len(built.counts))
|
||||
mesh.polygons.foreach_set("loop_start", (np.cumsum(built.counts) - built.counts).astype(np.int32))
|
||||
sharp = mesh.attributes.get("sharp_face") or mesh.attributes.new("sharp_face", "BOOLEAN", "FACE")
|
||||
sharp.data.foreach_set("value", ~built.smooth)
|
||||
mesh.update(calc_edges=True)
|
||||
|
||||
|
||||
def sync_bevel(obj, width: float) -> None:
|
||||
modifier = obj.modifiers.get(BEVEL)
|
||||
if modifier is None and width > 0:
|
||||
modifier = obj.modifiers.new(BEVEL, "BEVEL")
|
||||
modifier.segments, modifier.limit_method, modifier.angle_limit = BEVEL_SEGMENTS, "ANGLE", BEVEL_ANGLE
|
||||
if modifier is not None:
|
||||
modifier.width = width
|
||||
|
||||
|
||||
RIGID = 1e-5 # how far a world matrix's 3x3 may stand from a rotation
|
||||
|
||||
|
||||
def kit_part_of(obj):
|
||||
"""(part, stored params) of a placed part, read from its ID properties. Refuses a part whose world transform is
|
||||
not rigid: its socket frames would not be frames, and its size would have a second owner."""
|
||||
if PART not in obj:
|
||||
raise Refused(f"{obj.name!r} is not a kit part (it has no {PART} property); place_part makes one.")
|
||||
turn = np.array(obj.matrix_world)[:3, :3]
|
||||
if np.abs(turn.T @ turn - np.eye(3)).max() > RIGID or np.linalg.det(turn) < 0:
|
||||
scale = ", ".join(f"{s:.4g}" for s in obj.matrix_world.to_scale())
|
||||
raise Refused(f"{obj.name!r} is scaled, mirrored or sheared in the world (scale {scale}): a kit part's size is its params. "
|
||||
"Set its scale, and its parents', to 1 (setObjectTransform) and resize it with set_params.")
|
||||
try:
|
||||
stored = json.loads(obj.get(PARAMS, "{}"))
|
||||
except ValueError:
|
||||
stored = None
|
||||
if not isinstance(stored, dict):
|
||||
raise Refused(f"{obj.name!r} has a {PARAMS} property that is not a JSON object.")
|
||||
return core.part(core.load_kit(str(obj.get(KIT, ""))), str(obj[PART])), stored
|
||||
|
||||
|
||||
def part_report(obj, part, built) -> dict:
|
||||
return {"object": obj.name, "kit": part["kit"], "part": part["name"], "params": built.params,
|
||||
"faces": len(obj.data.polygons), "shells": built.shell_count, "bevel": round(built.bevel, 6),
|
||||
"sockets": core.socket_rows(built.sockets, np.array(obj.matrix_world))}
|
||||
|
||||
|
||||
def carried_materials(mesh, old, new):
|
||||
"""Per-face material indices for a rebuilt mesh, or None when there is nothing to carry: each shape of the part
|
||||
keeps the index most of its faces had (the lowest on a tie), since faces do not survive a change of segments
|
||||
or counts but shapes do. A mesh that is no longer the old build (edited by hand) carries nothing."""
|
||||
if old is None or len(mesh.polygons) != len(old.counts):
|
||||
return None
|
||||
index = np.zeros(len(old.counts), dtype=np.int32)
|
||||
mesh.polygons.foreach_get("material_index", index)
|
||||
if not index.any():
|
||||
return None
|
||||
carried = np.zeros(len(new.counts), dtype=np.int32)
|
||||
for shape in np.unique(old.shape):
|
||||
carried[new.shape == shape] = np.bincount(index[old.shape == shape]).argmax()
|
||||
return carried
|
||||
|
||||
|
||||
def bounded(report: dict, advice: str) -> dict:
|
||||
size = len(json.dumps(report, separators=(",", ":")))
|
||||
if size > REPORT_LIMIT:
|
||||
raise Refused(f"The report is {size} characters, over the {REPORT_LIMIT} a receipt carries: {advice}.")
|
||||
return report
|
||||
|
||||
|
||||
class BROKKR_KITBASH_OT_place_part(PolishOperator):
|
||||
"""Place a kit part at the origin as a new mesh object: its geometry from the kit and params, a Bevel modifier
|
||||
when the part has a bevel, and the kit, part and params stored on the object"""
|
||||
bl_idname = "brokkr_kitbash.place_part"
|
||||
bl_label = "Place Kit Part"
|
||||
kit: bpy.props.StringProperty(name="Kit", default="mechanical")
|
||||
part: bpy.props.StringProperty(name="Part")
|
||||
object_name: bpy.props.StringProperty(name="Object")
|
||||
params: bpy.props.StringProperty(name="Params", description="name=value; name=value ... the rest take the part's defaults")
|
||||
|
||||
@kit_work
|
||||
def work(self, context):
|
||||
part = core.part(core.load_kit(self.kit), self.part)
|
||||
if self.object_name in bpy.data.objects:
|
||||
raise Refused(f"An object named {self.object_name!r} exists; nothing changed.")
|
||||
built = core.build(part, core.parse_params(self.params))
|
||||
mesh = bpy.data.meshes.new(self.object_name)
|
||||
write_mesh(mesh, built)
|
||||
obj = bpy.data.objects.new(self.object_name, mesh)
|
||||
context.scene.collection.objects.link(obj)
|
||||
sync_bevel(obj, built.bevel)
|
||||
obj[KIT], obj[PART], obj[PARAMS] = part["kit"], part["name"], json.dumps(built.params)
|
||||
return part_report(obj, part, built)
|
||||
|
||||
|
||||
class BROKKR_KITBASH_OT_set_params(PolishOperator):
|
||||
"""Change params of a placed kit part and rebuild its mesh in place: its transform, parent, modifiers and
|
||||
material slots stay, each shape keeps its faces' material, and the Bevel width follows"""
|
||||
bl_idname = "brokkr_kitbash.set_params"
|
||||
bl_label = "Set Kit Part Params"
|
||||
object_name: bpy.props.StringProperty(name="Object")
|
||||
params: bpy.props.StringProperty(name="Params", description="name=value; name=value ... the rest keep their stored values")
|
||||
|
||||
@kit_work
|
||||
def work(self, context):
|
||||
obj = mesh_object(self.object_name)
|
||||
part, stored = kit_part_of(obj)
|
||||
if obj.data.users > 1:
|
||||
raise Refused(f"{obj.name!r} shares its mesh {obj.data.name!r} with {obj.data.users - 1} other user(s): rebuilding it would change "
|
||||
"them while their params stay. Give it its own mesh (place_part a new part) and set that; nothing changed.")
|
||||
built = core.build(part, core.resolve_params(part, core.parse_params(self.params), stored))
|
||||
try:
|
||||
old = core.build(part, stored)
|
||||
except core.KitError: # stored params an edited kit no longer admits: nothing to map faces by
|
||||
old = None
|
||||
materials = carried_materials(obj.data, old, built)
|
||||
obj.data.clear_geometry()
|
||||
write_mesh(obj.data, built)
|
||||
if materials is not None:
|
||||
obj.data.polygons.foreach_set("material_index", materials)
|
||||
obj.data.update()
|
||||
sync_bevel(obj, built.bevel)
|
||||
obj[PARAMS] = json.dumps(built.params)
|
||||
return part_report(obj, part, built)
|
||||
|
||||
|
||||
class BROKKR_KITBASH_OT_describe(PolishOperator):
|
||||
"""List a kit's parts, or one part: params with type, bounds, default and doc, and sockets in the part's frame
|
||||
at default params"""
|
||||
bl_idname = "brokkr_kitbash.describe"
|
||||
bl_label = "Describe Kit"
|
||||
bl_options = {"REGISTER"}
|
||||
kit: bpy.props.StringProperty(name="Kit", default="mechanical")
|
||||
part: bpy.props.StringProperty(name="Part", description="Empty: every part of the kit")
|
||||
|
||||
@kit_work
|
||||
def work(self, context):
|
||||
return bounded(core.describe(core.load_kit(self.kit), self.part), "name a part to describe it alone")
|
||||
|
||||
|
||||
class BROKKR_KITBASH_OT_report(PolishOperator):
|
||||
"""Report placed kit parts as the scene has them: kit, part, params, faces, shells and each socket's world frame"""
|
||||
bl_idname = "brokkr_kitbash.report"
|
||||
bl_label = "Report Kit Parts"
|
||||
bl_options = {"REGISTER"}
|
||||
object_name: bpy.props.StringProperty(name="Object", description="Empty: every object that is a kit part")
|
||||
|
||||
@kit_work
|
||||
def work(self, context):
|
||||
chosen = [mesh_object(self.object_name)] if self.object_name else sorted(
|
||||
(o for o in context.scene.objects if o.type == "MESH" and PART in o), key=lambda o: o.name)
|
||||
parts = []
|
||||
for obj in chosen:
|
||||
part, stored = kit_part_of(obj)
|
||||
parts.append(part_report(obj, part, core.build(part, stored)))
|
||||
return bounded({"parts": parts}, "name an object to report it alone")
|
||||
|
||||
|
||||
classes = (BROKKR_KITBASH_OT_place_part, BROKKR_KITBASH_OT_set_params, BROKKR_KITBASH_OT_describe, BROKKR_KITBASH_OT_report)
|
||||
|
||||
|
||||
def register():
|
||||
if MISSING is not None or not hasattr(bpy.types.WindowManager, RESULT):
|
||||
raise RuntimeError(f"brokkr_kitbash needs brokkr_mesh_polish enabled first ({MISSING or 'its result property is not registered'}).")
|
||||
for cls in classes:
|
||||
bpy.utils.register_class(cls)
|
||||
|
||||
|
||||
def unregister():
|
||||
for cls in reversed(classes):
|
||||
bpy.utils.unregister_class(cls)
|
||||
111
surfaces/blender/brokkr_kitbash/brokkr_actions.json
Normal file
111
surfaces/blender/brokkr_kitbash/brokkr_actions.json
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
{
|
||||
"schema": "brokkr.blender.host_actions.v0",
|
||||
"actions": [
|
||||
{
|
||||
"name": "brokkr_kitbash.place_part",
|
||||
"doc": "Place a kit part at the origin as a new mesh object (move it with setObjectTransform). Reports its params, faces, shells and each socket's world 4x4 (rows; column 2 is the outward normal, column 3 the origin).",
|
||||
"changesScene": true,
|
||||
"editModeSafe": false,
|
||||
"result": "brokkr_mesh_polish_result",
|
||||
"fields": [
|
||||
{
|
||||
"name": "kit",
|
||||
"type": "string",
|
||||
"chars": "id",
|
||||
"minLength": 1,
|
||||
"maxLength": 32,
|
||||
"default": "mechanical",
|
||||
"doc": "a kit shipped with the add-on (a-z, 0-9, _)"
|
||||
},
|
||||
{
|
||||
"name": "part",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"chars": "id",
|
||||
"minLength": 1,
|
||||
"maxLength": 32,
|
||||
"doc": "a part of the kit; brokkr_kitbash.describe lists them"
|
||||
},
|
||||
{
|
||||
"name": "object_name",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"minLength": 1,
|
||||
"maxLength": 63,
|
||||
"doc": "the new object's name; refused when an object has it"
|
||||
},
|
||||
{
|
||||
"name": "params",
|
||||
"type": "string",
|
||||
"maxLength": 4000,
|
||||
"default": "",
|
||||
"doc": "name=value; name=value ... inside each param's bounds; the rest take the part's defaults"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "brokkr_kitbash.set_params",
|
||||
"doc": "Change params of a placed kit part and rebuild its mesh in place; transform, parent, modifiers and materials stay. Refuses a mesh another object shares and a scaled part. Reports as place_part.",
|
||||
"changesScene": true,
|
||||
"editModeSafe": false,
|
||||
"result": "brokkr_mesh_polish_result",
|
||||
"fields": [
|
||||
{
|
||||
"name": "object_name",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"minLength": 1,
|
||||
"maxLength": 63
|
||||
},
|
||||
{
|
||||
"name": "params",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"maxLength": 4000,
|
||||
"doc": "name=value; name=value ... the rest keep their stored values"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "brokkr_kitbash.describe",
|
||||
"doc": "A kit's parts, or one part: params (type, min, max, default, doc) and sockets in the part's frame at default params.",
|
||||
"changesScene": false,
|
||||
"editModeSafe": true,
|
||||
"result": "brokkr_mesh_polish_result",
|
||||
"fields": [
|
||||
{
|
||||
"name": "kit",
|
||||
"type": "string",
|
||||
"chars": "id",
|
||||
"minLength": 1,
|
||||
"maxLength": 32,
|
||||
"default": "mechanical"
|
||||
},
|
||||
{
|
||||
"name": "part",
|
||||
"type": "string",
|
||||
"chars": "id",
|
||||
"maxLength": 32,
|
||||
"default": "",
|
||||
"doc": "empty: every part of the kit"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "brokkr_kitbash.report",
|
||||
"doc": "Placed kit parts as the scene has them: kit, part, params, faces, shells and each socket's world 4x4. Refuses a part scaled in the world: resize with set_params.",
|
||||
"changesScene": false,
|
||||
"editModeSafe": true,
|
||||
"result": "brokkr_mesh_polish_result",
|
||||
"fields": [
|
||||
{
|
||||
"name": "object_name",
|
||||
"type": "string",
|
||||
"maxLength": 63,
|
||||
"default": "",
|
||||
"doc": "empty: every object that is a kit part"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
501
surfaces/blender/brokkr_kitbash/core.py
Normal file
501
surfaces/blender/brokkr_kitbash/core.py
Normal file
|
|
@ -0,0 +1,501 @@
|
|||
"""The kit format: what a kit document may say, and the geometry and socket frames a part and its params produce.
|
||||
|
||||
numpy and the standard library only, no Blender: tests/test_kitbash.py runs this file as it is. A kit is data
|
||||
(kits/<name>.v0.json beside this file). A part is a list of shapes (tube, box, repeat) whose numbers may be
|
||||
expressions over the part's params, and a list of sockets, each a frame on one of the part's flat faces. An
|
||||
expression is parsed with ast.parse and walked against a whitelist; nothing in a kit is ever run as Python.
|
||||
|
||||
kit = load_kit("mechanical")
|
||||
built = build(part(kit, "tank"), {"length": 1.2}) # Built: V, faces, counts, smooth, shell_count, sockets
|
||||
|
||||
Every refusal is a KitError whose message names the kit, part and field.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Any, NamedTuple
|
||||
|
||||
import numpy as np
|
||||
|
||||
SCHEMA = "brokkr.kit.v0"
|
||||
KITS = Path(__file__).with_name("kits")
|
||||
KIT_NAME = r"[a-z0-9_]{1,32}"
|
||||
NAME = r"[a-z][a-z0-9_]{0,31}"
|
||||
CALLS = {"min": min, "max": max}
|
||||
AXES = {"+x": (1.0, 0.0, 0.0), "-x": (-1.0, 0.0, 0.0), "+y": (0.0, 1.0, 0.0), "-y": (0.0, -1.0, 0.0),
|
||||
"+z": (0.0, 0.0, 1.0), "-z": (0.0, 0.0, -1.0)}
|
||||
PLACED = ("at", "rot")
|
||||
SHAPES = {"tube": (("r0", "r1", "length", "segments"), ("inner0", "inner1", "smooth") + PLACED),
|
||||
"box": (("size",), PLACED),
|
||||
"repeat": (("count", "step", "of"), ())}
|
||||
SEGMENTS = (3, 128)
|
||||
COPIES = (1, 256)
|
||||
|
||||
|
||||
class KitError(ValueError):
|
||||
"""The kit document, a param or a build breaks a rule of the format; the message names where."""
|
||||
|
||||
|
||||
def finite(value: Any) -> bool:
|
||||
"""A number (not a bool) a float can hold: an integer too large for one is not finite."""
|
||||
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
||||
return False
|
||||
try:
|
||||
return math.isfinite(float(value))
|
||||
except OverflowError:
|
||||
return False
|
||||
|
||||
|
||||
# --- expressions ---------------------------------------------------------------------------------------------
|
||||
|
||||
class Expr:
|
||||
"""A number, or an expression over a part's params that passed the whitelist. value(env) walks the tree."""
|
||||
__slots__ = ("source", "tree", "where")
|
||||
|
||||
def __init__(self, source, tree, where):
|
||||
self.source, self.tree, self.where = source, tree, where
|
||||
|
||||
def value(self, env: dict[str, float]) -> float:
|
||||
try:
|
||||
result = self.source if self.tree is None else _walk(self.tree, env, self)
|
||||
except OverflowError: # an integer literal no float holds
|
||||
result = math.inf
|
||||
if not finite(result):
|
||||
raise KitError(f"{self.where}: {self.source!r} is not a finite number")
|
||||
return float(result)
|
||||
|
||||
|
||||
def parse(value: Any, names, where: str) -> Expr:
|
||||
"""The Expr for a numeric field: a finite number, or a string of + - * /, unary minus, parentheses, min(a,b),
|
||||
max(a,b), numbers and the names given. Anything else is refused here, before any build."""
|
||||
if isinstance(value, (int, float)) and not isinstance(value, bool):
|
||||
if not finite(value):
|
||||
raise KitError(f"{where}: {str(value)[:40]} is not a finite number")
|
||||
return Expr(value, None, where)
|
||||
if not isinstance(value, str):
|
||||
raise KitError(f"{where} must be a number or an expression string, not {type(value).__name__}")
|
||||
try:
|
||||
tree = ast.parse(value, mode="eval").body
|
||||
except (SyntaxError, ValueError, RecursionError, MemoryError):
|
||||
raise KitError(f"{where}: {value!r} does not parse as an expression") from None
|
||||
try:
|
||||
_admit(tree, frozenset(names), where, value)
|
||||
except RecursionError:
|
||||
raise KitError(f"{where}: {value!r} nests too deeply") from None
|
||||
return Expr(value, tree, where)
|
||||
|
||||
|
||||
def _admit(node, names, where, source) -> None:
|
||||
if isinstance(node, ast.BinOp) and isinstance(node.op, (ast.Add, ast.Sub, ast.Mult, ast.Div)):
|
||||
_admit(node.left, names, where, source)
|
||||
_admit(node.right, names, where, source)
|
||||
elif isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.USub, ast.UAdd)):
|
||||
_admit(node.operand, names, where, source)
|
||||
elif isinstance(node, ast.Constant) and type(node.value) in (int, float):
|
||||
pass
|
||||
elif isinstance(node, ast.Name):
|
||||
if node.id not in names:
|
||||
raise KitError(f"{where}: {source!r} names {node.id!r}, which is not a param of this part ({', '.join(sorted(names)) or 'it has none'})")
|
||||
elif isinstance(node, ast.Call):
|
||||
if not isinstance(node.func, ast.Name) or node.func.id not in CALLS:
|
||||
raise KitError(f"{where}: {source!r} calls something other than min or max")
|
||||
if len(node.args) != 2 or node.keywords:
|
||||
raise KitError(f"{where}: {source!r}: {node.func.id} takes exactly two positional arguments")
|
||||
for argument in node.args:
|
||||
_admit(argument, names, where, source)
|
||||
else:
|
||||
raise KitError(f"{where}: {source!r} uses {type(node).__name__}; an expression is + - * /, unary minus, "
|
||||
"parentheses, min(a,b), max(a,b), numbers and param names")
|
||||
|
||||
|
||||
def _walk(node, env, expr: Expr) -> float:
|
||||
if isinstance(node, ast.Constant):
|
||||
return node.value
|
||||
if isinstance(node, ast.Name):
|
||||
return env[node.id]
|
||||
if isinstance(node, ast.UnaryOp):
|
||||
operand = _walk(node.operand, env, expr)
|
||||
return -operand if isinstance(node.op, ast.USub) else operand
|
||||
if isinstance(node, ast.Call):
|
||||
return CALLS[node.func.id](_walk(node.args[0], env, expr), _walk(node.args[1], env, expr))
|
||||
left, right = _walk(node.left, env, expr), _walk(node.right, env, expr)
|
||||
if isinstance(node.op, ast.Add):
|
||||
return left + right
|
||||
if isinstance(node.op, ast.Sub):
|
||||
return left - right
|
||||
if isinstance(node.op, ast.Mult):
|
||||
return left * right
|
||||
if right == 0:
|
||||
raise KitError(f"{expr.where}: division by zero in {expr.source!r}")
|
||||
return left / right
|
||||
|
||||
|
||||
# --- the kit document ----------------------------------------------------------------------------------------
|
||||
|
||||
def _keys(value: Any, where: str, required, optional=()) -> None:
|
||||
if not isinstance(value, dict):
|
||||
raise KitError(f"{where} must be an object")
|
||||
for key in value:
|
||||
if key not in required and key not in optional:
|
||||
raise KitError(f"{where} has no key {key!r}; its keys: {', '.join((*required, *optional))}")
|
||||
for key in required:
|
||||
if key not in value:
|
||||
raise KitError(f"{where} lacks {key!r}")
|
||||
|
||||
|
||||
def _text(value: Any, where: str) -> str:
|
||||
if not isinstance(value, str):
|
||||
raise KitError(f"{where} must be a string")
|
||||
return value
|
||||
|
||||
|
||||
def _name(value: Any, where: str, seen: set) -> str:
|
||||
if not isinstance(value, str) or not re.fullmatch(NAME, value) or value in CALLS:
|
||||
raise KitError(f"{where}: {value!r} is not a name (a-z first, then a-z, 0-9 or _, at most 32, not min or max)")
|
||||
if value in seen:
|
||||
raise KitError(f"{where}: {value!r} is listed twice")
|
||||
seen.add(value)
|
||||
return value
|
||||
|
||||
|
||||
def _number(value: Any, where: str) -> float:
|
||||
if not finite(value):
|
||||
raise KitError(f"{where} must be a finite number")
|
||||
return value
|
||||
|
||||
|
||||
def _vector(value: Any, names, where: str) -> list[Expr]:
|
||||
if not isinstance(value, list) or len(value) != 3:
|
||||
raise KitError(f"{where} must be an array of three numbers or expressions")
|
||||
return [parse(item, names, f"{where}[{i}]") for i, item in enumerate(value)]
|
||||
|
||||
|
||||
ZERO = [Expr(0.0, None, "zero")] * 3
|
||||
|
||||
|
||||
def _shape(shape: Any, names, where: str, inside_repeat: bool = False) -> dict:
|
||||
kind = shape.get("shape") if isinstance(shape, dict) else None
|
||||
if not isinstance(kind, str) or kind not in SHAPES:
|
||||
raise KitError(f"{where}: unknown shape {kind!r}; shapes are {', '.join(SHAPES)}")
|
||||
where = f"{where} ({kind})"
|
||||
required, optional = SHAPES[kind]
|
||||
_keys(shape, where, ("shape", *required), optional)
|
||||
if kind == "repeat":
|
||||
if inside_repeat:
|
||||
raise KitError(f"{where}: a repeat cannot hold a repeat")
|
||||
return {"shape": kind, "count": parse(shape["count"], names, f"{where} count"),
|
||||
"step": _vector(shape["step"], names, f"{where} step"),
|
||||
"of": _shape(shape["of"], names, f"{where} of", inside_repeat=True)}
|
||||
made = {"shape": kind, "where": where,
|
||||
"at": _vector(shape["at"], names, f"{where} at") if "at" in shape else ZERO,
|
||||
"rot": _vector(shape["rot"], names, f"{where} rot") if "rot" in shape else ZERO}
|
||||
if kind == "box":
|
||||
made["size"] = _vector(shape["size"], names, f"{where} size")
|
||||
return made
|
||||
for key in ("r0", "r1", "length", "segments"):
|
||||
made[key] = parse(shape[key], names, f"{where} {key}")
|
||||
for key in ("inner0", "inner1"):
|
||||
made[key] = parse(shape.get(key, 0), names, f"{where} {key}")
|
||||
if not isinstance(shape.get("smooth", False), bool):
|
||||
raise KitError(f"{where} smooth must be true or false")
|
||||
made["smooth"] = shape.get("smooth", False)
|
||||
return made
|
||||
|
||||
|
||||
def check_kit(document: Any) -> dict:
|
||||
"""The checked kit: {'kit', 'doc', 'socketTypes', 'parts': {name: part}} with every numeric field an Expr.
|
||||
Refuses, naming kit, part and field, anything the format does not say (the module docstring and docs/kitbash.md)."""
|
||||
if not isinstance(document, dict) or document.get("schema") != SCHEMA:
|
||||
raise KitError(f"kit schema must be {SCHEMA}")
|
||||
_keys(document, "kit", ("schema", "kit", "doc", "socketTypes", "parts"))
|
||||
kit = document["kit"]
|
||||
if not isinstance(kit, str) or not re.fullmatch(KIT_NAME, kit):
|
||||
raise KitError(f"kit name {kit!r} must be 1 to 32 of a-z, 0-9 and _")
|
||||
here = f"kit {kit!r}"
|
||||
_text(document["doc"], f"{here} doc")
|
||||
if not isinstance(document["socketTypes"], dict) or not isinstance(document["parts"], list):
|
||||
raise KitError(f"{here}: socketTypes must be an object and parts an array")
|
||||
types = {}
|
||||
for name, entry in document["socketTypes"].items():
|
||||
where = f"{here} socket type {name!r}"
|
||||
_name(name, where, set())
|
||||
_keys(entry, where, ("match", "doc"))
|
||||
if entry["match"] not in ("equal", "fits"):
|
||||
raise KitError(f"{where}: match must be 'equal' or 'fits'")
|
||||
types[name] = {"match": entry["match"], "doc": _text(entry["doc"], f"{where} doc")}
|
||||
parts, part_names = {}, set()
|
||||
for index, part in enumerate(document["parts"]):
|
||||
name = _name(part.get("name") if isinstance(part, dict) else None, f"{here} part {index}", part_names)
|
||||
where = f"{here} part {name!r}"
|
||||
_keys(part, where, ("name", "doc", "params", "shapes", "sockets"), ("bevel",))
|
||||
if not all(isinstance(part[key], list) for key in ("params", "shapes", "sockets")):
|
||||
raise KitError(f"{where}: params, shapes and sockets must be arrays")
|
||||
params, names = [], set()
|
||||
for p_index, param in enumerate(part["params"]):
|
||||
p_name = _name(param.get("name") if isinstance(param, dict) else None, f"{where} param {p_index}", names)
|
||||
p_where = f"{where} param {p_name!r}"
|
||||
_keys(param, p_where, ("name", "type", "min", "max", "default", "doc"))
|
||||
if param["type"] not in ("number", "integer"):
|
||||
raise KitError(f"{p_where}: type must be 'number' or 'integer'")
|
||||
low, high, default = (_number(param[key], f"{p_where} {key}") for key in ("min", "max", "default"))
|
||||
if low > high:
|
||||
raise KitError(f"{p_where}: min {low} is above max {high}")
|
||||
if not low <= default <= high:
|
||||
raise KitError(f"{p_where}: default {default} is outside [{low}, {high}]")
|
||||
if param["type"] == "integer":
|
||||
for key, value in (("min", low), ("max", high), ("default", default)):
|
||||
if value != int(value):
|
||||
raise KitError(f"{p_where}: an integer param's {key} must be whole, not {value}")
|
||||
low, high, default = int(low), int(high), int(default)
|
||||
params.append({"name": p_name, "type": param["type"], "min": low, "max": high, "default": default,
|
||||
"doc": _text(param["doc"], f"{p_where} doc")})
|
||||
shapes = [_shape(shape, names, f"{where} shape {i}") for i, shape in enumerate(part["shapes"])]
|
||||
if not shapes:
|
||||
raise KitError(f"{where} has no shapes")
|
||||
sockets, socket_names = [], set()
|
||||
for s_index, socket in enumerate(part["sockets"]):
|
||||
s_name = _name(socket.get("name") if isinstance(socket, dict) else None, f"{where} socket {s_index}", socket_names)
|
||||
s_where = f"{where} socket {s_name!r}"
|
||||
_keys(socket, s_where, ("name", "type", "size", "at", "z", "y"))
|
||||
if not isinstance(socket["type"], str) or socket["type"] not in types:
|
||||
raise KitError(f"{s_where}: type {socket['type']!r} is not one of the kit's socketTypes ({', '.join(types) or 'none'})")
|
||||
for key in ("z", "y"):
|
||||
if not isinstance(socket[key], str) or socket[key] not in AXES:
|
||||
raise KitError(f"{s_where}: {key} must be one of {', '.join(AXES)}")
|
||||
if socket["z"][1] == socket["y"][1]:
|
||||
raise KitError(f"{s_where}: z ({socket['z']}) and y ({socket['y']}) lie on the same axis")
|
||||
sockets.append({"name": s_name, "type": socket["type"], "size": parse(socket["size"], names, f"{s_where} size"),
|
||||
"at": _vector(socket["at"], names, f"{s_where} at"), "z": socket["z"], "y": socket["y"]})
|
||||
parts[name] = {"kit": kit, "name": name, "doc": _text(part["doc"], f"{where} doc"), "params": params,
|
||||
"bevel": parse(part["bevel"], names, f"{where} bevel") if "bevel" in part else None,
|
||||
"shapes": shapes, "sockets": sockets}
|
||||
return {"kit": kit, "doc": document["doc"], "socketTypes": types, "parts": parts}
|
||||
|
||||
|
||||
def load_kit(name: str) -> dict:
|
||||
"""The checked kit kits/<name>.v0.json. The name is the only thing a caller chooses: it cannot spell a path."""
|
||||
if not isinstance(name, str) or not re.fullmatch(KIT_NAME, name):
|
||||
raise KitError(f"kit name {name!r} must be 1 to 32 of a-z, 0-9 and _")
|
||||
path = KITS / f"{name}.v0.json"
|
||||
if not path.is_file():
|
||||
raise KitError(f"no kit named {name!r}; kits: {', '.join(kit_names()) or 'none'}")
|
||||
try:
|
||||
document = json.loads(path.read_text(encoding="utf-8"))
|
||||
except ValueError as error:
|
||||
raise KitError(f"kit {name!r} is not JSON: {error}") from None
|
||||
kit = check_kit(document)
|
||||
if kit["kit"] != name:
|
||||
raise KitError(f"kit file {path.name} says it is kit {kit['kit']!r}")
|
||||
return kit
|
||||
|
||||
|
||||
def kit_names() -> list[str]:
|
||||
return sorted(p.name[:-len(".v0.json")] for p in KITS.glob("*.v0.json"))
|
||||
|
||||
|
||||
def part(kit: dict, name: str) -> dict:
|
||||
found = kit["parts"].get(name)
|
||||
if found is None:
|
||||
raise KitError(f"kit {kit['kit']!r} has no part {name!r}; its parts: {', '.join(kit['parts'])}")
|
||||
return found
|
||||
|
||||
|
||||
# --- params --------------------------------------------------------------------------------------------------
|
||||
|
||||
def parse_params(text: str) -> dict[str, float]:
|
||||
"""'k=v; k=v' as a dict of numbers. Refuses a repeated key and a value that is not a finite number."""
|
||||
given: dict[str, float] = {}
|
||||
for item in text.split(";"):
|
||||
if not item.strip():
|
||||
continue
|
||||
key, equals, value = item.partition("=")
|
||||
key = key.strip()
|
||||
if not equals or not key:
|
||||
raise KitError(f"params: {item.strip()!r} is not name=value")
|
||||
if key in given:
|
||||
raise KitError(f"params: {key!r} is given twice")
|
||||
try:
|
||||
number = float(value)
|
||||
except ValueError:
|
||||
number = math.nan
|
||||
if not math.isfinite(number):
|
||||
raise KitError(f"params: {key} = {value.strip()!r} is not a number")
|
||||
given[key] = number
|
||||
return given
|
||||
|
||||
|
||||
def resolve_params(part: dict, given: dict, base: dict | None = None) -> dict:
|
||||
"""Every param of the part, in the part's order: base overlaid by given, defaults for the rest. Refuses an
|
||||
unknown param, a value outside the inclusive [min, max], and a fraction for an integer param."""
|
||||
merged = {**(base or {}), **given}
|
||||
here = f"kit {part['kit']!r} part {part['name']!r}"
|
||||
known = [p["name"] for p in part["params"]]
|
||||
for key in merged:
|
||||
if key not in known:
|
||||
raise KitError(f"{here} has no param {key!r}; its params: {', '.join(known) or 'none'}")
|
||||
resolved = {}
|
||||
for param in part["params"]:
|
||||
name = param["name"]
|
||||
value = merged.get(name, param["default"])
|
||||
if not finite(value):
|
||||
raise KitError(f"{here} param {name!r} must be a finite number")
|
||||
if not param["min"] <= value <= param["max"]:
|
||||
raise KitError(f"{here} param {name!r} = {value} is outside [{param['min']}, {param['max']}] (bounds included)")
|
||||
if param["type"] == "integer":
|
||||
if value != int(value):
|
||||
raise KitError(f"{here} param {name!r} is an integer; {value} is not whole")
|
||||
value = int(value)
|
||||
resolved[name] = value if param["type"] == "integer" else float(value)
|
||||
return resolved
|
||||
|
||||
|
||||
# --- geometry ------------------------------------------------------------------------------------------------
|
||||
|
||||
class Built(NamedTuple):
|
||||
"""A part at given params, in the part's frame, metres. Face i has counts[i] corners, listed in order in
|
||||
faces (quads and n-gon caps, wound outward); smooth[i] marks tube sides to shade smooth; shape[i] is the index,
|
||||
in the part's shapes list, of the shape the face belongs to (every copy of a repeat shares one). Each socket is
|
||||
{'name', 'type', 'size', 'matrix'} with matrix the 4x4 frame: column 2 the outward normal, column 1 up,
|
||||
column 0 = y cross z, column 3 the origin."""
|
||||
V: np.ndarray
|
||||
faces: np.ndarray
|
||||
counts: np.ndarray
|
||||
smooth: np.ndarray
|
||||
shape: np.ndarray
|
||||
shell_count: int
|
||||
sockets: list
|
||||
bevel: float
|
||||
params: dict
|
||||
|
||||
|
||||
def _whole(expr: Expr, env, bounds) -> int:
|
||||
value = expr.value(env)
|
||||
if abs(value - round(value)) > 1e-9 or not bounds[0] <= round(value) <= bounds[1]:
|
||||
raise KitError(f"{expr.where} is {value}: it must be a whole number from {bounds[0]} to {bounds[1]}")
|
||||
return int(round(value))
|
||||
|
||||
|
||||
def _rotation(degrees) -> np.ndarray:
|
||||
"""XYZ Euler: about x, then y, then z, each about the fixed axes of the shape's own origin."""
|
||||
(cx, sx), (cy, sy), (cz, sz) = ((math.cos(math.radians(a)), math.sin(math.radians(a))) for a in degrees)
|
||||
rx = np.array([[1.0, 0.0, 0.0], [0.0, cx, -sx], [0.0, sx, cx]])
|
||||
ry = np.array([[cy, 0.0, sy], [0.0, 1.0, 0.0], [-sy, 0.0, cy]])
|
||||
rz = np.array([[cz, -sz, 0.0], [sz, cz, 0.0], [0.0, 0.0, 1.0]])
|
||||
return rz @ ry @ rx
|
||||
|
||||
|
||||
def _tube(shape: dict, env):
|
||||
r0, r1, length = (shape[key].value(env) for key in ("r0", "r1", "length"))
|
||||
i0, i1 = shape["inner0"].value(env), shape["inner1"].value(env)
|
||||
n = _whole(shape["segments"], env, SEGMENTS)
|
||||
where = shape["where"]
|
||||
if length <= 0:
|
||||
raise KitError(f"{where}: length {length} must be above 0")
|
||||
if not (0 <= i0 < r0 and 0 <= i1 < r1):
|
||||
raise KitError(f"{where}: needs 0 <= inner < outer at both ends, got inner {i0}, {i1} and outer {r0}, {r1}")
|
||||
if (i0 > 0) != (i1 > 0):
|
||||
raise KitError(f"{where}: inner0 and inner1 must both be above 0 (hollow) or both be 0 (solid), got {i0}, {i1}")
|
||||
angle = 2.0 * math.pi * np.arange(n) / n
|
||||
cos, sin = np.cos(angle), np.sin(angle)
|
||||
ring = lambda r, z: np.column_stack([r * cos, r * sin, np.full(n, z)]) # noqa: E731
|
||||
k = np.arange(n)
|
||||
j = (k + 1) % n
|
||||
side = np.column_stack([k, j, n + j, n + k])
|
||||
if i0 > 0:
|
||||
V = np.vstack([ring(r0, 0.0), ring(r1, length), ring(i0, 0.0), ring(i1, length)])
|
||||
inner = np.column_stack([2 * n + j, 2 * n + k, 3 * n + k, 3 * n + j])
|
||||
bottom = np.column_stack([k, 2 * n + k, 2 * n + j, j])
|
||||
top = np.column_stack([n + k, n + j, 3 * n + j, 3 * n + k])
|
||||
faces = np.concatenate([side, inner, bottom, top]).ravel()
|
||||
counts = np.full(4 * n, 4)
|
||||
smooth = np.repeat([shape["smooth"], shape["smooth"], False, False], n)
|
||||
else:
|
||||
V = np.vstack([ring(r0, 0.0), ring(r1, length)])
|
||||
faces = np.concatenate([side.ravel(), k[::-1], n + k])
|
||||
counts = np.concatenate([np.full(n, 4), [n, n]])
|
||||
smooth = np.concatenate([np.full(n, shape["smooth"]), [False, False]])
|
||||
return V, faces, counts, smooth
|
||||
|
||||
|
||||
BOX_FACES = np.array([[0, 3, 2, 1], [4, 5, 6, 7], [0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [3, 0, 4, 7]])
|
||||
BOX_SIGNS = np.array([[-1, -1, -1], [1, -1, -1], [1, 1, -1], [-1, 1, -1], [-1, -1, 1], [1, -1, 1], [1, 1, 1], [-1, 1, 1]]) * 0.5
|
||||
|
||||
|
||||
def _box(shape: dict, env):
|
||||
size = np.array([e.value(env) for e in shape["size"]])
|
||||
if not (size > 0).all():
|
||||
raise KitError(f"{shape['where']}: every size must be above 0, got {size.tolist()}")
|
||||
return BOX_SIGNS * size, BOX_FACES.ravel(), np.full(6, 4), np.zeros(6, dtype=bool)
|
||||
|
||||
|
||||
def _placed(shape: dict, env):
|
||||
V, faces, counts, smooth = (_tube if shape["shape"] == "tube" else _box)(shape, env)
|
||||
rotation = _rotation([e.value(env) for e in shape["rot"]])
|
||||
return V @ rotation.T + np.array([e.value(env) for e in shape["at"]]), faces, counts, smooth
|
||||
|
||||
|
||||
def build(part: dict, params: dict | None = None) -> Built:
|
||||
"""The part at these params (resolve_params fills and checks them). The same part and params give
|
||||
byte-identical arrays."""
|
||||
env = resolve_params(part, params or {})
|
||||
here = f"kit {part['kit']!r} part {part['name']!r}"
|
||||
shells, owner = [], []
|
||||
with np.errstate(over="ignore", invalid="ignore"): # a huge value is refused below, not warned about
|
||||
for index, shape in enumerate(part["shapes"]):
|
||||
if shape["shape"] == "repeat":
|
||||
count = _whole(shape["count"], env, COPIES)
|
||||
step = np.array([e.value(env) for e in shape["step"]])
|
||||
V, faces, counts, smooth = _placed(shape["of"], env)
|
||||
made = [(V + k * step, faces, counts, smooth) for k in range(count)]
|
||||
else:
|
||||
made = [_placed(shape, env)]
|
||||
for shell in made:
|
||||
if not np.isfinite(shell[0]).all():
|
||||
raise KitError(f"{here} shape {index} ({shape['shape']}): its vertices are not finite at these params")
|
||||
shells += made
|
||||
owner += [index] * len(made)
|
||||
offsets = np.cumsum([0] + [len(s[0]) for s in shells[:-1]])
|
||||
sockets = []
|
||||
for socket in part["sockets"]:
|
||||
z, y = np.array(AXES[socket["z"]]), np.array(AXES[socket["y"]])
|
||||
matrix = np.eye(4)
|
||||
matrix[:3, 0], matrix[:3, 1], matrix[:3, 2] = np.cross(y, z), y, z
|
||||
matrix[:3, 3] = [e.value(env) for e in socket["at"]]
|
||||
size = socket["size"].value(env)
|
||||
if size <= 0:
|
||||
raise KitError(f"{socket['size'].where} is {size}: a socket's size must be above 0")
|
||||
sockets.append({"name": socket["name"], "type": socket["type"], "size": size, "matrix": matrix})
|
||||
bevel = part["bevel"].value(env) if part["bevel"] is not None else 0.0
|
||||
if bevel < 0:
|
||||
raise KitError(f"{part['bevel'].where} is {bevel}: a bevel is 0 or more")
|
||||
return Built(V=np.vstack([s[0] for s in shells]).astype(np.float64),
|
||||
faces=np.concatenate([s[1] + o for s, o in zip(shells, offsets)]).astype(np.int32),
|
||||
counts=np.concatenate([s[2] for s in shells]).astype(np.int32),
|
||||
smooth=np.concatenate([s[3] for s in shells]).astype(bool),
|
||||
shape=np.concatenate([np.full(len(s[2]), o) for s, o in zip(shells, owner)]).astype(np.int32),
|
||||
shell_count=len(shells), sockets=sockets, bevel=bevel, params=env)
|
||||
|
||||
|
||||
# --- reports -------------------------------------------------------------------------------------------------
|
||||
|
||||
def rows(matrix) -> list[list[float]]:
|
||||
"""A 4x4 as rows of 6 decimals, for a report."""
|
||||
return [[round(float(value), 6) + 0.0 for value in row] for row in np.asarray(matrix)]
|
||||
|
||||
|
||||
def socket_rows(sockets: list, frame=None) -> list[dict]:
|
||||
"""Sockets for a report, their frames carried into `frame` (a 4x4; the part's own frame when None)."""
|
||||
frame = np.eye(4) if frame is None else np.asarray(frame, dtype=np.float64)
|
||||
return [{"name": s["name"], "type": s["type"], "size": round(s["size"], 6), "matrix": rows(frame @ s["matrix"])} for s in sockets]
|
||||
|
||||
|
||||
def describe(kit: dict, name: str = "") -> dict:
|
||||
"""The kit's parts (or the one named): params with their bounds, and sockets in the part frame at default params."""
|
||||
chosen = [part(kit, name)] if name else list(kit["parts"].values())
|
||||
return {"kit": kit["kit"], "doc": kit["doc"], "socketTypes": kit["socketTypes"],
|
||||
"parts": [{"name": p["name"], "doc": p["doc"], "params": p["params"],
|
||||
"sockets": socket_rows(build(p).sockets)} for p in chosen]}
|
||||
305
surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json
Normal file
305
surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json
Normal file
|
|
@ -0,0 +1,305 @@
|
|||
{
|
||||
"schema": "brokkr.kit.v0",
|
||||
"kit": "mechanical",
|
||||
"doc": "Ship machinery: engines, tanks, structure, plumbing and cooling. Parts run along +z; metres.",
|
||||
"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; size is the pin diameter"}
|
||||
},
|
||||
"parts": [
|
||||
{
|
||||
"name": "nozzle",
|
||||
"doc": "Rocket engine: mount flange, chamber with gimbal lugs, throat collar and a hollow hooped bell opening along +z.",
|
||||
"params": [
|
||||
{"name": "throat_r", "type": "number", "min": 0.04, "max": 0.12, "default": 0.07, "doc": "throat radius"},
|
||||
{"name": "exit_r", "type": "number", "min": 0.16, "max": 0.45, "default": 0.26, "doc": "bell exit radius"},
|
||||
{"name": "length", "type": "number", "min": 0.25, "max": 1.0, "default": 0.5, "doc": "bell length, throat to exit"},
|
||||
{"name": "wall", "type": "number", "min": 0.004, "max": 0.015, "default": 0.008, "doc": "bell wall thickness"},
|
||||
{"name": "segments", "type": "integer", "min": 8, "max": 48, "default": 24, "doc": "sides of every round"}
|
||||
],
|
||||
"bevel": "0.3*wall",
|
||||
"shapes": [
|
||||
{"shape": "tube", "r0": "2.1*throat_r", "r1": "2.1*throat_r", "length": "0.3*throat_r", "segments": "segments", "smooth": true},
|
||||
{"shape": "repeat", "count": 2, "step": ["2.62*throat_r", 0, 0], "of":
|
||||
{"shape": "tube", "r0": "0.14*throat_r", "r1": "0.14*throat_r", "length": "0.35*throat_r", "segments": 6, "at": ["-1.31*throat_r", "-1.31*throat_r", "0.1*throat_r"]}},
|
||||
{"shape": "repeat", "count": 2, "step": ["2.62*throat_r", 0, 0], "of":
|
||||
{"shape": "tube", "r0": "0.14*throat_r", "r1": "0.14*throat_r", "length": "0.35*throat_r", "segments": 6, "at": ["-1.31*throat_r", "1.31*throat_r", "0.1*throat_r"]}},
|
||||
{"shape": "tube", "r0": "1.6*throat_r", "r1": "1.6*throat_r", "length": "1.75*throat_r", "segments": "segments", "smooth": true, "at": [0, 0, "0.15*throat_r"]},
|
||||
{"shape": "tube", "r0": "1.6*throat_r", "r1": "throat_r+wall", "length": "throat_r", "segments": "segments", "smooth": true, "at": [0, 0, "1.9*throat_r"]},
|
||||
{"shape": "tube", "r0": "1.78*throat_r", "r1": "1.78*throat_r", "length": "0.5*throat_r", "segments": "segments", "smooth": true, "at": [0, 0, "1.6*throat_r"]},
|
||||
{"shape": "tube", "r0": "throat_r+wall", "r1": "throat_r+wall+0.1164*(exit_r-throat_r-wall)", "inner0": "throat_r", "inner1": "throat_r+0.1164*(exit_r-throat_r-wall)",
|
||||
"length": "0.06*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r"]},
|
||||
{"shape": "tube", "r0": "throat_r+wall+0.1164*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.2604*(exit_r-throat_r-wall)", "inner0": "throat_r+0.1164*(exit_r-throat_r-wall)", "inner1": "throat_r+0.2604*(exit_r-throat_r-wall)",
|
||||
"length": "0.08*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.06*length"]},
|
||||
{"shape": "tube", "r0": "throat_r+wall+0.2604*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.4224*(exit_r-throat_r-wall)", "inner0": "throat_r+0.2604*(exit_r-throat_r-wall)", "inner1": "throat_r+0.4224*(exit_r-throat_r-wall)",
|
||||
"length": "0.1*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.14*length"]},
|
||||
{"shape": "tube", "r0": "throat_r+wall+0.4224*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.5904*(exit_r-throat_r-wall)", "inner0": "throat_r+0.4224*(exit_r-throat_r-wall)", "inner1": "throat_r+0.5904*(exit_r-throat_r-wall)",
|
||||
"length": "0.12*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.24*length"]},
|
||||
{"shape": "tube", "r0": "throat_r+wall+0.5904*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.75*(exit_r-throat_r-wall)", "inner0": "throat_r+0.5904*(exit_r-throat_r-wall)", "inner1": "throat_r+0.75*(exit_r-throat_r-wall)",
|
||||
"length": "0.14*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.36*length"]},
|
||||
{"shape": "tube", "r0": "throat_r+wall+0.75*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.8844*(exit_r-throat_r-wall)", "inner0": "throat_r+0.75*(exit_r-throat_r-wall)", "inner1": "throat_r+0.8844*(exit_r-throat_r-wall)",
|
||||
"length": "0.16*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.5*length"]},
|
||||
{"shape": "tube", "r0": "throat_r+wall+0.8844*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.9676*(exit_r-throat_r-wall)", "inner0": "throat_r+0.8844*(exit_r-throat_r-wall)", "inner1": "throat_r+0.9676*(exit_r-throat_r-wall)",
|
||||
"length": "0.16*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.66*length"]},
|
||||
{"shape": "tube", "r0": "throat_r+wall+0.9676*(exit_r-throat_r-wall)", "r1": "exit_r", "inner0": "throat_r+0.9676*(exit_r-throat_r-wall)", "inner1": "exit_r-wall",
|
||||
"length": "0.18*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.82*length"]},
|
||||
{"shape": "tube", "r0": "throat_r+2.4*wall+0.6132*(exit_r-throat_r-wall)", "r1": "throat_r+2.4*wall+0.6474*(exit_r-throat_r-wall)", "inner0": "throat_r+0.5*wall+0.6132*(exit_r-throat_r-wall)", "inner1": "throat_r+0.5*wall+0.6474*(exit_r-throat_r-wall)",
|
||||
"length": "0.03*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.38*length"]},
|
||||
{"shape": "tube", "r0": "throat_r+2.4*wall+0.834*(exit_r-throat_r-wall)", "r1": "throat_r+2.4*wall+0.8592*(exit_r-throat_r-wall)", "inner0": "throat_r+0.5*wall+0.834*(exit_r-throat_r-wall)", "inner1": "throat_r+0.5*wall+0.8592*(exit_r-throat_r-wall)",
|
||||
"length": "0.03*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.6*length"]},
|
||||
{"shape": "tube", "r0": "throat_r+2.4*wall+0.9748*(exit_r-throat_r-wall)", "r1": "throat_r+2.4*wall+0.9802*(exit_r-throat_r-wall)", "inner0": "throat_r+0.5*wall+0.9748*(exit_r-throat_r-wall)", "inner1": "throat_r+0.5*wall+0.9802*(exit_r-throat_r-wall)",
|
||||
"length": "0.03*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.86*length"]},
|
||||
{"shape": "repeat", "count": 2, "step": ["3.4*throat_r", 0, 0], "of":
|
||||
{"shape": "box", "size": ["0.5*throat_r", "0.35*throat_r", "0.6*throat_r"], "at": ["-1.7*throat_r", 0, "throat_r"]}},
|
||||
{"shape": "repeat", "count": 2, "step": [0, "3.4*throat_r", 0], "of":
|
||||
{"shape": "box", "size": ["0.35*throat_r", "0.5*throat_r", "0.6*throat_r"], "at": [0, "-1.7*throat_r", "throat_r"]}},
|
||||
{"shape": "tube", "r0": "exit_r+1.6*wall", "r1": "exit_r+1.6*wall", "inner0": "exit_r-0.5*wall", "inner1": "exit_r-0.5*wall",
|
||||
"length": "3*wall", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+length-2.5*wall"]}
|
||||
],
|
||||
"sockets": [
|
||||
{"name": "mount", "type": "flange", "size": "2*throat_r", "at": [0, 0, 0], "z": "-z", "y": "+y"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "tank",
|
||||
"doc": "Pressure tank: elliptical domed ends with flanged ports, weld bands, two straps on saddle cradles and a mounting pad.",
|
||||
"params": [
|
||||
{"name": "radius", "type": "number", "min": 0.12, "max": 0.35, "default": 0.22, "doc": "shell radius"},
|
||||
{"name": "length", "type": "number", "min": 0.6, "max": 2.0, "default": 0.9, "doc": "port face to port face"},
|
||||
{"name": "segments", "type": "integer", "min": 8, "max": 48, "default": 24, "doc": "sides of every round"}
|
||||
],
|
||||
"bevel": "0.008*radius",
|
||||
"shapes": [
|
||||
{"shape": "tube", "r0": "0.3*radius", "r1": "0.3*radius", "length": "0.05*radius", "segments": "segments", "smooth": true},
|
||||
{"shape": "tube", "r0": "0.2*radius", "r1": "0.2*radius", "length": "0.18*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.02*radius"]},
|
||||
{"shape": "tube", "r0": "0.47*radius", "r1": "0.6984*radius", "length": "0.07*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.12*radius"]},
|
||||
{"shape": "tube", "r0": "0.6984*radius", "r1": "0.8512*radius", "length": "0.08*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.19*radius"]},
|
||||
{"shape": "tube", "r0": "0.8512*radius", "r1": "0.9581*radius", "length": "0.1*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.27*radius"]},
|
||||
{"shape": "tube", "r0": "0.9581*radius", "r1": "radius", "length": "0.12*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.37*radius"]},
|
||||
{"shape": "tube", "r0": "radius", "r1": "radius", "length": "length-0.98*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.49*radius"]},
|
||||
{"shape": "tube", "r0": "radius", "r1": "0.9581*radius", "length": "0.12*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.49*radius"]},
|
||||
{"shape": "tube", "r0": "0.9581*radius", "r1": "0.8512*radius", "length": "0.1*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.37*radius"]},
|
||||
{"shape": "tube", "r0": "0.8512*radius", "r1": "0.6984*radius", "length": "0.08*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.27*radius"]},
|
||||
{"shape": "tube", "r0": "0.6984*radius", "r1": "0.47*radius", "length": "0.07*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.19*radius"]},
|
||||
{"shape": "tube", "r0": "0.2*radius", "r1": "0.2*radius", "length": "0.18*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.2*radius"]},
|
||||
{"shape": "tube", "r0": "0.3*radius", "r1": "0.3*radius", "length": "0.05*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.05*radius"]},
|
||||
{"shape": "repeat", "count": 2, "step": [0, 0, "length-0.98*radius"], "of":
|
||||
{"shape": "tube", "r0": "1.012*radius", "r1": "1.012*radius", "inner0": "0.97*radius", "inner1": "0.97*radius", "length": "0.04*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.47*radius"]}},
|
||||
{"shape": "repeat", "count": 2, "step": [0, 0, "0.56*(length-0.98*radius)"], "of":
|
||||
{"shape": "tube", "r0": "1.035*radius", "r1": "1.035*radius", "inner0": "0.97*radius", "inner1": "0.97*radius", "length": "0.1*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.44*radius+0.22*(length-0.98*radius)"]}},
|
||||
{"shape": "repeat", "count": 2, "step": [0, 0, "0.56*(length-0.98*radius)"], "of":
|
||||
{"shape": "box", "size": ["1.3*radius", "0.55*radius", "0.1*radius"], "at": [0, "-0.85*radius", "0.49*radius+0.22*(length-0.98*radius)"]}},
|
||||
{"shape": "box", "size": ["1.5*radius", "0.08*radius", "0.56*(length-0.98*radius)+0.3*radius"], "at": [0, "-1.14*radius", "length/2"]}
|
||||
],
|
||||
"sockets": [
|
||||
{"name": "port_a", "type": "flange", "size": "0.4*radius", "at": [0, 0, 0], "z": "-z", "y": "+y"},
|
||||
{"name": "port_b", "type": "flange", "size": "0.4*radius", "at": [0, 0, "length"], "z": "+z", "y": "+y"},
|
||||
{"name": "saddle", "type": "mount", "size": "1.5*radius", "at": [0, "-1.18*radius", "length/2"], "z": "-y", "y": "+z"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "ribbed_cylinder",
|
||||
"doc": "Finned housing (motor, exchanger, capacitor): a drum with cooling ribs, end flanges, four tie bolts and a cable raceway.",
|
||||
"params": [
|
||||
{"name": "radius", "type": "number", "min": 0.08, "max": 0.3, "default": 0.15, "doc": "drum radius"},
|
||||
{"name": "length", "type": "number", "min": 0.3, "max": 1.5, "default": 0.6, "doc": "end face to end face"},
|
||||
{"name": "ribs", "type": "integer", "min": 2, "max": 24, "default": 10, "doc": "rib rings"},
|
||||
{"name": "rib_depth", "type": "number", "min": 0.01, "max": 0.05, "default": 0.03, "doc": "how far ribs stand off the drum"},
|
||||
{"name": "rib_width", "type": "number", "min": 0.008, "max": 0.03, "default": 0.015, "doc": "rib thickness along the axis (narrowed when ribs crowd)"},
|
||||
{"name": "segments", "type": "integer", "min": 8, "max": 48, "default": 24, "doc": "sides of every round"}
|
||||
],
|
||||
"bevel": "0.15*min(min(rib_width,rib_depth),0.6*(length-3*rib_width)/ribs)",
|
||||
"shapes": [
|
||||
{"shape": "tube", "r0": "radius+1.6*rib_depth", "r1": "radius+1.6*rib_depth", "length": "1.5*rib_width", "segments": "segments", "smooth": true},
|
||||
{"shape": "tube", "r0": "radius", "r1": "radius", "length": "length-1.5*rib_width", "segments": "segments", "smooth": true, "at": [0, 0, "0.75*rib_width"]},
|
||||
{"shape": "tube", "r0": "radius+1.6*rib_depth", "r1": "radius+1.6*rib_depth", "length": "1.5*rib_width", "segments": "segments", "smooth": true, "at": [0, 0, "length-1.5*rib_width"]},
|
||||
{"shape": "repeat", "count": "ribs", "step": [0, 0, "(length-3*rib_width)/ribs"], "of":
|
||||
{"shape": "tube", "r0": "radius+rib_depth", "r1": "radius+rib_depth", "length": "min(rib_width,0.6*(length-3*rib_width)/ribs)", "segments": "segments", "smooth": true,
|
||||
"at": [0, 0, "1.5*rib_width+0.5*(length-3*rib_width)/ribs-0.5*min(rib_width,0.6*(length-3*rib_width)/ribs)"]}},
|
||||
{"shape": "repeat", "count": 2, "step": ["1.4142*(radius+0.5*rib_depth)", 0, 0], "of":
|
||||
{"shape": "tube", "r0": "0.28*rib_depth", "r1": "0.28*rib_depth", "length": "length-1.5*rib_width", "segments": 6, "at": ["-0.7071*(radius+0.5*rib_depth)", "-0.7071*(radius+0.5*rib_depth)", "0.75*rib_width"]}},
|
||||
{"shape": "repeat", "count": 2, "step": ["1.4142*(radius+0.5*rib_depth)", 0, 0], "of":
|
||||
{"shape": "tube", "r0": "0.28*rib_depth", "r1": "0.28*rib_depth", "length": "length-1.5*rib_width", "segments": 6, "at": ["-0.7071*(radius+0.5*rib_depth)", "0.7071*(radius+0.5*rib_depth)", "0.75*rib_width"]}},
|
||||
{"shape": "box", "size": ["0.45*radius", "0.15*radius+1.3*rib_depth", "length-3*rib_width"], "at": [0, "0.925*radius+0.65*rib_depth", "length/2"]}
|
||||
],
|
||||
"sockets": [
|
||||
{"name": "end_a", "type": "flange", "size": "2*radius", "at": [0, 0, 0], "z": "-z", "y": "+y"},
|
||||
{"name": "end_b", "type": "flange", "size": "2*radius", "at": [0, 0, "length"], "z": "+z", "y": "+y"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "strut",
|
||||
"doc": "Structural strut: an I-beam with web stiffeners between two pinned end blocks.",
|
||||
"params": [
|
||||
{"name": "length", "type": "number", "min": 0.3, "max": 2.0, "default": 0.8, "doc": "end face to end face"},
|
||||
{"name": "width", "type": "number", "min": 0.04, "max": 0.12, "default": 0.08, "doc": "flange width (x)"},
|
||||
{"name": "thickness", "type": "number", "min": 0.02, "max": 0.08, "default": 0.05, "doc": "beam depth (y)"},
|
||||
{"name": "segments", "type": "integer", "min": 8, "max": 48, "default": 24, "doc": "sides of the pins"}
|
||||
],
|
||||
"bevel": "0.03*min(width,thickness)",
|
||||
"shapes": [
|
||||
{"shape": "box", "size": ["1.3*width", "1.3*thickness", "0.9*width"], "at": [0, 0, "0.45*width"]},
|
||||
{"shape": "box", "size": ["1.3*width", "1.3*thickness", "0.9*width"], "at": [0, 0, "length-0.45*width"]},
|
||||
{"shape": "repeat", "count": 2, "step": [0, 0, "length-0.9*width"], "of":
|
||||
{"shape": "tube", "r0": "0.3*width", "r1": "0.3*width", "length": "1.7*thickness", "segments": "segments", "smooth": true, "rot": [-90, 0, 0], "at": [0, "-0.85*thickness", "0.45*width"]}},
|
||||
{"shape": "repeat", "count": 2, "step": [0, "0.78*thickness", 0], "of":
|
||||
{"shape": "box", "size": ["width", "0.22*thickness", "length-0.9*width"], "at": [0, "-0.39*thickness", "length/2"]}},
|
||||
{"shape": "box", "size": ["0.18*width", "0.6*thickness", "length-0.9*width"], "at": [0, 0, "length/2"]},
|
||||
{"shape": "repeat", "count": 3, "step": [0, 0, "(length-1.8*width)/4"], "of":
|
||||
{"shape": "box", "size": ["0.9*width", "0.7*thickness", "0.08*width"], "at": [0, 0, "0.9*width+(length-1.8*width)/4"]}}
|
||||
],
|
||||
"sockets": [
|
||||
{"name": "end_a", "type": "pivot", "size": "0.6*width", "at": [0, 0, 0], "z": "-z", "y": "+y"},
|
||||
{"name": "end_b", "type": "pivot", "size": "0.6*width", "at": [0, 0, "length"], "z": "+z", "y": "+y"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "actuator",
|
||||
"doc": "Tie-rod hydraulic cylinder: pinned base eye, square caps, barrel, ports, and a rod with its eye; extension moves rod_end.",
|
||||
"params": [
|
||||
{"name": "body_r", "type": "number", "min": 0.05, "max": 0.12, "default": 0.06, "doc": "barrel radius"},
|
||||
{"name": "body_len", "type": "number", "min": 0.2, "max": 1.0, "default": 0.4, "doc": "barrel length between caps"},
|
||||
{"name": "rod_r", "type": "number", "min": 0.01, "max": 0.02, "default": 0.018, "doc": "rod radius"},
|
||||
{"name": "extension", "type": "number", "min": 0.0, "max": 0.8, "default": 0.15, "doc": "rod travel out of the gland"},
|
||||
{"name": "segments", "type": "integer", "min": 8, "max": 48, "default": 24, "doc": "sides of every round"}
|
||||
],
|
||||
"bevel": "0.04*body_r",
|
||||
"shapes": [
|
||||
{"shape": "box", "size": ["1.2*body_r", "0.9*body_r", "1.6*body_r"], "at": [0, 0, "0.8*body_r"]},
|
||||
{"shape": "tube", "r0": "0.45*body_r", "r1": "0.45*body_r", "length": "1.3*body_r", "segments": "segments", "smooth": true, "rot": [-90, 0, 0], "at": [0, "-0.65*body_r", "0.8*body_r"]},
|
||||
{"shape": "box", "size": ["2.4*body_r", "2.4*body_r", "0.5*body_r"], "at": [0, 0, "1.75*body_r"]},
|
||||
{"shape": "tube", "r0": "body_r", "r1": "body_r", "length": "body_len+0.2*body_r", "segments": "segments", "smooth": true, "at": [0, 0, "1.9*body_r"]},
|
||||
{"shape": "box", "size": ["2.4*body_r", "2.4*body_r", "0.5*body_r"], "at": [0, 0, "2.25*body_r+body_len"]},
|
||||
{"shape": "repeat", "count": 2, "step": ["1.9*body_r", 0, 0], "of":
|
||||
{"shape": "tube", "r0": "0.12*body_r", "r1": "0.12*body_r", "length": "body_len+1.3*body_r", "segments": 6, "at": ["-0.95*body_r", "-0.95*body_r", "1.35*body_r"]}},
|
||||
{"shape": "repeat", "count": 2, "step": ["1.9*body_r", 0, 0], "of":
|
||||
{"shape": "tube", "r0": "0.12*body_r", "r1": "0.12*body_r", "length": "body_len+1.3*body_r", "segments": 6, "at": ["-0.95*body_r", "0.95*body_r", "1.35*body_r"]}},
|
||||
{"shape": "repeat", "count": 2, "step": [0, 0, "body_len+0.5*body_r"], "of":
|
||||
{"shape": "tube", "r0": "0.2*body_r", "r1": "0.2*body_r", "length": "0.45*body_r", "segments": "segments", "smooth": true, "rot": [0, 90, 0], "at": ["body_r", 0, "1.75*body_r"]}},
|
||||
{"shape": "tube", "r0": "rod_r+0.25*body_r", "r1": "rod_r+0.25*body_r", "length": "0.4*body_r", "segments": "segments", "smooth": true, "at": [0, 0, "2.4*body_r+body_len"]},
|
||||
{"shape": "tube", "r0": "rod_r", "r1": "rod_r", "length": "extension+0.9*body_r", "segments": "segments", "smooth": true, "at": [0, 0, "2.4*body_r+body_len"]},
|
||||
{"shape": "box", "size": ["1.2*body_r", "0.9*body_r", "1.4*body_r"], "at": [0, 0, "3.8*body_r+body_len+extension"]},
|
||||
{"shape": "tube", "r0": "0.45*body_r", "r1": "0.45*body_r", "length": "1.3*body_r", "segments": "segments", "smooth": true, "rot": [-90, 0, 0], "at": [0, "-0.65*body_r", "3.8*body_r+body_len+extension"]}
|
||||
],
|
||||
"sockets": [
|
||||
{"name": "base", "type": "pivot", "size": "0.9*body_r", "at": [0, 0, 0], "z": "-z", "y": "+y"},
|
||||
{"name": "rod_end", "type": "pivot", "size": "0.9*body_r", "at": [0, 0, "4.5*body_r+body_len+extension"], "z": "+z", "y": "+y"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "pipe_fitting",
|
||||
"doc": "Flanged tee: a run along +z with a branch along +x at its middle, a reinforced hub and bolted flanges.",
|
||||
"params": [
|
||||
{"name": "pipe_r", "type": "number", "min": 0.03, "max": 0.07, "default": 0.05, "doc": "pipe radius"},
|
||||
{"name": "run", "type": "number", "min": 0.4, "max": 1.0, "default": 0.5, "doc": "run length, face a to face b"},
|
||||
{"name": "branch", "type": "number", "min": 0.15, "max": 0.5, "default": 0.25, "doc": "branch length, run axis to face c"},
|
||||
{"name": "flange_r", "type": "number", "min": 0.09, "max": 0.14, "default": 0.095, "doc": "flange radius"},
|
||||
{"name": "flange_t", "type": "number", "min": 0.012, "max": 0.04, "default": 0.02, "doc": "flange thickness"},
|
||||
{"name": "segments", "type": "integer", "min": 8, "max": 48, "default": 24, "doc": "sides of every round"}
|
||||
],
|
||||
"bevel": "min(0.15*flange_t,0.06*(flange_r-pipe_r))",
|
||||
"shapes": [
|
||||
{"shape": "tube", "r0": "pipe_r", "r1": "pipe_r", "length": "run-flange_t", "segments": "segments", "smooth": true, "at": [0, 0, "0.5*flange_t"]},
|
||||
{"shape": "tube", "r0": "flange_r", "r1": "flange_r", "length": "flange_t", "segments": "segments", "smooth": true},
|
||||
{"shape": "tube", "r0": "flange_r", "r1": "flange_r", "length": "flange_t", "segments": "segments", "smooth": true, "at": [0, 0, "run-flange_t"]},
|
||||
{"shape": "tube", "r0": "1.3*pipe_r", "r1": "1.3*pipe_r", "length": "min(3*pipe_r,run-4*flange_t)", "segments": "segments", "smooth": true, "at": [0, 0, "run/2-min(3*pipe_r,run-4*flange_t)/2"]},
|
||||
{"shape": "tube", "r0": "pipe_r", "r1": "pipe_r", "length": "branch-0.5*flange_t", "segments": "segments", "smooth": true, "rot": [0, 90, 0], "at": [0, 0, "run/2"]},
|
||||
{"shape": "tube", "r0": "1.3*pipe_r", "r1": "1.3*pipe_r", "length": "min(2.2*pipe_r,branch-2*flange_t)", "segments": "segments", "smooth": true, "rot": [0, 90, 0], "at": [0, 0, "run/2"]},
|
||||
{"shape": "tube", "r0": "flange_r", "r1": "flange_r", "length": "flange_t", "segments": "segments", "smooth": true, "rot": [0, 90, 0], "at": ["branch-flange_t", 0, "run/2"]},
|
||||
{"shape": "repeat", "count": 2, "step": ["0.7072*(flange_r+pipe_r)", 0, 0], "of":
|
||||
{"shape": "tube", "r0": "0.22*(flange_r-pipe_r)", "r1": "0.22*(flange_r-pipe_r)", "length": "1.35*flange_t", "segments": 6, "at": ["-0.3536*(flange_r+pipe_r)", "-0.3536*(flange_r+pipe_r)", "0.15*flange_t"]}},
|
||||
{"shape": "repeat", "count": 2, "step": ["0.7072*(flange_r+pipe_r)", 0, 0], "of":
|
||||
{"shape": "tube", "r0": "0.22*(flange_r-pipe_r)", "r1": "0.22*(flange_r-pipe_r)", "length": "1.35*flange_t", "segments": 6, "at": ["-0.3536*(flange_r+pipe_r)", "0.3536*(flange_r+pipe_r)", "0.15*flange_t"]}},
|
||||
{"shape": "repeat", "count": 2, "step": ["0.7072*(flange_r+pipe_r)", 0, 0], "of":
|
||||
{"shape": "tube", "r0": "0.22*(flange_r-pipe_r)", "r1": "0.22*(flange_r-pipe_r)", "length": "1.35*flange_t", "segments": 6, "at": ["-0.3536*(flange_r+pipe_r)", "-0.3536*(flange_r+pipe_r)", "run-1.5*flange_t"]}},
|
||||
{"shape": "repeat", "count": 2, "step": ["0.7072*(flange_r+pipe_r)", 0, 0], "of":
|
||||
{"shape": "tube", "r0": "0.22*(flange_r-pipe_r)", "r1": "0.22*(flange_r-pipe_r)", "length": "1.35*flange_t", "segments": 6, "at": ["-0.3536*(flange_r+pipe_r)", "0.3536*(flange_r+pipe_r)", "run-1.5*flange_t"]}},
|
||||
{"shape": "repeat", "count": 2, "step": [0, 0, "0.7072*(flange_r+pipe_r)"], "of":
|
||||
{"shape": "tube", "r0": "0.22*(flange_r-pipe_r)", "r1": "0.22*(flange_r-pipe_r)", "length": "1.35*flange_t", "segments": 6, "rot": [0, 90, 0], "at": ["branch-1.5*flange_t", "-0.3536*(flange_r+pipe_r)", "run/2-0.3536*(flange_r+pipe_r)"]}},
|
||||
{"shape": "repeat", "count": 2, "step": [0, 0, "0.7072*(flange_r+pipe_r)"], "of":
|
||||
{"shape": "tube", "r0": "0.22*(flange_r-pipe_r)", "r1": "0.22*(flange_r-pipe_r)", "length": "1.35*flange_t", "segments": 6, "rot": [0, 90, 0], "at": ["branch-1.5*flange_t", "0.3536*(flange_r+pipe_r)", "run/2-0.3536*(flange_r+pipe_r)"]}}
|
||||
],
|
||||
"sockets": [
|
||||
{"name": "a", "type": "flange", "size": "2*pipe_r", "at": [0, 0, 0], "z": "-z", "y": "+y"},
|
||||
{"name": "b", "type": "flange", "size": "2*pipe_r", "at": [0, 0, "run"], "z": "+z", "y": "+y"},
|
||||
{"name": "c", "type": "flange", "size": "2*pipe_r", "at": ["branch", 0, "run/2"], "z": "+x", "y": "+z"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "radiator_stack",
|
||||
"doc": "Fin stack: plate fins on a spine and two heat pipes, between a base block and a header.",
|
||||
"params": [
|
||||
{"name": "fins", "type": "integer", "min": 3, "max": 40, "default": 12, "doc": "fin plates"},
|
||||
{"name": "fin_w", "type": "number", "min": 0.15, "max": 0.6, "default": 0.3, "doc": "fin width (x)"},
|
||||
{"name": "fin_h", "type": "number", "min": 0.08, "max": 0.4, "default": 0.18, "doc": "fin height (y)"},
|
||||
{"name": "fin_t", "type": "number", "min": 0.003, "max": 0.012, "default": 0.005, "doc": "fin thickness"},
|
||||
{"name": "pitch", "type": "number", "min": 0.015, "max": 0.05, "default": 0.025, "doc": "fin spacing along +z"},
|
||||
{"name": "segments", "type": "integer", "min": 8, "max": 48, "default": 24, "doc": "sides of the heat pipes"}
|
||||
],
|
||||
"bevel": "0.2*fin_t",
|
||||
"shapes": [
|
||||
{"shape": "box", "size": ["0.5*fin_w", "0.85*fin_h", "0.12*fin_h"], "at": [0, 0, "0.06*fin_h"]},
|
||||
{"shape": "box", "size": ["0.1*fin_w", "0.55*fin_h", "fins*pitch+0.06*fin_h"], "at": [0, 0, "0.09*fin_h+0.5*fins*pitch"]},
|
||||
{"shape": "repeat", "count": "fins", "step": [0, 0, "pitch"], "of":
|
||||
{"shape": "box", "size": ["fin_w", "fin_h", "fin_t"], "at": [0, 0, "0.12*fin_h+0.5*pitch"]}},
|
||||
{"shape": "repeat", "count": 2, "step": ["0.64*fin_w", 0, 0], "of":
|
||||
{"shape": "tube", "r0": "0.07*fin_h", "r1": "0.07*fin_h", "length": "fins*pitch+0.1*fin_h", "segments": "segments", "smooth": true, "at": ["-0.32*fin_w", 0, "0.06*fin_h"]}},
|
||||
{"shape": "box", "size": ["0.8*fin_w", "0.3*fin_h", "0.1*fin_h"], "at": [0, 0, "0.17*fin_h+fins*pitch"]}
|
||||
],
|
||||
"sockets": [
|
||||
{"name": "base", "type": "mount", "size": "min(0.5*fin_w,0.85*fin_h)", "at": [0, 0, 0], "z": "-z", "y": "+y"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "vent",
|
||||
"doc": "Louvred vent: a framed box on a back plate with tilted slats; it breathes along +z.",
|
||||
"params": [
|
||||
{"name": "width", "type": "number", "min": 0.2, "max": 0.8, "default": 0.4, "doc": "frame width (x)"},
|
||||
{"name": "height", "type": "number", "min": 0.15, "max": 0.6, "default": 0.3, "doc": "frame height (y)"},
|
||||
{"name": "depth", "type": "number", "min": 0.04, "max": 0.15, "default": 0.08, "doc": "frame depth (z)"},
|
||||
{"name": "slats", "type": "integer", "min": 2, "max": 16, "default": 6, "doc": "louvre slats"},
|
||||
{"name": "slat_t", "type": "number", "min": 0.003, "max": 0.01, "default": 0.005, "doc": "slat thickness"},
|
||||
{"name": "tilt", "type": "number", "min": 0.0, "max": 60.0, "default": 35.0, "doc": "slat tilt in degrees; 0 is edge-on, fully open"}
|
||||
],
|
||||
"bevel": "0.25*slat_t",
|
||||
"shapes": [
|
||||
{"shape": "box", "size": ["width-0.048*min(width,height)", "height-0.048*min(width,height)", "0.12*depth"], "at": [0, 0, "0.06*depth"]},
|
||||
{"shape": "repeat", "count": 2, "step": ["width-0.08*min(width,height)", 0, 0], "of":
|
||||
{"shape": "box", "size": ["0.08*min(width,height)", "height", "0.95*depth"], "at": ["-(width-0.08*min(width,height))/2", 0, "0.525*depth"]}},
|
||||
{"shape": "repeat", "count": 2, "step": [0, "height-0.08*min(width,height)", 0], "of":
|
||||
{"shape": "box", "size": ["width-0.16*min(width,height)", "0.08*min(width,height)", "0.95*depth"], "at": [0, "-(height-0.08*min(width,height))/2", "0.525*depth"]}},
|
||||
{"shape": "repeat", "count": "slats", "step": [0, "(height-0.16*min(width,height))/slats", 0], "of":
|
||||
{"shape": "box", "size": ["width-0.12*min(width,height)", "slat_t", "min(0.62*depth,1.1*(height-0.16*min(width,height))/slats)"], "rot": ["tilt", 0, 0],
|
||||
"at": [0, "-(height-0.16*min(width,height))/2+0.5*(height-0.16*min(width,height))/slats", "0.56*depth"]}}
|
||||
],
|
||||
"sockets": [
|
||||
{"name": "back", "type": "mount", "size": "0.9*min(width,height)", "at": [0, 0, 0], "z": "-z", "y": "+y"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "plate",
|
||||
"doc": "Cover plate: a bolted rim around a raised panel; mounts on its back and carries a part on its front.",
|
||||
"params": [
|
||||
{"name": "width", "type": "number", "min": 0.1, "max": 1.0, "default": 0.4, "doc": "x size"},
|
||||
{"name": "height", "type": "number", "min": 0.1, "max": 1.0, "default": 0.3, "doc": "y size"},
|
||||
{"name": "thickness", "type": "number", "min": 0.005, "max": 0.05, "default": 0.015, "doc": "back face to panel face (z)"}
|
||||
],
|
||||
"bevel": "0.1*thickness",
|
||||
"shapes": [
|
||||
{"shape": "box", "size": ["width", "height", "0.7*thickness"], "at": [0, 0, "0.35*thickness"]},
|
||||
{"shape": "box", "size": ["width-0.24*min(width,height)", "height-0.24*min(width,height)", "0.7*thickness"], "at": [0, 0, "0.65*thickness"]},
|
||||
{"shape": "repeat", "count": 2, "step": ["width-0.12*min(width,height)", 0, 0], "of":
|
||||
{"shape": "tube", "r0": "0.036*min(width,height)", "r1": "0.036*min(width,height)", "length": "0.6*thickness", "segments": 6,
|
||||
"at": ["-(width-0.12*min(width,height))/2", "-(height-0.12*min(width,height))/2", "0.35*thickness"]}},
|
||||
{"shape": "repeat", "count": 2, "step": ["width-0.12*min(width,height)", 0, 0], "of":
|
||||
{"shape": "tube", "r0": "0.036*min(width,height)", "r1": "0.036*min(width,height)", "length": "0.6*thickness", "segments": 6,
|
||||
"at": ["-(width-0.12*min(width,height))/2", "(height-0.12*min(width,height))/2", "0.35*thickness"]}}
|
||||
],
|
||||
"sockets": [
|
||||
{"name": "back", "type": "mount", "size": "min(width,height)", "at": [0, 0, 0], "z": "-z", "y": "+y"},
|
||||
{"name": "front", "type": "mount", "size": "0.76*min(width,height)", "at": [0, 0, "thickness"], "z": "+z", "y": "+y"}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
173
surfaces/blender/docs/kitbash.md
Normal file
173
surfaces/blender/docs/kitbash.md
Normal file
|
|
@ -0,0 +1,173 @@
|
|||
# Kitbash parts: machinery from kits
|
||||
|
||||
`surfaces/blender/brokkr_kitbash` is a Blender add-on that places parametric machine parts from a **kit** and
|
||||
reports where their **sockets** are. It is the machinery vocabulary of a ship's fixed chassis: the frame, tanks,
|
||||
actuators, housings and plumbing an agent assembles offline under a hand-fit armor cage, baked once. It is a host
|
||||
add-on in Brokkr's sense (`install.md`, "Host add-on actions"), a sibling of `brokkr_mesh_polish` and `brokkr_rig`:
|
||||
it imports the polish package's operator base, `Refused` and `mesh_object`, and nothing from `brokkr_bridge`.
|
||||
Enable `brokkr_mesh_polish` first; `brokkr_kitbash` refuses to register without it. `brokkr_actions.json` beside
|
||||
its `__init__.py` lists the four operators agents may run. Every action writes a JSON report to
|
||||
`brokkr_mesh_polish_result`, returned in the receipt's `hostResult`.
|
||||
|
||||
Who owns what:
|
||||
|
||||
- `brokkr_kitbash/core.py` (numpy and the standard library, no Blender) owns the kit format: what a kit document
|
||||
may say (`check_kit`), what a part's params may be (`resolve_params`), and the geometry and socket frames a part
|
||||
and its params produce (`build`). There is no other validator of the format.
|
||||
- `brokkr_kitbash/kits/<name>.v0.json` own kit content. A kit is chosen by name (`a-z`, `0-9`, `_`, at most 32);
|
||||
the name is the only thing an intent contributes to the path.
|
||||
- In the scene, an object's `kit_kit`, `kit_part` and `kit_params` ID properties own what that part is. Its mesh is
|
||||
derived from them: `set_params` rebuilds it, and an edit made to the mesh by hand is lost at the next
|
||||
`set_params`. Socket frames are derived at every report and stored nowhere.
|
||||
- Two things would give a part a second owner, and are refused. `set_params` refuses an object whose mesh
|
||||
datablock another object uses (a linked duplicate): rebuilding it would change the other while its params stay.
|
||||
`set_params` and `report` refuse a part whose world transform scales, mirrors or shears, its parents'
|
||||
included: a part's size is its params, and a socket's frame is a rotation and an origin. Set scale to 1 and
|
||||
resize with `set_params`.
|
||||
|
||||
This add-on places and re-parameterises parts. Mating sockets, booleans and baking are not here.
|
||||
|
||||
## A part, end to end
|
||||
|
||||
A kit document is `{schema: "brokkr.kit.v0", kit, doc, socketTypes, parts}`. One part of a kit, whole:
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "standoff",
|
||||
"doc": "A post on a square foot.",
|
||||
"params": [
|
||||
{"name": "height", "type": "number", "min": 0.05, "max": 0.5, "default": 0.2, "doc": "foot face to top face"},
|
||||
{"name": "radius", "type": "number", "min": 0.01, "max": 0.05, "default": 0.02, "doc": "post radius"},
|
||||
{"name": "bolts", "type": "integer", "min": 1, "max": 4, "default": 2, "doc": "bolts along x"}
|
||||
],
|
||||
"bevel": "0.1*radius",
|
||||
"shapes": [
|
||||
{"shape": "box", "size": ["6*radius", "3*radius", "radius"], "at": [0, 0, "0.5*radius"]},
|
||||
{"shape": "tube", "r0": "radius", "r1": "0.8*radius", "length": "height-0.5*radius", "segments": 24, "smooth": true,
|
||||
"at": [0, 0, "0.5*radius"]},
|
||||
{"shape": "repeat", "count": "bolts", "step": ["4*radius/max(bolts-1,1)", 0, 0], "of":
|
||||
{"shape": "tube", "r0": "0.3*radius", "r1": "0.3*radius", "length": "0.4*radius", "segments": 6,
|
||||
"at": ["-2*radius", 0, "0.9*radius"]}}
|
||||
],
|
||||
"sockets": [
|
||||
{"name": "foot", "type": "mount", "size": "3*radius", "at": [0, 0, 0], "z": "-z", "y": "+y"},
|
||||
{"name": "top", "type": "mount", "size": "1.6*radius", "at": [0, 0, "height"], "z": "+z", "y": "+y"}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Lengths are metres in the part's own frame. Unknown keys are refused at every level, and so is a repeated part,
|
||||
param or socket name, a default outside `[min, max]`, and an integer param with a fractional bound or default.
|
||||
|
||||
**Params** are `number` or `integer` with inclusive bounds. A param name is lower case (`a-z`, then `a-z`, `0-9`,
|
||||
`_`) and is not `min` or `max`.
|
||||
|
||||
**Shapes.** Each is one or more closed shells wound outward. `at` (metres) and `rot` (XYZ Euler degrees: about x,
|
||||
then y, then z, about the shape's own origin) place it, rotation first; both default to zero.
|
||||
|
||||
| shape | fields | what it is |
|
||||
| --- | --- | --- |
|
||||
| `tube` | `r0`, `r1`, `length`, `segments`, `inner0`?, `inner1`?, `smooth`? | A frustum on +z from radius `r0` at z=0 to `r1` at z=`length`, with n-gon caps. Inner radii above 0 make it hollow (an inner wall and two flat end rings); they are both above 0 or both 0, and below the outer radius. `segments` is 3 to 128. `smooth` shades the walls smooth; caps stay flat. |
|
||||
| `box` | `size` | A box centred on its origin; every size above 0. |
|
||||
| `repeat` | `count`, `step`, `of` | `count` copies (1 to 256) of one tube or box at `k * step`, k from 0. A repeat cannot hold a repeat. |
|
||||
|
||||
Shells may overlap (a pad that runs into a tank), and a part is then not one solid: reports give the shell count.
|
||||
|
||||
**`bevel`** is the width of a Bevel modifier `place_part` adds (2 segments, edges sharper than 30 degrees). Keep it
|
||||
well under the part's thinnest feature at its smallest params.
|
||||
|
||||
**Sockets** are frames. `at` is the origin; `z` is the outward normal (a mating socket faces it), `y` is up (the
|
||||
roll reference), and x is y cross z; each is one of `+x -x +y -y +z -z` in the part's frame, on different axes.
|
||||
`size` is a diameter in metres. `type` names one of the kit's `socketTypes`, whose `match` says how sizes are to
|
||||
be compared when sockets are mated: `equal` (within 1 percent) or `fits` (the child at most the parent). A socket
|
||||
sits on a flat face of the part whose normal is its `z`; `test_kitbash` checks this for every part of a shipped
|
||||
kit at its default, smallest and largest params and at seeded draws between.
|
||||
|
||||
## Expressions
|
||||
|
||||
Every numeric field of a shape or socket, and `bevel`, is a number or a string over the part's params:
|
||||
|
||||
```text
|
||||
+ - * / unary minus ( ) min(a, b) max(a, b) numbers param names
|
||||
```
|
||||
|
||||
An expression is parsed once and walked against that list when the kit is checked; an attribute, subscript,
|
||||
power, comparison, any other call, a keyword argument, a lambda or a string is refused there, naming the part and
|
||||
field. Nothing in a kit is run as Python. Division by zero, a result that is not a finite number, and a `count`
|
||||
or `segments` that is not whole are refused when the part is built, naming the expression; so is a shape whose
|
||||
vertices overflow.
|
||||
|
||||
## The actions
|
||||
|
||||
| action | fields | what it does |
|
||||
| --- | --- | --- |
|
||||
| `brokkr_kitbash.describe` | `kit` (default `mechanical`), `part` (default: all) | Parts with their params (type, min, max, default, doc) and sockets in the part frame at default params. Changes nothing. |
|
||||
| `brokkr_kitbash.place_part` | `kit`, `part`, `object_name`, `params` | A new mesh object at the origin: the part's mesh, a `Kit Bevel` modifier when the part has a bevel, and the three ID properties. Refuses a name an object already has. |
|
||||
| `brokkr_kitbash.set_params` | `object_name`, `params` | Overlays `params` on the stored ones and rebuilds the mesh in the same datablock: transform, parent, modifiers and material slots stay, and the Bevel width follows. Per-face materials are carried by shape: each shape of the part keeps the material most of its faces had, whatever the new face count. |
|
||||
| `brokkr_kitbash.report` | `object_name` (default: every kit part) | Each part as the scene has it: kit, part, params, faces, shells, and each socket's world frame. Changes nothing. |
|
||||
|
||||
`params` is `name=value; name=value`; a param left out takes the part's default (`place_part`) or keeps its stored
|
||||
value (`set_params`). A value outside its bounds is refused with the bounds in the message.
|
||||
|
||||
A socket in a report is `{name, type, size, matrix}`: `matrix` is the 4x4 as four rows of 6 decimals, in world
|
||||
space for `place_part`, `set_params` and `report`. Column 2 is the outward normal, column 1 up, column 3 the
|
||||
origin. A report over 16000 characters (what a receipt carries) is refused with advice to name one part or
|
||||
object.
|
||||
|
||||
Placement, look and export are Brokkr's own rows: `setObjectTransform`, `assignMaterial`, `exportGltf`.
|
||||
`place_part` has no location or colour fields.
|
||||
|
||||
## A recipe
|
||||
|
||||
`tools/run_intents.py` runs this in a background Blender (`install.md`, private user directories required):
|
||||
|
||||
```json
|
||||
{"requestedBy": "nibu/hands", "outputDir": "/work/out", "hostAddons": ["brokkr_mesh_polish", "brokkr_kitbash"],
|
||||
"saveBlend": "/work/out/engine.blend",
|
||||
"intents": [
|
||||
{"action": "brokkr_kitbash.describe", "part": "tank"},
|
||||
{"action": "brokkr_kitbash.place_part", "part": "tank", "object_name": "Tank", "params": "radius=0.3; length=1.4"},
|
||||
{"action": "setObjectTransform", "targetObjectName": "Tank", "location": [0, 0.6, 0], "rotationEuler": [1.5708, 0, 0]},
|
||||
{"action": "assignMaterial", "targetObjectName": "Tank", "materialName": "Machinery", "color": [0.35, 0.35, 0.35]},
|
||||
{"action": "brokkr_kitbash.place_part", "part": "nozzle", "object_name": "Nozzle"},
|
||||
{"action": "brokkr_kitbash.set_params", "object_name": "Nozzle", "params": "exit_r=0.32"},
|
||||
{"action": "brokkr_kitbash.report"},
|
||||
{"action": "exportGltf", "filepath": "engine.glb", "selection": ["Tank", "Nozzle"]}
|
||||
]}
|
||||
```
|
||||
|
||||
The receipts file holds each report in `hostResult`. `tools/turntable_recipe.py` renders the saved `.blend`.
|
||||
|
||||
## The mechanical kit
|
||||
|
||||
`kits/mechanical.v0.json`: nine parts, each along +z, with socket types `flange` (equal), `mount` (fits) and
|
||||
`pivot` (equal).
|
||||
|
||||
| part | params | sockets |
|
||||
| --- | --- | --- |
|
||||
| `nozzle` | `throat_r`, `exit_r`, `length`, `wall`, `segments` | `mount` (flange) |
|
||||
| `tank` | `radius`, `length`, `segments` | `port_a`, `port_b` (flange), `saddle` (mount) |
|
||||
| `ribbed_cylinder` | `radius`, `length`, `ribs`, `rib_depth`, `rib_width`, `segments` | `end_a`, `end_b` (flange) |
|
||||
| `strut` | `length`, `width`, `thickness`, `segments` | `end_a`, `end_b` (pivot) |
|
||||
| `actuator` | `body_r`, `body_len`, `rod_r`, `extension`, `segments` | `base`, `rod_end` (pivot); `rod_end` moves with `extension` |
|
||||
| `pipe_fitting` | `pipe_r`, `run`, `branch`, `flange_r`, `flange_t`, `segments` | `a`, `b`, `c` (flange) |
|
||||
| `radiator_stack` | `fins`, `fin_w`, `fin_h`, `fin_t`, `pitch`, `segments` | `base` (mount) |
|
||||
| `vent` | `width`, `height`, `depth`, `slats`, `slat_t`, `tilt` | `back` (mount) |
|
||||
| `plate` | `width`, `height`, `thickness` | `back`, `front` (mount) |
|
||||
|
||||
`describe` gives the bounds and docs.
|
||||
|
||||
## Adding a part or a kit
|
||||
|
||||
Edit the kit's JSON (or add `kits/<name>.v0.json`, whose `kit` field is `<name>`), then run the tests:
|
||||
|
||||
```text
|
||||
python -m unittest discover -s surfaces/blender/tests -p "test_kitbash.py" -v
|
||||
```
|
||||
|
||||
`MechanicalKitTests` builds every part of `mechanical` at its default, all-minimum and all-maximum params and at
|
||||
16 seeded draws, and checks that every shell is closed and wound outward, every socket frame is right-handed and
|
||||
seated on a face that faces its `z`, and no build passes 20000 faces. Choose param ranges so every combination
|
||||
builds: a `min` or `max` in an expression keeps a derived length positive where two params could cross. A new
|
||||
part of `mechanical` also joins the part and socket list in `test_the_kit_is_the_nine_parts_and_three_socket_types`.
|
||||
The operators are exercised in a real Blender by `tests/live/kitbash.py`.
|
||||
245
surfaces/blender/tests/live/kitbash.py
Normal file
245
surfaces/blender/tests/live/kitbash.py
Normal file
|
|
@ -0,0 +1,245 @@
|
|||
"""Live proof, in a background Blender, that the brokkr_kitbash rows are admitted by Brokkr as host actions and that
|
||||
the mechanical kit goes through run_intent: describe, place_part for all nine parts, setObjectTransform,
|
||||
assignMaterial, set_params, report, the refusals, and exportGltf. Not part of the unittest run: it needs Blender.
|
||||
|
||||
blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash.py -- <out>
|
||||
|
||||
Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses
|
||||
without them). Writes <out>.result.json and exits 1 when a check failed.
|
||||
"""
|
||||
import importlib.util
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import types
|
||||
from pathlib import Path
|
||||
|
||||
import bpy
|
||||
import numpy as np
|
||||
|
||||
SURFACE = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(SURFACE / "tools"))
|
||||
import private_dirs # noqa: E402
|
||||
|
||||
_refused = private_dirs.refusal(os.environ, os.path.expanduser("~"), lambda kind: bpy.utils.user_resource(kind))
|
||||
if _refused:
|
||||
raise SystemExit(_refused)
|
||||
OUT = sys.argv[sys.argv.index("--") + 1]
|
||||
package = types.ModuleType("brokkr_bridge")
|
||||
package.__path__ = [str(SURFACE / "brokkr_bridge")]
|
||||
sys.modules["brokkr_bridge"] = package
|
||||
from brokkr_bridge import blender_target as bt # noqa: E402
|
||||
|
||||
import addon_utils # noqa: E402
|
||||
|
||||
spec = importlib.util.spec_from_file_location("brokkr_kitbash_core_reference", SURFACE / "brokkr_kitbash" / "core.py")
|
||||
core = importlib.util.module_from_spec(spec) # core as the tests load it: what each placed mesh is compared against
|
||||
spec.loader.exec_module(core)
|
||||
|
||||
sys.path.append(str(SURFACE))
|
||||
bpy.ops.wm.read_factory_settings(use_empty=True)
|
||||
for module in ("brokkr_mesh_polish", "brokkr_kitbash"):
|
||||
addon_utils.enable(module, default_set=True)
|
||||
target = bt.BrokkrBlenderTarget(bpy)
|
||||
WORK = Path(tempfile.mkdtemp(prefix="brokkr-kitbash-live-"))
|
||||
target.configure_action_dirs("", str(WORK))
|
||||
target.reload_host_actions()
|
||||
R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1],
|
||||
"hostRows": [row["name"] for row in target.host_actions()[0]]}
|
||||
COUNT = [0]
|
||||
|
||||
|
||||
def check(name, ok, detail=None):
|
||||
R["checks"].append({"name": name, "ok": bool(ok), "detail": None if ok else detail}) # what was seen, when it was not what was promised
|
||||
|
||||
|
||||
def send(action, **fields):
|
||||
COUNT[0] += 1
|
||||
receipt = target.run_intent(bpy.context, {"commandId": f"live-{COUNT[0]}", "requestedBy": "test/driver", "action": action, **fields})
|
||||
result = None
|
||||
if receipt.get("hostResult"):
|
||||
try:
|
||||
result = json.loads(receipt["hostResult"])
|
||||
except ValueError:
|
||||
result = None
|
||||
print("SEND", action, receipt["status"], str(receipt["message"])[:300], flush=True)
|
||||
return receipt, result
|
||||
|
||||
|
||||
def extent(obj, axis=2):
|
||||
co = np.array([v.co[:] for v in obj.data.vertices])
|
||||
return float(co[:, axis].max() - co[:, axis].min())
|
||||
|
||||
|
||||
check("the four kitbash rows load as host actions with no errors", not R["hostErrors"]
|
||||
and [r for r in R["hostRows"] if r.startswith("brokkr_kitbash.")] == ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params",
|
||||
"brokkr_kitbash.describe", "brokkr_kitbash.report"], [R["hostErrors"], R["hostRows"]])
|
||||
|
||||
# --- describe ---------------------------------------------------------------------------------------------------------
|
||||
kit = core.load_kit("mechanical")
|
||||
receipt, described = send("brokkr_kitbash.describe")
|
||||
names = [p["name"] for p in described["parts"]] if described else []
|
||||
check("describe lists nine parts, whole, inside a receipt", receipt["status"] == "accepted" and names == list(kit["parts"]) and len(names) == 9
|
||||
and "[truncated]" not in receipt["hostResult"], [names, len(receipt.get("hostResult") or "")])
|
||||
receipt, one = send("brokkr_kitbash.describe", part="actuator")
|
||||
check("describe of one part gives its params and its sockets at default params", one and [p["name"] for p in one["parts"]] == ["actuator"]
|
||||
and [p["name"] for p in one["parts"][0]["params"]] == ["body_r", "body_len", "rod_r", "extension", "segments"]
|
||||
and one["parts"][0]["sockets"] == core.socket_rows(core.build(kit["parts"]["actuator"]).sockets), one)
|
||||
check("describe changes nothing", len(bpy.data.objects) == 0 and len(bpy.data.meshes) == 0, [len(bpy.data.objects), len(bpy.data.meshes)])
|
||||
|
||||
# --- place every part at default -----------------------------------------------------------------------------------------
|
||||
placed = {}
|
||||
for index, name in enumerate(names):
|
||||
receipt, report = send("brokkr_kitbash.place_part", part=name, object_name=f"P_{name}")
|
||||
obj = bpy.data.objects.get(f"P_{name}")
|
||||
reference = core.build(kit["parts"][name])
|
||||
faces = len(obj.data.polygons) if obj else -1
|
||||
clean = obj is not None and not obj.data.validate(verbose=False)
|
||||
flat = np.zeros(max(faces, 0), dtype=bool)
|
||||
if obj:
|
||||
obj.data.attributes["sharp_face"].data.foreach_get("value", flat)
|
||||
bevel = obj.modifiers.get("Kit Bevel") if obj else None
|
||||
evaluated = len(obj.evaluated_get(bpy.context.evaluated_depsgraph_get()).data.polygons) if obj else -1
|
||||
placed[name] = report
|
||||
check(f"place_part {name}: core's faces, a valid mesh, core's flat faces, at the origin", receipt["status"] == "accepted" and report
|
||||
and faces == len(reference.counts) == report["faces"] and clean and report["shells"] == reference.shell_count
|
||||
and flat.tolist() == (~reference.smooth).tolist() and list(obj.location) == [0.0, 0.0, 0.0]
|
||||
and np.allclose(np.array([v.co[:] for v in obj.data.vertices]), reference.V, atol=1e-6),
|
||||
[receipt["message"], faces, len(reference.counts), clean])
|
||||
check(f"place_part {name}: a Bevel of the part's width, 2 segments, angle 30, that evaluates", bevel is not None
|
||||
and abs(bevel.width - reference.bevel) < 1e-7 and bevel.segments == 2 and bevel.limit_method == "ANGLE"
|
||||
and abs(bevel.angle_limit - math.radians(30)) < 1e-6 and evaluated > faces, [bevel and bevel.width, reference.bevel, evaluated, faces])
|
||||
check(f"place_part {name}: kit, part and every resolved param stored on the object, sockets reported in the part frame", obj is not None
|
||||
and obj["kit_kit"] == "mechanical" and obj["kit_part"] == name and json.loads(obj["kit_params"]) == reference.params == report["params"]
|
||||
and report["sockets"] == core.socket_rows(reference.sockets), report)
|
||||
check("nine parts are nine mesh objects", len(bpy.data.objects) == 9 and all(o.type == "MESH" for o in bpy.data.objects), len(bpy.data.objects))
|
||||
|
||||
# --- set_params keeps what is not derived --------------------------------------------------------------------------------
|
||||
tank = bpy.data.objects["P_tank"]
|
||||
send("setObjectTransform", targetObjectName="P_tank", location=[1.0, 2.0, 3.0], rotationEuler=[0.3, -0.2, 0.5], scale=[1.0, 1.0, 1.0])
|
||||
send("assignMaterial", targetObjectName="P_tank", materialName="Tank Paint", color=[0.35, 0.35, 0.35])
|
||||
send("setObjectParent", targetObjectName="P_tank", parentObjectName="P_plate")
|
||||
before = {"z": extent(tank), "mesh": tank.data.name, "basis": [list(r) for r in tank.matrix_basis], "parent": tank.parent and tank.parent.name,
|
||||
"materials": [s.material and s.material.name for s in tank.material_slots], "modifiers": [m.name for m in tank.modifiers],
|
||||
"faces": len(tank.data.polygons)}
|
||||
receipt, grown = send("brokkr_kitbash.set_params", object_name="P_tank", params="length=1.8")
|
||||
after = {"z": extent(tank), "mesh": tank.data.name, "basis": [list(r) for r in tank.matrix_basis], "parent": tank.parent and tank.parent.name,
|
||||
"materials": [s.material and s.material.name for s in tank.material_slots], "modifiers": [m.name for m in tank.modifiers],
|
||||
"faces": len(tank.data.polygons)}
|
||||
check("set_params doubling the tank's length doubles its z extent", receipt["status"] == "accepted" and abs(before["z"] - 0.9) < 1e-6
|
||||
and abs(after["z"] - 1.8) < 1e-6, [before["z"], after["z"]])
|
||||
check("set_params keeps the mesh datablock, transform, parent, Bevel and the assigned material", before["parent"] == "P_plate"
|
||||
and before["materials"] == ["Tank Paint"] and before["modifiers"] == ["Kit Bevel"]
|
||||
and {k: v for k, v in after.items() if k != "z"} == {k: v for k, v in before.items() if k != "z"} and not tank.data.validate(verbose=False), [before, after])
|
||||
check("set_params stores the merged params and reports them", grown and json.loads(tank["kit_params"]) == grown["params"]
|
||||
== {"radius": 0.22, "length": 1.8, "segments": 24}, grown)
|
||||
receipt, wide = send("brokkr_kitbash.set_params", object_name="P_tank", params="radius=0.3; segments=12")
|
||||
check("set_params overlays the stored params, and the Bevel width follows the part's bevel", wide and wide["params"] == {"radius": 0.3, "length": 1.8, "segments": 12}
|
||||
and abs(tank.modifiers["Kit Bevel"].width - 0.008 * 0.3) < 1e-7 and len(tank.data.polygons) == len(core.build(kit["parts"]["tank"], wide["params"]).counts),
|
||||
[wide and wide["params"], tank.modifiers["Kit Bevel"].width])
|
||||
|
||||
# --- report: sockets in the world -------------------------------------------------------------------------------------------
|
||||
send("setObjectTransform", targetObjectName="P_pipe_fitting", location=[-2.0, 0.5, 1.0], rotationEuler=[1.1, 0.4, -0.7])
|
||||
receipt, reported = send("brokkr_kitbash.report") # straight after the move, before anything here updates the view layer: the frames are already the moved ones
|
||||
bpy.context.view_layer.update()
|
||||
worst, listed = 0.0, []
|
||||
for entry in (reported or {}).get("parts", []):
|
||||
obj = bpy.data.objects[entry["object"]]
|
||||
listed.append(entry["object"])
|
||||
local = core.build(core.part(kit, entry["part"]), entry["params"]).sockets
|
||||
world = np.array(obj.matrix_world)
|
||||
for socket, mine in zip(entry["sockets"], local):
|
||||
worst = max(worst, float(np.abs(np.array(socket["matrix"]) - world @ mine["matrix"]).max()))
|
||||
check("report lists every kit part with socket frames equal to matrix_world times the local frame", receipt["status"] == "accepted"
|
||||
and listed == sorted(f"P_{n}" for n in names) and worst < 1e-6, [listed, worst])
|
||||
receipt, single = send("brokkr_kitbash.report", object_name="P_tank")
|
||||
tank_world = np.array(tank.matrix_world)
|
||||
check("report of the parented, rotated tank carries its parent's and its own transform", single and len(single["parts"]) == 1
|
||||
and single["parts"][0]["params"] == wide["params"] and single["parts"][0]["faces"] == len(tank.data.polygons)
|
||||
and np.abs(np.array(single["parts"][0]["sockets"][2]["matrix"]) - tank_world @ core.build(kit["parts"]["tank"], wide["params"]).sockets[2]["matrix"]).max() < 1e-6
|
||||
and np.abs(tank_world[:3, 3] - [1.0, 2.0, 3.0]).max() < 1e-6, single)
|
||||
|
||||
# --- per-face materials ride on the part's shapes ----------------------------------------------------------------------------
|
||||
strut = bpy.data.objects["P_strut"]
|
||||
send("assignMaterial", targetObjectName="P_strut", materialName="Strut Paint", color=[0.35, 0.35, 0.35])
|
||||
strut.data.materials.append(bpy.data.materials.new("Pin Steel"))
|
||||
PINS = 2 # the strut's third shape: the repeat of two pins
|
||||
was = core.build(kit["parts"]["strut"])
|
||||
strut.data.polygons.foreach_set("material_index", np.where(was.shape == PINS, 1, 0).astype(np.int32))
|
||||
receipt, _ = send("brokkr_kitbash.set_params", object_name="P_strut", params="segments=12; length=1.2")
|
||||
now = core.build(kit["parts"]["strut"], {"segments": 12, "length": 1.2})
|
||||
index = np.zeros(len(strut.data.polygons), dtype=np.int32)
|
||||
strut.data.polygons.foreach_get("material_index", index)
|
||||
check("set_params with other segments keeps each shape's material: the pins stay Pin Steel, the rest Strut Paint", receipt["status"] == "accepted"
|
||||
and len(now.counts) != len(was.counts) and index.tolist() == np.where(now.shape == PINS, 1, 0).tolist() and int(index.sum()) == 2 * (12 + 2)
|
||||
and [s.material.name for s in strut.material_slots] == ["Strut Paint", "Pin Steel"], [receipt["message"], int(index.sum()), len(index)])
|
||||
|
||||
# --- refusals leave the scene as it was --------------------------------------------------------------------------------------
|
||||
bpy.ops.mesh.primitive_cube_add()
|
||||
bpy.context.active_object.name = "Plain"
|
||||
twin = bpy.data.objects["P_vent"].copy() # a linked duplicate: one mesh, two objects, each with its own kit_params
|
||||
twin.name = "P_vent_twin"
|
||||
bpy.context.scene.collection.objects.link(twin)
|
||||
send("setObjectTransform", targetObjectName="P_radiator_stack", scale=[2.0, 2.0, 2.0])
|
||||
send("setObjectTransform", targetObjectName="P_actuator", scale=[-1.0, 1.0, 1.0])
|
||||
|
||||
|
||||
def scene_state():
|
||||
return (sorted(o.name for o in bpy.data.objects), sorted(m.name for m in bpy.data.meshes),
|
||||
{o.name: (len(o.data.polygons), o.get("kit_params")) for o in bpy.data.objects})
|
||||
|
||||
|
||||
state = scene_state()
|
||||
refusals = [
|
||||
("an unknown kit", "brokkr_kitbash.place_part", {"kit": "hydraulic", "part": "tank", "object_name": "X"}, "no kit named 'hydraulic'"),
|
||||
("a kit name that spells a path", "brokkr_kitbash.place_part", {"kit": "../x", "part": "tank", "object_name": "X"}, "kit"),
|
||||
("a kit name with a dot", "brokkr_kitbash.place_part", {"kit": "mechanical.v0", "part": "tank", "object_name": "X"}, "must be 1 to 32 of"),
|
||||
("an unknown part", "brokkr_kitbash.place_part", {"part": "wing", "object_name": "X"}, "has no part 'wing'"),
|
||||
("an out-of-range param", "brokkr_kitbash.place_part", {"part": "tank", "object_name": "X", "params": "radius=5"}, "param 'radius' = 5.0 is outside [0.12, 0.35]"),
|
||||
("a fraction for an integer param", "brokkr_kitbash.place_part", {"part": "tank", "object_name": "X", "params": "segments=12.5"}, "is an integer"),
|
||||
("an existing name", "brokkr_kitbash.place_part", {"part": "tank", "object_name": "P_plate"}, "An object named 'P_plate' exists"),
|
||||
("set_params on a plain mesh", "brokkr_kitbash.set_params", {"object_name": "Plain", "params": "length=1"}, "is not a kit part"),
|
||||
("set_params with an unknown param", "brokkr_kitbash.set_params", {"object_name": "P_tank", "params": "girth=1"}, "has no param 'girth'"),
|
||||
("set_params out of range", "brokkr_kitbash.set_params", {"object_name": "P_tank", "params": "length=0.1"}, "is outside [0.6, 2.0]"),
|
||||
("set_params with a repeated key", "brokkr_kitbash.set_params", {"object_name": "P_tank", "params": "length=1; length=1.2"}, "'length' is given twice"),
|
||||
("report of a plain mesh", "brokkr_kitbash.report", {"object_name": "Plain"}, "is not a kit part"),
|
||||
("set_params on a mesh a linked duplicate shares", "brokkr_kitbash.set_params", {"object_name": "P_vent", "params": "slats=9"}, "shares its mesh 'P_vent' with 1 other user"),
|
||||
("set_params on the linked duplicate", "brokkr_kitbash.set_params", {"object_name": "P_vent_twin", "params": "slats=9"}, "shares its mesh 'P_vent' with 1 other user"),
|
||||
("report of a scaled part", "brokkr_kitbash.report", {"object_name": "P_radiator_stack"}, "'P_radiator_stack' is scaled, mirrored or sheared in the world (scale 2, 2, 2)"),
|
||||
("set_params on a scaled part", "brokkr_kitbash.set_params", {"object_name": "P_radiator_stack", "params": "fins=5"}, "is scaled, mirrored or sheared"),
|
||||
("report of a mirrored part", "brokkr_kitbash.report", {"object_name": "P_actuator"}, "'P_actuator' is scaled, mirrored or sheared"),
|
||||
("report of every part while one is scaled", "brokkr_kitbash.report", {}, "is scaled, mirrored or sheared"),
|
||||
("describe of an unknown part", "brokkr_kitbash.describe", {"part": "wing"}, "has no part 'wing'"),
|
||||
]
|
||||
for label, action, fields, expected in refusals:
|
||||
receipt, _ = send(action, **fields)
|
||||
check(f"refused, scene unchanged: {label}", receipt["status"] != "accepted" and expected in str(receipt["message"]) and scene_state() == state,
|
||||
[receipt["status"], receipt["message"]])
|
||||
|
||||
bpy.data.objects.remove(twin)
|
||||
send("setObjectTransform", targetObjectName="P_radiator_stack", scale=[1.0, 1.0, 1.0])
|
||||
send("setObjectTransform", targetObjectName="P_actuator", scale=[1.0, 1.0, 1.0])
|
||||
receipt, alone = send("brokkr_kitbash.set_params", object_name="P_vent", params="slats=9")
|
||||
check("with the duplicate gone the vent's mesh is its own again and set_params rebuilds it", receipt["status"] == "accepted" and alone
|
||||
and alone["params"]["slats"] == 9 and len(bpy.data.objects["P_vent"].data.polygons) == len(core.build(kit["parts"]["vent"], {"slats": 9}).counts), receipt["message"])
|
||||
receipt, whole = send("brokkr_kitbash.report")
|
||||
check("with scale back at 1 every part reports again", receipt["status"] == "accepted" and whole and len(whole["parts"]) == 9, receipt["message"])
|
||||
|
||||
# --- export ---------------------------------------------------------------------------------------------------------------
|
||||
receipt, _ = send("exportGltf", filepath="kit.glb", extras=False, yUp=True, applyModifiers=True, selection=[f"P_{n}" for n in names])
|
||||
glb = WORK / "kit.glb"
|
||||
meshes = -1
|
||||
if glb.is_file():
|
||||
blob = glb.read_bytes()
|
||||
meshes = len(json.loads(blob[20:20 + int.from_bytes(blob[12:16], "little")]).get("meshes", []))
|
||||
check("exportGltf of all nine parts succeeds", receipt["status"] == "accepted" and meshes == 9, [receipt["message"], meshes])
|
||||
|
||||
R["placed"] = {name: {"faces": report["faces"], "shells": report["shells"], "bevel": report["bevel"], "sockets": [s["name"] for s in report["sockets"]]}
|
||||
for name, report in placed.items() if report}
|
||||
R["ok"] = all(c["ok"] for c in R["checks"])
|
||||
Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8")
|
||||
for c in R["checks"]:
|
||||
print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True)
|
||||
sys.exit(0 if R["ok"] else 1)
|
||||
407
surfaces/blender/tests/live/kitbash.result.json
Normal file
407
surfaces/blender/tests/live/kitbash.result.json
Normal file
|
|
@ -0,0 +1,407 @@
|
|||
{
|
||||
"blender": "5.3.0",
|
||||
"checks": [
|
||||
{
|
||||
"name": "the four kitbash rows load as host actions with no errors",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "describe lists nine parts, whole, inside a receipt",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "describe of one part gives its params and its sockets at default params",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "describe changes nothing",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "place_part nozzle: core's faces, a valid mesh, core's flat faces, at the origin",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "place_part nozzle: a Bevel of the part's width, 2 segments, angle 30, that evaluates",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "place_part nozzle: kit, part and every resolved param stored on the object, sockets reported in the part frame",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "place_part tank: core's faces, a valid mesh, core's flat faces, at the origin",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "place_part tank: a Bevel of the part's width, 2 segments, angle 30, that evaluates",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "place_part tank: kit, part and every resolved param stored on the object, sockets reported in the part frame",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "place_part ribbed_cylinder: core's faces, a valid mesh, core's flat faces, at the origin",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "place_part ribbed_cylinder: a Bevel of the part's width, 2 segments, angle 30, that evaluates",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "place_part ribbed_cylinder: kit, part and every resolved param stored on the object, sockets reported in the part frame",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "place_part strut: core's faces, a valid mesh, core's flat faces, at the origin",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "place_part strut: a Bevel of the part's width, 2 segments, angle 30, that evaluates",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "place_part strut: kit, part and every resolved param stored on the object, sockets reported in the part frame",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "place_part actuator: core's faces, a valid mesh, core's flat faces, at the origin",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "place_part actuator: a Bevel of the part's width, 2 segments, angle 30, that evaluates",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "place_part actuator: kit, part and every resolved param stored on the object, sockets reported in the part frame",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "place_part pipe_fitting: core's faces, a valid mesh, core's flat faces, at the origin",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "place_part pipe_fitting: a Bevel of the part's width, 2 segments, angle 30, that evaluates",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "place_part pipe_fitting: kit, part and every resolved param stored on the object, sockets reported in the part frame",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "place_part radiator_stack: core's faces, a valid mesh, core's flat faces, at the origin",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "place_part radiator_stack: a Bevel of the part's width, 2 segments, angle 30, that evaluates",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "place_part radiator_stack: kit, part and every resolved param stored on the object, sockets reported in the part frame",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "place_part vent: core's faces, a valid mesh, core's flat faces, at the origin",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "place_part vent: a Bevel of the part's width, 2 segments, angle 30, that evaluates",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "place_part vent: kit, part and every resolved param stored on the object, sockets reported in the part frame",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "place_part plate: core's faces, a valid mesh, core's flat faces, at the origin",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "place_part plate: a Bevel of the part's width, 2 segments, angle 30, that evaluates",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "place_part plate: kit, part and every resolved param stored on the object, sockets reported in the part frame",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "nine parts are nine mesh objects",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "set_params doubling the tank's length doubles its z extent",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "set_params keeps the mesh datablock, transform, parent, Bevel and the assigned material",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "set_params stores the merged params and reports them",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "set_params overlays the stored params, and the Bevel width follows the part's bevel",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "report lists every kit part with socket frames equal to matrix_world times the local frame",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "report of the parented, rotated tank carries its parent's and its own transform",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "set_params with other segments keeps each shape's material: the pins stay Pin Steel, the rest Strut Paint",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: an unknown kit",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: a kit name that spells a path",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: a kit name with a dot",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: an unknown part",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: an out-of-range param",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: a fraction for an integer param",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: an existing name",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: set_params on a plain mesh",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: set_params with an unknown param",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: set_params out of range",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: set_params with a repeated key",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: report of a plain mesh",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: set_params on a mesh a linked duplicate shares",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: set_params on the linked duplicate",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: report of a scaled part",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: set_params on a scaled part",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: report of a mirrored part",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: report of every part while one is scaled",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: describe of an unknown part",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "with the duplicate gone the vent's mesh is its own again and set_params rebuilds it",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "with scale back at 1 every part reports again",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "exportGltf of all nine parts succeeds",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
}
|
||||
],
|
||||
"hostErrors": [],
|
||||
"hostRows": [
|
||||
"brokkr_mesh_polish.audit",
|
||||
"brokkr_mesh_polish.repair",
|
||||
"brokkr_mesh_polish.orient",
|
||||
"brokkr_mesh_polish.delight",
|
||||
"brokkr_mesh_polish.scrub_markings",
|
||||
"brokkr_mesh_polish.cut_parts",
|
||||
"brokkr_mesh_polish.pick",
|
||||
"brokkr_kitbash.place_part",
|
||||
"brokkr_kitbash.set_params",
|
||||
"brokkr_kitbash.describe",
|
||||
"brokkr_kitbash.report"
|
||||
],
|
||||
"placed": {
|
||||
"nozzle": {
|
||||
"faces": 1312,
|
||||
"shells": 24,
|
||||
"bevel": 0.0024,
|
||||
"sockets": [
|
||||
"mount"
|
||||
]
|
||||
},
|
||||
"tank": {
|
||||
"faces": 740,
|
||||
"shells": 20,
|
||||
"bevel": 0.00176,
|
||||
"sockets": [
|
||||
"port_a",
|
||||
"port_b",
|
||||
"saddle"
|
||||
]
|
||||
},
|
||||
"ribbed_cylinder": {
|
||||
"faces": 376,
|
||||
"shells": 18,
|
||||
"bevel": 0.00225,
|
||||
"sockets": [
|
||||
"end_a",
|
||||
"end_b"
|
||||
]
|
||||
},
|
||||
"strut": {
|
||||
"faces": 100,
|
||||
"shells": 10,
|
||||
"bevel": 0.0015,
|
||||
"sockets": [
|
||||
"end_a",
|
||||
"end_b"
|
||||
]
|
||||
},
|
||||
"actuator": {
|
||||
"faces": 238,
|
||||
"shells": 15,
|
||||
"bevel": 0.0024,
|
||||
"sockets": [
|
||||
"base",
|
||||
"rod_end"
|
||||
]
|
||||
},
|
||||
"pipe_fitting": {
|
||||
"faces": 278,
|
||||
"shells": 19,
|
||||
"bevel": 0.0027,
|
||||
"sockets": [
|
||||
"a",
|
||||
"b",
|
||||
"c"
|
||||
]
|
||||
},
|
||||
"radiator_stack": {
|
||||
"faces": 142,
|
||||
"shells": 17,
|
||||
"bevel": 0.001,
|
||||
"sockets": [
|
||||
"base"
|
||||
]
|
||||
},
|
||||
"vent": {
|
||||
"faces": 66,
|
||||
"shells": 11,
|
||||
"bevel": 0.00125,
|
||||
"sockets": [
|
||||
"back"
|
||||
]
|
||||
},
|
||||
"plate": {
|
||||
"faces": 44,
|
||||
"shells": 6,
|
||||
"bevel": 0.0015,
|
||||
"sockets": [
|
||||
"back",
|
||||
"front"
|
||||
]
|
||||
}
|
||||
},
|
||||
"ok": true
|
||||
}
|
||||
457
surfaces/blender/tests/test_kitbash.py
Normal file
457
surfaces/blender/tests/test_kitbash.py
Normal file
|
|
@ -0,0 +1,457 @@
|
|||
"""Kitbash tests. No Blender: the kit format and geometry in brokkr_kitbash/core.py, the mechanical kit at every
|
||||
corner of its params, and the host action file against Brokkr's own checker.
|
||||
|
||||
Run: python3 -m unittest discover -s surfaces/blender/tests -v (needs numpy; skipped without it)
|
||||
The operators are exercised in a real Blender by tests/live/kitbash.py.
|
||||
|
||||
Bounds follow lodur:ruling:deterministic-bound-margin: a deterministic reading is exact here, so each assertion is
|
||||
the built value, and each names the mutant it kills.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import importlib.util
|
||||
import json
|
||||
import math
|
||||
import random
|
||||
import re
|
||||
import sys
|
||||
import types
|
||||
import unittest
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
|
||||
SURFACE = Path(__file__).resolve().parents[1]
|
||||
package = types.ModuleType("brokkr_bridge")
|
||||
package.__path__ = [str(SURFACE / "brokkr_bridge")]
|
||||
sys.modules.setdefault("brokkr_bridge", package)
|
||||
from brokkr_bridge import action_table as at # noqa: E402
|
||||
|
||||
try:
|
||||
import numpy as np
|
||||
except ImportError: # pragma: no cover
|
||||
np = None
|
||||
|
||||
if np is not None:
|
||||
spec = importlib.util.spec_from_file_location("brokkr_kitbash_core", SURFACE / "brokkr_kitbash" / "core.py")
|
||||
core = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(core)
|
||||
|
||||
|
||||
def param(name, low=0.0, high=10.0, default=1.0, kind="number"):
|
||||
return {"name": name, "type": kind, "min": low, "max": high, "default": default, "doc": ""}
|
||||
|
||||
|
||||
def document(shapes=None, params=(), sockets=(), **extra):
|
||||
"""A kit of one part 'p'."""
|
||||
part = {"name": "p", "doc": "", "params": list(params), "shapes": shapes or [{"shape": "box", "size": [1, 1, 1]}],
|
||||
"sockets": list(sockets), **extra}
|
||||
return {"schema": "brokkr.kit.v0", "kit": "t", "doc": "", "socketTypes": {"mount": {"match": "fits", "doc": ""}}, "parts": [part]}
|
||||
|
||||
|
||||
def built(shapes, params=(), given=None):
|
||||
return core.build(core.part(core.check_kit(document(shapes, params)), "p"), given or {})
|
||||
|
||||
|
||||
def faces_of(b):
|
||||
start = 0
|
||||
for count in b.counts:
|
||||
yield b.faces[start:start + count]
|
||||
start += count
|
||||
|
||||
|
||||
def closed_and_oriented(b) -> bool:
|
||||
"""Every directed edge exactly once, with its reverse exactly once."""
|
||||
edges = Counter()
|
||||
for face in faces_of(b):
|
||||
for i in range(len(face)):
|
||||
edges[(int(face[i]), int(face[(i + 1) % len(face)]))] += 1
|
||||
return all(n == 1 and edges.get((v, u)) == 1 for (u, v), n in edges.items())
|
||||
|
||||
|
||||
def signed_volume(b) -> float:
|
||||
total = 0.0
|
||||
for face in faces_of(b):
|
||||
p = b.V[face]
|
||||
for i in range(1, len(face) - 1):
|
||||
total += float(np.dot(p[0], np.cross(p[i], p[i + 1]))) / 6.0
|
||||
return total
|
||||
|
||||
|
||||
def frustum(r0, r1, h, n) -> float:
|
||||
a0, a1 = (0.5 * n * r * r * math.sin(2 * math.pi / n) for r in (r0, r1))
|
||||
return h / 3.0 * (a0 + a1 + math.sqrt(a0 * a1))
|
||||
|
||||
|
||||
def point_triangle(p, a, b, c) -> float:
|
||||
"""Distance from p to triangle abc (Ericson, Real-Time Collision Detection 5.1.5)."""
|
||||
ab, ac, ap = b - a, c - a, p - a
|
||||
d1, d2 = ab @ ap, ac @ ap
|
||||
if d1 <= 0 and d2 <= 0:
|
||||
return float(np.linalg.norm(ap))
|
||||
bp = p - b
|
||||
d3, d4 = ab @ bp, ac @ bp
|
||||
if d3 >= 0 and d4 <= d3:
|
||||
return float(np.linalg.norm(bp))
|
||||
vc = d1 * d4 - d3 * d2
|
||||
if vc <= 0 and d1 >= 0 and d3 <= 0:
|
||||
return float(np.linalg.norm(ap - ab * (d1 / (d1 - d3))))
|
||||
cp = p - c
|
||||
d5, d6 = ab @ cp, ac @ cp
|
||||
if d6 >= 0 and d5 <= d6:
|
||||
return float(np.linalg.norm(cp))
|
||||
vb = d5 * d2 - d1 * d6
|
||||
if vb <= 0 and d2 >= 0 and d6 <= 0:
|
||||
return float(np.linalg.norm(ap - ac * (d2 / (d2 - d6))))
|
||||
va = d3 * d6 - d5 * d4
|
||||
if va <= 0 and d4 - d3 >= 0 and d5 - d6 >= 0:
|
||||
return float(np.linalg.norm(bp - (c - b) * ((d4 - d3) / ((d4 - d3) + (d5 - d6)))))
|
||||
normal = np.cross(ab, ac)
|
||||
return float(abs(ap @ normal) / np.linalg.norm(normal))
|
||||
|
||||
|
||||
def socket_seat(b, socket) -> float:
|
||||
"""Distance from the socket's origin to the nearest face whose normal is the socket's z (inf when none faces it)."""
|
||||
origin, z = socket["matrix"][:3, 3], socket["matrix"][:3, 2]
|
||||
best = math.inf
|
||||
for face in faces_of(b):
|
||||
p = b.V[face]
|
||||
normal = np.cross(p[1] - p[0], p[2] - p[0])
|
||||
normal /= np.linalg.norm(normal)
|
||||
if np.abs(normal - z).max() > 1e-6:
|
||||
continue
|
||||
best = min([best] + [point_triangle(origin, p[0], p[i], p[i + 1]) for i in range(1, len(face) - 1)])
|
||||
return best
|
||||
|
||||
|
||||
@unittest.skipIf(np is None, "numpy is not installed")
|
||||
class ExpressionTests(unittest.TestCase):
|
||||
def test_the_whitelist_evaluates_exactly_and_refuses_the_rest(self):
|
||||
"""expr-whitelist. Mutant M1 (drop the call-name check): pow(a,b) is admitted (abs(a) still dies on its one
|
||||
argument, so the two-argument call is the witness)."""
|
||||
env = {"a": 1.5, "b": 0.25}
|
||||
self.assertEqual(core.parse("2*(a+b)-min(a,3)/4", env, "t").value(env), 2 * (1.5 + 0.25) - 1.5 / 4)
|
||||
self.assertEqual(core.parse("-a+max(b,-2)", env, "t").value(env), -1.25)
|
||||
self.assertEqual(core.parse("+a", env, "t").value(env), 1.5)
|
||||
self.assertEqual(core.parse(3, env, "t").value(env), 3.0)
|
||||
for text in ("a.real", "a[0]", "a**2", "a<b", "abs(a)", "pow(a,b)", "getattr(a,b)", "min(a)", "min(a,b,c)", "min(a=1,b=2)", "lambda: a",
|
||||
"__import__('os')", "c", "'a'", "True", "a if b else a", "a +", "min", "(a).__class__", "min(*[a,b])"):
|
||||
with self.assertRaises(core.KitError, msg=text) as caught:
|
||||
core.check_kit(document([{"shape": "box", "size": [text, 1, 1]}], [param("a"), param("b")]))
|
||||
self.assertIn("'p'", str(caught.exception))
|
||||
self.assertIn("size[0]", str(caught.exception))
|
||||
for value in (True, None, [1], float("inf")):
|
||||
with self.assertRaises(core.KitError):
|
||||
core.parse(value, env, "t")
|
||||
|
||||
def test_division_by_zero_is_a_build_refusal_naming_the_expression(self):
|
||||
kit = core.check_kit(document([{"shape": "box", "size": ["1/(a-1)", 1, 1]}], [param("a")]))
|
||||
with self.assertRaisesRegex(core.KitError, r"division by zero in '1/\(a-1\)'"):
|
||||
core.build(core.part(kit, "p"))
|
||||
self.assertEqual(float(np.ptp(core.build(core.part(kit, "p"), {"a": 3}).V[:, 0])), 0.5)
|
||||
|
||||
def test_a_value_no_float_holds_is_refused_by_name(self):
|
||||
"""Mutant N4 (finite check dropped in Expr.value): 1e308*a at a=10 is inf and is no longer refused there."""
|
||||
part = core.part(core.check_kit(document([{"shape": "box", "size": ["1e308*a", 1, "a*" + "9" * 400]}], [param("a", 0, 10, 0)])), "p")
|
||||
with self.assertRaisesRegex(core.KitError, r"part 'p' shape 0 \(box\) size\[0\]: '1e308\*a' is not a finite number"):
|
||||
core.build(part, {"a": 10})
|
||||
with self.assertRaisesRegex(core.KitError, r"size\[2\]: 'a\*9+' is not a finite number"): # an integer literal no float holds
|
||||
core.build(part, {"a": 1e-300})
|
||||
for doc, message in ((document([{"shape": "box", "size": [10 ** 400, 1, 1]}]), r"size\[0\]: 1000\d+ is not a finite number"),
|
||||
(document(params=[param("a", 0, 10 ** 400, 1)]), r"param 'a' max must be a finite number")):
|
||||
with self.assertRaisesRegex(core.KitError, message):
|
||||
core.check_kit(doc)
|
||||
with self.assertRaisesRegex(core.KitError, r"param 'a' must be a finite number"):
|
||||
core.resolve_params(part, {"a": 10 ** 400})
|
||||
far = core.part(core.check_kit(document([{"shape": "box", "size": [1, 1, 1]}, {"shape": "box", "size": [1e308, 1, 1], "at": [1.5e308, 0, 0]}])), "p")
|
||||
with self.assertRaisesRegex(core.KitError, r"part 'p' shape 1 \(box\): its vertices are not finite"): # each number finite, their sum not
|
||||
core.build(far)
|
||||
|
||||
def test_a_socket_size_is_above_zero_and_a_bevel_is_not_negative(self):
|
||||
"""Mutants N8 (socket size <= 0 allowed) and N9 (negative bevel allowed)."""
|
||||
socket = {"name": "s", "type": "mount", "size": "a-1", "at": [0, 0, 0], "z": "+z", "y": "+y"}
|
||||
part = core.part(core.check_kit(document(params=[param("a")], sockets=[socket], bevel="2-a")), "p")
|
||||
self.assertEqual((core.build(part, {"a": 2}).sockets[0]["size"], core.build(part, {"a": 2}).bevel), (1.0, 0.0))
|
||||
for a in (1.0, 0.5):
|
||||
with self.assertRaisesRegex(core.KitError, r"part 'p' socket 's' size is -?0\.\d: a socket's size must be above 0"):
|
||||
core.build(part, {"a": a})
|
||||
with self.assertRaisesRegex(core.KitError, r"part 'p' bevel is -1\.0: a bevel is 0 or more"):
|
||||
core.build(part, {"a": 3})
|
||||
|
||||
|
||||
@unittest.skipIf(np is None, "numpy is not installed")
|
||||
class CheckKitTests(unittest.TestCase):
|
||||
def test_each_refusal_names_the_part_and_field(self):
|
||||
"""check-kit-refusals. Mutant M2 (skip the unknown-key check): the 'colour' and 'radius' documents are admitted."""
|
||||
socket = {"name": "s", "type": "mount", "size": 1, "at": [0, 0, 0], "z": "+z", "y": "+y"}
|
||||
box = {"shape": "box", "size": [1, 1, 1]}
|
||||
cases = [
|
||||
({**document(), "schema": "brokkr.kit.v1"}, r"schema must be brokkr\.kit\.v0"),
|
||||
({**document(), "colour": 1}, r"kit has no key 'colour'"),
|
||||
(document([{**box, "radius": 1}]), r"part 'p' shape 0 \(box\) has no key 'radius'"),
|
||||
(document(sockets=[socket, socket]), r"part 'p' socket 1: 's' is listed twice"),
|
||||
(document(params=[param("a"), param("a")]), r"part 'p' param 1: 'a' is listed twice"),
|
||||
(document(params=[param("a", 0, 1, 2)]), r"part 'p' param 'a': default 2 is outside \[0, 1\]"),
|
||||
(document(params=[param("a", 0.5, 3, 1, "integer")]), r"part 'p' param 'a': an integer param's min must be whole, not 0\.5"),
|
||||
(document(params=[param("a", 0, 3, 1.5, "integer")]), r"part 'p' param 'a': an integer param's default must be whole"),
|
||||
(document(sockets=[{**socket, "type": "flange"}]), r"part 'p' socket 's': type 'flange' is not one of the kit's socketTypes"),
|
||||
(document([{"shape": "sphere", "r": 1}]), r"part 'p' shape 0: unknown shape 'sphere'"),
|
||||
(document([{"shape": "repeat", "count": 2, "step": [1, 0, 0], "of": {"shape": "repeat", "count": 2, "step": [0, 1, 0], "of": box}}]),
|
||||
r"part 'p' shape 0 \(repeat\) of \(repeat\): a repeat cannot hold a repeat"),
|
||||
(document(sockets=[{**socket, "y": "-z"}]), r"part 'p' socket 's': z \(\+z\) and y \(-z\) lie on the same axis"),
|
||||
(document([{**box, "size": ["a+", 1, 1]}]), r"part 'p' shape 0 \(box\) size\[0\]: 'a\+' does not parse"),
|
||||
(document([{**box, "size": ["width", 1, 1]}], [param("a")]), r"part 'p' shape 0 \(box\) size\[0\]: 'width' names 'width'"),
|
||||
(document(params=[param("min")]), r"part 'p' param 0: 'min' is not a name"),
|
||||
(document(bevel="a.b"), r"part 'p' bevel: 'a\.b' uses Attribute"),
|
||||
(document(sockets=[{**socket, "type": ["mount"]}]), r"part 'p' socket 's': type \['mount'\] is not one of"), # unhashable where a name belongs
|
||||
(document(sockets=[{**socket, "z": {}}]), r"part 'p' socket 's': z must be one of"),
|
||||
(document([{"shape": ["box"], "size": [1, 1, 1]}]), r"part 'p' shape 0: unknown shape \['box'\]"),
|
||||
(document(sockets=[{**socket, "at": [0, 0, 10 ** 400]}]), r"part 'p' socket 's' at\[2\]: 1000\d+ is not a finite number"),
|
||||
]
|
||||
for doc, message in cases:
|
||||
with self.assertRaisesRegex(core.KitError, message):
|
||||
core.check_kit(doc)
|
||||
two = document()
|
||||
two["parts"].append(copy.deepcopy(two["parts"][0]))
|
||||
with self.assertRaisesRegex(core.KitError, r"kit 't' part 1: 'p' is listed twice"):
|
||||
core.check_kit(two)
|
||||
self.assertEqual(list(core.check_kit(document())["parts"]), ["p"])
|
||||
|
||||
def test_a_kit_name_cannot_spell_a_path(self):
|
||||
for name in ("../x", "mechanical.v0", "Mechanical", "", "a/b", "x" * 33, 3):
|
||||
with self.assertRaisesRegex(core.KitError, "must be 1 to 32 of"):
|
||||
core.load_kit(name)
|
||||
with self.assertRaisesRegex(core.KitError, "no kit named 'absent'; kits: mechanical"):
|
||||
core.load_kit("absent")
|
||||
with self.assertRaisesRegex(core.KitError, "has no part 'wing'; its parts: nozzle, tank"):
|
||||
core.part(core.load_kit("mechanical"), "wing")
|
||||
|
||||
|
||||
@unittest.skipIf(np is None, "numpy is not installed")
|
||||
class ShapeTests(unittest.TestCase):
|
||||
def test_tubes_are_closed_oriented_and_hold_their_volume(self):
|
||||
"""tube-closed-oriented. Mutants M3 (inner wall not reversed) and M4 (solid tube without its top cap) break
|
||||
the edge census; M5 (r0 and r1 swapped) puts the z=0 ring at r1; N10 (inner0 and inner1 swapped) puts the
|
||||
z=0 inner ring at inner1, which volume and the census cannot see."""
|
||||
for n in (3, 32):
|
||||
solid = built([{"shape": "tube", "r0": 0.5, "r1": 0.3, "length": 2.0, "segments": n}])
|
||||
hollow = built([{"shape": "tube", "r0": 0.5, "r1": 0.3, "inner0": 0.2, "inner1": 0.1, "length": 2.0, "segments": n, "smooth": True}])
|
||||
for b, expected, faces in ((solid, frustum(0.5, 0.3, 2.0, n), n + 2),
|
||||
(hollow, frustum(0.5, 0.3, 2.0, n) - frustum(0.2, 0.1, 2.0, n), 4 * n)):
|
||||
self.assertTrue(closed_and_oriented(b))
|
||||
self.assertLess(abs(signed_volume(b) - expected), 1e-9 * expected)
|
||||
self.assertEqual((len(b.counts), b.shell_count), (faces, 1))
|
||||
low = b.V[np.abs(b.V[:, 2]) < 1e-12]
|
||||
self.assertTrue(np.allclose(np.linalg.norm(low[:n, :2], axis=1), 0.5, atol=1e-12))
|
||||
self.assertEqual(float(b.V[:, 2].max()), 2.0)
|
||||
for rows_, radius, z in ((slice(2 * n, 3 * n), 0.2, 0.0), (slice(3 * n, 4 * n), 0.1, 2.0)):
|
||||
self.assertTrue(np.allclose(np.linalg.norm(hollow.V[rows_, :2], axis=1), radius, atol=1e-12))
|
||||
self.assertTrue((hollow.V[rows_, 2] == z).all())
|
||||
self.assertEqual(solid.smooth.tolist(), [False] * (n + 2))
|
||||
self.assertEqual(hollow.smooth.tolist(), [True] * (2 * n) + [False] * (2 * n)) # both walls smooth, both end rings flat
|
||||
tube = {"shape": "tube", "r0": 1, "r1": 1, "length": 1, "segments": 8}
|
||||
for change, message in (({"inner0": 1}, "0 <= inner < outer"), ({"inner1": -0.1}, "0 <= inner < outer"), ({"length": 0}, "length 0.0 must be above 0"),
|
||||
({"segments": 2}, "whole number from 3 to 128"), ({"segments": 129}, "whole number from 3 to 128"),
|
||||
({"segments": 8.5}, "whole number from 3 to 128"), ({"inner0": 0.5}, "both be above 0")):
|
||||
with self.assertRaisesRegex(core.KitError, message):
|
||||
built([{**tube, **change}])
|
||||
with self.assertRaisesRegex(core.KitError, "every size must be above 0"):
|
||||
built([{"shape": "box", "size": [1, 0, 1]}])
|
||||
|
||||
def test_a_shape_is_rotated_about_its_own_origin_and_then_placed(self):
|
||||
"""transform-order. Mutant M6 (translate before rotating): the box lands around (0, 1, 0)."""
|
||||
b = built([{"shape": "box", "size": [2, 1, 1], "rot": [0, 0, 90], "at": [1, 0, 0]}])
|
||||
self.assertTrue(np.allclose(b.V.min(axis=0), [0.5, -1.0, -0.5], atol=1e-12))
|
||||
self.assertTrue(np.allclose(b.V.max(axis=0), [1.5, 1.0, 0.5], atol=1e-12))
|
||||
self.assertTrue(closed_and_oriented(b))
|
||||
self.assertLess(abs(signed_volume(b) - 2.0), 1e-12)
|
||||
up = built([{"shape": "tube", "r0": 1, "r1": 1, "length": 3, "segments": 8, "rot": [-90, 0, 0]}]) # XYZ Euler: +z turns to +y
|
||||
self.assertTrue(np.allclose([up.V[:, 1].min(), up.V[:, 1].max()], [0.0, 3.0], atol=1e-12))
|
||||
both = built([{"shape": "tube", "r0": 1, "r1": 1, "length": 3, "segments": 8, "rot": [-90, 0, 90]}]) # x first, then z: +y turns on to -x
|
||||
self.assertTrue(np.allclose([both.V[:, 0].min(), both.V[:, 0].max()], [-3.0, 0.0], atol=1e-12))
|
||||
|
||||
def test_repeat_places_count_copies_a_step_apart(self):
|
||||
"""repeat-places-copies. Mutant M7 (ignore step): every copy's centroid is the first's."""
|
||||
shape = {"shape": "repeat", "count": "n", "step": [0.5, 0, "2*a"], "of": {"shape": "box", "size": [1, 1, 1], "at": [1, 2, 3]}}
|
||||
b = built([shape], [param("n", 1, 300, 4), param("a")])
|
||||
self.assertEqual(b.shell_count, 4)
|
||||
centroids = b.V.reshape(4, 8, 3).mean(axis=1)
|
||||
self.assertTrue(np.allclose(centroids, [[1 + 0.5 * k, 2, 3 + 2.0 * k] for k in range(4)], atol=1e-12))
|
||||
self.assertTrue(closed_and_oriented(b))
|
||||
for count in (0, 257, 2.5):
|
||||
with self.assertRaisesRegex(core.KitError, "count is .*whole number from 1 to 256"):
|
||||
built([shape], [param("n", 0, 300, 4), param("a")], {"n": count})
|
||||
|
||||
def test_every_face_names_its_shape(self):
|
||||
"""What set_params carries per-face materials by: a repeat's copies share their shape's index."""
|
||||
b = built([{"shape": "box", "size": [1, 1, 1]},
|
||||
{"shape": "repeat", "count": 3, "step": [2, 0, 0], "of": {"shape": "box", "size": [1, 1, 1]}},
|
||||
{"shape": "tube", "r0": 1, "r1": 1, "length": 1, "segments": 8}])
|
||||
self.assertEqual(b.shape.tolist(), [0] * 6 + [1] * 18 + [2] * 10)
|
||||
self.assertEqual((b.shape.dtype, b.shell_count), (np.int32, 5))
|
||||
|
||||
def test_sockets_are_right_handed_frames(self):
|
||||
socket = {"name": "s", "type": "mount", "size": "2*a", "at": ["a", 2, 3], "z": "+x", "y": "+z"}
|
||||
kit = core.check_kit(document(params=[param("a")], sockets=[socket]))
|
||||
(made,) = core.build(core.part(kit, "p"), {"a": 0.5}).sockets
|
||||
self.assertEqual(made["matrix"].tolist(), [[0, 0, 1, 0.5], [1, 0, 0, 2], [0, 1, 0, 3], [0, 0, 0, 1]]) # x = y cross z = +y
|
||||
self.assertEqual((made["size"], made["type"]), (1.0, "mount"))
|
||||
|
||||
|
||||
@unittest.skipIf(np is None, "numpy is not installed")
|
||||
class ParamTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.part = core.part(core.check_kit(document(params=[param("a", 0.5, 2.0, 1.0), param("n", 1, 8, 3, "integer")])), "p")
|
||||
|
||||
def test_bounds_are_inclusive_and_refusals_name_them(self):
|
||||
"""params-resolve. Mutant M9 (exclusive bounds): exactly min and exactly max are refused."""
|
||||
self.assertEqual(core.resolve_params(self.part, {"a": 0.5, "n": 8}), {"a": 0.5, "n": 8})
|
||||
self.assertEqual(core.resolve_params(self.part, {"a": 2.0, "n": 1.0}), {"a": 2.0, "n": 1})
|
||||
with self.assertRaisesRegex(core.KitError, r"param 'a' = 0\.499999999 is outside \[0\.5, 2\.0\]"):
|
||||
core.resolve_params(self.part, {"a": 0.5 - 1e-9})
|
||||
with self.assertRaisesRegex(core.KitError, r"param 'a' = 2\.000000001 is outside \[0\.5, 2\.0\]"):
|
||||
core.resolve_params(self.part, {"a": 2.0 + 1e-9})
|
||||
with self.assertRaisesRegex(core.KitError, r"param 'n' is an integer; 2\.5 is not whole"):
|
||||
core.resolve_params(self.part, {"n": 2.5})
|
||||
with self.assertRaisesRegex(core.KitError, r"has no param 'b'; its params: a, n"):
|
||||
core.resolve_params(self.part, {"b": 1})
|
||||
self.assertEqual(core.resolve_params(self.part, {"n": 5}, {"a": 1.5, "n": 2}), {"a": 1.5, "n": 5})
|
||||
self.assertEqual(core.resolve_params(self.part, {}), {"a": 1.0, "n": 3})
|
||||
self.assertIs(type(core.resolve_params(self.part, {"n": 4.0})["n"]), int)
|
||||
|
||||
def test_parse_params(self):
|
||||
self.assertEqual(core.parse_params(" a = 1.5 ;n=4; "), {"a": 1.5, "n": 4.0})
|
||||
self.assertEqual(core.parse_params(""), {})
|
||||
for text, message in (("a=1; a=2", "'a' is given twice"), ("a=x", "a = 'x' is not a number"), ("a", "'a' is not name=value"),
|
||||
("a=nan", "not a number"), ("a=inf", "not a number"), ("=1", "not name=value")):
|
||||
with self.assertRaisesRegex(core.KitError, message):
|
||||
core.parse_params(text)
|
||||
|
||||
|
||||
@unittest.skipIf(np is None, "numpy is not installed")
|
||||
class MechanicalKitTests(unittest.TestCase):
|
||||
PARTS = ["nozzle", "tank", "ribbed_cylinder", "strut", "actuator", "pipe_fitting", "radiator_stack", "vent", "plate"]
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.kit = core.load_kit("mechanical")
|
||||
|
||||
def test_the_kit_is_the_nine_parts_and_three_socket_types(self):
|
||||
self.assertEqual(list(self.kit["parts"]), self.PARTS)
|
||||
self.assertEqual({k: v["match"] for k, v in self.kit["socketTypes"].items()}, {"flange": "equal", "mount": "fits", "pivot": "equal"})
|
||||
self.assertEqual({name: [(s["name"], s["type"]) for s in part["sockets"]] for name, part in self.kit["parts"].items()}, {
|
||||
"nozzle": [("mount", "flange")], "tank": [("port_a", "flange"), ("port_b", "flange"), ("saddle", "mount")],
|
||||
"ribbed_cylinder": [("end_a", "flange"), ("end_b", "flange")], "strut": [("end_a", "pivot"), ("end_b", "pivot")],
|
||||
"actuator": [("base", "pivot"), ("rod_end", "pivot")], "pipe_fitting": [("a", "flange"), ("b", "flange"), ("c", "flange")],
|
||||
"radiator_stack": [("base", "mount")], "vent": [("back", "mount")], "plate": [("back", "mount"), ("front", "mount")]})
|
||||
|
||||
def test_every_part_holds_everywhere(self):
|
||||
"""kit-parts-hold-everywhere. Mutant M8 (flip one socket's z in the kit): no face at that origin faces it."""
|
||||
for name, part in self.kit["parts"].items():
|
||||
rng = random.Random(f"mechanical.{name}")
|
||||
draws = [{p["name"]: p[key] for p in part["params"]} for key in ("default", "min", "max")]
|
||||
for _ in range(16):
|
||||
draws.append({p["name"]: rng.randint(p["min"], p["max"]) if p["type"] == "integer" else rng.uniform(p["min"], p["max"])
|
||||
for p in part["params"]})
|
||||
for given in draws:
|
||||
b = core.build(part, given)
|
||||
self.assertTrue(closed_and_oriented(b), f"{name} {given}")
|
||||
self.assertLessEqual(len(b.counts), 20000)
|
||||
self.assertGreater(signed_volume(b), 0.0)
|
||||
self.assertEqual(len(b.sockets), len(part["sockets"]))
|
||||
for socket in b.sockets:
|
||||
frame = socket["matrix"][:3, :3]
|
||||
self.assertLess(np.abs(frame.T @ frame - np.eye(3)).max(), 1e-9)
|
||||
self.assertLess(abs(np.linalg.det(frame) - 1.0), 1e-9)
|
||||
self.assertLess(socket_seat(b, socket), 1e-6, f"{name}.{socket['name']} {given}")
|
||||
self.assertGreater(socket["size"], 0.0)
|
||||
|
||||
def test_extension_moves_the_rod_end_and_nothing_else(self):
|
||||
part = self.kit["parts"]["actuator"]
|
||||
short, long = core.build(part, {"extension": 0.0}), core.build(part, {"extension": 0.5})
|
||||
self.assertEqual(short.sockets[0]["matrix"].tolist(), long.sockets[0]["matrix"].tolist())
|
||||
self.assertAlmostEqual(long.sockets[1]["matrix"][2, 3] - short.sockets[1]["matrix"][2, 3], 0.5, places=12)
|
||||
|
||||
def test_builds_are_deterministic(self):
|
||||
"""build-deterministic."""
|
||||
for part in self.kit["parts"].values():
|
||||
a, b = core.build(part), core.build(part)
|
||||
self.assertEqual((a.V.tobytes(), a.faces.tobytes(), a.counts.tobytes(), a.smooth.tobytes()),
|
||||
(b.V.tobytes(), b.faces.tobytes(), b.counts.tobytes(), b.smooth.tobytes()))
|
||||
self.assertEqual((a.V.dtype, a.faces.dtype, a.counts.dtype), (np.float64, np.int32, np.int32))
|
||||
|
||||
def test_describe_fits_a_receipt(self):
|
||||
text = json.dumps(core.describe(self.kit), separators=(",", ":"))
|
||||
self.assertLess(len(text), 16000)
|
||||
described = core.describe(self.kit, "tank")
|
||||
self.assertEqual([p["name"] for p in described["parts"]], ["tank"])
|
||||
self.assertEqual(described["parts"][0]["sockets"][1]["matrix"][2], [0.0, 0.0, 1.0, 0.9])
|
||||
self.assertEqual(described["parts"][0]["params"][0], {"name": "radius", "type": "number", "min": 0.12, "max": 0.35, "default": 0.22, "doc": "shell radius"})
|
||||
|
||||
|
||||
class HostFileTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.document = json.loads((SURFACE / "brokkr_kitbash" / "brokkr_actions.json").read_text(encoding="utf-8"))
|
||||
|
||||
def test_brokkr_admits_the_file(self):
|
||||
"""rows-check: Brokkr's own host-file checker."""
|
||||
at.check_host(self.document, at.table()["charsets"])
|
||||
self.assertEqual([row["name"] for row in self.document["actions"]],
|
||||
["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", "brokkr_kitbash.describe", "brokkr_kitbash.report"])
|
||||
|
||||
def test_every_row_names_an_operator_and_property_the_add_on_defines(self):
|
||||
source = (SURFACE / "brokkr_kitbash" / "__init__.py").read_text(encoding="utf-8")
|
||||
for row in self.document["actions"]:
|
||||
self.assertIn(f'bl_idname = "{row["name"]}"', source)
|
||||
self.assertEqual(row.get("result"), "brokkr_mesh_polish_result")
|
||||
body = source.split(f'bl_idname = "{row["name"]}"')[1].split("def work")[0]
|
||||
for field in row["fields"]:
|
||||
self.assertIn(f" {field['name']}: bpy.props.", body, f"{row['name']}.{field['name']}")
|
||||
|
||||
def test_a_valid_intent_is_admitted_and_long_params_are_refused(self):
|
||||
host = [{**row, "host": "brokkr_kitbash"} for row in self.document["actions"]]
|
||||
envelope = {"schema": "brokkr.blender.command_intent.v0", "commandId": "t-1", "requestedBy": "test/driver"}
|
||||
admitted = at.validate({**envelope, "action": "brokkr_kitbash.place_part", "part": "tank", "object_name": "Tank"}, host)
|
||||
self.assertEqual((admitted["kit"], admitted["params"]), ("mechanical", ""))
|
||||
at.validate({**envelope, "action": "brokkr_kitbash.place_part", "part": "tank", "object_name": "Tank", "params": "a=1;" * 1000}, host)
|
||||
with self.assertRaisesRegex(at.IntentInvalid, "params must have at most 4000 characters"):
|
||||
at.validate({**envelope, "action": "brokkr_kitbash.place_part", "part": "tank", "object_name": "Tank", "params": "a=1;" * 1000 + "b"}, host)
|
||||
with self.assertRaises(at.IntentInvalid):
|
||||
at.validate({**envelope, "action": "brokkr_kitbash.place_part", "part": "../x", "object_name": "Tank"}, host)
|
||||
with self.assertRaises(at.IntentInvalid):
|
||||
at.validate({**envelope, "action": "brokkr_kitbash.place_part", "part": "tank", "object_name": "Tank", "location": "0,0,0"}, host)
|
||||
|
||||
|
||||
class OwnershipTests(unittest.TestCase):
|
||||
"""The negative patterns of the cut: expressions are walked and never run, the bridge stays out, core needs no
|
||||
Blender, and schemas/ holds no second statement of the kit format."""
|
||||
PACKAGE = (r"\beval\(|\bexec\(|\bcompile\(", r"brokkr_bridge")
|
||||
CORE = r"^import bpy|^from bpy|^import bmesh"
|
||||
SCHEMAS = r"brokkr\.kit\.v0"
|
||||
|
||||
def sources(self):
|
||||
return {p.name: p.read_text(encoding="utf-8") for p in sorted((SURFACE / "brokkr_kitbash").rglob("*")) if p.suffix in (".py", ".json")}
|
||||
|
||||
def test_no_pattern_matches(self):
|
||||
self.assertEqual(sorted(self.sources()), ["__init__.py", "brokkr_actions.json", "core.py", "mechanical.v0.json"])
|
||||
for pattern in self.PACKAGE:
|
||||
for name, text in self.sources().items():
|
||||
self.assertIsNone(re.search(pattern, text), f"{pattern} in {name}")
|
||||
self.assertIsNone(re.search(self.CORE, self.sources()["core.py"], re.M))
|
||||
schemas = [p for p in (SURFACE.parents[1] / "schemas").rglob("*") if p.is_file()]
|
||||
self.assertTrue(schemas)
|
||||
for path in schemas:
|
||||
self.assertIsNone(re.search(self.SCHEMAS, path.read_text(encoding="utf-8", errors="replace")), path.name)
|
||||
|
||||
def test_the_patterns_bite(self):
|
||||
for pattern, planted in zip(self.PACKAGE, ("value = eval(text)", "from brokkr_bridge import x")):
|
||||
self.assertIsNotNone(re.search(pattern, planted))
|
||||
for planted in ("exec(text)", "code = compile(text, 'kit', 'eval')", "KIT = re.compile('x')"):
|
||||
self.assertIsNotNone(re.search(self.PACKAGE[0], planted))
|
||||
for planted in ("import bpy", "x = 1\nfrom bpy import props", "import bmesh"):
|
||||
self.assertIsNotNone(re.search(self.CORE, planted, re.M))
|
||||
self.assertIsNotNone(re.search(self.SCHEMAS, '{"const": "brokkr.kit.v0"}'))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Loading…
Reference in a new issue