diff --git a/blender-5.2.0/source/blender/web_engine/web_engine_api.cpp b/blender-5.2.0/source/blender/web_engine/web_engine_api.cpp index da599ddb1..9fcc535ba 100644 --- a/blender-5.2.0/source/blender/web_engine/web_engine_api.cpp +++ b/blender-5.2.0/source/blender/web_engine/web_engine_api.cpp @@ -1081,6 +1081,10 @@ bool refresh_scene_from_main(EngineState &engine, const bool advance_revision = true) { std::vector bytes; + if (engine.authoritative_main != nullptr) { + std::string pose_error; + web_armature_refresh_all_poses(engine.authoritative_main, pose_error); + } if (engine.authoritative_main == nullptr || !web_engine_blend_main_write(engine.authoritative_main, bytes, error, true)) { diff --git a/blender-5.2.0/source/blender/web_engine/web_engine_main_state.cpp b/blender-5.2.0/source/blender/web_engine/web_engine_main_state.cpp index 8fc3c5a5d..f7c5729ff 100644 --- a/blender-5.2.0/source/blender/web_engine/web_engine_main_state.cpp +++ b/blender-5.2.0/source/blender/web_engine/web_engine_main_state.cpp @@ -19689,11 +19689,36 @@ bool web_armature_refresh_pose(WebBlendMainState *state, const char *object_id, return false; } Depsgraph *depsgraph = BKE_scene_ensure_depsgraph(state->main, state->scene, view_layer); + /* Bones created by Python reach here before any depsgraph pass, so the rest + * matrices must be rebuilt first; without them pose_mat is evaluated from + * stale arm_mat and every later readback disagrees. */ + BKE_armature_where_is(reinterpret_cast(object->data)); BKE_pose_where_is(depsgraph, state->scene, object); object->id.recalc |= ID_RECALC_GEOMETRY | ID_RECALC_TRANSFORM; return true; } +/* Python edits (the robot rig) reach Main without going through an armature + * command, so the snapshot must evaluate every pose before it is read back; + * otherwise pose_mat is stale and bone-parented worlds drift. */ +bool web_armature_refresh_all_poses(WebBlendMainState *state, std::string &error) +{ + error.clear(); + if (state == nullptr || state->main == nullptr || state->scene == nullptr) return true; + ViewLayer *view_layer = state->view_layer != nullptr ? state->view_layer : + static_cast(state->scene->view_layers.first); + if (view_layer == nullptr) return true; + Depsgraph *depsgraph = BKE_scene_ensure_depsgraph(state->main, state->scene, view_layer); + LISTBASE_FOREACH (Object *, object, &state->main->objects) { + if (object->type == OB_ARMATURE && object->pose != nullptr) { + BKE_armature_where_is(reinterpret_cast(object->data)); + BKE_pose_where_is(depsgraph, state->scene, object); + object->id.recalc |= ID_RECALC_GEOMETRY | ID_RECALC_TRANSFORM; + } + } + return true; +} + bool web_engine_blend_main_armature_edit_operations( WebBlendMainState *state, const char *object_id, diff --git a/blender-5.2.0/source/blender/web_engine/web_engine_main_state.h b/blender-5.2.0/source/blender/web_engine/web_engine_main_state.h index 4835012d3..abb93ad4c 100644 --- a/blender-5.2.0/source/blender/web_engine/web_engine_main_state.h +++ b/blender-5.2.0/source/blender/web_engine/web_engine_main_state.h @@ -746,6 +746,7 @@ bool web_engine_blend_main_armature_edit_operations( * readable through the snapshot and usable as bone-parent references. */ bool web_armature_refresh_pose(WebBlendMainState *state, const char *object_id, std::string &error); +bool web_armature_refresh_all_poses(WebBlendMainState *state, std::string &error); bool web_engine_blend_main_set_bone_roll(WebBlendMainState *state, const char *object_id, const char *bone_name, diff --git a/docs/web/ARMATURE-ROBOT-HEADED-TESTS.md b/docs/web/ARMATURE-ROBOT-HEADED-TESTS.md index 68b3c1690..efb76eb3d 100644 --- a/docs/web/ARMATURE-ROBOT-HEADED-TESTS.md +++ b/docs/web/ARMATURE-ROBOT-HEADED-TESTS.md @@ -65,6 +65,10 @@ node tools/web/check-armature-robot-headed.mjs --dir /abs/tests/golden/ARMATURE- ## 残余 -- 机器人工具动作「建立骨架(6 骨骼 + 刚性绑定)」尚未落地(`bundleHasRigAction` 仍为软探针)。 +- rig 阶段骨骼父级的世界保持偏差:绑定后各 link 的世界矩阵与绑定前不一致(`robot-rig-web` 证据 + `residuals.worldPreservation.deltas`,最大约 1.26)。按用户指示归入机器人逆解一并处理;该用例当前 + 只判定 URDF 层级与装配绑定关系(6 骨骼对应 6 个转动关节、每个 link 绑定到自己的关节骨骼、无产品控制台错误)。 +- 机器人工具动作「建立骨架(6 骨骼 + 刚性绑定)」已落地:Python 只建骨架与 6 根骨骼,刚性绑定经引擎 + `setParent(BONE, keepTransform)` 完成,与 `armature-bind-web` 共用同一实现。 - `armature-reopen-web`(OPFS 保存重开一致)尚未编写。 - 姿态表单「编辑 / 姿态 / 物体」模式分离与 Ctrl+Tab 进入姿态待实现。 diff --git a/tools/web/check-armature-robot-headed.mjs b/tools/web/check-armature-robot-headed.mjs index 82911ace9..244310ffd 100644 --- a/tools/web/check-armature-robot-headed.mjs +++ b/tools/web/check-armature-robot-headed.mjs @@ -19,7 +19,7 @@ import path from "node:path"; import { fileURLToPath } from "node:url"; const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../.."); -const EXPECTED_CASES = ["robot-sample-web", "robot-assemble-check-web", "robot-pose-web", "armature-bones-web", "armature-bind-web", "armature-pose-web", "armature-viewport-web", "armature-decimal-input-web", "armature-ui-readback-web"]; +const EXPECTED_CASES = ["robot-sample-web", "robot-assemble-check-web", "robot-pose-web", "robot-rig-web", "armature-bones-web", "armature-bind-web", "armature-pose-web", "armature-viewport-web", "armature-decimal-input-web", "armature-ui-readback-web"]; const errors = []; const sha256 = (file) => crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex"); diff --git a/tools/web/run-armature-robot-headed.mjs b/tools/web/run-armature-robot-headed.mjs index d1a1b351d..4589e6602 100644 --- a/tools/web/run-armature-robot-headed.mjs +++ b/tools/web/run-armature-robot-headed.mjs @@ -33,6 +33,7 @@ const KNOWN_CASES = [ { id: "robot-sample-web", title: /\[robot-sample-web\]/ }, { id: "robot-assemble-check-web", title: /\[robot-assemble-check-web\]/ }, { id: "robot-pose-web", title: /\[robot-pose-web\]/ }, + { id: "robot-rig-web", title: /\[robot-rig-web\]/ }, { id: "armature-bones-web", title: /\[armature-bones-web\]/ }, { id: "armature-bind-web", title: /\[armature-bind-web\]/ }, { id: "armature-pose-web", title: /\[armature-pose-web\]/ }, diff --git a/web/app/public/vendor/blender/web_engine.wasm b/web/app/public/vendor/blender/web_engine.wasm index cebffed3b..6d735a182 100644 Binary files a/web/app/public/vendor/blender/web_engine.wasm and b/web/app/public/vendor/blender/web_engine.wasm differ diff --git a/web/app/public/wasm-module-manifest.json b/web/app/public/wasm-module-manifest.json index f54e60f6f..b64656d6e 100644 --- a/web/app/public/wasm-module-manifest.json +++ b/web/app/public/wasm-module-manifest.json @@ -10,7 +10,7 @@ "single": { "fileName": "web_engine.wasm", "url": "/vendor/blender/web_engine.wasm", - "sha256": "03185a413f615d3d2fa14bba59f37fa33f2df6e6e967fa925ba1c48f944879a2" + "sha256": "f3678ad48723668b2282bdea3227900c918bf0ad9e36abe5f11754cda2ff5c56" }, "pthread": { "fileName": "web_engine.wasm", @@ -27,7 +27,7 @@ "single": { "fileName": "web_engine.wasm", "url": "/vendor/blender/web_engine.wasm", - "sha256": "03185a413f615d3d2fa14bba59f37fa33f2df6e6e967fa925ba1c48f944879a2" + "sha256": "f3678ad48723668b2282bdea3227900c918bf0ad9e36abe5f11754cda2ff5c56" }, "pthread": { "fileName": "web_engine.wasm", @@ -44,7 +44,7 @@ "single": { "fileName": "web_engine.wasm", "url": "/vendor/blender/web_engine.wasm", - "sha256": "03185a413f615d3d2fa14bba59f37fa33f2df6e6e967fa925ba1c48f944879a2" + "sha256": "f3678ad48723668b2282bdea3227900c918bf0ad9e36abe5f11754cda2ff5c56" }, "pthread": { "fileName": "web_engine.wasm", @@ -61,7 +61,7 @@ "single": { "fileName": "web_engine.wasm", "url": "/vendor/blender/web_engine.wasm", - "sha256": "03185a413f615d3d2fa14bba59f37fa33f2df6e6e967fa925ba1c48f944879a2" + "sha256": "f3678ad48723668b2282bdea3227900c918bf0ad9e36abe5f11754cda2ff5c56" }, "pthread": { "fileName": "web_engine.wasm", diff --git a/web/app/src/robot/RobotTool.tsx b/web/app/src/robot/RobotTool.tsx index aa5bc52e1..95caaea22 100644 --- a/web/app/src/robot/RobotTool.tsx +++ b/web/app/src/robot/RobotTool.tsx @@ -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;checks:{name:string;status:string;stepRadians:number;maxWorldDelta:number;descendants:number}[];objects:string[];matrices:Record} +interface Result {schemaVersion:1;model:RobotModel;assembled:boolean;angles:Record;checks:{name:string;status:string;stepRadians:number;maxWorldDelta:number;descendants:number}[];objects:string[];matrices:Record;rig?:{armature:string;bindings:Record;bones:string[]}} type Applied=Awaited>; interface Props {client:WebEngineClient|null;snapshot:SceneSnapshotIR|null;onApplied:(scene:Applied)=>void;onStart:()=>Promise;onSave:()=>Promise;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={})=>{ 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
{model?
{model.name} · {model.links.length} links · {files.length} files
:null} -

2 · 装配与检查

+

2 · 装配与检查

{result?{result.model.joints.map(j=>)}
关节父级 → 子级轴检查
{j.name}{j.type}{j.parent} → {j.child}{j.type==='fixed'?'--':j.axis.join(', ')}{result.checks.find(c=>c.name===j.name)?.status??'--'}
:null}
{result?.assembled?

3 · 关节姿态

{result.model.joints.filter(j=>j.type!=='fixed').map(j=>)} diff --git a/web/app/src/robot/robot-workflow.py b/web/app/src/robot/robot-workflow.py index d31dff2b4..f58138a39 100644 --- a/web/app/src/robot/robot-workflow.py +++ b/web/app/src/robot/robot-workflow.py @@ -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('未知机器人操作') diff --git a/web/app/src/vendor/blender/web_engine.wasm b/web/app/src/vendor/blender/web_engine.wasm index cebffed3b..6d735a182 100644 Binary files a/web/app/src/vendor/blender/web_engine.wasm and b/web/app/src/vendor/blender/web_engine.wasm differ diff --git a/web/protocol/web-engine.ts b/web/protocol/web-engine.ts index b0e3e20eb..07aa3f563 100644 --- a/web/protocol/web-engine.ts +++ b/web/protocol/web-engine.ts @@ -184,8 +184,8 @@ export type WebEngineEditCommand = | { type: "setActiveAction"; objectId: string; actionId: string | null } | { type: "setConstraint"; baseRevision?: number; objectId: string; constraintName: string; enabled: boolean; influence: number } | { type: "moveConstraint"; baseRevision?: number; objectId: string; constraintName: string; direction: "UP" | "DOWN"; boneName?: string } - | { type: "setParent"; objectId: string; parentId: string | null; keepTransform?: boolean } - | { type: "setParents"; objectIds: string[]; parentId: string | null; keepTransform?: boolean } + | { type: "setParent"; objectId: string; parentId: string | null; keepTransform?: boolean; parentType?: "OBJECT" | "BONE"; parentBone?: string } + | { type: "setParents"; objectIds: string[]; parentId: string | null; keepTransform?: boolean; parentType?: "OBJECT" | "BONE"; parentBone?: string } | { type: "createCollection"; name: string; parentCollectionId?: string | null } | { type: "moveObjectToCollection"; objectId: string; collectionId: string; keepExistingLinks?: boolean } | { type: "moveCollection"; collectionId: string; parentCollectionId?: string | null; anchorCollectionId?: string | null; after?: boolean } diff --git a/web/tests/e2e/armature-robot-headed-production.spec.ts b/web/tests/e2e/armature-robot-headed-production.spec.ts index c757db2f5..1ec2bcc3b 100644 --- a/web/tests/e2e/armature-robot-headed-production.spec.ts +++ b/web/tests/e2e/armature-robot-headed-production.spec.ts @@ -222,3 +222,58 @@ test('joint_1 pose moves the link chain and 恢复零位 restores it [robot-pose expect(joints).toEqual(REVOLUTE.map((name) => `${name} 角度`)); expect(productConsole(errors)).toEqual([]); }); + +/* 建立骨架 converts each revolute joint into a bone and rigidly binds the child + * link to it (desktop ob_parbone semantics). The check runs on the engine + * snapshot, never on the tool's own report. */ +const EXPECTED_BONES: Record = { link_1: 'joint_1', link_2: 'joint_2', link_3: 'joint_3', link_4: 'joint_4', link_5: 'joint_5', link_6: 'joint_6' }; + +test('establishing the armature binds every link to its joint bone [robot-rig-web]', async ({ page }, testInfo) => { + const errors = consoleCollector(page); + await installEngineBridge(page); + const dialog = await openRobotTool(page); + await loadSample(dialog); + await importParts(page, dialog); + await assembleAndCheck(dialog); + const before = await snapshotFacts(page, [ROOT_OBJECT, ...LINKS]); + + await dialog.getByRole('button', { name: '建立骨架(6 骨骼 + 刚性绑定)', exact: true }).click(); + await expect(dialog).toContainText('骨架已建立(6 骨骼 + 刚性绑定)', { timeout: 180_000 }); + const rigged = await readAfterRevision(page, before.revision ?? 0, [ROOT_OBJECT, ...LINKS]); + + const bones = (rigged.armatures ?? []).flatMap((armature) => armature.bones).map((bone) => bone.name).sort(); + const bound = Object.fromEntries(Object.entries(rigged.nodes ?? {}) + .filter(([, node]) => node.parentType === 'BONE') + .map(([name, node]) => [name, node.parentBoneName])); + const worldDelta = Object.fromEntries(Object.keys(EXPECTED_BONES).map((link) => [link, + matrixDistance(before.nodes?.[link]?.worldMatrix ?? null, rigged.nodes?.[link]?.worldMatrix ?? null)])); + const evidence = { + schemaVersion: 1, + case: 'robot-rig-web', + candidate: CANDIDATE, + revisions: { before: before.revision ?? null, rigged: rigged.revision ?? null }, + bones, + bound, + worldDelta, + matrices: Object.fromEntries(Object.keys(EXPECTED_BONES).map((link) => [link, { before: before.nodes?.[link]?.worldMatrix ?? null, rigged: rigged.nodes?.[link]?.worldMatrix ?? null, boundMatrix: rigged.nodes?.[link]?.parentBoneMatrix ?? null }])), + bonePose: Object.fromEntries((rigged.armatures ?? []).flatMap((armature) => armature.bones).map((bone) => [bone.name, { rest: bone.restMatrix, pose: bone.poseMatrix }])), + rawNodes: Object.fromEntries(Object.entries(rigged.nodes ?? {}).filter(([, node]) => node.parentType === 'BONE' || node.type === 'ARMATURE')), + console: { productErrors: productConsole(errors), rawErrorCount: errors.length }, + residuals: { + worldPreservation: { + status: 'deferred', + note: 'rig 阶段骨骼父级的世界保持偏差归入机器人逆解一并处理;本用例只判定 URDF 层级与装配绑定关系', + deltas: worldDelta, + }, + }, + acceptance: 'NOT_CLAIMED', + }; + await attachEvidence(testInfo, 'robot-rig-web', evidence); + + expect(bones).toEqual([...REVOLUTE].sort()); + for (const [link, bone] of Object.entries(EXPECTED_BONES)) expect(bound[link]).toBe(bone); + /* World preservation across the rig step is recorded in evidence (residuals) + * and handled together with robot inverse kinematics; this case asserts the + * URDF hierarchy and assembly binding only. */ + expect(productConsole(errors)).toEqual([]); +});