oda-engine 0.0.0-stage → 0.1.1
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 +151 -2
- package/bin/nowhere.mjs +352 -0
- package/lib/account.mjs +57 -0
- package/lib/agentModules.mjs +57 -0
- package/lib/devServer.mjs +351 -0
- package/lib/headless.mjs +231 -0
- package/lib/headlessPreview.mjs +212 -0
- package/lib/keys.mjs +517 -0
- package/lib/make.mjs +855 -0
- package/lib/mcp.mjs +537 -0
- package/lib/open.mjs +22 -0
- package/lib/preview.mjs +87 -0
- package/lib/previewRpc.mjs +134 -0
- package/lib/project.mjs +359 -0
- package/lib/publishFlow.mjs +131 -0
- package/lib/resources.mjs +50 -0
- package/lib/rules.mjs +60 -0
- package/lib/scaffold.mjs +42 -0
- package/lib/setup.mjs +59 -0
- package/lib/tools.mjs +668 -0
- package/package.json +51 -4
- package/template/game.config.json +9 -0
- package/template/scene.json +4 -0
- package/template/src/main.ts +11 -0
- package/vendor/DOCS.md +447 -0
- package/vendor/agent/appRun.mjs +520 -0
- package/vendor/agent/assets/brief.mjs +242 -0
- package/vendor/agent/assets/collider.mjs +531 -0
- package/vendor/agent/assets/environments/index.mjs +12 -0
- package/vendor/agent/assets/environments/worldlabs.mjs +161 -0
- package/vendor/agent/assets/fetch.mjs +168 -0
- package/vendor/agent/assets/footprint.mjs +13 -0
- package/vendor/agent/assets/gltf.mjs +547 -0
- package/vendor/agent/assets/hdr.mjs +269 -0
- package/vendor/agent/assets/imageOps.mjs +171 -0
- package/vendor/agent/assets/images/codex.mjs +307 -0
- package/vendor/agent/assets/images/fal.mjs +75 -0
- package/vendor/agent/assets/images/gemini.mjs +84 -0
- package/vendor/agent/assets/images/index.mjs +25 -0
- package/vendor/agent/assets/images/openai.mjs +75 -0
- package/vendor/agent/assets/images/stability.mjs +71 -0
- package/vendor/agent/assets/images/views.mjs +31 -0
- package/vendor/agent/assets/import.mjs +1352 -0
- package/vendor/agent/assets/inspect.mjs +465 -0
- package/vendor/agent/assets/jobs.mjs +196 -0
- package/vendor/agent/assets/ktx2.mjs +290 -0
- package/vendor/agent/assets/ledger.mjs +466 -0
- package/vendor/agent/assets/net.mjs +254 -0
- package/vendor/agent/assets/prices.json +39 -0
- package/vendor/agent/assets/providers/fal.mjs +115 -0
- package/vendor/agent/assets/providers/index.mjs +22 -0
- package/vendor/agent/assets/providers/meshy.mjs +119 -0
- package/vendor/agent/assets/providers/tripo.mjs +188 -0
- package/vendor/agent/assets/sources/ambientcg.mjs +129 -0
- package/vendor/agent/assets/sources/index.mjs +23 -0
- package/vendor/agent/assets/sources/polyhaven.mjs +237 -0
- package/vendor/agent/assets/sources/polypizza.mjs +121 -0
- package/vendor/agent/assets/splat.mjs +631 -0
- package/vendor/agent/assets/targets.mjs +122 -0
- package/vendor/agent/assets/tile.mjs +261 -0
- package/vendor/agent/assets/unzip.mjs +180 -0
- package/vendor/agent/blender/cleanup.py +360 -0
- package/vendor/agent/blender/convert.py +167 -0
- package/vendor/agent/blender/find.mjs +192 -0
- package/vendor/agent/blender/nw_export.py +104 -0
- package/vendor/agent/blender/nw_rubric.py +426 -0
- package/vendor/agent/blender/run.mjs +193 -0
- package/vendor/agent/blender/runner.py +252 -0
- package/vendor/agent/blender/sheet.py +743 -0
- package/vendor/agent/depth.mjs +134 -0
- package/vendor/agent/director/board.mjs +451 -0
- package/vendor/agent/director/contracts.mjs +663 -0
- package/vendor/agent/director/director.mjs +2365 -0
- package/vendor/agent/director/estimate.mjs +200 -0
- package/vendor/agent/director/gate.mjs +802 -0
- package/vendor/agent/director/limits.json +16 -0
- package/vendor/agent/director/methods.mjs +457 -0
- package/vendor/agent/director/policy.json +33 -0
- package/vendor/agent/director/prompts.mjs +244 -0
- package/vendor/agent/director/reading.mjs +341 -0
- package/vendor/agent/director/router.mjs +184 -0
- package/vendor/agent/director/seams.mjs +243 -0
- package/vendor/agent/director/session.mjs +643 -0
- package/vendor/agent/director/store.mjs +119 -0
- package/vendor/agent/director/taskGate.mjs +110 -0
- package/vendor/agent/director/teamLedger.mjs +118 -0
- package/vendor/agent/director/triage.mjs +63 -0
- package/vendor/agent/downloads.cjs +363 -0
- package/vendor/agent/flow.mjs +78 -0
- package/vendor/agent/guard.mjs +613 -0
- package/vendor/agent/host.mjs +1736 -0
- package/vendor/agent/language.mjs +58 -0
- package/vendor/agent/ledger.mjs +360 -0
- package/vendor/agent/locale.cjs +186 -0
- package/vendor/agent/loop/capacity.mjs +74 -0
- package/vendor/agent/loop/compose.mjs +127 -0
- package/vendor/agent/loop/gate.mjs +205 -0
- package/vendor/agent/loop/judge.mjs +189 -0
- package/vendor/agent/loop/levels.mjs +273 -0
- package/vendor/agent/loop/state.mjs +358 -0
- package/vendor/agent/notes.cjs +278 -0
- package/vendor/agent/pace.mjs +258 -0
- package/vendor/agent/panels.mjs +431 -0
- package/vendor/agent/prompt.mjs +342 -0
- package/vendor/agent/reference/board.mjs +410 -0
- package/vendor/agent/reference/compose.mjs +364 -0
- package/vendor/agent/reference/decode.mjs +56 -0
- package/vendor/agent/reference/facts.mjs +1874 -0
- package/vendor/agent/reference/png.mjs +107 -0
- package/vendor/agent/reference/records.mjs +63 -0
- package/vendor/agent/reference/web.mjs +252 -0
- package/vendor/agent/roles/artist.mjs +69 -0
- package/vendor/agent/roles/builder.mjs +79 -0
- package/vendor/agent/roles/checks.mjs +223 -0
- package/vendor/agent/roles/common.mjs +188 -0
- package/vendor/agent/roles/critic.mjs +171 -0
- package/vendor/agent/roles/index.mjs +39 -0
- package/vendor/agent/roles/modeller.mjs +142 -0
- package/vendor/agent/roles/qa.mjs +58 -0
- package/vendor/agent/roles/rubrics.mjs +79 -0
- package/vendor/agent/roles/sound.mjs +69 -0
- package/vendor/agent/rounds.cjs +333 -0
- package/vendor/agent/shared.mjs +284 -0
- package/vendor/agent/stopGate.mjs +574 -0
- package/vendor/agent/subagents.mjs +129 -0
- package/vendor/agent/tools/assets.mjs +499 -0
- package/vendor/agent/tools/blender.mjs +754 -0
- package/vendor/agent/tools/cards.mjs +479 -0
- package/vendor/agent/tools/choices.mjs +479 -0
- package/vendor/agent/tools/compose.mjs +74 -0
- package/vendor/agent/tools/environment.mjs +488 -0
- package/vendor/agent/tools/eyes.mjs +733 -0
- package/vendor/agent/tools/generate.mjs +338 -0
- package/vendor/agent/tools/guide.mjs +46 -0
- package/vendor/agent/tools/harness.mjs +193 -0
- package/vendor/agent/tools/image.mjs +643 -0
- package/vendor/agent/tools/index.mjs +162 -0
- package/vendor/agent/tools/look.mjs +578 -0
- package/vendor/agent/tools/loop.mjs +858 -0
- package/vendor/agent/tools/others.mjs +123 -0
- package/vendor/agent/tools/pictures.mjs +535 -0
- package/vendor/agent/tools/reference.mjs +366 -0
- package/vendor/agent/transcripts.mjs +118 -0
- package/vendor/agent-loop.mjs +602 -0
- package/vendor/agent-plugin/.claude-plugin/plugin.json +5 -0
- package/vendor/agent-plugin/skills/art-direction/SKILL.md +82 -0
- package/vendor/agent-plugin/skills/asset-legality/SKILL.md +101 -0
- package/vendor/agent-plugin/skills/asset-sources/SKILL.md +111 -0
- package/vendor/agent-plugin/skills/blender-modeling/SKILL.md +97 -0
- package/vendor/agent-plugin/skills/look-dev/SKILL.md +104 -0
- package/vendor/agent-plugin/skills/playtesting/SKILL.md +74 -0
- package/vendor/agent-plugin/skills/reference-loop/SKILL.md +102 -0
- package/vendor/agent-plugin/skills/sound-design/SKILL.md +60 -0
- package/vendor/agent-plugin/skills/style/SKILL.md +35 -0
- package/vendor/agent-plugin/skills/tsl-r185/SKILL.md +107 -0
- package/vendor/auth.cjs +570 -0
- package/vendor/build.cjs +953 -0
- package/vendor/catalog.json +455 -0
- package/vendor/connectors.cjs +688 -0
- package/vendor/eyes.mjs +733 -0
- package/vendor/gameExports.json +1390 -0
- package/vendor/git.cjs +222 -0
- package/vendor/models.json +57 -0
- package/vendor/publish.cjs +1018 -0
- package/vendor/refBoard.cjs +301 -0
- package/vendor/schema/dist/assets.d.ts +335 -0
- package/vendor/schema/dist/assets.js +439 -0
- package/vendor/schema/dist/brief.d.ts +357 -0
- package/vendor/schema/dist/brief.js +302 -0
- package/vendor/schema/dist/common.d.ts +9 -0
- package/vendor/schema/dist/common.js +13 -0
- package/vendor/schema/dist/config.d.ts +406 -0
- package/vendor/schema/dist/config.js +355 -0
- package/vendor/schema/dist/contract.d.ts +599 -0
- package/vendor/schema/dist/contract.js +1146 -0
- package/vendor/schema/dist/index.d.ts +14 -0
- package/vendor/schema/dist/index.js +21 -0
- package/vendor/schema/dist/look.d.ts +463 -0
- package/vendor/schema/dist/look.js +681 -0
- package/vendor/schema/dist/lookStats.d.ts +230 -0
- package/vendor/schema/dist/lookStats.js +768 -0
- package/vendor/schema/dist/pilot.d.ts +32 -0
- package/vendor/schema/dist/pilot.js +44 -0
- package/vendor/schema/dist/publish.d.ts +214 -0
- package/vendor/schema/dist/publish.js +291 -0
- package/vendor/schema/dist/scene.d.ts +75 -0
- package/vendor/schema/dist/scene.js +120 -0
- package/vendor/schema/dist/skyLight.d.ts +141 -0
- package/vendor/schema/dist/skyLight.js +436 -0
- package/vendor/schema/dist/style.d.ts +131 -0
- package/vendor/schema/dist/style.js +155 -0
- package/vendor/schema/package.json +1 -0
- package/vendor/selectionPrompt.mjs +51 -0
- package/vendor/useTools.mjs +195 -0
- package/vendor/userMessage.mjs +26 -0
- package/web-dist/assets/GaussianSplatUtils-CptQkDVX.js +1 -0
- package/web-dist/assets/KTX2Loader-C53LJqss.js +2 -0
- package/web-dist/assets/SPZLoader-BQ3tjaTv.js +1 -0
- package/web-dist/assets/gaussianSplat-_9tcWegB.js +1 -0
- package/web-dist/assets/index-Baka-ZO7.js +693 -0
- package/web-dist/assets/index-CcjyyQco.css +1 -0
- package/web-dist/assets/meshopt_decoder.module-BvwdjiD3.js +1 -0
- package/web-dist/assets/zstddec.module-CfFeQW7d.js +1 -0
- package/web-dist/index.html +34 -0
|
@@ -0,0 +1,754 @@
|
|
|
1
|
+
// nw_blender: modelling the agent can see. Before it, every Blender session
|
|
2
|
+
// was one large script run once in the background with its output filtered
|
|
3
|
+
// to "EXPORTED", and nothing was ever rendered; the one run where the agent
|
|
4
|
+
// rendered its own model and looked at it gave a model as good as a person
|
|
5
|
+
// working in Blender would. So the tool does the looking for it: it runs the
|
|
6
|
+
// agent's script without a window, exports the GLB the game will load,
|
|
7
|
+
// imports that GLB again and renders contact sheets with the numbers.
|
|
8
|
+
//
|
|
9
|
+
// Every export is also scored (sheet.py's rubric: silhouette, bevel,
|
|
10
|
+
// materials, budget, and what to fix first), so a blockout says it is
|
|
11
|
+
// one, and recorded in the licence ledger as a model the project made, with
|
|
12
|
+
// the licences of the files it was built from. The script is the agent's own
|
|
13
|
+
// bpy, written for the one asset it models: there is no toolkit to build
|
|
14
|
+
// from, only this tool to see and measure what the script made.
|
|
15
|
+
//
|
|
16
|
+
// The handler never leaves the agent host (no rpc). Its Blender search, its
|
|
17
|
+
// runner and the ledger come in through makeBlenderTool, so a check can spy
|
|
18
|
+
// on them.
|
|
19
|
+
|
|
20
|
+
import { z } from 'zod'
|
|
21
|
+
import { createHash } from 'node:crypto'
|
|
22
|
+
import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
|
|
23
|
+
import os from 'node:os'
|
|
24
|
+
import path from 'node:path'
|
|
25
|
+
import { fileURLToPath } from 'node:url'
|
|
26
|
+
import { findBlender } from '../blender/find.mjs'
|
|
27
|
+
import { runBlender } from '../blender/run.mjs'
|
|
28
|
+
import { lineChanges } from '../stopGate.mjs'
|
|
29
|
+
import { webLookOnlyAll } from '../reference/web.mjs'
|
|
30
|
+
|
|
31
|
+
const here = path.dirname(fileURLToPath(import.meta.url))
|
|
32
|
+
const RUNNER = path.join(here, '..', 'blender', 'runner.py')
|
|
33
|
+
const SHEET = path.join(here, '..', 'blender', 'sheet.py')
|
|
34
|
+
/** Converts FBX, OBJ, STL, PLY, USD (and Collada where Blender still reads it) to one GLB: asset_import runs it with runBlender. */
|
|
35
|
+
export const CONVERT = path.join(here, '..', 'blender', 'convert.py')
|
|
36
|
+
/** The licence ledger (ASSETS); a tree without it yet records nothing and says so. */
|
|
37
|
+
const LEDGER_URL = new URL('../assets/ledger.mjs', import.meta.url)
|
|
38
|
+
|
|
39
|
+
export const RPC_METHODS = []
|
|
40
|
+
|
|
41
|
+
/** Contact-sheet folders kept per model; older ones are removed. */
|
|
42
|
+
export const KEEP_RENDERS = 5
|
|
43
|
+
|
|
44
|
+
const FALLBACK_AUTO_SIZE = { target: 3, max: 12, min: 0.375 }
|
|
45
|
+
let autoSizeRule = null
|
|
46
|
+
/** The studio's auto-size rule, as the schema states it (loadModel.ts applies it). */
|
|
47
|
+
export function autoSize() {
|
|
48
|
+
autoSizeRule ??= import('../../schema/dist/index.js')
|
|
49
|
+
.then((m) => m.AUTO_SIZE ?? FALLBACK_AUTO_SIZE)
|
|
50
|
+
.catch(() => FALLBACK_AUTO_SIZE)
|
|
51
|
+
return autoSizeRule
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// The schema's asset classes and their triangle budgets (packages/schema
|
|
55
|
+
// assets.ts), read the way autoSize() reads its rule: the schema when it has
|
|
56
|
+
// them, else the same table.
|
|
57
|
+
const FALLBACK_CLASSES = ['small', 'prop', 'large', 'hero', 'character', 'building', 'terrain']
|
|
58
|
+
const FALLBACK_BUDGETS = { small: 2000, prop: 5000, large: 20000, hero: 50000, character: 30000, building: 40000, terrain: 100000 }
|
|
59
|
+
let budgetTable = null
|
|
60
|
+
/** { classes, triangles } from @nowhere/schema, or the fallback table. */
|
|
61
|
+
export function budgets() {
|
|
62
|
+
budgetTable ??= import('../../schema/dist/index.js')
|
|
63
|
+
.then((m) => {
|
|
64
|
+
const classes = Array.isArray(m.ASSET_CLASSES) && m.ASSET_CLASSES.length ? [...m.ASSET_CLASSES] : FALLBACK_CLASSES
|
|
65
|
+
const triangles = m.TRIANGLE_BUDGETS && classes.every((c) => Number.isFinite(m.TRIANGLE_BUDGETS[c])) ? { ...m.TRIANGLE_BUDGETS } : FALLBACK_BUDGETS
|
|
66
|
+
return { classes: triangles === FALLBACK_BUDGETS ? FALLBACK_CLASSES : classes, triangles }
|
|
67
|
+
})
|
|
68
|
+
.catch(() => ({ classes: FALLBACK_CLASSES, triangles: FALLBACK_BUDGETS }))
|
|
69
|
+
return budgetTable
|
|
70
|
+
}
|
|
71
|
+
const { classes: ASSET_CLASSES } = await budgets()
|
|
72
|
+
|
|
73
|
+
const metresField = (what) => z.number().positive().max(10_000).describe(what)
|
|
74
|
+
|
|
75
|
+
export const SHAPE = {
|
|
76
|
+
script: z.string().describe('Project-relative .py you wrote, e.g. "blender/lighthouse.py".'),
|
|
77
|
+
out: z.string().describe('Project-relative .glb under assets/, e.g. "assets/lighthouse.glb".'),
|
|
78
|
+
collection: z.string().max(63).optional().describe('Export only this collection. Default: every visible mesh, curve, text and empty.'),
|
|
79
|
+
render: z.boolean().default(true).describe('false skips the contact sheets and only measures the export.'),
|
|
80
|
+
closeup: z
|
|
81
|
+
.object({ target: z.array(z.number()).length(3).optional(), radius: z.number().positive().max(1000).optional() })
|
|
82
|
+
.optional()
|
|
83
|
+
.describe('What the close-up frames, in Blender coordinates (metres, Z up). Default: the top third of the model.'),
|
|
84
|
+
size: z.number().int().min(256).max(768).default(512).describe('Pixels per cell of the contact sheets.'),
|
|
85
|
+
blend: z.string().optional().describe('Also save the scene as this project-relative .blend under blender/.'),
|
|
86
|
+
timeoutSec: z.number().int().min(30).max(600).default(240).describe('Seconds each Blender run (the export, then the sheets) may take before it is stopped.'),
|
|
87
|
+
class: z
|
|
88
|
+
.enum(ASSET_CLASSES)
|
|
89
|
+
.optional()
|
|
90
|
+
.describe(`The asset class the rubric scores against, which sets how many triangles the model may have (${ASSET_CLASSES.join(', ')}). Default: prop.`),
|
|
91
|
+
expect: z
|
|
92
|
+
.object({ height: metresField('Metres, Z.'), width: metresField('Metres, X.'), depth: metresField('Metres, Y.') })
|
|
93
|
+
.partial()
|
|
94
|
+
.optional()
|
|
95
|
+
.describe('The size the model should have, checked within 5%. Without it the size is not checked.'),
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export const DESCRIPTION =
|
|
99
|
+
'Runs your bpy script in Blender without a window (factory settings, auto-run scripts off), exports the result as a GLB into assets/, then imports that GLB into an empty scene and renders two contact sheets, colour and clay, each a 3 x 2 grid: front, side (+X), back on top; three-quarter, top and a close-up below, with a 1.75 m figure beside the model in the front, back and three-quarter views. Returns the sheets and the numbers: the rubric (silhouette, bevel, materials and triangles against what the asset class allows, each 1 to 5, and what to fix first), the checks (expected size, pivot, manifold, normals, UVs, texel density, the material nodes glTF would drop), size in metres, triangles, meshes, materials, textures, whether the studio would auto-size the model, and which round of the model this is (or that the script did not change since the last render). The export is recorded in the licence ledger (assets.lock.json). Write the script for this one asset in plain bpy (the nowhere:blender-modeling skill has the facts) to blender/ first, after deciding its form from the brief; model in real metres, Z up, front facing -Y, origin at the base centre, and pass class and expect. Run it again after every change and look at the sheets and the rubric each time.'
|
|
100
|
+
|
|
101
|
+
// ---------------------------------------------------------------- paths
|
|
102
|
+
|
|
103
|
+
// Both sides of a containment check are real paths: on macOS the temp and
|
|
104
|
+
// home trees are symlinked (/var -> /private/var), and a project reached
|
|
105
|
+
// through a link must not read as outside itself.
|
|
106
|
+
function realOrSelf(p) {
|
|
107
|
+
let head = path.resolve(p)
|
|
108
|
+
const rest = []
|
|
109
|
+
for (;;) {
|
|
110
|
+
try {
|
|
111
|
+
return path.join(realpathSync(head), ...rest)
|
|
112
|
+
} catch {
|
|
113
|
+
const up = path.dirname(head)
|
|
114
|
+
if (up === head) return path.resolve(p)
|
|
115
|
+
rest.unshift(path.basename(head))
|
|
116
|
+
head = up
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const slash = (p) => p.split(path.sep).join('/')
|
|
122
|
+
|
|
123
|
+
function inProject(root, given, what) {
|
|
124
|
+
if (typeof given !== 'string' || !given.trim()) return { error: `${what} is empty.` }
|
|
125
|
+
const abs = realOrSelf(path.resolve(root, given))
|
|
126
|
+
const rel = path.relative(root, abs)
|
|
127
|
+
if (rel === '' || rel === '..' || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)) {
|
|
128
|
+
return { error: `${what} "${given}" is outside the project. Give a path inside it, such as "blender/<asset>.py" for the script and "assets/<asset>.glb" for out.` }
|
|
129
|
+
}
|
|
130
|
+
return { abs, rel: slash(rel) }
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Checks the three paths before anything runs. */
|
|
134
|
+
export function checkPaths(args, projectRoot) {
|
|
135
|
+
const root = realOrSelf(projectRoot)
|
|
136
|
+
const script = inProject(root, args.script, 'script')
|
|
137
|
+
if (script.error) return script
|
|
138
|
+
if (/^(\.git|\.nowhere)(\/|$)/.test(script.rel)) {
|
|
139
|
+
return { error: `script "${args.script}" is inside ${script.rel.split('/')[0]}/. nw_blender runs only scripts you wrote in the project (blender/<asset>.py); a downloaded script is never run.` }
|
|
140
|
+
}
|
|
141
|
+
if (!/\.py$/i.test(script.rel)) return { error: `script "${args.script}" is not a .py file.` }
|
|
142
|
+
const out = inProject(root, args.out, 'out')
|
|
143
|
+
if (out.error) return out
|
|
144
|
+
if (!out.rel.startsWith('assets/')) return { error: `out "${args.out}" is not under assets/. Models the game loads live there: use "assets/<asset>.glb".` }
|
|
145
|
+
if (!/\.glb$/i.test(out.rel)) return { error: `out "${args.out}" is not a .glb file. nw_blender exports one binary glTF: use "assets/<asset>.glb".` }
|
|
146
|
+
let blend = null
|
|
147
|
+
if (args.blend !== undefined && args.blend !== null) {
|
|
148
|
+
blend = inProject(root, args.blend, 'blend')
|
|
149
|
+
if (blend.error) return blend
|
|
150
|
+
if (!blend.rel.startsWith('blender/') || !/\.blend$/i.test(blend.rel)) return { error: `blend "${args.blend}" must be a .blend file under blender/, e.g. "blender/<asset>.blend".` }
|
|
151
|
+
}
|
|
152
|
+
let isFile = false
|
|
153
|
+
try {
|
|
154
|
+
isFile = statSync(script.abs).isFile()
|
|
155
|
+
} catch {
|
|
156
|
+
// missing
|
|
157
|
+
}
|
|
158
|
+
if (!isFile) return { error: `The script ${script.rel} does not exist. Write it first (blender/<asset>.py), then run nw_blender on it.` }
|
|
159
|
+
return { root, script, out, blend }
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// ---------------------------------------------------------------- text
|
|
163
|
+
|
|
164
|
+
/** Metres the way a person writes them: 18.6, 4.2, 1, 0.375. */
|
|
165
|
+
export function metres(v) {
|
|
166
|
+
const a = Math.abs(v)
|
|
167
|
+
return String(Number(v.toFixed(a >= 10 ? 1 : a >= 1 ? 2 : 3)))
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const seconds = (ms) => `${(ms / 1000).toFixed(1)} s`
|
|
171
|
+
const fileSize = (bytes) => (bytes >= 1e6 ? `${(bytes / 1e6).toFixed(1)} MB` : `${Math.max(0.1, bytes / 1e3).toFixed(1)} KB`)
|
|
172
|
+
const ENGINE_NAMES = { BLENDER_EEVEE: 'EEVEE', BLENDER_EEVEE_NEXT: 'EEVEE', BLENDER_WORKBENCH: 'Workbench', CYCLES: 'Cycles' }
|
|
173
|
+
|
|
174
|
+
/** Whether the studio would rescale the model, and what the agent should do about it. */
|
|
175
|
+
export function autoSizeLine(size, rule = FALLBACK_AUTO_SIZE) {
|
|
176
|
+
const largest = Math.max(size.width, size.height, size.depth)
|
|
177
|
+
const keep = 'unless its placement sets "normalize": false'
|
|
178
|
+
if (largest > rule.max) {
|
|
179
|
+
return `studio auto-size: yes. The largest side is ${metres(largest)} m, over ${metres(rule.max)} m, so the studio would show it at ${metres(rule.target)} m ${keep}.`
|
|
180
|
+
}
|
|
181
|
+
if (largest > 0 && largest < rule.min) {
|
|
182
|
+
const factor = rule.target / largest
|
|
183
|
+
return `studio auto-size: yes. The largest side is ${metres(largest)} m, under ${metres(rule.min)} m, so the studio would show it at ${metres(rule.target)} m (${factor >= 10 ? Math.round(factor) : factor.toFixed(1)}x larger) ${keep}.`
|
|
184
|
+
}
|
|
185
|
+
return `studio auto-size: no. The largest side is ${metres(largest)} m, between ${metres(rule.min)} m and ${metres(rule.max)} m, so the studio shows it at its real size.`
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function materialText(m) {
|
|
189
|
+
const parts = [m.texture ? `texture ${m.texture}` : m.color ?? 'no base colour']
|
|
190
|
+
const num = (v) => (typeof v === 'number' ? String(Number(v.toFixed(2))) : String(v))
|
|
191
|
+
if (m.roughness !== undefined) parts.push(`roughness ${num(m.roughness)}`)
|
|
192
|
+
if (m.metallic === 'texture' || m.metallic > 0) parts.push(`metallic ${num(m.metallic)}`)
|
|
193
|
+
if (m.emission) parts.push(`emission ${Number(m.emission).toFixed(1)}`)
|
|
194
|
+
if (m.alpha === 'texture' || (typeof m.alpha === 'number' && m.alpha < 1)) parts.push(`alpha ${num(m.alpha)}`)
|
|
195
|
+
return `${m.name} (${parts.join(', ')})`
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const listOf = (items, max, fmt) => {
|
|
199
|
+
if (!items?.length) return 'none'
|
|
200
|
+
const shown = items.slice(0, max).map(fmt).join(', ')
|
|
201
|
+
return items.length > max ? `${shown} and ${items.length - max} more` : shown
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const score = (part) => (part && Number.isInteger(part.score) ? `${part.score}/5` : 'not scored')
|
|
205
|
+
|
|
206
|
+
/** The rubric, what to fix first and the checks, as the three lines after the round. */
|
|
207
|
+
export function rubricLines({ sheet, sheetError, exported }) {
|
|
208
|
+
const rubric = sheet?.rubric
|
|
209
|
+
if (!rubric) {
|
|
210
|
+
const why = sheetError ? 'unknown (the sheet run failed)' : sheet ? 'unknown (it could not be scored; see blender warnings)' : 'unknown (the GLB has no mesh)'
|
|
211
|
+
return [`rubric: ${why}`, `fix first: ${why}`, `checks: ${why}`]
|
|
212
|
+
}
|
|
213
|
+
const part = (name, p) => `${name} ${score(p)}${p?.note ? ` (${p.note})` : ''}`
|
|
214
|
+
const head = `rubric: ${[part('silhouette', rubric.silhouette), part('bevel', rubric.bevel), part('materials', rubric.materials), part('budget', rubric.budget)].join(', ')}`
|
|
215
|
+
const c = rubric.checks ?? {}
|
|
216
|
+
const bits = []
|
|
217
|
+
if (c.scale?.ok === null || c.scale?.ok === undefined) bits.push('scale not checked (no expected size)')
|
|
218
|
+
else bits.push(`scale ${c.scale.ok ? 'ok' : 'off'} (${c.scale.note})`)
|
|
219
|
+
if (c.pivot) bits.push(c.pivot.ok ? 'pivot ok' : `pivot off (${c.pivot.note})`)
|
|
220
|
+
if (c.manifold) {
|
|
221
|
+
bits.push(c.manifold.ok ? 'manifold ok' : `manifold: ${c.manifold.open} open edge${c.manifold.open === 1 ? '' : 's'}, ${c.manifold.nonManifold} shared by more than two faces`)
|
|
222
|
+
}
|
|
223
|
+
if (c.normals) {
|
|
224
|
+
bits.push(c.normals.ok ? 'normals ok' : `normals: ${c.normals.flipped} edge${c.normals.flipped === 1 ? '' : 's'} between faces wound against each other, ${c.normals.inverted} shell${c.normals.inverted === 1 ? '' : 's'} inside out`)
|
|
225
|
+
}
|
|
226
|
+
if (c.uvs) bits.push(c.uvs.ok ? 'UVs ok' : `UVs missing on ${c.uvs.missing.join(', ')} (textured)`)
|
|
227
|
+
if (c.texel) bits.push(`texel density ${c.texel.note}`)
|
|
228
|
+
const dropped = exported?.dropped ?? []
|
|
229
|
+
bits.push(dropped.length ? `glTF dropped nodes in ${dropped.map((d) => d.material).join(', ')}` : 'glTF dropped none')
|
|
230
|
+
return [head, `fix first: ${rubric.fixFirst ?? 'unknown'}`, `checks: ${bits.join(', ')}`]
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* The tool's answer from the two runs' JSON. Pure, so a check can feed it
|
|
235
|
+
* canned results. Every line is always there, saying "none" when empty.
|
|
236
|
+
*/
|
|
237
|
+
export function describeRun({ script, out, bytes, exportMs, sheetMs, blender, exported, sheet, sheetError, render, renders, blend, warnings, rule, klass = 'prop', budget = FALLBACK_BUDGETS.prop, ledger = null }) {
|
|
238
|
+
const lines = []
|
|
239
|
+
const engine = sheet?.engine ? ENGINE_NAMES[sheet.engine] ?? sheet.engine : null
|
|
240
|
+
const how = sheetError
|
|
241
|
+
? `, but the contact sheets failed: ${sheetError}`
|
|
242
|
+
: render
|
|
243
|
+
? `; sheets rendered in ${seconds(sheetMs)} with ${engine}`
|
|
244
|
+
: `; measured in ${seconds(sheetMs)}, sheets not rendered (render: false)`
|
|
245
|
+
lines.push(`Exported ${out} (${fileSize(bytes)}) from ${script} in ${seconds(exportMs)}${how} (Blender ${blender}).`)
|
|
246
|
+
lines.push(...rubricLines({ sheet, sheetError, exported }))
|
|
247
|
+
const size = sheet?.size_m
|
|
248
|
+
const unknown = sheetError ? 'unknown (the sheet run failed)' : 'unknown (the GLB has no mesh)'
|
|
249
|
+
lines.push(size ? `size: ${metres(size.width)} m wide, ${metres(size.height)} m tall, ${metres(size.depth)} m deep (the figure is 1.75 m)` : `size: ${unknown}`)
|
|
250
|
+
if (sheet) {
|
|
251
|
+
const tris = sheet.triangles.toLocaleString('en-US')
|
|
252
|
+
const heavy = sheet.triangles > budget ? ` (over the ${budget.toLocaleString('en-US')} a ${klass} should stay under)` : ''
|
|
253
|
+
const anims = sheet.animations?.length ? `; animations: ${sheet.animations.join(', ')}` : ''
|
|
254
|
+
lines.push(`triangles: ${tris} in ${sheet.meshes} ${sheet.meshes === 1 ? 'mesh' : 'meshes'}${heavy}; objects: ${sheet.objects}${anims}`)
|
|
255
|
+
} else {
|
|
256
|
+
lines.push(`triangles: ${unknown}; objects: ${exported?.objects ?? 'unknown'}`)
|
|
257
|
+
}
|
|
258
|
+
lines.push(sheet ? `materials (${sheet.materials.length}): ${listOf(sheet.materials, 12, materialText)}` : `materials: ${unknown}`)
|
|
259
|
+
lines.push(sheet ? `textures (${sheet.textures.length}): ${listOf(sheet.textures, 12, (t) => `${t.name} ${t.width}x${t.height}`)}` : `textures: ${unknown}`)
|
|
260
|
+
const dropped = exported?.dropped ?? []
|
|
261
|
+
lines.push(
|
|
262
|
+
dropped.length
|
|
263
|
+
? `glTF dropped: ${dropped.map((d) => `${d.material} uses ${d.nodes.join(', ')}`).join('; ')} (procedural nodes do not export: bake them to images in your script, or model the detail)`
|
|
264
|
+
: 'glTF dropped: none',
|
|
265
|
+
)
|
|
266
|
+
lines.push(size ? autoSizeLine(size, rule) : `studio auto-size: ${unknown}`)
|
|
267
|
+
if (render && sheet?.sheets) {
|
|
268
|
+
lines.push('sheet 1 is colour, sheet 2 is clay. Top row: front, side (+X), back. Bottom row: three-quarter, top, close-up.')
|
|
269
|
+
lines.push(`renders kept in ${renders}/`)
|
|
270
|
+
} else {
|
|
271
|
+
const why = render ? 'the sheet run failed' : 'render: false'
|
|
272
|
+
lines.push(`sheets: none (${why})`)
|
|
273
|
+
lines.push(`renders kept: none (${why})`)
|
|
274
|
+
}
|
|
275
|
+
if (blend) lines.push(`blend: saved as ${blend}`)
|
|
276
|
+
lines.push(`ledger: ${ledger ?? 'not recorded'}`)
|
|
277
|
+
lines.push(`blender warnings: ${warnings?.length ? warnings.join('; ') : 'none'}`)
|
|
278
|
+
return lines.join('\n')
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
const lastLines = (text, n) => String(text ?? '').trimEnd().split('\n').slice(-n).join('\n')
|
|
282
|
+
|
|
283
|
+
// Blender's own banner and goodbye say nothing about the model.
|
|
284
|
+
const CHATTER = /^(Blender \d+\.\d+.*\(hash |Blender quit$|Error: script failed, file: )/
|
|
285
|
+
|
|
286
|
+
/** The last lines Blender and the agent's script printed, with the project's path shortened. */
|
|
287
|
+
function blenderOutput(run, root, n = 40) {
|
|
288
|
+
const lines = `${run.stdout ?? ''}\n${run.stderr ?? ''}`.split('\n').filter((l) => !CHATTER.test(l.trim()))
|
|
289
|
+
const text = lastLines(lines.join('\n').replace(/\n{3,}/g, '\n\n'), n).trim()
|
|
290
|
+
return shorten(text || '(nothing)', root)
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
const shorten = (text, root) => (root ? String(text).split(root + path.sep).join('') : String(text))
|
|
294
|
+
|
|
295
|
+
// Blender's own notes that are about Blender, not the model: 5.1 asks to
|
|
296
|
+
// "Call save()" when it quits after a Cycles bake into colour attributes.
|
|
297
|
+
const NOT_ABOUT_THE_MODEL = /Call `save\(\)` to make sure that changes persist/
|
|
298
|
+
|
|
299
|
+
/** Warning lines from Blender's output: the exporter's, the importer's, Python's. */
|
|
300
|
+
export function outputWarnings(...outputs) {
|
|
301
|
+
const found = []
|
|
302
|
+
for (const text of outputs) {
|
|
303
|
+
for (const raw of String(text ?? '').split('\n')) {
|
|
304
|
+
const line = raw.trim()
|
|
305
|
+
if (!/\bWARNING\b|Warning:/.test(line) || NOT_ABOUT_THE_MODEL.test(line)) continue
|
|
306
|
+
const cut = line.length > 200 ? `${line.slice(0, 200)}...` : line
|
|
307
|
+
if (!found.includes(cut)) found.push(cut)
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
return found.slice(0, 8)
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** Why the export run gave no GLB, in words the agent can act on; null when it did. */
|
|
314
|
+
function exportFailure(run, ctx) {
|
|
315
|
+
const output = blenderOutput(run, ctx.root)
|
|
316
|
+
if (run.error) return `Blender could not be started (${ctx.bin}): ${run.error}.`
|
|
317
|
+
if (run.timedOut) {
|
|
318
|
+
return `The export run (your script and the GLB export) did not finish within ${ctx.timeoutSec} s, so Blender was stopped. Make the script lighter (fewer subdivision levels, modifiers or array copies) or raise timeoutSec.\nBlender's output (last 40 lines):\n${output}`
|
|
319
|
+
}
|
|
320
|
+
const r = run.result
|
|
321
|
+
if (!r) return `Blender stopped without an answer (exit code ${run.code ?? run.signal}).\nBlender's output (last 40 lines):\n${output}`
|
|
322
|
+
if (r.ok) return existsSync(r.exported ?? '') ? null : 'The export reported success but wrote no file.'
|
|
323
|
+
if (r.stage === 'script') {
|
|
324
|
+
const at = r.at ? `${ctx.script} line ${r.at.line}${r.at.text ? `: ${r.at.text}` : ''}` : ctx.script
|
|
325
|
+
const argvHabit = /'--' is not in list|sys\.argv/.test(`${r.error}\n${r.traceback}`)
|
|
326
|
+
? '\nnw_blender passes your script no arguments: do not read sys.argv, and do not export, save or reset the scene; it does all three.'
|
|
327
|
+
: ''
|
|
328
|
+
// A script from before the toolkit was taken out still imports it.
|
|
329
|
+
const kitHabit = /No module named 'nwkit'/.test(r.error ?? '')
|
|
330
|
+
? '\nThere is no nwkit any more: write this asset in plain bpy and bmesh (the nowhere:blender-modeling skill has the facts), and pass class and expect to nw_blender.'
|
|
331
|
+
: ''
|
|
332
|
+
// The traceback is in the output too (the runner prints it, from the
|
|
333
|
+
// script's own frame down), so it is not repeated.
|
|
334
|
+
return `Your script failed at ${at}\n${r.error}${argvHabit}${kitHabit}\nBlender's output (last 40 lines):\n${output}`
|
|
335
|
+
}
|
|
336
|
+
if (r.stage === 'collection') {
|
|
337
|
+
return `The script ran but there is no collection "${r.collection}". Collections: ${r.collections?.length ? r.collections.join(', ') : 'none'}.`
|
|
338
|
+
}
|
|
339
|
+
if (r.stage === 'empty') {
|
|
340
|
+
return `The script ran but left nothing to export: no visible mesh, curve, text or empty${r.collection ? `, or the collection "${r.collection}" is empty` : ''}.`
|
|
341
|
+
}
|
|
342
|
+
return `The glTF export failed: ${r.error}\nBlender's output (last 40 lines):\n${output}`
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
// ---------------------------------------------------------------- files
|
|
346
|
+
|
|
347
|
+
/** One rename, so the studio's watcher sees one complete file (copy first across disks). */
|
|
348
|
+
function place(from, to) {
|
|
349
|
+
mkdirSync(path.dirname(to), { recursive: true })
|
|
350
|
+
try {
|
|
351
|
+
renameSync(from, to)
|
|
352
|
+
} catch (err) {
|
|
353
|
+
if (err.code !== 'EXDEV') throw err
|
|
354
|
+
const part = path.join(path.dirname(to), `.${path.basename(to)}.${process.pid}.part`)
|
|
355
|
+
copyFileSync(from, part)
|
|
356
|
+
renameSync(part, to)
|
|
357
|
+
unlinkSync(from)
|
|
358
|
+
}
|
|
359
|
+
return statSync(to).size
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
const pad = (n) => String(n).padStart(2, '0')
|
|
363
|
+
const stamp = (d = new Date()) => `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`
|
|
364
|
+
const STAMP_RE = /^\d{8}-\d{6}(-\d+)?$/
|
|
365
|
+
|
|
366
|
+
/** A model's name among the render folders: assets/props/crate.glb is props_crate. */
|
|
367
|
+
const stemOf = (outRel) => outRel.replace(/^assets\//, '').replace(/\.glb$/i, '').replace(/\//g, '_').replace(/[^A-Za-z0-9._-]/g, '_')
|
|
368
|
+
|
|
369
|
+
/** `.nowhere/renders/<stem>/<stamp>/`, outside git and the watcher. */
|
|
370
|
+
function renderDir(root, outRel) {
|
|
371
|
+
const stem = stemOf(outRel)
|
|
372
|
+
const base = path.join(root, '.nowhere', 'renders', stem)
|
|
373
|
+
mkdirSync(base, { recursive: true })
|
|
374
|
+
// Several runs in one second (two helpers, a quick retry) get -2, -3 after
|
|
375
|
+
// the stamp, always above what is there, so the newest sorts last even
|
|
376
|
+
// when an older folder of the same second was pruned already.
|
|
377
|
+
const now = stamp()
|
|
378
|
+
const taken = readdirSync(base)
|
|
379
|
+
.filter((n) => n === now || n.startsWith(`${now}-`))
|
|
380
|
+
.map((n) => (n === now ? 1 : Number(n.slice(now.length + 1)) || 1))
|
|
381
|
+
const name = taken.length ? `${now}-${Math.max(...taken) + 1}` : now
|
|
382
|
+
const dir = path.join(base, name)
|
|
383
|
+
mkdirSync(dir, { recursive: true })
|
|
384
|
+
return { base, dir }
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
const byAge = (a, b) => a.localeCompare(b, 'en', { numeric: true })
|
|
388
|
+
|
|
389
|
+
function prune(base, current) {
|
|
390
|
+
try {
|
|
391
|
+
const runs = readdirSync(base)
|
|
392
|
+
.filter((n) => STAMP_RE.test(n) && path.join(base, n) !== current)
|
|
393
|
+
.sort(byAge)
|
|
394
|
+
for (const old of runs.slice(0, Math.max(0, runs.length - (KEEP_RENDERS - 1)))) rmSync(path.join(base, old), { recursive: true, force: true })
|
|
395
|
+
} catch {
|
|
396
|
+
// a folder the creator removed meanwhile
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
// ---------------------------------------------------------------- rounds
|
|
401
|
+
// A QA run's blender-modeler reported three rounds that were mostly the same
|
|
402
|
+
// script rendered again with a closer camera, two small edits in all
|
|
403
|
+
// (2026-10-20). A round changes the model in answer to what the sheets
|
|
404
|
+
// showed; so each export is compared with the last one of the same model:
|
|
405
|
+
// the script and the .py files beside it that it uses (a helper it imports),
|
|
406
|
+
// by content. Only those: every asset's script sits in the same blender/
|
|
407
|
+
// folder, so another asset's script written meanwhile is not this model's
|
|
408
|
+
// change. Kept beside the model's render folders, outside git and the
|
|
409
|
+
// watcher.
|
|
410
|
+
|
|
411
|
+
/** The longest script whose text is kept, for counting the lines a round changed. */
|
|
412
|
+
const ROUND_TEXT_MAX = 256 * 1024
|
|
413
|
+
|
|
414
|
+
/** The module names a script's text reaches for: import a, b as c; from a
|
|
415
|
+
* import x; importlib.import_module('a') or __import__('a'); and a file
|
|
416
|
+
* named in quotes ('a.py', 'blender/a.py'), as exec(open(...)) or
|
|
417
|
+
* runpy.run_path read one. Comments are left out; a line continued with a
|
|
418
|
+
* backslash is read as one. */
|
|
419
|
+
export function usedModules(text) {
|
|
420
|
+
const names = new Set()
|
|
421
|
+
const code = String(text)
|
|
422
|
+
.replace(/(^|\s)#[^\n]*/g, '$1')
|
|
423
|
+
.replace(/\\\r?\n/g, ' ')
|
|
424
|
+
for (const m of code.matchAll(/(?:^|[;:])[ \t]*import[ \t]+([^\n;#]+)/gm)) {
|
|
425
|
+
for (const part of m[1].replace(/[()\\]/g, ' ').split(',')) {
|
|
426
|
+
const name = part.trim().split(/\s+/)[0]?.split('.')[0]
|
|
427
|
+
if (name) names.add(name)
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
for (const m of code.matchAll(/(?:^|[;:])[ \t]*from[ \t]+(\.*)([\w.]*)[ \t]+import[ \t]+([^\n;#]+)/gm)) {
|
|
431
|
+
if (m[2]) names.add(m[2].split('.')[0])
|
|
432
|
+
// from . import lib: the names are modules beside it
|
|
433
|
+
if (m[1] && !m[2]) for (const part of m[3].replace(/[()\\]/g, ' ').split(',')) names.add(part.trim().split(/\s+/)[0])
|
|
434
|
+
}
|
|
435
|
+
for (const m of code.matchAll(/(?:import_module|__import__)\(\s*['"]([\w.]+)['"]/g)) names.add(m[1].split('.')[0])
|
|
436
|
+
for (const m of code.matchAll(/['"]([^'"\n]*?)([\w-]+)\.py['"]/g)) names.add(m[2])
|
|
437
|
+
names.delete('')
|
|
438
|
+
return names
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/** The script and the .py files beside it that it uses, directly or through
|
|
442
|
+
* one another, as one fingerprint. */
|
|
443
|
+
function sourcesHash(scriptAbs) {
|
|
444
|
+
const hash = createHash('sha1')
|
|
445
|
+
const own = readFileSync(scriptAbs)
|
|
446
|
+
hash.update(own)
|
|
447
|
+
const dir = path.dirname(scriptAbs)
|
|
448
|
+
const beside = new Map()
|
|
449
|
+
try {
|
|
450
|
+
for (const n of readdirSync(dir)) {
|
|
451
|
+
if (/\.py$/i.test(n) && path.join(dir, n) !== scriptAbs) beside.set(n.slice(0, -3), n)
|
|
452
|
+
}
|
|
453
|
+
} catch {
|
|
454
|
+
// no folder to read
|
|
455
|
+
}
|
|
456
|
+
const used = new Map()
|
|
457
|
+
const queue = [own.toString('utf8')]
|
|
458
|
+
while (queue.length) {
|
|
459
|
+
for (const name of usedModules(queue.shift())) {
|
|
460
|
+
const file = beside.get(name)
|
|
461
|
+
if (!file || used.has(file)) continue
|
|
462
|
+
let bytes = null
|
|
463
|
+
try {
|
|
464
|
+
bytes = readFileSync(path.join(dir, file))
|
|
465
|
+
} catch {
|
|
466
|
+
// gone meanwhile
|
|
467
|
+
}
|
|
468
|
+
used.set(file, bytes)
|
|
469
|
+
if (bytes) queue.push(bytes.toString('utf8'))
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
for (const file of [...used.keys()].sort()) {
|
|
473
|
+
const bytes = used.get(file)
|
|
474
|
+
if (bytes) hash.update(`\0${file}\0`).update(bytes)
|
|
475
|
+
}
|
|
476
|
+
return hash.digest('hex')
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
/** How many lines of `before` changed to make `after`; null when too big to tell. */
|
|
480
|
+
function changedLines(before, after) {
|
|
481
|
+
const changes = lineChanges(before.split('\n'), after.split('\n'))
|
|
482
|
+
return changes ? changes.reduce((n, [a0, a1, b0, b1]) => n + Math.max(a1 - a0, b1 - b0), 0) : null
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/**
|
|
486
|
+
* Which round of the model this export is, against the last export of the
|
|
487
|
+
* same model: { round, changed, lines }. changed is null for the first one,
|
|
488
|
+
* false when nothing the script runs changed since the last render.
|
|
489
|
+
*/
|
|
490
|
+
export function noteRound(root, scriptRel, scriptAbs, outRel) {
|
|
491
|
+
const file = path.join(root, '.nowhere', 'renders', `${stemOf(outRel)}.rounds.json`)
|
|
492
|
+
let last = null
|
|
493
|
+
try {
|
|
494
|
+
last = JSON.parse(readFileSync(file, 'utf8'))
|
|
495
|
+
} catch {
|
|
496
|
+
// the first export of this model
|
|
497
|
+
}
|
|
498
|
+
let text = ''
|
|
499
|
+
try {
|
|
500
|
+
text = readFileSync(scriptAbs, 'utf8')
|
|
501
|
+
} catch {
|
|
502
|
+
// read just before the run; gone since
|
|
503
|
+
}
|
|
504
|
+
const hash = sourcesHash(scriptAbs)
|
|
505
|
+
let at
|
|
506
|
+
if (!last || last.script !== scriptRel || !Number.isInteger(last.round)) at = { round: 1, changed: null, lines: null }
|
|
507
|
+
else if (last.hash === hash) at = { round: last.round, changed: false, lines: 0 }
|
|
508
|
+
else at = { round: last.round + 1, changed: true, lines: typeof last.text === 'string' ? changedLines(last.text, text) : null }
|
|
509
|
+
try {
|
|
510
|
+
mkdirSync(path.dirname(file), { recursive: true })
|
|
511
|
+
writeFileSync(file, JSON.stringify({ script: scriptRel, hash, round: at.round, text: text.length <= ROUND_TEXT_MAX ? text : null }))
|
|
512
|
+
} catch {
|
|
513
|
+
// a folder that cannot be written only loses the count
|
|
514
|
+
}
|
|
515
|
+
return at
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/** The round as one line of the tool's answer. */
|
|
519
|
+
export function roundLine({ round, changed, lines }, scriptRel) {
|
|
520
|
+
if (changed === null) return `round 1: the first export of this model from ${scriptRel}.`
|
|
521
|
+
if (changed) {
|
|
522
|
+
const how = lines === null ? '' : lines === 0 ? ' (in the .py files it imports)' : ` (${lines} line${lines === 1 ? '' : 's'})`
|
|
523
|
+
return `round ${round}: ${scriptRel} changed since the last render${how}.`
|
|
524
|
+
}
|
|
525
|
+
return `same model as round ${round}: ${scriptRel} and the .py files it imports are unchanged since the last render, so this only rendered the same model again (a closer camera is a look, not a round). A round changes the model: fix the biggest difference you saw in the sheets in the script, then run again.`
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
// ---------------------------------------------------------------- the ledger
|
|
529
|
+
// Every model nw_blender exports goes into assets.lock.json as one the
|
|
530
|
+
// project made, so publishing knows where it came from: its licence is the
|
|
531
|
+
// strictest of the project's own and those of the files the script read
|
|
532
|
+
// (a CC BY texture keeps its credit in the model made with it).
|
|
533
|
+
|
|
534
|
+
/** ASSETS' ledger.mjs, or null in a tree that does not have it yet. Any other failure to load it is thrown. */
|
|
535
|
+
export async function loadLedger({ log } = {}) {
|
|
536
|
+
try {
|
|
537
|
+
return await import(LEDGER_URL.href)
|
|
538
|
+
} catch (err) {
|
|
539
|
+
if (err?.code === 'ERR_MODULE_NOT_FOUND' && err.url === LEDGER_URL.href) {
|
|
540
|
+
log?.('nw_blender: agent/assets/ledger.mjs is not there yet; exports are not recorded')
|
|
541
|
+
return null
|
|
542
|
+
}
|
|
543
|
+
throw err
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
const OWN = 'LicenseRef-Own'
|
|
548
|
+
const todayDate = (d = new Date()) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
|
|
549
|
+
|
|
550
|
+
/** Records one export; returns the ledger line's text. */
|
|
551
|
+
export async function recordExport({ ledger, root, outRel, script, round, exported, sheet, klass, log }) {
|
|
552
|
+
let mod
|
|
553
|
+
try {
|
|
554
|
+
mod = await ledger({ log })
|
|
555
|
+
} catch (err) {
|
|
556
|
+
log?.(`nw_blender: the ledger module failed to load: ${err?.message ?? err}`)
|
|
557
|
+
return `not recorded: the ledger module failed to load (${String(err?.message ?? err).split('\n')[0].slice(0, 200)})`
|
|
558
|
+
}
|
|
559
|
+
if (!mod?.recordAsset) return 'not recorded (this build has no asset ledger yet)'
|
|
560
|
+
try {
|
|
561
|
+
const got = await mod.readLedger(root)
|
|
562
|
+
const files = (got?.files ?? got?.lock?.files) || {}
|
|
563
|
+
const inputs = (exported?.inputs ?? []).filter((p) => typeof p === 'string' && p !== outRel).slice(0, 64)
|
|
564
|
+
const known = inputs.filter((p) => files[p]?.license)
|
|
565
|
+
const unknown = inputs.filter((p) => !files[p]?.license)
|
|
566
|
+
const license = mod.deriveLicense([{ spdx: OWN, checkedAt: todayDate() }, ...known.map((p) => files[p].license)])
|
|
567
|
+
// A web reference kept to look at only, read as a texture, would ship
|
|
568
|
+
// inside the model: such a model stays on this machine.
|
|
569
|
+
const lookOnly = (await webLookOnlyAll(root, inputs.map((p) => path.join(root, p)))).map((w) => ({ p: inputs.find((q) => path.join(root, q) === w.file), why: w.why }))
|
|
570
|
+
const previous = files[outRel]?.origin === 'made' && Array.isArray(files[outRel].steps) ? files[outRel].steps : []
|
|
571
|
+
const step = { op: 'nw_blender', at: new Date().toISOString(), detail: `${script} round ${round}`.slice(0, 400) }
|
|
572
|
+
const rubric = sheet?.rubric
|
|
573
|
+
const scores = rubric ? Object.fromEntries(['silhouette', 'bevel', 'materials', 'budget'].map((k) => [k, rubric[k]?.score ?? null])) : null
|
|
574
|
+
const size = sheet?.size_m
|
|
575
|
+
const entry = {
|
|
576
|
+
kind: 'model',
|
|
577
|
+
origin: 'made',
|
|
578
|
+
license,
|
|
579
|
+
...(inputs.length ? { derivedFrom: inputs } : {}),
|
|
580
|
+
steps: [...previous, step].slice(-50),
|
|
581
|
+
publish: lookOnly.length === 0,
|
|
582
|
+
meta: {
|
|
583
|
+
triangles: sheet?.triangles ?? null,
|
|
584
|
+
size_m: size ? { width: Number(size.width.toFixed(4)), height: Number(size.height.toFixed(4)), depth: Number(size.depth.toFixed(4)) } : null,
|
|
585
|
+
class: klass,
|
|
586
|
+
rubric: scores,
|
|
587
|
+
},
|
|
588
|
+
}
|
|
589
|
+
const done = await mod.recordAsset(root, outRel, entry)
|
|
590
|
+
if (!done?.ok) return `not recorded: ${done?.error ?? 'the ledger gave no answer'}`
|
|
591
|
+
const from = known.length ? ` from ${known.length} recorded input${known.length === 1 ? '' : 's'}` : ''
|
|
592
|
+
const outside = unknown.filter((p) => !lookOnly.some((w) => w.p === p))
|
|
593
|
+
const loose = outside.length
|
|
594
|
+
? `; not in the ledger: ${listOf(outside, 4, (p) => p)} (their licence is unknown: bring outside files in with nw_take_download or asset_import)`
|
|
595
|
+
: ''
|
|
596
|
+
const held = lookOnly.length
|
|
597
|
+
? `; not for publishing: ${listOf(lookOnly, 4, (w) => `${w.p} is a web reference kept to look at only (${w.why})`)}, so the model stays on this machine. Model what it shows, or texture it from a CC0 or public-domain picture, and export again`
|
|
598
|
+
: ''
|
|
599
|
+
return `${outRel} recorded in ${mod.LEDGER ?? 'assets.lock.json'} (made${from}, ${license.spdx})${loose}${held}`
|
|
600
|
+
} catch (err) {
|
|
601
|
+
log?.(`nw_blender: recording ${outRel} failed: ${err?.message ?? err}`)
|
|
602
|
+
return `not recorded: ${String(err?.message ?? err).split('\n')[0].slice(0, 200)}`
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
/** The class and expected size to score against: the call's, else a prop with no size to check. */
|
|
607
|
+
export function scoringFor(args, classes = ASSET_CLASSES) {
|
|
608
|
+
const klass = classes.includes(args?.class) ? args.class : 'prop'
|
|
609
|
+
const given = args?.expect && typeof args.expect === 'object' ? args.expect : null
|
|
610
|
+
const expect = given ? Object.fromEntries(['height', 'width', 'depth'].filter((k) => Number(given[k]) > 0).map((k) => [k, Number(given[k])])) : null
|
|
611
|
+
return { klass, expect: expect && Object.keys(expect).length ? expect : null }
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
// ---------------------------------------------------------------- the tool
|
|
615
|
+
|
|
616
|
+
const fail = (text) => ({ text, isError: true })
|
|
617
|
+
const STOPPED = 'The request was stopped, so Blender was stopped too.'
|
|
618
|
+
|
|
619
|
+
async function blender(input, ctx, { find, run, ledger }) {
|
|
620
|
+
const parsed = z.object(SHAPE).safeParse(input ?? {})
|
|
621
|
+
if (!parsed.success) {
|
|
622
|
+
return fail(`nw_blender: ${parsed.error.issues.map((i) => `${i.path.join('.') || 'input'}: ${i.message}`).join('; ')}`)
|
|
623
|
+
}
|
|
624
|
+
const args = parsed.data
|
|
625
|
+
if (!ctx?.projectRoot) return fail('No project is open, so there is nowhere to export to.')
|
|
626
|
+
const paths = checkPaths(args, ctx.projectRoot)
|
|
627
|
+
if (paths.error) return fail(paths.error)
|
|
628
|
+
|
|
629
|
+
const found = await find()
|
|
630
|
+
if (found.error) return fail(found.error)
|
|
631
|
+
|
|
632
|
+
const scratch = ctx.runDir && existsSync(ctx.runDir) ? ctx.runDir : os.tmpdir()
|
|
633
|
+
const work = mkdtempSync(path.join(scratch, 'blender-'))
|
|
634
|
+
const timeoutMs = args.timeoutSec * 1000
|
|
635
|
+
try {
|
|
636
|
+
const exportArgs = {
|
|
637
|
+
project: paths.root,
|
|
638
|
+
script: paths.script.abs,
|
|
639
|
+
out_tmp: path.join(work, 'export.glb'),
|
|
640
|
+
collection: args.collection ?? null,
|
|
641
|
+
blend: paths.blend?.abs ?? null,
|
|
642
|
+
result: path.join(work, 'export-result.json'),
|
|
643
|
+
}
|
|
644
|
+
const exported = await run({ bin: found.path, script: RUNNER, args: exportArgs, cwd: work, timeoutMs })
|
|
645
|
+
if (exported.stopped) return fail(STOPPED)
|
|
646
|
+
const problem = exportFailure(exported, { bin: found.path, script: paths.script.rel, timeoutSec: args.timeoutSec, root: paths.root })
|
|
647
|
+
if (problem) {
|
|
648
|
+
ctx.log?.(`nw_blender: ${paths.script.rel} failed in ${seconds(exported.ms)}`)
|
|
649
|
+
return fail(problem)
|
|
650
|
+
}
|
|
651
|
+
let bytes
|
|
652
|
+
try {
|
|
653
|
+
bytes = place(exportArgs.out_tmp, paths.out.abs)
|
|
654
|
+
} catch (err) {
|
|
655
|
+
return fail(`The export worked but ${paths.out.rel} could not be written: ${err.message}`)
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
const { triangles: budgetsOf } = await budgets()
|
|
659
|
+
const { klass, expect } = scoringFor(args)
|
|
660
|
+
const renders = args.render ? renderDir(paths.root, paths.out.rel) : null
|
|
661
|
+
const sheetArgs = {
|
|
662
|
+
glb: paths.out.abs,
|
|
663
|
+
out_dir: renders?.dir ?? path.join(work, 'sheet'),
|
|
664
|
+
size: args.size,
|
|
665
|
+
closeup: args.closeup ?? null,
|
|
666
|
+
render: args.render,
|
|
667
|
+
engines: null,
|
|
668
|
+
result: path.join(work, 'sheet-result.json'),
|
|
669
|
+
class: klass,
|
|
670
|
+
expect,
|
|
671
|
+
budget: budgetsOf[klass] ?? FALLBACK_BUDGETS[klass] ?? FALLBACK_BUDGETS.prop,
|
|
672
|
+
}
|
|
673
|
+
let sheetRun = await run({ bin: found.path, script: SHEET, args: sheetArgs, cwd: work, timeoutMs })
|
|
674
|
+
// A GPU engine can take Blender down with it where there is no GPU to
|
|
675
|
+
// render on (a remote session, some Linux machines); Cycles on the CPU
|
|
676
|
+
// always works, slowly. A Blender the creator's Stop killed is no crash.
|
|
677
|
+
if (args.render && !sheetRun.result && !sheetRun.timedOut && !sheetRun.error && !sheetRun.stopped) {
|
|
678
|
+
ctx.log?.('nw_blender: the sheet run crashed; trying again with Cycles on the CPU')
|
|
679
|
+
sheetRun = await run({ bin: found.path, script: SHEET, args: { ...sheetArgs, engines: ['CYCLES'] }, cwd: work, timeoutMs })
|
|
680
|
+
}
|
|
681
|
+
if (sheetRun.stopped) {
|
|
682
|
+
if (renders) rmSync(renders.dir, { recursive: true, force: true })
|
|
683
|
+
return fail(`${STOPPED} The GLB was exported to ${paths.out.rel}; its contact sheets were not rendered.`)
|
|
684
|
+
}
|
|
685
|
+
const sheet = sheetRun.result?.ok ? sheetRun.result : null
|
|
686
|
+
if (renders && !sheet?.sheets) rmSync(renders.dir, { recursive: true, force: true })
|
|
687
|
+
if (renders) prune(renders.base, renders.dir)
|
|
688
|
+
let sheetError = null
|
|
689
|
+
if (!sheet) {
|
|
690
|
+
sheetError = sheetRun.timedOut
|
|
691
|
+
? `the render run did not finish within ${args.timeoutSec} s and was stopped (try a smaller size or raise timeoutSec)`
|
|
692
|
+
: sheetRun.result?.error ?? `Blender stopped without an answer (exit code ${sheetRun.code ?? sheetRun.signal}): ${blenderOutput(sheetRun, paths.root, 6)}`
|
|
693
|
+
}
|
|
694
|
+
const warnings = [...(exported.result.warnings ?? []), ...(sheetRun.result?.warnings ?? []), ...outputWarnings(exported.stdout, exported.stderr, sheetRun.stdout, sheetRun.stderr)]
|
|
695
|
+
// Which round this is, second in the answer so it is read; the ledger
|
|
696
|
+
// step names it too.
|
|
697
|
+
const at = noteRound(paths.root, paths.script.rel, paths.script.abs, paths.out.rel)
|
|
698
|
+
const ledgerText = await recordExport({
|
|
699
|
+
ledger, root: paths.root, outRel: paths.out.rel, script: paths.script.rel, round: at.round,
|
|
700
|
+
exported: exported.result, sheet, klass, log: ctx.log,
|
|
701
|
+
})
|
|
702
|
+
const text = describeRun({
|
|
703
|
+
script: paths.script.rel,
|
|
704
|
+
out: paths.out.rel,
|
|
705
|
+
bytes,
|
|
706
|
+
exportMs: exported.ms,
|
|
707
|
+
sheetMs: sheetRun.ms,
|
|
708
|
+
blender: sheetRun.result?.blender ?? found.version,
|
|
709
|
+
exported: exported.result,
|
|
710
|
+
sheet,
|
|
711
|
+
sheetError,
|
|
712
|
+
render: args.render,
|
|
713
|
+
renders: renders ? slash(path.relative(paths.root, renders.dir)) : null,
|
|
714
|
+
blend: paths.blend && !warnings.some((w) => w.startsWith('the .blend was not saved')) ? paths.blend.rel : null,
|
|
715
|
+
warnings: [...new Set(warnings.map((w) => shorten(w, paths.root)))],
|
|
716
|
+
rule: await autoSize(),
|
|
717
|
+
klass,
|
|
718
|
+
budget: sheetArgs.budget,
|
|
719
|
+
ledger: ledgerText,
|
|
720
|
+
})
|
|
721
|
+
const round = roundLine(at, paths.script.rel)
|
|
722
|
+
const answer = text.split('\n')
|
|
723
|
+
answer.splice(1, 0, round)
|
|
724
|
+
const images = []
|
|
725
|
+
if (sheet?.sheets) {
|
|
726
|
+
for (const file of [sheet.sheets.color_model ?? sheet.sheets.color, sheet.sheets.clay_model ?? sheet.sheets.clay]) {
|
|
727
|
+
try {
|
|
728
|
+
images.push({ data: readFileSync(file).toString('base64'), mime: 'image/jpeg' })
|
|
729
|
+
} catch {
|
|
730
|
+
// the text says where the renders are; a missing sheet is not worth failing over
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
ctx.log?.(`nw_blender: ${paths.script.rel} -> ${paths.out.rel}, export ${seconds(exported.ms)}, sheets ${seconds(sheetRun.ms)}${sheet?.engine ? ` (${sheet.engine})` : ''}`)
|
|
735
|
+
return { text: answer.join('\n'), ...(images.length ? { images } : {}) }
|
|
736
|
+
} catch (err) {
|
|
737
|
+
return fail(`nw_blender failed: ${err.message}`)
|
|
738
|
+
} finally {
|
|
739
|
+
rmSync(work, { recursive: true, force: true })
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
/** The ToolDef, with Blender's search, its runner and the ledger replaceable for checks. */
|
|
744
|
+
export function makeBlenderTool({ find = findBlender, run = runBlender, ledger = loadLedger } = {}) {
|
|
745
|
+
return {
|
|
746
|
+
name: 'nw_blender',
|
|
747
|
+
description: DESCRIPTION,
|
|
748
|
+
shape: SHAPE,
|
|
749
|
+
readOnly: false,
|
|
750
|
+
handler: (args, ctx) => blender(args, ctx, { find, run, ledger }),
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
export const TOOLS = [makeBlenderTool()]
|