Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
1362 lines (1278 loc) · 47.8 KB
/
Copy pathindex.js
File metadata and controls
1362 lines (1278 loc) · 47.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
/**
* GuaDa Blender — 三方插件入口(Phase 1)
*
* 8 个工具 + 1 个编排技能:
* blender_status / blender_scene_info / blender_run_script / blender_import
* blender_python / blender_preview / blender_render / blender_export
*
* 约束:
* - 零依赖 CommonJS;只使用 onLoad(api) 的公开 PluginApi;
* - 不修改宿主源码;所有路径在插件侧做 workspace 守卫;
* - 每次调用启动独立 Blender 后台进程,不开放控制端口。
*/
const fs = require('node:fs');
const path = require('node:path');
const os = require('node:os');
const {
DEFAULTS,
detectBlender,
resolveExecutable,
getConfig,
saveConfig,
} = require('./lib/config');
const {
workspaceOf,
resolveWorkspacePath,
assertRegularFile,
assertWritableTarget,
} = require('./lib/paths');
const { getVersion, runBlender, runScript } = require('./lib/blender');
const { parseFrames } = require('./lib/frames');
const { HELPERS, UNSUPPORTED, getHelper, getUnsupported } = require('./lib/helpers');
const { detectAndProbe, missingPackages } = require('./lib/python');
const { runHelper, prepareHelperCommand } = require('./lib/helper-runner');
const { clip, spawnToLog, readLogSlice } = require('./lib/process');
const PLUGIN_ID = 'guada-blender';
const PLUGIN_NAME = 'GuaDa Blender';
const VERSION = '0.5.0';
const SUPPORTED_IMPORTS = new Set([
'.glb', '.gltf', '.fbx', '.obj', '.stl', '.usd', '.usda', '.usdc', '.ply', '.dae',
]);
const SUPPORTED_EXPORTS = new Set(['.glb', '.gltf', '.fbx', '.obj', '.stl', '.usd', '.usda', '.usdc', '.ply']);
const IMAGE_EXTS = new Set(['.png', '.jpg', '.jpeg']);
const PREVIEW_VIEWS = ['isometric', 'front', 'back', 'left', 'right', 'top', 'bottom'];
const VALIDATION_PROFILES = ['general', 'web', '3d-print', 'animation'];
const NLS_ZH = {
'settings.title': 'GuaDa Blender',
'settings.desc': 'Blender 3D 建模、检查、预览、渲染与导出',
};
const NLS_EN = {
'settings.title': 'GuaDa Blender',
'settings.desc': 'Blender 3D modeling, inspection, preview, render and export',
};
function json(value) {
return JSON.stringify(value, null, 2);
}
function mediaTypeOf(file) {
const ext = path.extname(file).toLowerCase();
return ext === '.png' ? 'image/png' : 'image/jpeg';
}
function imageRefFor(file) {
return {
url: file,
refType: 'local',
media_type: mediaTypeOf(file),
name: path.basename(file),
};
}
function imageRefsFor(files, max = 8) {
return (files || []).slice(0, max).map(imageRefFor);
}
function imageResult(file, summary) {
return {
content: json(summary),
imageRefs: [imageRefFor(file)],
};
}
function asNumber(value, fallback) {
const n = Number(value);
return Number.isFinite(n) && n > 0 ? n : fallback;
}
function asBool(value) {
return value === true || value === 'true' || value === 1 || value === '1';
}
function ensureExt(target, allowed, label) {
const ext = path.extname(target).toLowerCase();
if (!allowed.has(ext)) {
throw new Error(`${label} has unsupported extension: ${ext || '(none)'}`);
}
return ext;
}
class GuadaBlenderPlugin {
constructor() {
this.manifest = {
id: PLUGIN_ID,
name: PLUGIN_NAME,
version: VERSION,
description: 'Blender 3D 建模、场景检查、预览、渲染与导出工具',
author: 'donggua-zen',
category: 'user',
icon: 'assets/icon.svg',
};
this.api = null;
this.dataDir = null;
this.pluginDir = null;
this.cachedVersion = null;
}
async onLoad(api) {
this.api = api;
this.pluginDir = typeof api.getPluginDir === 'function' ? api.getPluginDir() : path.dirname(__filename);
try {
this.dataDir = typeof api.getDataDir === 'function' ? api.getDataDir() : path.join(os.tmpdir(), PLUGIN_ID);
} catch {
this.dataDir = path.join(os.tmpdir(), PLUGIN_ID);
}
fs.mkdirSync(this.dataDir, { recursive: true });
this.registerNls(api);
this.registerSlot(api);
this.registerSkill(api);
this.registerTools(api);
this.registerRpc(api);
}
async onStart() {
// 预热版本探测(失败不阻塞启用)
try {
const config = await getConfig(this.api);
const { executable } = resolveExecutable(config);
this.cachedVersion = await getVersion(executable, { timeoutMs: 15000 });
} catch {
this.cachedVersion = null;
}
}
async onStop() {}
async onUnload() {}
// ── 注册 ──
registerNls(api) {
if (typeof api.registerNls !== 'function') return;
api.registerNls('zh', NLS_ZH);
api.registerNls('en', NLS_EN);
}
registerSlot(api) {
if (typeof api.registerSlot !== 'function') return;
api.registerSlot({
name: 'settings',
component: 'SettingsPage',
mode: 'list',
order: 70,
meta: { label: '%settings.title%', group: 'plugin' },
});
}
registerSkill(api) {
if (typeof api.registerSkill !== 'function') return;
const skillRoot = path.join(this.pluginDir, 'skills');
if (!fs.existsSync(skillRoot)) return;
// 编排技能 + references/modules 下的 29 个领域技能
const targets = [{ dir: path.join(skillRoot, 'create-3d-model'), orchestration: true }];
const modulesRoot = path.join(skillRoot, 'create-3d-model', 'references', 'modules');
if (fs.existsSync(modulesRoot)) {
for (const entry of fs.readdirSync(modulesRoot, { withFileTypes: true })) {
if (!entry.isDirectory()) continue;
targets.push({ dir: path.join(modulesRoot, entry.name), orchestration: false });
}
}
this.registeredSkills = 0;
for (const target of targets) {
try {
const file = path.join(target.dir, 'SKILL.md');
if (!fs.existsSync(file)) continue;
const raw = fs.readFileSync(file, 'utf8');
const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/u.exec(raw);
if (!match) continue;
const name = (/^name:\s*(.+)$/mu.exec(match[1]) || [])[1];
const description = (/^description:\s*(.+)$/mu.exec(match[1]) || [])[1];
if (!name || !description) continue;
api.registerSkill({
name: name.trim(),
description: description.trim(),
content: match[2].trim(),
version: VERSION,
author: 'donggua-zen',
tags: target.orchestration
? ['blender', '3d', 'modeling', 'render']
: ['blender', '3d', 'module'],
resourceBase: { kind: 'directory', path: target.dir },
});
this.registeredSkills++;
} catch (err) {
// 单个技能失败不阻断插件加载
this.skillErrors = (this.skillErrors || 0) + 1;
}
}
}
// ── 工具 ──
registerTools(api) {
api.registerTool(this.toolStatus());
api.registerTool(this.toolSceneInfo());
api.registerTool(this.toolRunScript());
api.registerTool(this.toolImport());
api.registerTool(this.toolPython());
api.registerTool(this.toolPreview());
api.registerTool(this.toolRender());
api.registerTool(this.toolRenderFrames());
api.registerTool(this.toolExport());
api.registerTool(this.toolValidateScene());
api.registerTool(this.toolValidateExport());
api.registerTool(this.toolHelperCatalog());
api.registerTool(this.toolHelperRun());
}
async prepare(ctx) {
const config = await getConfig(this.api);
const { executable, source } = resolveExecutable(config);
return { config, executable, source, workspace: workspaceOf(ctx && ctx.session) };
}
/**
* 后台执行一个 Blender 进程,登记为宿主 job。
* 返回 { jobId, logFilePath };调用方用 job_read / job_stop 管理。
*/
startBlenderJob(options) {
const { executable, args, config, workspace, label, signal, sessionId } = options;
if (!this.api || typeof this.api.startJob !== 'function') {
throw new Error('background jobs are not supported by this host');
}
// 先校验会话,避免"进程已起、job 没登记"的孤儿
if (!sessionId) {
throw new Error(
'background mode requires a session context (sessionId); run in the foreground instead',
);
}
const jobDir = path.join(this.dataDir, 'jobs');
const logFilePath = path.join(
jobDir,
`${Date.now()}-${Math.random().toString(36).slice(2, 8)}.log`,
);
const handle = spawnToLog(executable, args, {
cwd: workspace,
logFilePath,
timeoutMs: config.timeoutMs,
signal,
});
const jobId = this.api.startJob(
{
label,
logFilePath,
notify: true,
read: (opts) => readLogSlice(logFilePath, opts),
cancel: () => handle.kill(),
done: handle.done.then((outcome) => ({
status: outcome.status,
exitCode: outcome.exitCode,
detail: outcome.detail,
})),
},
sessionId,
);
return { jobId, logFilePath, handle };
}
/**
* 构造后台渲染的 Blender 参数(与 runBlender 的 driver 调用一致)。
*/
buildDriverArgs(operation, payloadPath, resultPath, blendPath) {
const args = blendPath
? [blendPath, '--background']
: ['--background', '--factory-startup'];
args.push(
'--disable-autoexec',
'--python-exit-code',
'1',
'--python',
path.join(this.pluginDir, 'scripts', 'blender_driver.py'),
'--',
'--operation',
operation,
'--payload',
payloadPath,
'--result',
resultPath,
);
return args;
}
toolStatus() {
return {
name: 'blender_status',
description:
'检查 Blender 是否可用、版本、当前 workspace 与插件配置。首次建模前先调用。',
parameters: {},
readOnly: true,
dangerLevel: 'safe',
display: { icon: 'info', text: { executing: '检查 Blender', completed: 'Blender 检查完成' } },
execute: async (_args, ctx, signal) => {
const workspace = workspaceOf(ctx && ctx.session);
let config;
let executable = '';
let source = '';
try {
config = await getConfig(this.api);
const resolved = resolveExecutable(config);
executable = resolved.executable;
source = resolved.source;
} catch (err) {
return {
content: json({
available: false,
workspace,
error: err.message,
hint: '在 设置 → GuaDa Blender 中填写 blender 可执行文件路径',
}),
};
}
const version = await getVersion(executable, {
timeoutMs: Math.min(config.timeoutMs, 15000),
signal,
});
const analysis = await detectAndProbe({
analysisPythonExecutable: config.analysisPythonExecutable,
blenderExecutable: executable,
timeoutMs: Math.min(config.timeoutMs, 15000),
signal,
});
return {
content: json({
available: version.available,
executable,
executableSource: source,
version: version.version,
error: version.error || undefined,
workspace,
pythonEnabled: config.enablePython !== false,
analysis: {
available: analysis.available,
executable: analysis.executable,
source: analysis.source,
version: analysis.version,
packages: analysis.packages,
error: analysis.error || undefined,
},
helpers: {
enabled: config.enableHelpers !== false,
count: HELPERS.length,
},
skills: this.registeredSkills || 0,
config,
}),
};
},
};
}
toolSceneInfo() {
return {
name: 'blender_scene_info',
description:
'只读检查 .blend 场景;传 object_name 时返回该对象的详细几何/材质/UV/修改器/动画信息。',
parameters: {
blend_path: { type: 'string', required: true, description: 'workspace 内的 .blend 路径' },
object_name: { type: 'string', required: false, description: '可选:只看某个对象' },
max_objects: { type: 'number', required: false, description: '场景对象上限,默认 200' },
},
readOnly: true,
dangerLevel: 'safe',
display: { icon: 'scene', argsKey: 'blend_path' },
execute: async (args, ctx, signal) => {
const { config, executable, workspace } = await this.prepare(ctx);
const blend = await resolveWorkspacePath(args.blend_path, ctx && ctx.session, config, {
mustExist: true,
kind: 'blend_path',
});
await assertRegularFile(blend, 'blend_path');
ensureExt(blend, new Set(['.blend']), 'blend_path');
const operation = args.object_name ? 'inspect_object' : 'inspect';
const payload = args.object_name
? { object_names: [String(args.object_name)], evaluated: true }
: { max_objects: asNumber(args.max_objects, 200) };
const result = await runBlender({
executable,
operation,
payload,
blendPath: blend,
config,
cwd: workspace,
signal,
});
return { content: json(result) };
},
};
}
toolRunScript() {
return {
name: 'blender_run_script',
description:
'在 Blender 后台运行 workspace 内的 .py 脚本(等价 blender --background --python)。脚本内部的文件读写不受工具参数守卫限制。',
parameters: {
script_path: { type: 'string', required: true, description: 'workspace 内的 .py 脚本路径' },
script_args: { type: 'string', required: false, description: '可选:传给脚本的参数,空格分隔' },
},
dangerLevel: 'high',
display: { icon: 'code', argsKey: 'script_path' },
execute: async (args, ctx, signal) => {
const { config, executable, workspace } = await this.prepare(ctx);
if (config.enablePython === false) {
throw new Error('blender_run_script is disabled by plugin config (enablePython=false)');
}
const script = await resolveWorkspacePath(args.script_path, ctx && ctx.session, config, {
mustExist: true,
kind: 'script_path',
});
await assertRegularFile(script, 'script_path');
ensureExt(script, new Set(['.py']), 'script_path');
const scriptArgs = String(args.script_args || '')
.split(/\s+/)
.map((s) => s.trim())
.filter(Boolean);
const result = await runScript({
executable,
scriptPath: script,
scriptArgs,
config,
cwd: workspace,
signal,
});
if (result.code !== 0 || result.timedOut || result.aborted) {
const reason = result.timedOut
? 'timed out'
: result.aborted
? 'aborted'
: `exit ${result.code}`;
throw new Error(
`blender_run_script failed (${reason})\n${clip(
`${result.stdout}\n${result.stderr}`.trim(),
config.maxOutputChars,
)}`,
);
}
return {
content: json({
scriptPath: script,
code: result.code,
durationMs: result.durationMs,
stdout: result.stdout,
stderr: result.stderr,
}),
};
},
};
}
toolImport() {
return {
name: 'blender_import',
description:
'把 GLB/glTF、FBX、OBJ、STL、USD、PLY、DAE 导入干净场景并保存为新的 .blend。',
parameters: {
source_path: { type: 'string', required: true, description: 'workspace 内的模型文件' },
save_path: { type: 'string', required: true, description: '新的 .blend 输出路径' },
allow_overwrite: { type: 'boolean', required: false, description: '允许覆盖已有输出,默认 false' },
},
dangerLevel: 'normal',
display: { icon: 'import', argsKey: 'source_path' },
execute: async (args, ctx, signal) => {
const { config, executable, workspace } = await this.prepare(ctx);
const source = await resolveWorkspacePath(args.source_path, ctx && ctx.session, config, {
mustExist: true,
kind: 'source_path',
});
await assertRegularFile(source, 'source_path');
ensureExt(source, SUPPORTED_IMPORTS, 'source_path');
const save = await resolveWorkspacePath(args.save_path, ctx && ctx.session, config, {
kind: 'save_path',
});
ensureExt(save, new Set(['.blend']), 'save_path');
await assertWritableTarget(save, asBool(args.allow_overwrite), 'save_path');
const result = await runBlender({
executable,
operation: 'import',
payload: { source_path: source, output_path: save },
config,
cwd: workspace,
signal,
});
const info = await assertRegularFile(save, 'import output');
return {
content: json({
sourcePath: source,
blendPath: save,
bytes: info.size,
importedObjects: result.imported_objects || [],
scene: result.scene,
log: result.log,
}),
};
},
};
}
toolPython() {
return {
name: 'blender_python',
description:
'执行一小段 bpy/bmesh Python 并保存为新的 .blend。脚本可使用 bpy/bmesh/mathutils/workspace/input_path/output_path,并可设置 dsh_result 返回证据。',
parameters: {
script: { type: 'string', required: true, description: '要执行的 Python 代码' },
save_path: { type: 'string', required: true, description: '新的 .blend 输出路径' },
blend_path: { type: 'string', required: false, description: '可选:基于已有 .blend 修改' },
allow_overwrite: { type: 'boolean', required: false, description: '允许覆盖已有输出,默认 false' },
},
dangerLevel: 'high',
display: { icon: 'code', argsKey: 'save_path' },
execute: async (args, ctx, signal) => {
const { config, executable, workspace } = await this.prepare(ctx);
if (config.enablePython === false) {
throw new Error('blender_python is disabled by plugin config (enablePython=false)');
}
let blend;
if (args.blend_path) {
blend = await resolveWorkspacePath(args.blend_path, ctx && ctx.session, config, {
mustExist: true,
kind: 'blend_path',
});
await assertRegularFile(blend, 'blend_path');
ensureExt(blend, new Set(['.blend']), 'blend_path');
}
const save = await resolveWorkspacePath(args.save_path, ctx && ctx.session, config, {
kind: 'save_path',
});
ensureExt(save, new Set(['.blend']), 'save_path');
await assertWritableTarget(save, asBool(args.allow_overwrite), 'save_path');
const result = await runBlender({
executable,
operation: 'execute',
payload: {
workspace,
input_path: blend || '',
output_path: save,
script: String(args.script || ''),
},
blendPath: blend,
config,
cwd: workspace,
signal,
});
const info = await assertRegularFile(save, 'python output');
return {
content: json({
blendPath: save,
bytes: info.size,
scene: result.scene,
scriptResult: result.script_result,
log: result.log,
}),
};
},
};
}
toolPreview() {
return {
name: 'blender_preview',
description:
'为 .blend 生成临时相机+灯光的预览图(不修改源文件);成功后用 image_view 看图再判断。',
parameters: {
blend_path: { type: 'string', required: true, description: 'workspace 内的 .blend' },
output_path: { type: 'string', required: true, description: '新的 .png/.jpg 输出路径' },
view: {
type: 'string',
required: false,
enum: PREVIEW_VIEWS,
description: '视角,默认 isometric',
},
width: { type: 'number', required: false, description: '宽度,默认 512' },
height: { type: 'number', required: false, description: '高度,默认 512' },
samples: { type: 'number', required: false, description: '渲染采样数,默认 32' },
transparent: { type: 'boolean', required: false, description: '透明背景' },
object_names: { type: 'string', required: false, description: '可选:只框选这些对象,逗号分隔' },
allow_overwrite: { type: 'boolean', required: false, description: '允许覆盖已有输出' },
},
dangerLevel: 'normal',
display: { icon: 'image', argsKey: 'output_path' },
execute: async (args, ctx, signal) => {
const { config, executable, workspace } = await this.prepare(ctx);
const blend = await resolveWorkspacePath(args.blend_path, ctx && ctx.session, config, {
mustExist: true,
kind: 'blend_path',
});
await assertRegularFile(blend, 'blend_path');
const output = await resolveWorkspacePath(args.output_path, ctx && ctx.session, config, {
kind: 'output_path',
});
ensureExt(output, IMAGE_EXTS, 'output_path');
await assertWritableTarget(output, asBool(args.allow_overwrite), 'output_path');
const objects = String(args.object_names || '')
.split(',')
.map((s) => s.trim())
.filter(Boolean);
const result = await runBlender({
executable,
operation: 'preview',
payload: {
output_path: output,
view: PREVIEW_VIEWS.includes(args.view) ? args.view : 'isometric',
width: asNumber(args.width, 512),
height: asNumber(args.height, 512),
samples: asNumber(args.samples, 32),
transparent: asBool(args.transparent),
object_names: objects.length ? objects : undefined,
},
blendPath: blend,
config,
cwd: workspace,
signal,
});
const info = await assertRegularFile(output, 'preview output');
return imageResult(output, {
imagePath: output,
bytes: info.size,
view: result.view,
bounds: result.bounds,
log: result.log,
});
},
};
}
toolRender() {
return {
name: 'blender_render',
description:
'用场景当前相机渲染一帧 PNG/JPEG;成功后用 image_view 看图再判断。',
parameters: {
blend_path: { type: 'string', required: true, description: 'workspace 内的 .blend' },
output_path: { type: 'string', required: true, description: '新的 .png/.jpg 输出路径' },
frame: { type: 'number', required: false, description: '可选:帧号' },
width: { type: 'number', required: false, description: '宽度,默认 960' },
height: { type: 'number', required: false, description: '高度,默认 960' },
samples: { type: 'number', required: false, description: '渲染采样数,默认 64' },
transparent: { type: 'boolean', required: false, description: '透明背景' },
camera: { type: 'string', required: false, description: '可选:相机对象名' },
allow_overwrite: { type: 'boolean', required: false, description: '允许覆盖已有输出' },
run_in_background: {
type: 'boolean',
required: false,
description: '后台执行并返回 jobId(用 job_read/job_stop 管理),默认 false',
},
},
dangerLevel: 'normal',
display: { icon: 'image', argsKey: 'output_path' },
execute: async (args, ctx, signal) => {
const { config, executable, workspace } = await this.prepare(ctx);
const blend = await resolveWorkspacePath(args.blend_path, ctx && ctx.session, config, {
mustExist: true,
kind: 'blend_path',
});
await assertRegularFile(blend, 'blend_path');
const output = await resolveWorkspacePath(args.output_path, ctx && ctx.session, config, {
kind: 'output_path',
});
ensureExt(output, IMAGE_EXTS, 'output_path');
await assertWritableTarget(output, asBool(args.allow_overwrite), 'output_path');
const payload = {
output_path: output,
frame: args.frame === undefined ? undefined : asNumber(args.frame, 1),
width: asNumber(args.width, 960),
height: asNumber(args.height, 960),
samples: asNumber(args.samples, 64),
transparent: asBool(args.transparent),
camera: args.camera ? String(args.camera) : undefined,
};
if (asBool(args.run_in_background)) {
const tempDir = await fs.promises.mkdtemp(
path.join(os.tmpdir(), 'guada-blender-job-'),
);
const payloadPath = path.join(tempDir, 'payload.json');
const resultPath = path.join(tempDir, 'result.json');
await fs.promises.writeFile(payloadPath, JSON.stringify(payload), 'utf8');
const { jobId, logFilePath } = this.startBlenderJob({
executable,
args: this.buildDriverArgs('render', payloadPath, resultPath, blend),
config,
workspace,
label: `blender_render: ${path.basename(output)}`,
signal,
sessionId: ctx && ctx.session && ctx.session.sessionId,
});
return {
content: json({
jobId,
logFilePath,
outputPath: output,
note: 'running in background; use job_read to follow progress',
}),
};
}
const result = await runBlender({
executable,
operation: 'render',
payload,
blendPath: blend,
config,
cwd: workspace,
signal,
});
const info = await assertRegularFile(output, 'render output');
return imageResult(output, {
imagePath: output,
bytes: info.size,
frame: result.frame,
log: result.log,
});
},
};
}
toolRenderFrames() {
return {
name: 'blender_render_frames',
description:
'按帧号批量渲染 PNG/JPEG(动画代表帧/序列帧)。frames 支持 "1,3,5-7",单次最多 120 帧。',
parameters: {
blend_path: { type: 'string', required: true, description: 'workspace 内的 .blend' },
output_dir: { type: 'string', required: true, description: 'workspace 内的输出目录(自动创建)' },
frames: { type: 'string', required: true, description: '帧号表达式,如 "1,3,5-7"' },
format: { type: 'string', required: false, description: 'png(默认)或 jpg' },
prefix: { type: 'string', required: false, description: '文件名前缀,默认 frame' },
width: { type: 'number', required: false, description: '宽度,默认 640' },
height: { type: 'number', required: false, description: '高度,默认 640' },
samples: { type: 'number', required: false, description: '采样数,默认 32' },
camera: { type: 'string', required: false, description: '可选:相机对象名' },
allow_overwrite: { type: 'boolean', required: false, description: '允许覆盖已有帧文件' },
run_in_background: {
type: 'boolean',
required: false,
description: '后台执行并返回 jobId(用 job_read/job_stop 管理),默认 false',
},
},
dangerLevel: 'normal',
display: { icon: 'image', argsKey: 'frames' },
execute: async (args, ctx, signal) => {
const { config, executable, workspace } = await this.prepare(ctx);
const blend = await resolveWorkspacePath(args.blend_path, ctx && ctx.session, config, {
mustExist: true,
kind: 'blend_path',
});
await assertRegularFile(blend, 'blend_path');
ensureExt(blend, new Set(['.blend']), 'blend_path');
const outDir = await resolveWorkspacePath(args.output_dir, ctx && ctx.session, config, {
kind: 'output_dir',
});
const frames = parseFrames(args.frames);
await fs.promises.mkdir(outDir, { recursive: true });
const format = String(args.format || 'png').toLowerCase() === 'jpg' ? 'jpg' : 'png';
const prefix =
String(args.prefix || 'frame').replace(/[^A-Za-z0-9._-]/g, '_') || 'frame';
const files = frames.map((frame) =>
path.join(outDir, `${prefix}-${String(frame).padStart(6, '0')}.${format}`),
);
if (!asBool(args.allow_overwrite)) {
const conflicts = files.filter((file) => fs.existsSync(file));
if (conflicts.length > 0) {
throw new Error(
`render frames would overwrite ${conflicts.length} file(s): ${conflicts
.slice(0, 3)
.join(', ')} (set allow_overwrite=true to replace)`,
);
}
}
const payload = {
frames,
output_dir: outDir,
format,
prefix,
width: asNumber(args.width, 640),
height: asNumber(args.height, 640),
samples: asNumber(args.samples, 32),
camera: args.camera ? String(args.camera) : undefined,
};
if (asBool(args.run_in_background)) {
const tempDir = await fs.promises.mkdtemp(
path.join(os.tmpdir(), 'guada-blender-job-'),
);
const payloadPath = path.join(tempDir, 'payload.json');
const resultPath = path.join(tempDir, 'result.json');
await fs.promises.writeFile(payloadPath, JSON.stringify(payload), 'utf8');
const { jobId, logFilePath } = this.startBlenderJob({
executable,
args: this.buildDriverArgs('render_frames', payloadPath, resultPath, blend),
config,
workspace,
label: `blender_render_frames: ${frames.length} frame(s)`,
signal,
sessionId: ctx && ctx.session && ctx.session.sessionId,
});
return {
content: json({
jobId,
logFilePath,
outputDir: outDir,
frames,
note: 'running in background; use job_read with the job id to follow progress, job_stop to cancel',
}),
};
}
const result = await runBlender({
executable,
operation: 'render_frames',
payload,
blendPath: blend,
config,
cwd: workspace,
signal,
});
const imagePaths =
Array.isArray(result.image_paths) && result.image_paths.length > 0
? result.image_paths
: files;
return {
content: json({
outputDir: outDir,
frames,
imagePaths,
imageCount: imagePaths.length,
log: result.log,
}),
imageRefs: imageRefsFor(imagePaths, 8),
};
},
};
}
toolExport() {
return {
name: 'blender_export',
description:
'把 .blend 导出为 GLB/glTF、FBX、OBJ、STL、USD 或 PLY;扩展名决定格式。',
parameters: {
blend_path: { type: 'string', required: true, description: 'workspace 内的 .blend' },
output_path: { type: 'string', required: true, description: '导出路径(扩展名决定格式)' },
selection_only: { type: 'boolean', required: false, description: '只导出选中对象' },
allow_overwrite: { type: 'boolean', required: false, description: '允许覆盖已有输出' },
},
dangerLevel: 'normal',
display: { icon: 'export', argsKey: 'output_path' },
execute: async (args, ctx, signal) => {
const { config, executable, workspace } = await this.prepare(ctx);
const blend = await resolveWorkspacePath(args.blend_path, ctx && ctx.session, config, {
mustExist: true,
kind: 'blend_path',
});
await assertRegularFile(blend, 'blend_path');
const output = await resolveWorkspacePath(args.output_path, ctx && ctx.session, config, {
kind: 'output_path',
});
ensureExt(output, SUPPORTED_EXPORTS, 'output_path');
await assertWritableTarget(output, asBool(args.allow_overwrite), 'output_path');
const result = await runBlender({
executable,
operation: 'export',
payload: {
output_path: output,
selection_only: asBool(args.selection_only),
},
blendPath: blend,
config,
cwd: workspace,
signal,
});
const info = await assertRegularFile(output, 'export output');
return {
content: json({
modelPath: output,
format: result.format,
bytes: info.size,
log: result.log,
}),
};
},
};
}
toolValidateScene() {
return {
name: 'blender_validate_scene',
description:
'对 .blend 做非破坏性结构审计(拓扑/非流形/松散点/UV/材质/变换/动画)。profile: general、web、3d-print、animation。errors 非空时工具结果标记为失败。',
parameters: {
blend_path: { type: 'string', required: true, description: 'workspace 内的 .blend' },
profile: {
type: 'string',
required: false,
enum: VALIDATION_PROFILES,
description: '审计目标,默认 general',
},
object_names: {
type: 'string',
required: false,
description: '可选:只审这些对象,逗号分隔;缺省全场景',
},
},
readOnly: true,
dangerLevel: 'safe',
display: { icon: 'check', argsKey: 'blend_path' },
execute: async (args, ctx, signal) => {
const { config, executable, workspace } = await this.prepare(ctx);
const blend = await resolveWorkspacePath(args.blend_path, ctx && ctx.session, config, {
mustExist: true,
kind: 'blend_path',
});
await assertRegularFile(blend, 'blend_path');
ensureExt(blend, new Set(['.blend']), 'blend_path');
const profile = args.profile ? String(args.profile) : 'general';
if (!VALIDATION_PROFILES.includes(profile)) {
throw new Error(`profile must be one of: ${VALIDATION_PROFILES.join(', ')}`);
}
const objectNames = String(args.object_names || '')
.split(',')
.map((s) => s.trim())
.filter(Boolean);
const result = await runBlender({
executable,
operation: 'validate_scene',
payload: { profile, object_names: objectNames },
blendPath: blend,
config,
cwd: workspace,
signal,
});
return {
content: json({
blendPath: blend,
profile,
passed: result.passed,
errors: result.errors || [],
warnings: result.warnings || [],
objects: result.objects || [],
scene: result.scene,
log: result.log,
}),
isError: result.passed !== true,
};
},
};
}
toolValidateExport() {