Files
robot-assembly/scripts/analyze-urdf-mapping.mjs

382 lines
14 KiB
JavaScript

/**
* 一次性分析脚本 —— 自动把 assembly.json 里所有零件 placement 归类到 URDF link。
*
* 算法:
* 1. 解析 URDF,构建 link 父子树 + 每个 joint 的 origin (xyz/rpy)
* 2. 计算每个 link 在 **URDF 系** 下的初始世界变换(关节角=0,只用 origin)
* 3. 把 link 位置变换到 **Scene 系**(URDF (x,y,z) → Scene (y,z,x))
* 4. 读 assembly.json,枚举每条 assemblypos 作为一个零件 placement(Scene 系)
* 5. 对每个 placement,找最近的 link(欧氏距离)
* 6. 输出 JSON 报告:每个 link 下挂了哪些零件 + 距离
*
* 用法:
* node scripts/analyze-urdf-mapping.mjs
* 输出:
* scripts/out/urdf-mapping-report.json
*/
import { readFileSync, mkdirSync, writeFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import * as THREE from 'three';
const __dirname = dirname(fileURLToPath(import.meta.url));
const PROJECT_ROOT = resolve(__dirname, '..');
const URDF_PATH = resolve(PROJECT_ROOT, 'src/assets/O6/urdf/linkerhand_o6_left.urdf');
const ASSEMBLY_PATH = resolve(PROJECT_ROOT, 'src/data/O6/assembly.json');
const OUT_DIR = resolve(__dirname, 'out');
const OUT_PATH = resolve(OUT_DIR, 'urdf-mapping-report.json');
// ===================================================================
// 1. URDF 解析
// ===================================================================
/**
* @typedef {{ name: string; parent: string|null; joint: { xyz: [number,number,number]; rpy: [number,number,number] } | null }} LinkNode
*/
/** @returns {Map<string, LinkNode>} */
function parseUrdf(xml) {
const links = new Map();
// 收集所有 link 名(先全部置为 root,稍后被 joint 改 parent)
for (const m of xml.matchAll(/<link\s+name="([^"]+)"/g)) {
links.set(m[1], { name: m[1], parent: null, joint: null });
}
// 解析 joint:parent → child 的偏移
const jointRe = /<joint\s+name="([^"]+)"[\s\S]*?<\/joint>/g;
for (const m of xml.matchAll(jointRe)) {
const block = m[0];
const parent = /<parent\s+link="([^"]+)"/.exec(block)?.[1];
const child = /<child\s+link="([^"]+)"/.exec(block)?.[1];
const origin = /<origin\s+xyz="([^"]+)"\s+rpy="([^"]+)"/.exec(block);
if (!parent || !child || !origin) continue;
const xyz = origin[1].trim().split(/\s+/).map(Number);
const rpy = origin[2].trim().split(/\s+/).map(Number);
const node = links.get(child);
if (!node) continue;
node.parent = parent;
node.joint = { xyz, rpy };
}
return links;
}
/**
* 计算每个 link 在 URDF 坐标系下的初始世界 4x4 矩阵(关节角=0,只用 origin)。
* @param {Map<string, LinkNode>} links
* @returns {Map<string, THREE.Matrix4>}
*/
function computeUrdfWorldMatrices(links) {
/** @type {Map<string, THREE.Matrix4>} */
const cache = new Map();
function world(name) {
if (cache.has(name)) return cache.get(name);
const node = links.get(name);
if (!node) throw new Error(`unknown link ${name}`);
if (!node.parent) {
// root
cache.set(name, new THREE.Matrix4().identity());
return cache.get(name);
}
const parentMat = world(node.parent).clone();
const local = new THREE.Matrix4().compose(
new THREE.Vector3(...node.joint.xyz),
new THREE.Quaternion().setFromEuler(new THREE.Euler(...node.joint.rpy, 'XYZ')),
new THREE.Vector3(1, 1, 1),
);
cache.set(name, parentMat.multiply(local));
return cache.get(name);
}
for (const name of links.keys()) world(name);
return cache;
}
// ===================================================================
// 2. Scene 系下的 link 位置
// ===================================================================
/** URDF 系 → Scene 系:(x, y, z) → (y, z, x) */
function urdfPosToScene(v) {
return [v[1], v[2], v[0]];
}
/** @param {Map<string, THREE.Matrix4>} urdfWorlds */
function linksInScene(urdfWorlds) {
/** @type {Array<{ link: string; pos: [number,number,number] }>} */
const out = [];
for (const [name, mat] of urdfWorlds) {
const p = new THREE.Vector3();
const q = new THREE.Quaternion();
const s = new THREE.Vector3();
mat.decompose(p, q, s);
out.push({ link: name, pos: urdfPosToScene([p.x, p.y, p.z]) });
}
return out;
}
// ===================================================================
// 3. 解析 assembly.json 拿到所有零件 placement
// ===================================================================
function parsePos(str) {
return str.split(',').map(Number);
}
/**
* 枚举每一条 assemblypos,把零件 placement 收集出来。
* 同一个零件名可能出现多次(不同 placement)。
*
* @returns {Array<{ phase: string; step: string; part: string; index: number; pos: [number,number,number]; rot: [number,number,number] }>}
*/
function collectPlacements(assembly) {
const out = [];
for (const phaseObj of assembly.AllStep) {
const [phaseName, phaseBody] = Object.entries(phaseObj)[0];
for (const phaseStep of phaseBody.phases ?? []) {
for (const sub of phaseStep.subphase ?? []) {
const subpart = sub.subpart;
const positions = sub.assemblypos ?? [];
if (!subpart || positions.length === 0) continue;
// 跳过 line(线束)
if (sub.action === 'line') continue;
for (const ap of positions) {
out.push({
phase: phaseName,
step: sub.step ?? phaseStep.step ?? '',
part: subpart,
index: ap.index,
pos: parsePos(ap.pos),
rot: parsePos(ap.rot),
});
}
}
}
}
return out;
}
// ===================================================================
// 4. 归类 —— "沿手指方向投影" 算法
// ===================================================================
/**
* 对每根手指,我们已知 MCP / DIP 关节的世界坐标(Scene 系)。
* 任一零件 placement 都可以投影到 "MCP → DIP" 方向上,得到归一化参数 t:
* t < 0 → 在 MCP 后方(沿手掌内部)→ 该手指的"驱动电机/支架" → 归 hand_base_link
* 0 ≤ t < 0.5 → 在近节范围内 → finger_proximal
* t ≥ 0.5 → 在远节范围内 → finger_distal
*
* 拇指有 3 段:base2 → metacarpals → distal,用两段分别投影,分到 3 个 bucket。
*/
/** 描述一个手指的运动学链 */
function buildFingerChains(linkPoses) {
const map = new Map(linkPoses.map((lp) => [lp.link, lp.pos]));
// 4 指 (index/middle/ring/pinky):MCP=proximal 位置, DIP=distal 位置, 两段 link
const fourFingers = ['index', 'middle', 'ring', 'pinky'].map((name) => ({
name,
segments: [
{ link: `lh_${name}_proximal`, from: map.get(`lh_${name}_proximal`), to: map.get(`lh_${name}_distal`) },
// distal 没有 child,用"沿同方向再延伸"作为段长(估指尖)
(() => {
const a = map.get(`lh_${name}_proximal`);
const b = map.get(`lh_${name}_distal`);
const dir = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
const len = Math.hypot(...dir);
const u = dir.map((v) => v / len);
const tip = [b[0] + u[0] * len, b[1] + u[1] * len, b[2] + u[2] * len];
return { link: `lh_${name}_distal`, from: b, to: tip };
})(),
],
}));
// 拇指:3 段
const thumb = {
name: 'thumb',
segments: [
{ link: 'lh_thumb_metacarpals_base2', from: map.get('lh_thumb_metacarpals_base2'), to: map.get('lh_thumb_metacarpals') },
{ link: 'lh_thumb_metacarpals', from: map.get('lh_thumb_metacarpals'), to: map.get('lh_thumb_distal') },
(() => {
const a = map.get('lh_thumb_metacarpals');
const b = map.get('lh_thumb_distal');
const dir = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
const len = Math.hypot(...dir);
const u = dir.map((v) => v / len);
const tip = [b[0] + u[0] * len, b[1] + u[1] * len, b[2] + u[2] * len];
return { link: 'lh_thumb_distal', from: b, to: tip };
})(),
],
};
return [thumb, ...fourFingers];
}
/** 点 P 投影到从 A 到 B 的线段上,返回 {t, perpDist}:
* t = 投影参数(0=A, 1=B)
* perpDist = P 到无限延伸直线的垂直距离 */
function projectOnSegment(p, a, b) {
const ab = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
const ap = [p[0] - a[0], p[1] - a[1], p[2] - a[2]];
const ab2 = ab[0] * ab[0] + ab[1] * ab[1] + ab[2] * ab[2];
const t = (ap[0] * ab[0] + ap[1] * ab[1] + ap[2] * ab[2]) / ab2;
const proj = [a[0] + ab[0] * t, a[1] + ab[1] * t, a[2] + ab[2] * t];
const perp = Math.hypot(p[0] - proj[0], p[1] - proj[1], p[2] - proj[2]);
return { t, perpDist: perp };
}
/**
* 归类规则:
* 1. 对每根手指(thumb + 4 指),用各 segment 找"最优手指"(基于第一段[MCP→DIP]的中心距)
* 2. 在最优手指内部,根据 t 在哪一段决定归到哪个 link
* 3. 如果 t < -0.15(明显在 MCP 后方,且垂直距离不大)→ 归 hand_base_link
* 4. 如果零件到所有手指都太远(perpDist > 25mm)→ 归 hand_base_link
*/
function classify(placements, linkPoses) {
const fingers = buildFingerChains(linkPoses);
const FAR_DIST = 0.022; // 点到折线 > 22mm,归 hand_base_link
const STATIC_T_THRESHOLD = -0.1; // 第一段未夹紧 t < -0.1 → 显著在 MCP 后方,归 hand_base_link
return placements.map((pl) => {
// 对每根手指的每个 segment,算 P 到线段的最近距离 + clamped t
let bestFinger = null;
let bestSegIdx = -1;
let bestT = 0;
let bestDist = Infinity;
let bestUnclampedT0 = 0;
for (const f of fingers) {
// 记录第一段(MCP→DIP)的 unclamped t,用来识别 "MCP 后方" 静态区
const seg0 = f.segments[0];
const r0 = projectOnSegment(pl.pos, seg0.from, seg0.to);
const fingerUnclampedT = r0.t;
for (let i = 0; i < f.segments.length; i++) {
const seg = f.segments[i];
const { t } = projectOnSegment(pl.pos, seg.from, seg.to);
const ct = Math.max(0, Math.min(1, t));
const proj = [
seg.from[0] + (seg.to[0] - seg.from[0]) * ct,
seg.from[1] + (seg.to[1] - seg.from[1]) * ct,
seg.from[2] + (seg.to[2] - seg.from[2]) * ct,
];
const d = Math.hypot(pl.pos[0] - proj[0], pl.pos[1] - proj[1], pl.pos[2] - proj[2]);
if (d < bestDist) {
bestDist = d;
bestFinger = f;
bestSegIdx = i;
bestT = ct;
bestUnclampedT0 = fingerUnclampedT;
}
}
}
if (!bestFinger || bestDist > FAR_DIST) {
return { ...pl, link: 'lh_hand_base_link', reason: 'no-close-link', distMm: +(bestDist * 1000).toFixed(2) };
}
// 在第一段起点之前(显著)→ 手掌驱动零件
if (bestSegIdx === 0 && bestUnclampedT0 < STATIC_T_THRESHOLD) {
return { ...pl, link: 'lh_hand_base_link', reason: 'behind-mcp', t: +bestUnclampedT0.toFixed(3), distMm: +(bestDist * 1000).toFixed(2), finger: bestFinger.name };
}
return { ...pl, link: bestFinger.segments[bestSegIdx].link, reason: 'on-segment', segIdx: bestSegIdx, t: +bestT.toFixed(3), distMm: +(bestDist * 1000).toFixed(2), finger: bestFinger.name };
});
}
// ===================================================================
// 5. 入口
// ===================================================================
function main() {
const urdfXml = readFileSync(URDF_PATH, 'utf-8');
const assembly = JSON.parse(readFileSync(ASSEMBLY_PATH, 'utf-8'));
const links = parseUrdf(urdfXml);
const urdfWorlds = computeUrdfWorldMatrices(links);
const linkPoses = linksInScene(urdfWorlds);
const placements = collectPlacements(assembly);
const classified = classify(placements, linkPoses);
// 按 link 聚合
/** @type {Record<string, Array<{ part: string; phase: string; index: number; pos: number[]; distMm: number }>>} */
const byLink = {};
for (const lp of linkPoses) byLink[lp.link] = [];
for (const c of classified) {
byLink[c.link].push({
part: c.part,
phase: c.phase,
index: c.index,
pos: c.pos.map((v) => +v.toFixed(4)),
t: c.t ?? null,
distMm: c.distMm,
reason: c.reason,
finger: c.finger ?? null,
});
}
// 排序方便看(按 t 升序,t 为 null 的排在最后)
for (const link of Object.keys(byLink)) {
byLink[link].sort((a, b) => {
const ta = a.t ?? Infinity;
const tb = b.t ?? Infinity;
return ta - tb;
});
}
// 同一种零件的归类汇总(供"重复零件分散在多 link"的参考)
/** @type {Record<string, Record<string, number>>} */
const partToLinkCount = {};
for (const c of classified) {
partToLinkCount[c.part] ??= {};
partToLinkCount[c.part][c.link] = (partToLinkCount[c.part][c.link] || 0) + 1;
}
// 食指建议结构(模仿 O6_INDEX_FINGER 格式),方便用户复制
const fingerSummary = {};
for (const link of Object.keys(byLink)) {
const m = /^lh_(thumb|index|middle|ring|pinky)_(.*)$/.exec(link);
if (!m) continue;
const finger = m[1];
const seg = m[2];
fingerSummary[finger] ??= {};
fingerSummary[finger][seg] = Array.from(new Set(byLink[link].map((x) => x.part))).sort();
}
const report = {
meta: {
urdf: 'src/assets/O6/urdf/linkerhand_o6_left.urdf',
assembly: 'src/data/O6/assembly.json',
totalPlacements: classified.length,
uniqueParts: Object.keys(partToLinkCount).length,
links: linkPoses.map((lp) => ({
link: lp.link,
scenePos: lp.pos.map((v) => +v.toFixed(4)),
})),
},
fingerSummary,
byLink,
partToLinkCount,
};
mkdirSync(OUT_DIR, { recursive: true });
writeFileSync(OUT_PATH, JSON.stringify(report, null, 2), 'utf-8');
// 控制台简版输出
console.log('=== Link 初始世界位置(Scene 系,单位:米)===');
for (const lp of linkPoses) {
console.log(` ${lp.link.padEnd(32)} (${lp.pos.map((v) => v.toFixed(4)).join(', ')})`);
}
console.log('');
console.log('=== 各 link 下挂的零件数(去重)===');
for (const link of Object.keys(byLink)) {
const uniq = new Set(byLink[link].map((x) => x.part));
console.log(` ${link.padEnd(32)} ${byLink[link].length.toString().padStart(3)} placements / ${uniq.size} 种零件`);
}
console.log('');
console.log('=== 5 根手指的零件分段(去重,可直接复制)===');
console.log(JSON.stringify(fingerSummary, null, 2));
console.log('');
console.log(`完整报告写入:${OUT_PATH}`);
}
main();