@ajsmonty/adobe-mcp 1.1.2 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +307 -120
- package/SECURITY.md +19 -1
- package/adapters/blender.mjs +230 -0
- package/adapters/ppro.mjs +4 -3
- package/adapters/substance.mjs +193 -0
- package/adapters/texlib.mjs +193 -0
- package/bridges/blender/adobe_mcp_bridge.py +132 -0
- package/cep/mcp-bridge/main.js +2 -2
- package/cli/doctor.mjs +203 -0
- package/cli/index.mjs +67 -0
- package/cli/install.mjs +142 -0
- package/core/blender_pbr.py +148 -0
- package/core/bridge.mjs +111 -61
- package/core/harness.py +34 -0
- package/core/platform.mjs +205 -0
- package/core/pybridge.mjs +256 -0
- package/core/telemetry.mjs +80 -0
- package/core/texlib.mjs +279 -0
- package/core/win/run_com.js +25 -0
- package/core/workspace.mjs +1 -1
- package/knowledge/knowledge.mjs +8 -5
- package/knowledge/lessons.jsonl +19 -0
- package/package.json +45 -3
- package/scripts/ae/Cinematic_3D_Composite.jsx +173 -0
- package/scripts/blender/Creature_Walk_Cinematic.py +569 -0
- package/scripts/substance/Creature_Skin_LookDev.py +148 -0
- package/server.mjs +69 -27
- package/workflow/vfx.mjs +136 -0
- package/workflow/workflow.mjs +66 -21
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
// Blender adapter — Python (bpy) via the live add-on or a headless background process.
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { runBlender, blenderSaveSnippet } from "../core/pybridge.mjs";
|
|
7
|
+
|
|
8
|
+
const MODE = z
|
|
9
|
+
.enum(["auto", "live", "background"])
|
|
10
|
+
.optional()
|
|
11
|
+
.describe(
|
|
12
|
+
"live = the running Blender (needs the adobe-mcp add-on), background = headless process, " +
|
|
13
|
+
"auto (default) = live if the add-on answers and no blend_file is given, else background."
|
|
14
|
+
);
|
|
15
|
+
const BLEND = z
|
|
16
|
+
.string()
|
|
17
|
+
.optional()
|
|
18
|
+
.describe("Absolute .blend path to open (background mode). Without it background starts from factory settings.");
|
|
19
|
+
|
|
20
|
+
const STATE_PY = `
|
|
21
|
+
import bpy
|
|
22
|
+
s = bpy.context.scene
|
|
23
|
+
r = s.render
|
|
24
|
+
objs = []
|
|
25
|
+
for o in s.objects:
|
|
26
|
+
rec = {"name": o.name, "type": o.type, "location": [round(v, 4) for v in o.location],
|
|
27
|
+
"rotation_euler": [round(v, 4) for v in o.rotation_euler], "scale": [round(v, 4) for v in o.scale],
|
|
28
|
+
"parent": o.parent.name if o.parent else None, "hide_render": o.hide_render,
|
|
29
|
+
"animated": bool(o.animation_data and o.animation_data.action)}
|
|
30
|
+
if o.type == "CAMERA":
|
|
31
|
+
rec["lens_mm"] = o.data.lens; rec["sensor_mm"] = o.data.sensor_width
|
|
32
|
+
rec["dof"] = {"use": o.data.dof.use_dof, "fstop": o.data.dof.aperture_fstop,
|
|
33
|
+
"focus_object": o.data.dof.focus_object.name if o.data.dof.focus_object else None}
|
|
34
|
+
elif o.type == "ARMATURE":
|
|
35
|
+
rec["bones"] = [b.name for b in o.data.bones][:200]
|
|
36
|
+
elif o.type == "MESH":
|
|
37
|
+
rec["verts"] = len(o.data.vertices); rec["materials"] = [m.name for m in o.data.materials if m]
|
|
38
|
+
objs.append(rec)
|
|
39
|
+
vl = bpy.context.view_layer
|
|
40
|
+
passes = [p for p in ("use_pass_z", "use_pass_mist", "use_pass_normal", "use_pass_ambient_occlusion",
|
|
41
|
+
"use_pass_cryptomatte_object") if getattr(vl, p, False)]
|
|
42
|
+
if getattr(getattr(vl, "cycles", None), "use_pass_shadow_catcher", False):
|
|
43
|
+
passes.append("use_pass_shadow_catcher")
|
|
44
|
+
result = {
|
|
45
|
+
"blender": bpy.app.version_string, "file": bpy.data.filepath or None, "scene": s.name,
|
|
46
|
+
"frame_range": [s.frame_start, s.frame_end], "frame_current": s.frame_current,
|
|
47
|
+
"fps": round(r.fps / r.fps_base, 3), "resolution": [r.resolution_x, r.resolution_y, r.resolution_percentage],
|
|
48
|
+
"engine": r.engine, "motion_blur": r.use_motion_blur, "shutter": r.motion_blur_shutter,
|
|
49
|
+
"camera": s.camera.name if s.camera else None, "output": r.filepath,
|
|
50
|
+
"file_format": r.image_settings.file_format, "passes": passes,
|
|
51
|
+
"unit_scale": s.unit_settings.scale_length, "objects": objs,
|
|
52
|
+
}
|
|
53
|
+
`;
|
|
54
|
+
|
|
55
|
+
export function register(server, { text, errText, registerAsset }) {
|
|
56
|
+
server.registerTool(
|
|
57
|
+
"blender_run_python",
|
|
58
|
+
{
|
|
59
|
+
title: "Run Python (bpy) in Blender",
|
|
60
|
+
description:
|
|
61
|
+
"Execute Python inside Blender with bpy available. Runs as a module body; set `result = <value>` " +
|
|
62
|
+
"to return JSON (print() output comes back as stdout). Check objects exist before touching them " +
|
|
63
|
+
"(bpy.data.objects.get(name)). Work in real-world meters/seconds; key animation with keyframe_insert. " +
|
|
64
|
+
"In background mode nothing persists unless you pass save_as (or call bpy.ops.wm.save_mainfile). " +
|
|
65
|
+
"GOTCHAS: Blender 5.x compositor lives in scene.compositing_node_group (scene.node_tree is gone); " +
|
|
66
|
+
"EEVEE engine id is 'BLENDER_EEVEE_NEXT' in 4.2–4.5 but 'BLENDER_EEVEE' in 5.x. More: knowledge_search app=blender.",
|
|
67
|
+
inputSchema: {
|
|
68
|
+
code: z.string().describe("Python source; assign `result` to return data."),
|
|
69
|
+
mode: MODE,
|
|
70
|
+
blend_file: BLEND,
|
|
71
|
+
save_as: z.string().optional().describe("Absolute .blend path to save to after the code runs."),
|
|
72
|
+
timeout_seconds: z.number().optional().describe("Max seconds (default 120)."),
|
|
73
|
+
},
|
|
74
|
+
},
|
|
75
|
+
async ({ code, mode, blend_file, save_as, timeout_seconds }) => {
|
|
76
|
+
try {
|
|
77
|
+
const full = save_as
|
|
78
|
+
? `${code}\n${blenderSaveSnippet(save_as)}`
|
|
79
|
+
: code;
|
|
80
|
+
const r = await runBlender(full, { mode, blendFile: blend_file, timeoutMs: (timeout_seconds ?? 120) * 1000 });
|
|
81
|
+
if (save_as) registerAsset({ app: "blender", kind: "blend", path: save_as, meta: {} });
|
|
82
|
+
return text({ ok: true, ...r });
|
|
83
|
+
} catch (e) {
|
|
84
|
+
return errText(e);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
);
|
|
88
|
+
|
|
89
|
+
server.registerTool(
|
|
90
|
+
"blender_get_state",
|
|
91
|
+
{
|
|
92
|
+
title: "Inspect the Blender scene",
|
|
93
|
+
description:
|
|
94
|
+
"Scene summary: version, file, frame range, fps, resolution, engine, motion blur, active camera " +
|
|
95
|
+
"(lens/DoF), enabled render passes, and every object (type, transform, parent, animated, bones).",
|
|
96
|
+
inputSchema: { mode: MODE, blend_file: BLEND },
|
|
97
|
+
},
|
|
98
|
+
async ({ mode, blend_file }) => {
|
|
99
|
+
try {
|
|
100
|
+
const r = await runBlender(STATE_PY, { mode, blendFile: blend_file, timeoutMs: 60000 });
|
|
101
|
+
return text({ ...r.result, bridge_mode: r.mode });
|
|
102
|
+
} catch (e) {
|
|
103
|
+
return errText(e);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
);
|
|
107
|
+
|
|
108
|
+
server.registerTool(
|
|
109
|
+
"blender_render_frame",
|
|
110
|
+
{
|
|
111
|
+
title: "Render a Blender frame to PNG",
|
|
112
|
+
description:
|
|
113
|
+
"Render one frame through the scene camera and return it inline so you can visually verify " +
|
|
114
|
+
"blocking, lighting and framing. Uses a reduced resolution and sample count for speed; scene " +
|
|
115
|
+
"render settings are restored afterwards.",
|
|
116
|
+
inputSchema: {
|
|
117
|
+
frame: z.number().int().optional().describe("Frame to render (default: current frame)."),
|
|
118
|
+
max_width: z.number().optional().describe("Preview width in px (default 960)."),
|
|
119
|
+
samples: z.number().int().optional().describe("Cycles/EEVEE samples for the preview (default 16)."),
|
|
120
|
+
mode: MODE,
|
|
121
|
+
blend_file: BLEND,
|
|
122
|
+
timeout_seconds: z.number().optional().describe("Max seconds (default 300)."),
|
|
123
|
+
},
|
|
124
|
+
},
|
|
125
|
+
async ({ frame, max_width, samples, mode, blend_file, timeout_seconds }) => {
|
|
126
|
+
const pngPath = path.join(os.tmpdir(), `adobe_mcp_blender_${Date.now()}.png`);
|
|
127
|
+
try {
|
|
128
|
+
const py = `
|
|
129
|
+
import bpy
|
|
130
|
+
s = bpy.context.scene
|
|
131
|
+
r = s.render
|
|
132
|
+
if s.camera is None:
|
|
133
|
+
raise RuntimeError("Scene has no active camera (set scene.camera)")
|
|
134
|
+
saved = dict(fp=r.filepath, fmt=r.image_settings.file_format, pct=r.resolution_percentage,
|
|
135
|
+
frame=s.frame_current, mode=r.image_settings.color_mode,
|
|
136
|
+
media=getattr(r.image_settings, "media_type", None), comp=r.use_compositing)
|
|
137
|
+
cy_samples = s.cycles.samples if r.engine == "CYCLES" else None
|
|
138
|
+
ee = getattr(s, "eevee", None)
|
|
139
|
+
ee_samples = ee.taa_render_samples if ee is not None and hasattr(ee, "taa_render_samples") else None
|
|
140
|
+
try:
|
|
141
|
+
frame = ${frame === undefined ? "s.frame_current" : Number(frame)}
|
|
142
|
+
s.frame_set(frame)
|
|
143
|
+
r.use_compositing = False # File Output nodes would write the preview into the pass sequences
|
|
144
|
+
r.resolution_percentage = max(1, min(100, int(100 * ${Number(max_width ?? 960)} / max(1, r.resolution_x))))
|
|
145
|
+
if cy_samples is not None: s.cycles.samples = ${Number(samples ?? 16)}
|
|
146
|
+
if ee_samples is not None: ee.taa_render_samples = ${Number(samples ?? 16)}
|
|
147
|
+
if saved["media"] is not None:
|
|
148
|
+
r.image_settings.media_type = "IMAGE" # Blender 5.x
|
|
149
|
+
r.image_settings.file_format = "PNG"
|
|
150
|
+
r.image_settings.color_mode = "RGBA"
|
|
151
|
+
r.filepath = ${JSON.stringify(pngPath)}
|
|
152
|
+
bpy.ops.render.render(write_still=True)
|
|
153
|
+
result = {"frame": frame, "engine": r.engine, "camera": s.camera.name,
|
|
154
|
+
"size": [r.resolution_x * r.resolution_percentage // 100, r.resolution_y * r.resolution_percentage // 100]}
|
|
155
|
+
finally:
|
|
156
|
+
r.filepath = saved["fp"]
|
|
157
|
+
r.use_compositing = saved["comp"]
|
|
158
|
+
if saved["media"] is not None:
|
|
159
|
+
r.image_settings.media_type = saved["media"]
|
|
160
|
+
r.image_settings.file_format = saved["fmt"]
|
|
161
|
+
r.image_settings.color_mode = saved["mode"]; r.resolution_percentage = saved["pct"]
|
|
162
|
+
if cy_samples is not None: s.cycles.samples = cy_samples
|
|
163
|
+
if ee_samples is not None: ee.taa_render_samples = ee_samples
|
|
164
|
+
s.frame_set(saved["frame"])
|
|
165
|
+
`;
|
|
166
|
+
const r = await runBlender(py, { mode, blendFile: blend_file, timeoutMs: (timeout_seconds ?? 300) * 1000 });
|
|
167
|
+
if (!fs.existsSync(pngPath)) throw new Error("Render finished but no PNG was written.");
|
|
168
|
+
const data = fs.readFileSync(pngPath).toString("base64");
|
|
169
|
+
fs.rmSync(pngPath, { force: true });
|
|
170
|
+
return {
|
|
171
|
+
content: [
|
|
172
|
+
{ type: "text", text: JSON.stringify({ ...r.result, bridge_mode: r.mode }) },
|
|
173
|
+
{ type: "image", data, mimeType: "image/png" },
|
|
174
|
+
],
|
|
175
|
+
};
|
|
176
|
+
} catch (e) {
|
|
177
|
+
fs.rmSync(pngPath, { force: true });
|
|
178
|
+
return errText(e);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
);
|
|
182
|
+
|
|
183
|
+
server.registerTool(
|
|
184
|
+
"blender_render_animation",
|
|
185
|
+
{
|
|
186
|
+
title: "Render a Blender animation to disk",
|
|
187
|
+
description:
|
|
188
|
+
"Render the scene's frame range (or an override) with the scene's own output settings — e.g. the " +
|
|
189
|
+
"multilayer EXR + pass sequences set up by scripts/blender/Creature_Walk_Cinematic.py — and register " +
|
|
190
|
+
"the output folder as a workflow asset for the After Effects handoff. Prefer mode 'background' with " +
|
|
191
|
+
"a saved blend_file for long renders so the Blender UI stays usable.",
|
|
192
|
+
inputSchema: {
|
|
193
|
+
output_dir: z.string().optional().describe("Directory for frames (default: scene output path)."),
|
|
194
|
+
frame_start: z.number().int().optional(),
|
|
195
|
+
frame_end: z.number().int().optional(),
|
|
196
|
+
mode: MODE,
|
|
197
|
+
blend_file: BLEND,
|
|
198
|
+
timeout_seconds: z.number().optional().describe("Max seconds (default 3600)."),
|
|
199
|
+
},
|
|
200
|
+
},
|
|
201
|
+
async ({ output_dir, frame_start, frame_end, mode, blend_file, timeout_seconds }) => {
|
|
202
|
+
try {
|
|
203
|
+
const py = `
|
|
204
|
+
import bpy, os
|
|
205
|
+
s = bpy.context.scene
|
|
206
|
+
r = s.render
|
|
207
|
+
if s.camera is None:
|
|
208
|
+
raise RuntimeError("Scene has no active camera")
|
|
209
|
+
out_dir = ${output_dir ? JSON.stringify(output_dir) : "None"}
|
|
210
|
+
if out_dir:
|
|
211
|
+
os.makedirs(out_dir, exist_ok=True)
|
|
212
|
+
r.filepath = os.path.join(out_dir, (s.camera.name or "render") + "_")
|
|
213
|
+
${frame_start !== undefined ? `s.frame_start = ${Number(frame_start)}` : ""}
|
|
214
|
+
${frame_end !== undefined ? `s.frame_end = ${Number(frame_end)}` : ""}
|
|
215
|
+
bpy.ops.render.render(animation=True)
|
|
216
|
+
folder = os.path.dirname(bpy.path.abspath(r.filepath))
|
|
217
|
+
files = sorted(f for f in os.listdir(folder)) if os.path.isdir(folder) else []
|
|
218
|
+
result = {"output_dir": folder, "frames": [s.frame_start, s.frame_end], "file_format": r.image_settings.file_format,
|
|
219
|
+
"num_files": len(files), "sample": files[:5]}
|
|
220
|
+
`;
|
|
221
|
+
const r = await runBlender(py, { mode, blendFile: blend_file, timeoutMs: (timeout_seconds ?? 3600) * 1000 });
|
|
222
|
+
if (r.result?.output_dir)
|
|
223
|
+
registerAsset({ app: "blender", kind: "image-sequence", path: r.result.output_dir, meta: { frames: r.result.frames } });
|
|
224
|
+
return text({ ...r.result, bridge_mode: r.mode });
|
|
225
|
+
} catch (e) {
|
|
226
|
+
return errText(e);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
);
|
|
230
|
+
}
|
package/adapters/ppro.mjs
CHANGED
|
@@ -4,6 +4,7 @@ import fs from "node:fs";
|
|
|
4
4
|
import os from "node:os";
|
|
5
5
|
import path from "node:path";
|
|
6
6
|
import { runJSX, downscalePng, pproPanelAlive } from "../core/bridge.mjs";
|
|
7
|
+
import { findAdobeInstallDirs } from "../core/platform.mjs";
|
|
7
8
|
|
|
8
9
|
export function register(server, { text, errText, registerAsset }) {
|
|
9
10
|
server.registerTool(
|
|
@@ -204,9 +205,9 @@ return { time: t, width: fs2.videoFrameWidth, height: fs2.videoFrameHeight };`;
|
|
|
204
205
|
try {
|
|
205
206
|
let preset = preset_path;
|
|
206
207
|
if (!preset) {
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
208
|
+
// Newest Premiere install first (/Applications on macOS, Program Files\Adobe on Windows).
|
|
209
|
+
const roots = findAdobeInstallDirs(/^Adobe Premiere Pro/i).reverse();
|
|
210
|
+
outer: for (const base of roots) {
|
|
210
211
|
const stack = [base];
|
|
211
212
|
while (stack.length) {
|
|
212
213
|
const dir = stack.pop();
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
// Substance 3D Painter adapter — Python via the remote-scripting HTTP endpoint (port 60041).
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import { runPainter } from "../core/pybridge.mjs";
|
|
5
|
+
|
|
6
|
+
const STATE_PY = `
|
|
7
|
+
import substance_painter.project as sp_proj
|
|
8
|
+
import substance_painter.textureset as sp_ts
|
|
9
|
+
import substance_painter.layerstack as sp_ls
|
|
10
|
+
if not sp_proj.is_open():
|
|
11
|
+
result = {"project_open": False}
|
|
12
|
+
else:
|
|
13
|
+
sets = []
|
|
14
|
+
for ts in sp_ts.all_texture_sets():
|
|
15
|
+
rec = {"name": ts.name(), "stacks": []}
|
|
16
|
+
try:
|
|
17
|
+
res = ts.get_resolution(); rec["resolution"] = [res.width, res.height]
|
|
18
|
+
except Exception as e:
|
|
19
|
+
rec["resolution"] = str(e)
|
|
20
|
+
for st in ts.all_stacks():
|
|
21
|
+
srec = {"name": st.name(), "channels": [], "layers": []}
|
|
22
|
+
try:
|
|
23
|
+
srec["channels"] = sorted(str(k).split(".")[-1] for k in st.all_channels().keys())
|
|
24
|
+
except Exception:
|
|
25
|
+
pass
|
|
26
|
+
try:
|
|
27
|
+
srec["layers"] = [n.get_name() for n in sp_ls.get_root_layer_nodes(st)][:100]
|
|
28
|
+
except Exception:
|
|
29
|
+
pass
|
|
30
|
+
rec["stacks"].append(srec)
|
|
31
|
+
sets.append(rec)
|
|
32
|
+
result = {"project_open": True, "name": sp_proj.name(), "file": sp_proj.file_path(),
|
|
33
|
+
"dirty": sp_proj.needs_saving() if hasattr(sp_proj, "needs_saving") else None,
|
|
34
|
+
"texture_sets": sets}
|
|
35
|
+
`;
|
|
36
|
+
|
|
37
|
+
export function register(server, { text, errText, registerAsset }) {
|
|
38
|
+
server.registerTool(
|
|
39
|
+
"substance_run_python",
|
|
40
|
+
{
|
|
41
|
+
title: "Run Python in Substance 3D Painter",
|
|
42
|
+
description:
|
|
43
|
+
"Execute Python inside Substance 3D Painter (modules: substance_painter.project, .textureset, " +
|
|
44
|
+
".layerstack, .baking, .export, .resource, .colormanagement). Runs as a module body; set " +
|
|
45
|
+
"`result = <value>` to return JSON. Requires Painter launched with --enable-remote-scripting " +
|
|
46
|
+
"(port 60041). ALWAYS guard with substance_painter.project.is_open(). Wrap layer edits in " +
|
|
47
|
+
"`with substance_painter.layerstack.ScopedModification('name'):` so they are one undo step. " +
|
|
48
|
+
"GOTCHAS: baking is ASYNC — bake_*_async() returns immediately; never block/sleep the main thread " +
|
|
49
|
+
"waiting for it (Painter deadlocks). There is no bake_mesh_maps(). More: knowledge_search app=substance.",
|
|
50
|
+
inputSchema: {
|
|
51
|
+
code: z.string().describe("Python source; assign `result` to return data."),
|
|
52
|
+
timeout_seconds: z.number().optional().describe("Max seconds (default 120)."),
|
|
53
|
+
},
|
|
54
|
+
},
|
|
55
|
+
async ({ code, timeout_seconds }) => {
|
|
56
|
+
try {
|
|
57
|
+
return text({ ok: true, ...(await runPainter(code, { timeoutMs: (timeout_seconds ?? 120) * 1000 })) });
|
|
58
|
+
} catch (e) {
|
|
59
|
+
return errText(e);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
);
|
|
63
|
+
|
|
64
|
+
server.registerTool(
|
|
65
|
+
"substance_get_state",
|
|
66
|
+
{
|
|
67
|
+
title: "Inspect the open Substance Painter project",
|
|
68
|
+
description: "Project name/file and every texture set with resolution, stacks, channels and root layers.",
|
|
69
|
+
inputSchema: {},
|
|
70
|
+
},
|
|
71
|
+
async () => {
|
|
72
|
+
try {
|
|
73
|
+
return text((await runPainter(STATE_PY, { timeoutMs: 60000 })).result);
|
|
74
|
+
} catch (e) {
|
|
75
|
+
return errText(e);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
);
|
|
79
|
+
|
|
80
|
+
server.registerTool(
|
|
81
|
+
"substance_bake_mesh_maps",
|
|
82
|
+
{
|
|
83
|
+
title: "Bake mesh maps in Substance Painter",
|
|
84
|
+
description:
|
|
85
|
+
"Start baking mesh maps (normal, AO, curvature, thickness, position, world-space normal, ID) — " +
|
|
86
|
+
"smart materials and generators need curvature/AO to find edges and cavities. Optionally set " +
|
|
87
|
+
"the bake resolution first. Baking is ASYNC: this returns once the bake has STARTED; poll " +
|
|
88
|
+
"substance_get_state or just proceed — Painter queues edits behind the bake.",
|
|
89
|
+
inputSchema: {
|
|
90
|
+
texture_sets: z.array(z.string()).optional().describe("Texture set names (default: all)."),
|
|
91
|
+
size_log2: z.number().int().min(7).max(13).optional().describe("Output size as log2 (11 = 2048)."),
|
|
92
|
+
},
|
|
93
|
+
},
|
|
94
|
+
async ({ texture_sets, size_log2 }) => {
|
|
95
|
+
try {
|
|
96
|
+
const py = `
|
|
97
|
+
import substance_painter.project as sp_proj
|
|
98
|
+
import substance_painter.textureset as sp_ts
|
|
99
|
+
import substance_painter.baking as sp_bake
|
|
100
|
+
if not sp_proj.is_open():
|
|
101
|
+
raise RuntimeError("No Substance Painter project is open")
|
|
102
|
+
wanted = ${JSON.stringify(texture_sets ?? null)}
|
|
103
|
+
targets = [t for t in sp_ts.all_texture_sets() if wanted is None or t.name() in wanted]
|
|
104
|
+
if not targets:
|
|
105
|
+
raise RuntimeError("No matching texture sets: %s" % wanted)
|
|
106
|
+
notes = []
|
|
107
|
+
size_log2 = ${size_log2 ?? "None"}
|
|
108
|
+
if size_log2 is not None:
|
|
109
|
+
for t in targets:
|
|
110
|
+
try:
|
|
111
|
+
params = sp_bake.BakingParameters.from_texture_set(t)
|
|
112
|
+
common = params.common()
|
|
113
|
+
params.set({common["OutputSize"]: (size_log2, size_log2)})
|
|
114
|
+
except Exception as e:
|
|
115
|
+
notes.append("size on %s not set: %s" % (t.name(), e))
|
|
116
|
+
started = []
|
|
117
|
+
if hasattr(sp_bake, "bake_async"):
|
|
118
|
+
for t in targets:
|
|
119
|
+
sp_bake.bake_async(t); started.append(t.name())
|
|
120
|
+
elif hasattr(sp_bake, "bake_selected_textures_async"):
|
|
121
|
+
# older builds bake whatever is selected in the Baking window, not an arbitrary list
|
|
122
|
+
if wanted is not None and len(targets) < len(sp_ts.all_texture_sets()):
|
|
123
|
+
raise RuntimeError("This Painter version can only bake the texture sets selected in the Baking window; "
|
|
124
|
+
"select them there, or omit texture_sets")
|
|
125
|
+
sp_bake.bake_selected_textures_async(); started = ["(Baking window selection)"]
|
|
126
|
+
else:
|
|
127
|
+
raise RuntimeError("This Painter version exposes no async baking API")
|
|
128
|
+
result = {"bake_started": started, "notes": notes}
|
|
129
|
+
`;
|
|
130
|
+
return text((await runPainter(py, { timeoutMs: 60000 })).result);
|
|
131
|
+
} catch (e) {
|
|
132
|
+
return errText(e);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
);
|
|
136
|
+
|
|
137
|
+
server.registerTool(
|
|
138
|
+
"substance_export_textures",
|
|
139
|
+
{
|
|
140
|
+
title: "Export PBR texture maps from Substance Painter",
|
|
141
|
+
description:
|
|
142
|
+
"Export the project's textures with an export preset (default the starter-assets 'PBR Metallic " +
|
|
143
|
+
"Roughness': BaseColor, Metallic, Roughness, Normal, Height/Displacement, AO). Registers each " +
|
|
144
|
+
"written map as a workflow asset so Blender can pick them up for the beauty render.",
|
|
145
|
+
inputSchema: {
|
|
146
|
+
output_dir: z.string().describe("Absolute export folder."),
|
|
147
|
+
preset: z.string().optional().describe("Starter-assets export preset name (default 'PBR Metallic Roughness')."),
|
|
148
|
+
file_format: z.enum(["png", "exr", "tif", "jpeg", "tga"]).optional().describe("Default png."),
|
|
149
|
+
bit_depth: z.enum(["8", "16", "32f"]).optional().describe("Default 16 (8 for jpeg)."),
|
|
150
|
+
size_log2: z.number().int().min(7).max(13).optional().describe("11 = 2048, 12 = 4096 (default: texture set size)."),
|
|
151
|
+
texture_sets: z.array(z.string()).optional().describe("Texture set names (default: all)."),
|
|
152
|
+
},
|
|
153
|
+
},
|
|
154
|
+
async ({ output_dir, preset, file_format, bit_depth, size_log2, texture_sets }) => {
|
|
155
|
+
try {
|
|
156
|
+
fs.mkdirSync(output_dir, { recursive: true });
|
|
157
|
+
const fmt = file_format ?? "png";
|
|
158
|
+
const depth = bit_depth ?? (fmt === "jpeg" ? "8" : "16");
|
|
159
|
+
const py = `
|
|
160
|
+
import substance_painter.project as sp_proj
|
|
161
|
+
import substance_painter.textureset as sp_ts
|
|
162
|
+
import substance_painter.export as sp_exp
|
|
163
|
+
import substance_painter.resource as sp_res
|
|
164
|
+
if not sp_proj.is_open():
|
|
165
|
+
raise RuntimeError("No Substance Painter project is open")
|
|
166
|
+
wanted = ${JSON.stringify(texture_sets ?? null)}
|
|
167
|
+
names = [t.name() for t in sp_ts.all_texture_sets() if wanted is None or t.name() in wanted]
|
|
168
|
+
params = {"fileFormat": ${JSON.stringify(fmt)}, "bitDepth": ${JSON.stringify(depth)}, "dithering": True, "paddingAlgorithm": "infinite"}
|
|
169
|
+
size_log2 = ${size_log2 ?? "None"}
|
|
170
|
+
if size_log2 is not None:
|
|
171
|
+
params["sizeLog2"] = size_log2
|
|
172
|
+
config = {
|
|
173
|
+
"exportShaderParams": False,
|
|
174
|
+
"exportPath": ${JSON.stringify(output_dir)},
|
|
175
|
+
"defaultExportPreset": sp_res.ResourceID(context="starter_assets", name=${JSON.stringify(preset ?? "PBR Metallic Roughness")}).url(),
|
|
176
|
+
"exportList": [{"rootPath": n} for n in names],
|
|
177
|
+
"exportParameters": [{"parameters": params}],
|
|
178
|
+
}
|
|
179
|
+
res = sp_exp.export_project_textures(config)
|
|
180
|
+
files = []
|
|
181
|
+
for _k, paths in (res.textures or {}).items():
|
|
182
|
+
files.extend(paths)
|
|
183
|
+
result = {"status": str(res.status), "message": res.message, "files": files}
|
|
184
|
+
`;
|
|
185
|
+
const r = (await runPainter(py, { timeoutMs: 600000 })).result;
|
|
186
|
+
for (const f of r.files || []) registerAsset({ app: "substance", kind: "texture", path: f, meta: { preset: preset ?? "PBR Metallic Roughness" } });
|
|
187
|
+
return text(r);
|
|
188
|
+
} catch (e) {
|
|
189
|
+
return errText(e);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
);
|
|
193
|
+
}
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
// Free texture libraries (Poly Haven, ambientCG — all CC0) → search, download, apply in Blender.
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { runBlender, blenderSaveSnippet } from "../core/pybridge.mjs";
|
|
7
|
+
import { searchLibraries, downloadAsset, classifyAmbientFile, TEXTURE_CACHE } from "../core/texlib.mjs";
|
|
8
|
+
|
|
9
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
10
|
+
const PBR_PY = fs.readFileSync(path.join(__dirname, "..", "core", "blender_pbr.py"), "utf8");
|
|
11
|
+
|
|
12
|
+
const SOURCE = z.enum(["polyhaven", "ambientcg"]).describe("Library the asset id comes from (see texture_search).");
|
|
13
|
+
const RES = z.enum(["1k", "2k", "4k", "8k"]).optional().describe("Resolution (default 2k; 4k+ for hero close-ups).");
|
|
14
|
+
const MODE = z.enum(["auto", "live", "background"]).optional().describe("Blender bridge mode (see blender_run_python).");
|
|
15
|
+
|
|
16
|
+
/** Python that runs a blender_pbr helper with JSON kwargs. */
|
|
17
|
+
function pbrCall(fn, kwargs, saveAs) {
|
|
18
|
+
return (
|
|
19
|
+
`${PBR_PY}\nimport json as __json\n` +
|
|
20
|
+
`result = ${fn}(**__json.loads(${JSON.stringify(JSON.stringify(kwargs))}))\n` +
|
|
21
|
+
(saveAs ? blenderSaveSnippet(saveAs) : "")
|
|
22
|
+
);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Canonical maps from a local folder (e.g. a Substance export). */
|
|
26
|
+
function mapsFromDir(dir) {
|
|
27
|
+
const maps = {};
|
|
28
|
+
for (const f of fs.readdirSync(dir).sort()) {
|
|
29
|
+
if (!/\.(png|jpe?g|exr|tiff?)$/i.test(f)) continue;
|
|
30
|
+
const canon = classifyAmbientFile(f);
|
|
31
|
+
if (canon && !maps[canon]) maps[canon] = path.join(dir, f);
|
|
32
|
+
}
|
|
33
|
+
if (!Object.keys(maps).length) throw new Error(`No recognisable maps (…_BaseColor, _Roughness, _Normal…) in ${dir}`);
|
|
34
|
+
return maps;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function register(server, { text, errText, registerAsset }) {
|
|
38
|
+
const fetchAsset = async (args) => {
|
|
39
|
+
const a = await downloadAsset(args);
|
|
40
|
+
if (!a.cached)
|
|
41
|
+
for (const [map, p] of Object.entries(a.maps))
|
|
42
|
+
registerAsset({ app: a.source, kind: a.type === "hdri" ? "hdri" : "texture", path: p, meta: { id: a.id, map, resolution: a.resolution, license: a.license } });
|
|
43
|
+
return a;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
server.registerTool(
|
|
47
|
+
"texture_search",
|
|
48
|
+
{
|
|
49
|
+
title: "Search free CC0 texture & HDRI libraries",
|
|
50
|
+
description:
|
|
51
|
+
"Search Poly Haven and ambientCG, the two big free, CC0 (public domain, no attribution) PBR libraries " +
|
|
52
|
+
"Blender artists use. Returns asset ids, names, tags, preview thumbnails and pages. type=texture for " +
|
|
53
|
+
"materials (rock, bark, scales, ground, concrete…), type=hdri for image-based lighting that matches a plate. " +
|
|
54
|
+
"Poly Haven categories include e.g. rock, terrain, wood, fabric, brick; ambientCG is keyword search.",
|
|
55
|
+
inputSchema: {
|
|
56
|
+
query: z.string().optional().describe("Keywords, e.g. 'wet rock', 'reptile skin', 'forest ground'."),
|
|
57
|
+
type: z.enum(["texture", "hdri"]).optional().describe("Default texture."),
|
|
58
|
+
source: z.enum(["all", "polyhaven", "ambientcg"]).optional().describe("Default all."),
|
|
59
|
+
category: z.string().optional().describe("Optional category filter (Poly Haven category / extra ambientCG keyword)."),
|
|
60
|
+
limit: z.number().int().min(1).max(50).optional().describe("Results per library (default 12)."),
|
|
61
|
+
},
|
|
62
|
+
},
|
|
63
|
+
async ({ query, type, source, category, limit }) => {
|
|
64
|
+
try {
|
|
65
|
+
const r = await searchLibraries({ query, type: type ?? "texture", source: source ?? "all", category, limit: limit ?? 12 });
|
|
66
|
+
return text({ count: r.results.length, ...r, license: "All results are CC0 — free for commercial use, no attribution required." });
|
|
67
|
+
} catch (e) {
|
|
68
|
+
return errText(e);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
);
|
|
72
|
+
|
|
73
|
+
server.registerTool(
|
|
74
|
+
"texture_download",
|
|
75
|
+
{
|
|
76
|
+
title: "Download a library texture or HDRI",
|
|
77
|
+
description:
|
|
78
|
+
"Download one asset at a resolution into the local cache (<workspace>/textures, reused on repeat calls) " +
|
|
79
|
+
"with maps renamed to a common convention (<id>_BaseColor, _Roughness, _Normal (OpenGL), _Height, _AO, " +
|
|
80
|
+
"_Metallic, _ARM, _Opacity; HDRIs as _HDRI). Registers every map as a workflow asset. The folder works " +
|
|
81
|
+
"directly as texture_dir for Creature_Walk_Cinematic.py or blender_apply_texture.",
|
|
82
|
+
inputSchema: {
|
|
83
|
+
source: SOURCE,
|
|
84
|
+
id: z.string().describe("Asset id from texture_search (e.g. 'rock_face' or 'Rock030')."),
|
|
85
|
+
type: z.enum(["texture", "hdri"]).optional().describe("Default texture."),
|
|
86
|
+
resolution: RES,
|
|
87
|
+
format: z.enum(["jpg", "png", "exr", "hdr"]).optional().describe("Textures: jpg (default)/png/exr. HDRIs: hdr (default)/exr."),
|
|
88
|
+
},
|
|
89
|
+
},
|
|
90
|
+
async ({ source, id, type, resolution, format }) => {
|
|
91
|
+
try {
|
|
92
|
+
return text(await fetchAsset({ source, id, type: type ?? "texture", resolution: resolution ?? "2k", format }));
|
|
93
|
+
} catch (e) {
|
|
94
|
+
return errText(e);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
);
|
|
98
|
+
|
|
99
|
+
server.registerTool(
|
|
100
|
+
"blender_apply_texture",
|
|
101
|
+
{
|
|
102
|
+
title: "Apply a library (or local) PBR texture to Blender objects",
|
|
103
|
+
description:
|
|
104
|
+
"Build a Principled BSDF material from a Poly Haven / ambientCG asset (downloaded on demand) or a local " +
|
|
105
|
+
"folder of maps (e.g. a Substance Painter export), and assign it to objects. Colour maps are sRGB, data " +
|
|
106
|
+
"maps Non-Color, normals OpenGL, height drives true displacement (method BOTH), ARM is unpacked when " +
|
|
107
|
+
"separate maps are missing, and baked AO is left out (Cycles computes its own). Meshes without UVs get " +
|
|
108
|
+
"tri-planar box projection. Set tile_m to the real-world size one tile covers so scale reads correctly.",
|
|
109
|
+
inputSchema: {
|
|
110
|
+
objects: z.array(z.string()).min(1).describe("Blender object names to assign the material to."),
|
|
111
|
+
source: SOURCE.optional(),
|
|
112
|
+
id: z.string().optional().describe("Library asset id (with source)."),
|
|
113
|
+
texture_dir: z.string().optional().describe("Alternative: absolute folder of maps named *_BaseColor, *_Roughness, *_Normal…"),
|
|
114
|
+
resolution: RES,
|
|
115
|
+
format: z.enum(["jpg", "png", "exr"]).optional(),
|
|
116
|
+
material_name: z.string().optional().describe("Default: the asset id."),
|
|
117
|
+
tile_m: z.number().positive().optional().describe("Meters covered by one texture tile (default 2)."),
|
|
118
|
+
projection: z.enum(["auto", "uv", "box"]).optional().describe("Default auto (uv if every object has UVs)."),
|
|
119
|
+
displacement_m: z.number().min(0).optional().describe("Height-map displacement in meters (default 0.02; 0 disables)."),
|
|
120
|
+
mode: MODE,
|
|
121
|
+
blend_file: z.string().optional(),
|
|
122
|
+
save_as: z.string().optional().describe("Save the .blend here afterwards (needed in background mode)."),
|
|
123
|
+
},
|
|
124
|
+
},
|
|
125
|
+
async (a) => {
|
|
126
|
+
try {
|
|
127
|
+
let maps, label;
|
|
128
|
+
if (a.texture_dir) {
|
|
129
|
+
maps = mapsFromDir(a.texture_dir);
|
|
130
|
+
label = path.basename(a.texture_dir);
|
|
131
|
+
} else {
|
|
132
|
+
if (!a.source || !a.id) throw new Error("Pass source + id (from texture_search) or texture_dir.");
|
|
133
|
+
const asset = await fetchAsset({ source: a.source, id: a.id, type: "texture", resolution: a.resolution ?? "2k", format: a.format });
|
|
134
|
+
maps = asset.maps;
|
|
135
|
+
label = a.id;
|
|
136
|
+
}
|
|
137
|
+
const kwargs = {
|
|
138
|
+
name: a.material_name ?? label,
|
|
139
|
+
maps,
|
|
140
|
+
objects: a.objects,
|
|
141
|
+
tile_m: a.tile_m ?? 2.0,
|
|
142
|
+
projection: a.projection ?? "auto",
|
|
143
|
+
displacement_m: a.displacement_m ?? 0.02,
|
|
144
|
+
};
|
|
145
|
+
const r = await runBlender(pbrCall("build_pbr_material", kwargs, a.save_as), { mode: a.mode, blendFile: a.blend_file, timeoutMs: 180000 });
|
|
146
|
+
return text({ ...r.result, bridge_mode: r.mode, saved: a.save_as ?? null });
|
|
147
|
+
} catch (e) {
|
|
148
|
+
return errText(e);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
);
|
|
152
|
+
|
|
153
|
+
server.registerTool(
|
|
154
|
+
"blender_set_hdri",
|
|
155
|
+
{
|
|
156
|
+
title: "Light the Blender scene with a library HDRI",
|
|
157
|
+
description:
|
|
158
|
+
"Download a Poly Haven / ambientCG HDRI (or use a local .hdr/.exr) and set it as the world light. Pick " +
|
|
159
|
+
"an HDRI whose sun height, colour and cloud cover match the live-action plate, then rotate it " +
|
|
160
|
+
"(rotation_deg) until CG shadows line up with the plate's. This is the biggest single win for photo-real " +
|
|
161
|
+
"integration.",
|
|
162
|
+
inputSchema: {
|
|
163
|
+
source: SOURCE.optional(),
|
|
164
|
+
id: z.string().optional().describe("HDRI asset id from texture_search type=hdri."),
|
|
165
|
+
hdri_path: z.string().optional().describe("Alternative: absolute path to a local .hdr/.exr."),
|
|
166
|
+
resolution: RES,
|
|
167
|
+
strength: z.number().min(0).optional().describe("Background strength (default 1)."),
|
|
168
|
+
rotation_deg: z.number().optional().describe("Rotate the environment around Z (default 0)."),
|
|
169
|
+
mode: MODE,
|
|
170
|
+
blend_file: z.string().optional(),
|
|
171
|
+
save_as: z.string().optional(),
|
|
172
|
+
},
|
|
173
|
+
},
|
|
174
|
+
async (a) => {
|
|
175
|
+
try {
|
|
176
|
+
let hdri = a.hdri_path;
|
|
177
|
+
if (!hdri) {
|
|
178
|
+
if (!a.source || !a.id) throw new Error("Pass source + id (texture_search type=hdri) or hdri_path.");
|
|
179
|
+
const asset = await fetchAsset({ source: a.source, id: a.id, type: "hdri", resolution: a.resolution ?? "2k" });
|
|
180
|
+
hdri = asset.maps.HDRI;
|
|
181
|
+
}
|
|
182
|
+
if (!fs.existsSync(hdri)) throw new Error(`HDRI not found: ${hdri}`);
|
|
183
|
+
const kwargs = { path: hdri, strength: a.strength ?? 1.0, rotation_deg: a.rotation_deg ?? 0 };
|
|
184
|
+
const r = await runBlender(pbrCall("set_world_hdri", kwargs, a.save_as), { mode: a.mode, blendFile: a.blend_file, timeoutMs: 120000 });
|
|
185
|
+
return text({ ...r.result, path: hdri, bridge_mode: r.mode, saved: a.save_as ?? null });
|
|
186
|
+
} catch (e) {
|
|
187
|
+
return errText(e);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export { TEXTURE_CACHE };
|