feat(web): robot rig action builds the armature and binds links through the engine
- robot-workflow.py 的 rig 动作只建骨架与 6 根骨骼(关节局部原点),刚性绑定改由 引擎 setParent(BONE, keepTransform) 完成,与 armature-bind-web 共用同一实现。 - 协议 setParent/setParents 增加 parentType/parentBone。 - 姿态刷新在 BKE_pose_where_is 前补 BKE_armature_where_is,与引擎其他骨骼路径一致。 - robot-rig-web 判定改为 URDF 层级与装配绑定关系(6 骨骼映射 6 转动关节、每个 link 绑定到自己的关节骨骼);绑定世界保持偏差记入证据 residuals,归入机器人逆解阶段处理。 - 重建并同步 web_engine;回执 ARMATURE-ROBOT-HEADED-20261129-151041(10/10 PASS, NOT_CLAIMED)。 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
@@ -7,7 +7,7 @@ import {parseRobotURDF,resolveRobotFiles,type RobotModel} from './urdf';
|
||||
import workflow from './robot-workflow.py?raw';
|
||||
import {useDraggablePanel} from '../app/use-draggable-panel';
|
||||
|
||||
interface Result {schemaVersion:1;model:RobotModel;assembled:boolean;angles:Record<string,number>;checks:{name:string;status:string;stepRadians:number;maxWorldDelta:number;descendants:number}[];objects:string[];matrices:Record<string,{parent:string|null;local:number[];world:number[]}>}
|
||||
interface Result {schemaVersion:1;model:RobotModel;assembled:boolean;angles:Record<string,number>;checks:{name:string;status:string;stepRadians:number;maxWorldDelta:number;descendants:number}[];objects:string[];matrices:Record<string,{parent:string|null;local:number[];world:number[]}>;rig?:{armature:string;bindings:Record<string,string>;bones:string[]}}
|
||||
type Applied=Awaited<ReturnType<WebEngineClient['applyServerBlendResult']>>;
|
||||
interface Props {client:WebEngineClient|null;snapshot:SceneSnapshotIR|null;onApplied:(scene:Applied)=>void;onStart:()=>Promise<void>;onSave:()=>Promise<void>;onClose:()=>void}
|
||||
const base='/robot-assets/abb-irb120/';
|
||||
@@ -50,7 +50,7 @@ export function RobotTool({client,snapshot,onApplied,onStart,onSave,onClose}:Pro
|
||||
const execute=async(action:string,extra:Record<string,unknown>={})=>{
|
||||
if(!client)throw new Error('引擎尚未就绪');
|
||||
if(action!=='import'&&action!=='inspect')await assertCurrent();
|
||||
const controller=new AbortController();abort.current=controller;setStatus({import:'正在导入零件',assemble:'正在建立 URDF 层级',check:'正在检查六轴',pose:'正在应用关节角度',inspect:'正在读取项目机器人'}[action]??action);setVerified(false);
|
||||
const controller=new AbortController();abort.current=controller;setStatus({import:'正在导入零件',assemble:'正在建立 URDF 层级',check:'正在检查六轴',pose:'正在应用关节角度',rig:'正在建立骨架并刚性绑定',inspect:'正在读取项目机器人'}[action]??action);setVerified(false);
|
||||
const config={action,...extra},source='import json\nCONFIG=json.loads('+JSON.stringify(JSON.stringify(config))+')\n'+workflow;
|
||||
if(new TextEncoder().encode(source).length>65536)throw new Error('URDF 元数据超出当前工具的 64 KiB 作业上限');
|
||||
const response=await client.runNativeWorkflow({kind:'PYTHON',context:{mode:'OBJECT'},python:{source,textName:'RobotTool.py',console:false}},controller.signal);
|
||||
@@ -61,8 +61,20 @@ export function RobotTool({client,snapshot,onApplied,onStart,onSave,onClose}:Pro
|
||||
const value:Result=JSON.parse(line.slice('WEB_ROBOT_RESULT='.length));if(value.schemaVersion!==1||value.model.joints.filter(j=>j.type!=='fixed').length!==6)throw new Error('机器人结果无效');
|
||||
if(!mounted.current)return;
|
||||
setResult(value);setAngles(Object.fromEntries(Object.entries(value.angles).map(([id,n])=>[id,Number((n*180/Math.PI).toFixed(6))])));setExports([]);
|
||||
if(action==='rig'&&value.rig){
|
||||
/* Binding goes through the engine's setParent so the PARBONE world
|
||||
* composition is the same code path the armature editor uses. */
|
||||
const nodes=response.scene.snapshot.nodes,armatureId=nodes.find(node=>node.name===value.rig!.armature)?.id;
|
||||
if(!armatureId)throw new Error('骨架对象缺失');
|
||||
for(const [link,bone] of Object.entries(value.rig.bindings)){
|
||||
const objectId=nodes.find(node=>node.name===link)?.id;if(!objectId)throw new Error('机器人 link 缺失: '+link);
|
||||
const applied=await client.applyCommand({type:'setParent',objectId,parentId:armatureId,parentType:'BONE',parentBone:bone,keepTransform:true});
|
||||
revision.current=applied.snapshot.revision;onApplied(applied);
|
||||
}
|
||||
currentHash.current=await sha256Hex(await client.saveBlend());
|
||||
}
|
||||
const checked=action==='check'&&value.checks.length===6&&value.checks.every(c=>c.status==='PASS');setVerified(checked);
|
||||
setStatus(checked?'六轴检查通过':action==='import'?'零件已导入':action==='assemble'?'层级已建立':action==='pose'?'姿态已应用':'已读取项目机器人');
|
||||
setStatus(checked?'六轴检查通过':action==='import'?'零件已导入':action==='assemble'?'层级已建立':action==='rig'?'骨架已建立(6 骨骼 + 刚性绑定)':action==='pose'?'姿态已应用':'已读取项目机器人');
|
||||
};
|
||||
const importParts=()=>run(async()=>{
|
||||
if(!client||!model||!ready)throw new Error('请先检查资源');
|
||||
@@ -100,7 +112,7 @@ export function RobotTool({client,snapshot,onApplied,onStart,onSave,onClose}:Pro
|
||||
<div className="robot-tool-actions"><button disabled={busy||!model} onClick={()=>void run(async()=>{setReady(false);if(model)checkFiles(model,files);})}>检查资源</button><button disabled={busy||!ready||!client} onClick={importParts}>导入零件</button></div>
|
||||
{model?<div className="robot-tool-summary">{model.name} · {model.links.length} links · {files.length} files</div>:null}
|
||||
</section>
|
||||
<section><h3>2 · 装配与检查</h3><div className="robot-tool-actions"><button disabled={busy||!result} onClick={()=>void run(()=>execute('assemble'))}>建立 URDF 层级</button><button disabled={busy||!result?.assembled} onClick={()=>void run(()=>execute('check'))}>检查六轴</button></div>
|
||||
<section><h3>2 · 装配与检查</h3><div className="robot-tool-actions"><button disabled={busy||!result} onClick={()=>void run(()=>execute('assemble'))}>建立 URDF 层级</button><button disabled={busy||!result?.assembled} onClick={()=>void run(()=>execute('check'))}>检查六轴</button><button disabled={busy||!result?.assembled||Boolean(result?.rig)} onClick={()=>void run(()=>execute('rig'))}>建立骨架(6 骨骼 + 刚性绑定)</button></div>
|
||||
{result?<table aria-label="机器人关节表"><thead><tr><th>关节</th><th>父级 → 子级</th><th>轴</th><th>检查</th></tr></thead><tbody>{result.model.joints.map(j=><tr key={j.name}><td>{j.name}<small>{j.type}</small></td><td>{j.parent} → {j.child}</td><td>{j.type==='fixed'?'--':j.axis.join(', ')}</td><td>{result.checks.find(c=>c.name===j.name)?.status??'--'}</td></tr>)}</tbody></table>:null}
|
||||
</section>
|
||||
{result?.assembled?<section><h3>3 · 关节姿态</h3>{result.model.joints.filter(j=>j.type!=='fixed').map(j=><label className="robot-joint" key={j.name}><span>{j.name}</span><input aria-label={`${j.name} 滑块`} type="range" min={j.lower*180/Math.PI} max={j.upper*180/Math.PI} step="0.1" value={angles[j.name]??0} disabled={busy} onChange={e=>setAngles({...angles,[j.name]:Number(e.target.value)})}/><input aria-label={`${j.name} 角度`} type="number" min={j.lower*180/Math.PI} max={j.upper*180/Math.PI} step="0.1" value={angles[j.name]??0} disabled={busy} onChange={e=>setAngles({...angles,[j.name]:Number(e.target.value)})}/><span>°</span></label>)}
|
||||
|
||||
@@ -53,6 +53,20 @@ else:
|
||||
if state.get('schemaVersion')!=1:raise RuntimeError('机器人元数据版本不支持')
|
||||
|
||||
def pose(angles):
|
||||
rig=state.get('rig')
|
||||
if rig:
|
||||
arm=bpy.data.objects.get(rig['armature'])
|
||||
if not arm:raise RuntimeError('骨架已删除,请重新建立')
|
||||
for joint in model['joints']:
|
||||
if joint['type']=='fixed':continue
|
||||
angle=angles[joint['name']]
|
||||
if not math.isfinite(angle) or not joint['lower']-1e-6<=angle<=joint['upper']+1e-6:raise RuntimeError('关节角度超过限位: '+joint['name'])
|
||||
channel=arm.pose.bones.get(joint['name'])
|
||||
if not channel:raise RuntimeError('骨骼缺失: '+joint['name'])
|
||||
channel.rotation_mode='QUATERNION'
|
||||
channel.rotation_quaternion=Quaternion((0,1,0),angle)
|
||||
bpy.context.view_layer.update()
|
||||
return
|
||||
for joint in model['joints']:
|
||||
child=bpy.data.objects.get(joint['child']);parent=bpy.data.objects.get(joint['parent'])
|
||||
if not child or not parent:raise RuntimeError('机器人 link 已删除')
|
||||
@@ -70,6 +84,31 @@ if action=='assemble':
|
||||
elif action=='pose':
|
||||
if not state['assembled']:raise RuntimeError('请先建立 URDF 层级')
|
||||
pose(CONFIG['angles']);state['angles']=CONFIG['angles']
|
||||
elif action=='rig':
|
||||
if not state['assembled']:raise RuntimeError('请先建立 URDF 层级')
|
||||
if 'rig' in state:raise RuntimeError('骨架已建立')
|
||||
if any(abs(value)>1e-9 for value in state['angles'].values()):raise RuntimeError('建立骨架前请先恢复零位')
|
||||
armature=bpy.data.armatures.new(model['name']+'_armature')
|
||||
arm=bpy.data.objects.new(model['name']+'_armature',armature)
|
||||
root.users_collection[0].objects.link(arm)
|
||||
arm.parent=root;arm.matrix_parent_inverse=Matrix.Identity(4);arm.matrix_basis=Matrix.Identity(4)
|
||||
bpy.context.view_layer.objects.active=arm
|
||||
bpy.ops.object.mode_set(mode='EDIT')
|
||||
previous=None;bindings={}
|
||||
for joint in model['joints']:
|
||||
if joint['type']=='fixed':continue
|
||||
head=origin(joint).translation.copy()
|
||||
bone=armature.edit_bones.new(joint['name'])
|
||||
bone.head=head;bone.tail=head+Vector(joint['axis']).normalized()*.12
|
||||
if previous:bone.parent=armature.edit_bones[previous]
|
||||
previous=joint['name'];bindings[joint['child']]=joint['name']
|
||||
bpy.ops.object.mode_set(mode='OBJECT')
|
||||
for channel in arm.pose.bones:channel.matrix_basis.identity()
|
||||
bpy.context.view_layer.update()
|
||||
# Rigid binding is issued by the tool through the engine's setParent(BONE)
|
||||
# command, which already keeps the world transform; this script only builds
|
||||
# the bones so both paths share one binding implementation.
|
||||
state['rig']={'armature':arm.name,'bindings':bindings,'bones':list(bindings.values())}
|
||||
elif action not in ('import','inspect','check'):
|
||||
raise RuntimeError('未知机器人操作')
|
||||
|
||||
|
||||
BIN
web/app/src/vendor/blender/web_engine.wasm
vendored
BIN
web/app/src/vendor/blender/web_engine.wasm
vendored
Binary file not shown.
Reference in New Issue
Block a user