Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: prove the Blender adapter on a real 4.2.0 runtime and fix texture repacking (#9390)

[._.]/ Adam Eivy3c2d6c2c46cd
diff --git a/docs/CODE_ANIMATION_PACKAGES.md b/docs/CODE_ANIMATION_PACKAGES.md
index 8082a9c382..6dd37d2039 100644
--- a/docs/CODE_ANIMATION_PACKAGES.md
+++ b/docs/CODE_ANIMATION_PACKAGES.md
@@ -211,8 +211,10 @@ Memory and disk limits are watchdog-enforced, so brief overshoots are possible.
**Create painterly Blender starter** creates a data-only package containing the
original `build_scene(config)` Python source for *Lantern in a Painted Garden*:
-a deterministic pigment atlas, faceted paper forms, a subject animated on twos,
-baked sparks on threes, and a continuously keyed camera. No external assets,
+a deterministic brush-stroke pigment atlas, faceted paper forms, a subject animated on
+twos with anticipation/squash and sparks that lag on threes, a warm lantern light
+against a cool moon-side fill, dark foreground leaves, and a continuously keyed
+perspective camera with shallow focus on the lantern. No external assets,
downloads, add-ons, provider calls or rendering occur on import. The default
format is 10 seconds at 1920 × 1080 / 24 fps, Blender 4.2.0 / Cycles CPU. The
project's authoring provider remains independent from its renderer.
@@ -230,7 +232,8 @@ their children from motion blur; EEVEE disables blur to preserve the holds.
These are transform/cadence checks, not a claim that arbitrary mesh deformation
or semantic visual quality was independently reviewed.
-The baked `.blend` packs original textures. Scene, report, every decoded PNG,
+The baked `.blend` packs original textures (the driver packs each image once; repacking an
+already packed image re-encodes it and corrupts its colour channels). Scene, report, every decoded PNG,
pilot MP4 and final sequence are immutable run artifacts, separate from accepted
source revisions. Missing frames, malformed output, unsupported runtime/engine,
revoked readiness, worker failure and cancellation cannot pass. PNG geometry
@@ -242,29 +245,65 @@ apply throughout; cancellation keeps earlier accepted artifacts. Failed native
workers never fall back to browser rendering or a different engine.
Runtime/format/cadence fixtures test these contracts but do not constitute real
-Blender acceptance. A bounded native run on 2026-10-01 rendered frames 25, 121
-and 217 (seconds 1, 5 and 9) from package
-`e9cb67e74f33291ea444cfa79dc8648120b7359596a95cf4d8b7149a7958febf`
-at 1920 × 1080 / 24 fps in explicit trusted-local mode: Blender 4.2.0,
-Cycles CPU, four samples, seed 17, two threads. It took 68.12 seconds end to
-end (67.42 seconds in the worker), retained 11,883,500 artifact bytes, decoded
-all three PNGs and saved a packed `.blend`. The driver measured all 240
-frames' object/camera transforms; **only three images were rendered**.
-
-Decoded RGBA SHA-256 values:
-
-| Frame | SHA-256 |
-|---|---|
-| 25 | `fe18b712637f3bcb8259a46383ef8058cbe4d59aa70a3a29c9da233f2bbdd930` |
-| 121 | `61a864e4cb370d9dd1e00135c75c8f9271ffb2b24865c876289e988da74c10a6` |
-| 217 | `bfe102954770c5dc0b1a2a145c23f36dbfe466a31a8fa5d52532462babbc2e1c` |
-
-The native stills are a rough, faceted and noisy study, **not polished painterly
-acceptance**. #9390 remains open for the full 10–15 second 1080p/24fps pilot
-and final sequence, repeated sampled-frame comparison, actual EEVEE/GPU
-validation, and visual-quality refinement/review. The measured CPU cost did
-not justify silently starting a long full-sequence run during this bounded
-validation. No synthetic fixture substitutes for those remaining checks.
+Blender acceptance. That is established by
+`scripts/code-animation-blender-acceptance.js`, which drives the production
+`renderBlenderSequence` against an operator-supplied Blender 4.2.0 executable and
+writes an `evidence.json` verdict. It refuses to reuse an output directory, never
+writes machine settings, fingerprints the executable rather than recording its
+path, and `--mode trusted-local` prints the no-containment warning.
+
+```bash
+node scripts/code-animation-blender-acceptance.js --executable <Blender 4.2.0> --out <new dir> \
+ --mode trusted-local --phase pilot|final # full 10 s sequence
+node scripts/code-animation-blender-acceptance.js ... --repeat --times 1,5,9 # repeat sampled frames
+node scripts/code-animation-blender-acceptance.js ... --cancel-after 40 # real cancellation
+node scripts/code-animation-blender-acceptance.js ... --engine BLENDER_EEVEE_NEXT --backend METAL
+```
+
+**Acceptance run, 2026-10-02.** Official Blender 4.2.0 macOS arm64 build (the
+download's SHA-256 matched the published checksum), Apple Silicon host, explicit
+trusted-local mode, bundled starter source SHA-256
+`3e108ac6e3610219dfe8249a8292a499cae1e55db730826296713845c98d3b16`, seed 17, two
+CPU threads, 1920 × 1080 / 24 fps / 10 s. Every run produced all 240 PNGs, a
+packed `.blend`, a complete decode of every frame, and an H.264 MP4 probed at
+exactly 240 frames and 1920 × 1080 / 24 fps.
+
+| Engine / device | Profile | Samples | Wall time | Retained | MP4 SHA-256 |
+|---|---|---|---|---|---|
+| Cycles / CPU | pilot | 4 | 27.1 min | 1.08 GB | `1952dd80…133f3e` |
+| Cycles / CPU | final | 16 | 103 min | 0.88 GB | `963a0e30…f27394` |
+| EEVEE Next / GPU (Metal) | pilot | 4 | 55 s | 0.63 GB | `a3409aef…18ea` |
+| EEVEE Next / GPU (Metal) | final | 16 | 76 s | 0.59 GB | `f93885a3…133c` |
+
+Cycles CPU costs roughly 30× (pilot) to 80× (final) the wall time of EEVEE on this host, so the
+preview/final choice is a real cost decision. The cadence check passed in every
+run: the lantern holds on twos, nine sparks hold on threes, motion blur is off for
+held subjects, and the camera moves on every frame. Reported engine, device and
+backend came from Blender itself, and no engine was substituted.
+
+- **Repeatability.** Two independent renders of seconds 1, 5 and 9 gave
+ byte-identical decoded pixels for Cycles CPU (SHA-256 `59195b0d…ce3b`,
+ `e66853ca…58bd`, `77992468…ec36`) and for EEVEE Next/Metal, on the same
+ executable and host. This does not claim cross-machine or cross-version identity.
+- **Cancellation.** Aborting a Cycles pilot after 40 s terminated the worker
+ (`reason: canceled`, SIGKILL) with an empty process group and no accepted
+ artifacts.
+- **Memory.** A full EEVEE Next pilot peaked near 9.7 GiB resident and was killed
+ by the 8 GiB worker watchdog before the limit was raised for that engine only
+ (16 GiB; Cycles CPU stays on the default). The watchdog still applies.
+- **Missing or unsupported runtime.** The script refuses a missing executable
+ before starting a worker, and the readiness gate refuses an unchecked or
+ mismatched runtime. Contained mode on this macOS host fails closed: the Seatbelt
+ profile cannot start Blender, so nothing is accepted and no mode is substituted.
+- **Malformed output.** Truncated, missing and mismatched output is exercised by
+ the fixtures in `blenderRender.test.js`; the real runtime was not made to emit
+ malformed output.
+
+Not demonstrated: real contained-mode acceptance (Linux bubblewrap, or a macOS
+Blender build the Seatbelt profile can run), a GPU backend other than Metal, and
+cross-machine repeatability. The Cycles pilot was produced by the first revision of
+the acceptance script; the remaining runs used the current one, which calls the same
+`renderBlenderSequence`.
The browser lane does not use this worker. It reuses the HTML-composition
renderer sandbox (`server/services/htmlComposition/browser.js`): an in-memory
diff --git a/scripts/code-animation-blender-acceptance.js b/scripts/code-animation-blender-acceptance.js
new file mode 100644
index 0000000000..f09182490d
--- /dev/null
+++ b/scripts/code-animation-blender-acceptance.js
@@ -0,0 +1,133 @@
+#!/usr/bin/env node
+/** Real runtime acceptance of the bundled starter; no settings/provider/history writes. */
+import { mkdir, readFile, writeFile } from 'node:fs/promises';
+import { createHash } from 'node:crypto';
+import { join, resolve } from 'node:path';
+import { pathToFileURL } from 'node:url';
+import { parseArgs } from 'node:util';
+import { renderBlenderSequence } from '../server/services/codeAnimation/blenderRender.js';
+import { getBlenderStarterPackage } from '../server/services/codeAnimation/blenderStarter.js';
+import { runContainedWorker, runTrustedLocalWorker } from '../server/services/codeAnimation/containedWorker.js';
+import { codeAnimationManifestSchema } from '../server/lib/codeAnimationPackage.js';
+
+const sha = bytes => createHash('sha256').update(bytes).digest('hex');
+
+export function parseAcceptanceArgs(args) {
+ const { values } = parseArgs({ args, options: {
+ executable: { type: 'string' }, out: { type: 'string' }, mode: { type: 'string', default: 'contained' },
+ phase: { type: 'string', default: 'pilot' }, engine: { type: 'string', default: 'CYCLES' }, backend: { type: 'string' }, times: { type: 'string', default: '1,5,9' },
+ repeat: { type: 'boolean', default: false }, 'cancel-after': { type: 'string' },
+ size: { type: 'string', default: '1920x1080' }, seconds: { type: 'string', default: '10' },
+ } });
+ if (!values.executable || !values.out || !['contained', 'trusted-local'].includes(values.mode)
+ || !['pilot', 'final', 'style'].includes(values.phase) || !['CYCLES', 'BLENDER_EEVEE_NEXT'].includes(values.engine)
+ || (values.engine === 'CYCLES' ? values.backend !== undefined : !['METAL', 'OPENGL', 'VULKAN'].includes(values.backend)) || !/^\d+x\d+$/.test(values.size)) {
+ throw new Error('Usage: --executable <Blender 4.2.0> --out <new directory> [--mode contained|trusted-local] [--phase pilot|final|style] [--engine CYCLES|BLENDER_EEVEE_NEXT --backend METAL|OPENGL|VULKAN]');
+ }
+ const [width, height] = values.size.split('x').map(Number);
+ const format = codeAnimationManifestSchema.shape.format.parse({ width, height, fps: 24, durationSeconds: Number(values.seconds) });
+ const count = format.durationSeconds * format.fps;
+ const times = values.times.split(',').map(value => value.trim() ? Number(value) : NaN);
+ const cancelAfter = values['cancel-after'] === undefined ? null : Number(values['cancel-after']);
+ if (!Number.isInteger(count) || times.length === 0 || times.some(t => !Number.isFinite(t) || t < 0 || Math.round(t * 24) >= count)
+ || new Set(times.map(t => Math.round(t * 24))).size !== times.length
+ || (cancelAfter !== null && (!Number.isFinite(cancelAfter) || cancelAfter <= 0)) || (cancelAfter !== null && values.repeat)) {
+ throw new Error('Duration must land on the frame grid; sample times must be distinct in-range frames; cancellation needs positive seconds and cannot combine with --repeat');
+ }
+ return { ...values, format, times, cancelAfter };
+}
+
+/** Injectable renderer lets tests pin false-success verdicts, not simulate native acceptance. */
+export async function runAcceptance(options, { render = renderBlenderSequence } = {}) {
+ const out = resolve(options.out);
+ // Refuse reuse so an earlier run cannot masquerade as current evidence.
+ await mkdir(out, { recursive: false });
+ const pkg = await getBlenderStarterPackage();
+ pkg.manifest.format = options.format;
+ const revision = { manifest: pkg.manifest, files: pkg.files, entryPath: 'scene.py' };
+ const provenance = { binding: 'acceptance-script', version: '4.2.0', engine: options.engine, device: options.engine === 'CYCLES' ? 'CPU' : 'GPU',
+ backend: options.engine === 'CYCLES' ? 'CPU' : options.backend, executionMode: options.mode, contained: options.mode === 'contained' };
+ const nativeWorker = options.mode === 'contained' ? runContainedWorker : runTrustedLocalWorker;
+ const workerRuns = [];
+ const worker = async request => {
+ const result = await nativeWorker({ ...request, workspaceRoot: join(out, 'workers') });
+ workerRuns.push({ status: result.status, reason: result.reason, signal: result.signal,
+ durationMs: result.durationMs, processGroupClear: result.processGroupClear });
+ return result;
+ };
+ const resolveRuntime = async () => ({ executable: resolve(options.executable), worker, provenance });
+ const retained = [];
+ const evidence = { script: 'code-animation-blender-acceptance', startedAt: new Date().toISOString(),
+ mode: options.mode, engine: options.engine, format: options.format, phase: options.phase,
+ sourceHash: sha(pkg.files[0].content), workerRuns, accepted: false };
+ async function run(label, { phase, times = [], captureTimes = [], signal } = {}) {
+ const runDir = join(out, label);
+ await mkdir(runDir);
+ const retain = async (_project, _run, name, bytes) => {
+ const file = name.replace(/^[a-z]+-[0-9a-f-]{36}-/, '');
+ await writeFile(join(runDir, file), bytes, { flag: 'wx' });
+ retained.push({ label, file, bytes: bytes.length });
+ return { relativePath: join('acceptance', label, file), bytes: bytes.length, sha256: sha(bytes) };
+ };
+ const started = Date.now();
+ const result = await render({ revision, runtime: provenance, projectId: 'acceptance', runId: label, signal,
+ reserve: async () => {}, phase, times, captureTimes, diskBytes: 8 * 1024 ** 3, wallSeconds: 6 * 3600 }, { resolveRuntime, retain });
+ const elapsedMs = Date.now() - started;
+ console.log(`✅ ${label}: ${result.samples.length} sampled frames, ${result.artifacts.length} artifacts in ${(elapsedMs / 1000).toFixed(1)}s`);
+ return { result, elapsedMs };
+ }
+ try {
+ // Fingerprint bytes, never publish a machine-local executable path.
+ evidence.executableHash = sha(await readFile(options.executable));
+ await writeFile(join(out, 'scene.py'), pkg.files[0].content, { flag: 'wx' });
+ await writeFile(join(out, 'manifest.json'), JSON.stringify(pkg.manifest, null, 2), { flag: 'wx' });
+ if (options.cancelAfter !== null) {
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), options.cancelAfter * 1000);
+ const started = Date.now();
+ let error;
+ try { await run('cancel', { phase: options.phase, signal: controller.signal }); } catch (failure) { error = failure; }
+ finally { clearTimeout(timer); }
+ evidence.cancel = { aborted: controller.signal.aborted, rejected: Boolean(error), abortError: error?.name === 'AbortError',
+ afterMs: Date.now() - started, artifactsRetainedAfterCancel: retained.filter(item => item.label === 'cancel').length };
+ evidence.accepted = evidence.cancel.aborted && evidence.cancel.abortError && evidence.cancel.artifactsRetainedAfterCancel === 0
+ && workerRuns.length === 1 && workerRuns[0].processGroupClear === true && workerRuns[0].reason === 'canceled';
+ } else if (options.repeat) {
+ const first = await run('sample-a', { phase: 'style', times: options.times, captureTimes: options.times });
+ const second = await run('sample-b', { phase: 'style', times: options.times, captureTimes: options.times });
+ const pairs = first.result.samples.map((sample, index) => ({ t: sample.t, a: sample.renderHash, b: second.result.samples[index]?.renderHash,
+ identical: sample.t === second.result.samples[index]?.t && sample.renderHash === second.result.samples[index]?.renderHash }));
+ evidence.repeat = { samples: pairs, allIdentical: pairs.length === options.times.length
+ && second.result.samples.length === pairs.length && pairs.every(pair => pair.identical),
+ elapsedMs: [first.elapsedMs, second.elapsedMs], renderer: first.result.renderer };
+ evidence.accepted = evidence.repeat.allIdentical;
+ } else {
+ const { result, elapsedMs } = await run(options.phase, { phase: options.phase,
+ times: options.phase === 'style' ? options.times : [], captureTimes: options.phase === 'style' ? options.times : [] });
+ evidence.sequence = { elapsedMs, contract: result.contract, geometry: result.sequence?.geometry ?? null,
+ video: result.sequence?.artifact ? { file: 'sequence.mp4', bytes: result.sequence.artifact.bytes, sha256: result.sequence.artifact.sha256 } : null,
+ renderer: result.renderer, frameHashes: result.samples.map(sample => ({ t: sample.t, sha256: sample.renderHash })) };
+ evidence.accepted = options.phase === 'style' ? result.samples.length === options.times.length : Boolean(result.sequence);
+ }
+ } catch (error) {
+ // Detailed exceptions can contain private paths; retain only bounded failure identity.
+ evidence.error = { name: error.name, code: error.code ?? null };
+ }
+ evidence.retainedBytes = retained.reduce((sum, item) => sum + item.bytes, 0);
+ evidence.finishedAt = new Date().toISOString();
+ await writeFile(join(out, 'evidence.json'), JSON.stringify(evidence, null, 2), { flag: 'wx' });
+ console.log(`${evidence.accepted ? '✅' : '❌'} Acceptance ${evidence.accepted ? 'passed' : 'failed'}; evidence.json written`);
+ return evidence;
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
+ try {
+ const options = parseAcceptanceArgs(process.argv.slice(2));
+ if (options.mode === 'trusted-local') console.log('⚠️ Explicit trusted-local acceptance: bundled scene code has host filesystem/network access; no containment.');
+ const evidence = await runAcceptance(options);
+ process.exitCode = evidence.accepted ? 0 : 1;
+ } catch (error) {
+ console.error(`❌ Acceptance refused (${error.code || error.name})`);
+ process.exitCode = 2;
+ }
+}
diff --git a/scripts/code-animation-blender-acceptance.test.js b/scripts/code-animation-blender-acceptance.test.js
new file mode 100644
index 0000000000..010a2fe6dc
--- /dev/null
+++ b/scripts/code-animation-blender-acceptance.test.js
@@ -0,0 +1,52 @@
+/** CLI verdict regressions; these fixtures are never real-renderer evidence. */
+import { afterAll, describe, expect, it, vi } from 'vitest';
+import { mkdtemp, readFile, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { parseAcceptanceArgs, runAcceptance } from './code-animation-blender-acceptance.js';
+
+const roots = [];
+afterAll(async () => { await Promise.all(roots.map(root => rm(root, { recursive: true, force: true }))); });
+async function options(extra = []) {
+ const root = await mkdtemp(join(tmpdir(), 'blender-acceptance-test-'));
+ roots.push(root);
+ return parseAcceptanceArgs(['--executable', process.execPath, '--out', join(root, 'run'), ...extra]);
+}
+const sample = hash => ({ samples: [{ t: 1, renderHash: hash }], artifacts: [], renderer: {} });
+
+describe('standalone Blender acceptance verdicts', () => {
+ it('refuses invalid formats/times and conflicting modes before creating output or starting a worker', () => {
+ const args = ['--executable', '/example/Blender', '--out', '/example/out'];
+ for (const extra of [['--seconds', 'NaN'], ['--times', ''], ['--times', '1,1.001'], ['--times', '10'],
+ ['--size', '63x64'], ['--phase', 'unknown'], ['--cancel-after', '0'], ['--cancel-after', '1', '--repeat'],
+ ['--engine', 'BLENDER_EEVEE_NEXT'], ['--backend', 'METAL'], ['--engine', 'BLENDER_EEVEE_NEXT', '--backend', 'CPU']]) {
+ expect(() => parseAcceptanceArgs([...args, ...extra])).toThrow();
+ }
+ expect(parseAcceptanceArgs(args).mode).toBe('contained');
+ expect(parseAcceptanceArgs([...args, '--engine', 'BLENDER_EEVEE_NEXT', '--backend', 'METAL']).backend).toBe('METAL');
+ });
+ it('writes a failed verdict for unequal repeated frames and refuses stale output reuse', async () => {
+ const config = await options(['--repeat', '--times', '1']);
+ const render = vi.fn().mockResolvedValueOnce(sample('first')).mockResolvedValueOnce(sample('different'));
+ const evidence = await runAcceptance(config, { render });
+ expect(evidence).toMatchObject({ accepted: false, repeat: { allIdentical: false } });
+ expect(JSON.parse(await readFile(join(config.out, 'evidence.json'), 'utf8')).accepted).toBe(false);
+ await expect(runAcceptance(config, { render })).rejects.toMatchObject({ code: 'EEXIST' });
+ expect(render).toHaveBeenCalledTimes(2);
+ });
+ it('does not mistake an unrelated error after abort for proved cancellation/process cleanup', async () => {
+ const config = await options(['--cancel-after', '0.001']);
+ const render = ({ signal }) => new Promise((_, reject) => {
+ signal.addEventListener('abort', () => reject(new Error('unrelated failure')), { once: true });
+ });
+ expect(await runAcceptance(config, { render })).toMatchObject({ accepted: false,
+ cancel: { aborted: true, rejected: true, abortError: false } });
+ });
+ it('preserves bounded failure evidence when the executable is missing without claiming renderer acceptance', async () => {
+ const config = await options();
+ config.executable = join(config.out, 'missing-Blender');
+ const render = vi.fn();
+ expect(await runAcceptance(config, { render })).toMatchObject({ accepted: false, error: { code: 'ENOENT' }, workerRuns: [] });
+ expect(render).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/codeAnimation/blenderDriver.js b/server/services/codeAnimation/blenderDriver.js
index 7108437139..bb69990a26 100644
--- a/server/services/codeAnimation/blenderDriver.js
+++ b/server/services/codeAnimation/blenderDriver.js
@@ -78,8 +78,9 @@ for obj in subjects:
if any(a == b for a, b in zip(camera_transforms, camera_transforms[1:])):
raise RuntimeError('Camera movement is not continuous across the sequence')
# Pack original textures into the immutable scene artifact; no live caches.
+# Repacking an already packed image re-encodes it and corrupts its colour channels.
for image in bpy.data.images:
- if image.source in ('FILE', 'GENERATED') and image.has_data:
+ if image.source in ('FILE', 'GENERATED') and image.has_data and not image.packed_file:
image.pack()
bpy.ops.wm.save_as_mainfile(filepath=os.path.join(out, 'scene.blend'))
for frame in config['frames']:
diff --git a/server/services/codeAnimation/blenderRender.js b/server/services/codeAnimation/blenderRender.js
index 1f14e2b165..b2011ae5ea 100644
--- a/server/services/codeAnimation/blenderRender.js
+++ b/server/services/codeAnimation/blenderRender.js
@@ -14,6 +14,9 @@ import { BLENDER_DRIVER } from './blenderDriver.js';
const fail = message => new ServerError(message, { status: 422, code: 'CODE_ANIMATION_BLENDER_RENDER_FAILED' });
const hash = bytes => createHash('sha256').update(bytes).digest('hex');
+// A measured full 1080p EEVEE Next/Metal pilot peaked near 9.7 GiB resident, over the 8 GiB worker default
+// (CPU Cycles stays under it), so only the GPU engine gets headroom; the watchdog still applies.
+const GPU_ENGINE_LIMITS = { BLENDER_EEVEE_NEXT: { memoryBytes: 16 * 1024 ** 3 } };
const frameName = frame => `frame-${String(frame).padStart(6, '0')}.png`;
/** Validate every image and persist the baked scene, report and real sequence. */
@@ -48,7 +51,7 @@ export async function renderBlenderSequence({ revision, runtime, projectId, runI
tool: { executable: checked.executable, argv: entry => ['--background', '--factory-startup', '--disable-autoexec', '--threads', '2', '--python-exit-code', '1', '--python', entry] },
workspaceRoot: join(PATHS.data, 'code-animation-workspaces'), entrypoint: 'portos-driver.py', signal,
files: [...revision.files, { path: 'portos-driver.py', content: BLENDER_DRIVER }, { path: 'portos-render.json', content: JSON.stringify(config) }],
- limits: { wallSeconds: Math.max(1, Math.min(86400, Math.ceil(wallSeconds))), diskBytes: Math.max(1024, diskBytes) },
+ limits: { wallSeconds: Math.max(1, Math.min(86400, Math.ceil(wallSeconds))), diskBytes: Math.max(1024, diskBytes), ...GPU_ENGINE_LIMITS[config.engine] },
onOutput: async (directory, outputs) => {
signal?.throwIfAborted();
const metadata = outputs.find(file => file.path === 'report.json');
diff --git a/server/services/codeAnimation/blenderRender.test.js b/server/services/codeAnimation/blenderRender.test.js
index 131a859504..3216068b8e 100644
--- a/server/services/codeAnimation/blenderRender.test.js
+++ b/server/services/codeAnimation/blenderRender.test.js
@@ -48,6 +48,16 @@ describe('Blender production artifact boundary', () => {
expect(reserve).toHaveBeenCalledTimes(3);
expect(worker.mock.calls[0][0].files.find(file => file.path === 'scene.py').content).toBe(options.revision.files[0].content);
});
+ it('gives only the GPU engine memory headroom over the worker default', async () => {
+ const cycles = await fixture();
+ await renderBlenderSequence(cycles.options, cycles.deps);
+ expect(cycles.worker.mock.calls[0][0].limits).not.toHaveProperty('memoryBytes');
+ const eevee = await fixture({ report: { engine: 'BLENDER_EEVEE_NEXT', device: 'GPU', backend: 'METAL' } });
+ const gpu = { ...provenance, engine: 'BLENDER_EEVEE_NEXT', device: 'GPU', backend: 'METAL' };
+ eevee.deps.resolveRuntime.mockResolvedValue({ executable: '/example/Blender', worker: eevee.worker, provenance: gpu });
+ await renderBlenderSequence({ ...eevee.options, runtime: gpu }, eevee.deps);
+ expect(eevee.worker.mock.calls[0][0].limits.memoryBytes).toBe(16 * 1024 ** 3);
+ });
it.each([
['missing frame', { missing: 'frame-000001.png' }], ['corrupt image', { corrupt: true }],
['wrong runtime', { report: { version: '4.3.0' } }], ['failed worker', { failed: true }],
diff --git a/server/services/codeAnimation/blenderStarter.py b/server/services/codeAnimation/blenderStarter.py
index f10758657f..5a0463ace9 100644
--- a/server/services/codeAnimation/blenderStarter.py
+++ b/server/services/codeAnimation/blenderStarter.py
@@ -7,52 +7,75 @@ import random
from mathutils import Vector
+def brush_atlas(rng, size=256):
+ """Layered, directional bristle strokes painted into a tiling grey pigment map."""
+ pixels = [0.72 + rng.uniform(-.05, .05) for _ in range(size * size)]
+ for _ in range(170):
+ cx, cy = rng.uniform(0, size), rng.uniform(0, size)
+ angle = rng.uniform(-.55, .55) + (math.pi / 2 if rng.random() < .35 else 0)
+ length, width = rng.randint(36, 110), rng.randint(5, 13)
+ dx, dy = math.cos(angle), math.sin(angle)
+ tone = rng.uniform(-.3, .2)
+ for bristle in range(width):
+ offset = bristle - width / 2
+ shade = tone * (.45 + rng.random())
+ for step in range(length):
+ # Strokes thin out toward the end like a lifting brush.
+ weight = .62 * (1 - step / length) ** .6
+ x = int(cx + dx * step - dy * offset) % size
+ y = int(cy + dy * step + dx * offset) % size
+ index = y * size + x
+ pixels[index] += (min(1, max(.25, .78 + shade)) - pixels[index]) * weight
+ out = []
+ for value in pixels:
+ out.extend((value, value, value, 1))
+ return out
+
+
def build_scene(config):
rng = random.Random(config['seed'])
scene = bpy.context.scene
if scene.world is None:
scene.world = bpy.data.worlds.new('Painted night')
- scene.world.color = (0.025, 0.04, 0.09)
+ scene.world.color = (0.008, 0.016, 0.045)
scene.view_settings.view_transform = 'Standard'
- # Original pigment atlas: layered irregular brush marks, packed by driver.
- size = 128
+ size = 256
image = bpy.data.images.new('Original pigment brush atlas', width=size, height=size)
- pixels = []
- for y in range(size):
- for x in range(size):
- pigment = 0.62 + 0.18 * math.sin(x * .19 + math.sin(y * .11) * 3) + rng.uniform(-.13, .13)
- pixels.extend((pigment, pigment, pigment, 1))
- image.pixels = pixels
- image.pack()
+ image.pixels = brush_atlas(rng, size) # the owned driver packs it into the scene artifact
- def material(name, color, glow=0):
+ def material(name, color, glow=0, tiling=3.0):
mat = bpy.data.materials.new(name)
mat.diffuse_color = (*color, 1)
mat.use_nodes = True
nodes = mat.node_tree.nodes
+ links = mat.node_tree.links
bsdf = nodes.get('Principled BSDF')
tex = nodes.new('ShaderNodeTexImage')
tex.image = image
tex.projection = 'BOX'
tex.projection_blend = .25
coordinate = nodes.new('ShaderNodeTexCoord')
- mat.node_tree.links.new(coordinate.outputs['Generated'], tex.inputs['Vector'])
+ mapping = nodes.new('ShaderNodeMapping')
+ mapping.inputs['Scale'].default_value = (tiling, tiling, tiling)
+ links.new(coordinate.outputs['Generated'], mapping.inputs['Vector'])
+ links.new(mapping.outputs['Vector'], tex.inputs['Vector'])
mix = nodes.new('ShaderNodeMixRGB')
mix.blend_type = 'MULTIPLY'
- mix.inputs[0].default_value = .75
+ mix.inputs[0].default_value = .9
mix.inputs[1].default_value = (*color, 1)
- mat.node_tree.links.new(tex.outputs['Color'], mix.inputs[2])
- mat.node_tree.links.new(mix.outputs[0], bsdf.inputs['Base Color'])
- bsdf.inputs['Roughness'].default_value = .92
- bsdf.inputs['Emission Color'].default_value = (*color, 1)
+ links.new(tex.outputs['Color'], mix.inputs[2])
+ links.new(mix.outputs[0], bsdf.inputs['Base Color'])
+ bsdf.inputs['Roughness'].default_value = .95
+ links.new(mix.outputs[0], bsdf.inputs['Emission Color'])
bsdf.inputs['Emission Strength'].default_value = glow
return mat
- indigo = material('Ultramarine pigment', (.055, .09, .22), .25)
- teal = material('Viridian pigment', (.05, .32, .33), .25)
- coral = material('Vermilion paper', (.95, .25, .12), .3)
- gold = material('Warm lantern light', (1, .63, .2), 1.4)
- cream = material('Ivory dry brush', (.94, .83, .59), .3)
+ indigo = material('Ultramarine pigment', (.07, .11, .3), .05, 2.0)
+ teal = material('Viridian pigment', (.06, .38, .4), .04)
+ deep = material('Prussian shadow', (.015, .03, .08), .0, 2.0)
+ coral = material('Vermilion paper', (1, .24, .1), .3, 2.0)
+ gold = material('Warm lantern light', (1, .68, .22), 1.5, 2.0)
+ cream = material('Ivory dry brush', (.98, .84, .52), .6, 2.0)
def sphere(name, location, scale, mat, subdivisions=1):
bpy.ops.mesh.primitive_ico_sphere_add(subdivisions=subdivisions, radius=1, location=location)
@@ -72,32 +95,60 @@ def build_scene(config):
for i in range(48):
sphere('Dry brush star %02d' % i, (rng.uniform(-9, 9), 3.7, rng.uniform(1, 7)),
(.025, .018, .06), cream)
+ # Dark foreground leaves frame the subject and push value contrast toward it.
+ for side in (-1, 1):
+ for i in range(3):
+ sphere('Foreground shadow leaf %d%d' % (side > 0, i), (side * (4.6 + i * .9), -4, -.4 + i * .5),
+ (.7 + i * .15, .2, 2.6 - i * .35), deep, 1)
+
lantern = sphere('Lantern - animation on twos', (0, 0, 1), (.7, .55, 1), coral, 2)
lantern['portos_cadence'] = 2
heart = sphere('Lantern glow', (0, -.47, 1), (.4, .12, .55), gold, 2)
# Parent glow follows the exact baked subject keys without another track.
heart.parent = lantern
heart.location = (0, -.7, 0)
+ # A real warm light rides with the lantern, so the garden answers its motion.
+ bpy.ops.object.light_add(type='POINT', location=(0, 0, 0))
+ glow = bpy.context.object
+ glow.name = 'Lantern light'
+ glow.data.color = (1, .62, .2)
+ glow.data.energy = 420
+ glow.data.shadow_soft_size = .35
+ glow.parent = lantern
+ glow.location = (0, -1.4, .2)
sparks = []
for i in range(9):
- obj = sphere('Baked brush spark %02d' % i, (0, 0, 0), (.045, .035, .12), gold)
+ obj = sphere('Baked brush spark %02d' % i, (0, 0, 0), (.05, .035, .16), gold)
obj['portos_cadence'] = 3
sparks.append(obj)
count = config['frameCount']
fps = config['fps']
for frame in range(1, count + 1, 2):
t = (frame - 1) / fps
- lantern.location = (-3.5 + 7 * t / (count / fps), 0, 1.6 + .45 * math.sin(t * 1.2))
- lantern.rotation_euler = (.04 * math.sin(t), .13 * math.sin(t * 1.7), .1 * math.sin(t * .8))
+ run = t / (count / fps)
+ # Anticipation: draw back and squash before travelling, then overshoot and settle.
+ wind = min(1, t / .9)
+ pull = -.32 * math.sin(math.pi * wind)
+ squash = .14 * math.sin(math.pi * wind)
+ stretch = .1 * max(0, math.sin(math.pi * min(1, max(0, (t - .9) / .7))))
+ lantern.location = (-3.5 + 7 * run + pull, 0, 1.6 + .45 * math.sin(t * 1.2) - squash * .8)
+ lantern.rotation_euler = (.04 * math.sin(t), .13 * math.sin(t * 1.7) + .1 * pull, .1 * math.sin(t * .8))
+ lantern.scale = (.7 * (1 + squash - stretch * .4), .55 * (1 + squash), 1 * (1 - squash + stretch))
lantern.keyframe_insert('location', frame=frame)
lantern.keyframe_insert('rotation_euler', frame=frame)
+ lantern.keyframe_insert('scale', frame=frame)
for i, obj in enumerate(sparks):
for frame in range(1, count + 1, 3):
t = (frame - 1) / fps
- obj.location = (-3.5 + 7 * t / (count / fps) - .2 * i, -.2, .8 + (t * .45 + i * .27) % 2)
- obj.rotation_euler = (0, .35 * math.sin(t + i), 0)
+ # Sparks lag behind the lantern and flicker outward: overlapping action.
+ lag = .22 * i + .18
+ obj.location = (-3.5 + 7 * max(0, t - lag * .35) / (count / fps) - .2 * i, -.2, .8 + (t * .45 + i * .27) % 2)
+ obj.rotation_euler = (0, .35 * math.sin(t + i), .5 * math.sin(t * 2 + i))
+ s = .6 + .8 * abs(math.sin(t * 3 + i * .9))
+ obj.scale = (.05 * s, .035 * s, .16 * s)
obj.keyframe_insert('location', frame=frame)
obj.keyframe_insert('rotation_euler', frame=frame)
+ obj.keyframe_insert('scale', frame=frame)
for obj in [lantern, *sparks]:
for curve in obj.animation_data.action.fcurves:
for point in curve.keyframe_points:
@@ -105,8 +156,12 @@ def build_scene(config):
bpy.ops.object.camera_add(location=(0, -18, 5))
camera = bpy.context.object
camera.name = 'Smooth camera - continuous track'
- camera.data.type = 'ORTHO'
- camera.data.ortho_scale = 12
+ camera.data.type = 'PERSP'
+ camera.data.lens = 54
+ # Shallow focus on the lantern softens both the far garden and the foreground leaves.
+ camera.data.dof.use_dof = True
+ camera.data.dof.focus_object = lantern
+ camera.data.dof.aperture_fstop = 5.6
scene.camera = camera
for frame in (1, count):
camera.location = (-.45 + .9 * (frame - 1) / max(1, count - 1), -18, 4.3)
@@ -116,6 +171,11 @@ def build_scene(config):
for curve in camera.animation_data.action.fcurves:
for point in curve.keyframe_points:
point.interpolation = 'LINEAR'
- bpy.ops.object.light_add(type='AREA', location=(-3, -5, 8))
- bpy.context.object.data.energy = 900
- bpy.context.object.data.size = 8
+ # Cool moon-side fill against the warm lantern: the colour contrast carries the mood.
+ bpy.ops.object.light_add(type='AREA', location=(6, -6, 9))
+ fill = bpy.context.object
+ fill.name = 'Cool moon fill'
+ fill.data.color = (.45, .72, .85)
+ fill.data.energy = 320
+ fill.data.size = 9
+ fill.rotation_euler = (Vector((0, 0, 1)) - fill.location).to_track_quat('-Z', 'Y').to_euler()