Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add a persistent Cycles render session to the native tracer (#896)

Nguyen Xuan Ane260ccff0d7d
diff --git a/bench/cycles-parity/session-timing.mjs b/bench/cycles-parity/session-timing.mjs
new file mode 100644
index 00000000..81ad4d41
--- /dev/null
+++ b/bench/cycles-parity/session-timing.mjs
@@ -0,0 +1,75 @@
+// Times two frames of a persistent native session on an exported scene: a cold frame (shader compile, upload and
+// acceleration structure build) against a warm frame (a second camera of the same scene), and the one-shot render of each
+// camera for comparison. Prints one SESSION_TIMING line of JSON with the phase seconds, the reuse flags and the SHA-256
+// of every float plane, so a run on another build (one without sessions) can be compared byte for byte.
+// node bench/cycles-parity/session-timing.mjs <sceneJsonPath> [--samples 64] [--width 480] [--height 270] [--seed 1]
+import { createHash } from 'node:crypto';
+import { readFile } from 'node:fs/promises';
+import { resolve } from 'node:path';
+import { createCamera } from '../../src/path-tracer.js';
+import * as packModule from '../../src/path-tracer-gpu-pack.js';
+import * as renderNative from '../../packages/render-native/index.mjs';
+import { buildTraceSceneWithManyLights } from './trace-scene-many-lights.mjs';
+import { reconstructTraceSceneSource } from './scene-bridge.mjs';
+
+const CAMERA_SHIFT = [0.25, 0.1, 0];
+const PHASE_NAMES = ['setupSeconds', 'compileSeconds', 'uploadSeconds', 'accelerationBuildSeconds', 'tracedSeconds'];
+
+function readNumberFlag(argumentList, flagName, fallbackValue) {
+ const flagIndex = argumentList.indexOf(flagName);
+ return flagIndex === -1 ? fallbackValue : Number(argumentList[flagIndex + 1]);
+}
+
+function sha256Of(values) {
+ return createHash('sha256').update(Buffer.from(values.buffer, values.byteOffset, values.byteLength)).digest('hex');
+}
+
+function summarize(result) {
+ const summary = { rgbaSha256: sha256Of(result.rgba), depthSha256: sha256Of(result.depth), adapter: result.adapter };
+ for (const phaseName of PHASE_NAMES) {
+ summary[phaseName] = Number(result[phaseName].toFixed(6));
+ }
+ for (const flagName of ['pipelineReused', 'accelerationReused', 'filmReused', 'frameIndex']) {
+ if (result[flagName] !== undefined) summary[flagName] = result[flagName];
+ }
+ return summary;
+}
+
+async function run() {
+ const argumentList = process.argv.slice(2);
+ const width = readNumberFlag(argumentList, '--width', 480);
+ const height = readNumberFlag(argumentList, '--height', 270);
+ const samples = readNumberFlag(argumentList, '--samples', 64);
+ const seed = readNumberFlag(argumentList, '--seed', 1);
+ const description = JSON.parse(await readFile(resolve(argumentList[0]), 'utf8'));
+ const traceSource = await reconstructTraceSceneSource(description);
+ const traceScene = buildTraceSceneWithManyLights(traceSource.parts, traceSource.environment);
+ const renderOptions = { width, height, samples, bounces: 8, seed };
+ const packOptions = { ...renderOptions, parts: traceSource.parts };
+ const cameraA = traceSource.camera;
+ const cameraB = { ...cameraA, eye: cameraA.eye.map((value, axis) => value + CAMERA_SHIFT[axis]) };
+ const inputOf = (camera) => renderNative.buildNativeInputV2(traceScene, createCamera(camera, width, height), packOptions, packModule);
+ const inputA = inputOf(cameraA);
+ const inputB = inputOf(cameraB);
+ const traceOptions = { ...renderOptions, kernel: 'cycles' };
+
+ const report = { scene: description.id, width, height, samples, seed };
+ // The session goes first: a one-shot render would leave the compiled pipeline in the process cache and hide the cold compile.
+ if (typeof renderNative.createNativeSession === 'function') {
+ const session = renderNative.createNativeSession(inputA, { kernel: 'cycles' });
+ report.sessionColdA = summarize(session.render(traceOptions));
+ report.sessionWarmB = summarize(session.render({ ...traceOptions, kernelParams: inputB.kernelParams }));
+ report.sessionWarmA = summarize(session.render(traceOptions));
+ session.close();
+ }
+ report.oneShotA = summarize(renderNative.traceNative(inputA, traceOptions));
+ report.oneShotB = summarize(renderNative.traceNative(inputB, traceOptions));
+ if (report.sessionColdA) {
+ report.sessionMatchesOneShot = report.sessionColdA.rgbaSha256 === report.oneShotA.rgbaSha256
+ && report.sessionWarmB.rgbaSha256 === report.oneShotB.rgbaSha256
+ && report.sessionWarmA.rgbaSha256 === report.oneShotA.rgbaSha256;
+ }
+ console.log(`SESSION_TIMING ${JSON.stringify(report)}`);
+}
+
+await run();
diff --git a/changes/896-session-core.md b/changes/896-session-core.md
new file mode 100644
index 00000000..6a2ce156
--- /dev/null
+++ b/changes/896-session-core.md
@@ -0,0 +1 @@
+- `createNativeSession` in `@codepawlhq/67js-render-native` keeps a scene on the GPU between Cook frames, so a later frame of the same scene compiles no shader and builds no acceleration structure (#896)
diff --git a/packages/render-native/README.md b/packages/render-native/README.md
index 2b34db14..9e20e2d9 100644
--- a/packages/render-native/README.md
+++ b/packages/render-native/README.md
@@ -47,3 +47,23 @@ Numbers, GPU and method: [docs/cycles-parity.md](../../docs/cycles-parity.md), s
The Cook kernel splits a render into dispatches that each aim for about 0.5 s, sized from the time of the previous one, so a heavy scene does not run past the driver timeout and lose the device. `samplesPerDispatch` fixes the batch instead. A lost device raises an error that names the dispatch and how to lower the work per dispatch. The split is tested in `tests/dispatch.rs` (`cargo test --test dispatch`).
The split does not change the image. The `cycles` kernel carries each pixel's running sums through a dispatch and adds one sample at a time in sample order, so the float32 additions into the film come in the same order whether a dispatch draws 1 sample or 64, and two renders of the same scene, seed and settings are byte-identical even when their time-sized splits differ. The `legacy` kernel draws one sample per dispatch and adds it straight to the film, so it has the same property. `tests/native-dispatch-determinism.test.js` renders with different `samplesPerDispatch` values and compares the bytes. A fixed `samplesPerDispatch` of 1 gives the same bytes as before this change; larger batches now match it instead of adding a per-dispatch partial sum.
+
+## Sessions
+
+`traceNative` builds everything for each call: it opens the device handle, uploads the scene, builds the acceleration structures, compiles the kernel and allocates the film. A session keeps those on the card between frames of one scene (the `cycles` kernel only):
+
+```js
+import { buildNativeInputV2, createNativeSession } from '@codepawlhq/67js-render-native';
+
+const input = buildNativeInputV2(traceScene, camera, options, pack);
+const session = createNativeSession(input, { width: 960, height: 540, samples: 64 });
+const first = session.render({}); // uploads, builds, compiles
+const moved = session.render({ kernelParams: nextCamera.kernelParams, samples: 32 }); // reuses all three
+session.close(); // frees the card
+```
+
+`createNativeSession(input, options)` takes a FORMAT-v2 input (it throws a `TypeError` for anything else and for `kernel: "legacy"`); `options` are defaults for every frame. `render(renderOptions)` takes what `traceNative` takes (`width`, `height`, `samples`, `samplesPerDispatch`, `maxSeconds`, `denoise`, the sampling and filter options) and returns what it returns plus four fields that tell what the frame reused: `pipelineReused` (the compiled kernel was held; the specialized kernel text did not change), `accelerationReused` (no acceleration structure build; true from the second frame on), `filmReused` (same image size, so the film and its bind group were kept; the film is cleared for each frame) and `frameIndex`. A frame that reuses something spends no time on it: the first frame reports the setup, upload and acceleration build seconds of the creation, later frames report `0` for the setup and the build.
+
+`renderOptions.kernelParams` is the `kernelParams` of another `buildNativeInputV2` call on the same scene, which is how a frame gets another camera (or seed, bounces or filter). The seven record counts must match the session scene, or the frame throws and names the count. Changing the scene itself (geometry, materials, lights) needs a new session.
+
+A frame is byte-identical to the `traceNative` render of the same input and options: `traceNative` runs a session that renders once. `render` after `close()` throws, and so does a frame on a session whose device was lost; the error says to create a new session. The film does not carry samples from one frame to the next, and nothing in the scene can be updated in place yet.
diff --git a/packages/render-native/index.mjs b/packages/render-native/index.mjs
index 8b212e9d..64061011 100644
--- a/packages/render-native/index.mjs
+++ b/packages/render-native/index.mjs
@@ -311,3 +311,124 @@ function loadAddon() {
if (!addonPath) throw new Error('The native tracer is not built. Run `npm run build` in packages/render-native.');
return createRequire(import.meta.url)(addonPath);
}
+
+// ---- Persistent session (issue 896) ----
+
+function requireSessionKernelParams(kernelParams, callerName) {
+ if (!(kernelParams instanceof Uint8Array) || kernelParams.byteLength !== STRUCT_STRIDES_V2.kernelParams) {
+ throw new TypeError(
+ `${callerName}: \`kernelParams\` must be a Uint8Array of ${STRUCT_STRIDES_V2.kernelParams} bytes (the KernelParamsV2 block of buildNativeInputV2).`
+ );
+ }
+}
+
+function requireCyclesKernelOption(kernel, callerName) {
+ if (kernel !== undefined && resolveNativeKernel(kernel) !== 'cycles') {
+ throw new TypeError(`${callerName}: a native session runs the "cycles" kernel only; got kernel "${kernel}". Use traceNative for the legacy kernel.`);
+ }
+}
+
+function mergeDefinedOptions(sessionOptions, renderOptions) {
+ const merged = { ...sessionOptions };
+ for (const [name, value] of Object.entries(renderOptions)) {
+ if (value !== undefined) merged[name] = value;
+ }
+ return merged;
+}
+
+// The kernel parameters of a FORMAT-v2 input after the sampling, filter and light options of `options`: the same patches, in the
+// same order, that `traceNative` applies to a v2 input.
+function patchedSessionKernelParams(v2Input, kernelParams, options, callerName) {
+ const { sampler, lightSampling } = resolveSamplingOptions(options, callerName);
+ validatePathRegenerationOption(options.pathRegeneration, callerName);
+ let patchedParams = new Uint8Array(kernelParams);
+ const explicitFilterGlossy = options.filterGlossy ?? options.blurGlossy;
+ if (explicitFilterGlossy !== undefined) {
+ const rawFilterGlossy = Number(explicitFilterGlossy);
+ const resolvedFilterGlossy = Number.isFinite(rawFilterGlossy) && rawFilterGlossy > 0 ? rawFilterGlossy : 0.0;
+ new DataView(patchedParams.buffer, patchedParams.byteOffset, patchedParams.byteLength).setFloat32(KERNEL_PARAMS_V2_FILTER_GLOSSY_BYTE_OFFSET, resolvedFilterGlossy, true);
+ }
+ if (hasFilterOptions(options)) patchedParams = withFilterOptions(patchedParams, options);
+ if (sampler !== undefined) patchedParams = withSamplerFlag(patchedParams, sampler);
+ if (options.pathRegeneration !== undefined) patchedParams = withPathRegenerationFlag(patchedParams, options.pathRegeneration);
+ if (lightSampling !== undefined) patchedParams = withLightSamplingFlag({ ...v2Input, kernelParams: patchedParams }, lightSampling);
+ return patchedParams;
+}
+
+// Exported for tests; not part of the public API.
+export function resolveSessionCreation(input, options) {
+ if (input === null || typeof input !== 'object') {
+ throw new TypeError('createNativeSession: `input` must be a FORMAT-v2 input object from buildNativeInputV2.');
+ }
+ if (input.schemaVersion !== FORMAT_V2_VERSION) {
+ throw new TypeError(
+ `createNativeSession: \`input.schemaVersion\` must be ${FORMAT_V2_VERSION} (a FORMAT-v2 input from buildNativeInputV2); got ${JSON.stringify(input.schemaVersion)}. Convert a v1 input with upgradeNativeInputV1ToV2.`
+ );
+ }
+ requireSessionKernelParams(input.kernelParams, 'createNativeSession');
+ if (options === null || typeof options !== 'object') {
+ throw new TypeError('createNativeSession: `options` must be an object.');
+ }
+ requireCyclesKernelOption(options.kernel, 'createNativeSession');
+ validatePackOptions(options, 'createNativeSession');
+ return { ...input, kernelParams: patchedSessionKernelParams(input, input.kernelParams, options, 'createNativeSession') };
+}
+
+// Exported for tests; not part of the public API.
+export function resolveSessionFrame(sessionInput, sessionOptions, renderOptions) {
+ if (renderOptions === null || typeof renderOptions !== 'object') {
+ throw new TypeError('NativeSession.render: `renderOptions` must be an object.');
+ }
+ const options = mergeDefinedOptions(sessionOptions, renderOptions);
+ requireCyclesKernelOption(options.kernel, 'NativeSession.render');
+ validatePackOptions(options, 'NativeSession.render', true);
+ let baseKernelParams = sessionInput.kernelParams;
+ if (renderOptions.kernelParams !== undefined) {
+ requireSessionKernelParams(renderOptions.kernelParams, 'NativeSession.render');
+ baseKernelParams = renderOptions.kernelParams;
+ }
+ const kernelParams = patchedSessionKernelParams(sessionInput, baseKernelParams, options, 'NativeSession.render');
+ const { width, height, samples, samplesPerDispatch, maxSeconds, bootstrapKernel, denoise } = options;
+ return { width, height, samples, samplesPerDispatch, maxSeconds, bootstrapKernel, denoise, kernelParams };
+}
+
+// Exported for tests, which pass a stand-in for the addon's session class; not part of the public API.
+export function wrapNativeSession(nativeSession, sessionInput, sessionOptions) {
+ let closed = false;
+ return {
+ get closed() {
+ return closed;
+ },
+ render(renderOptions = {}) {
+ if (closed) {
+ throw new Error('NativeSession.render: this session is closed. Create a new one with createNativeSession(input).');
+ }
+ const frame = resolveSessionFrame(sessionInput, sessionOptions, renderOptions);
+ const { trace, session } = nativeSession.render(frame);
+ return { ...trace, ...session };
+ },
+ close() {
+ if (closed) return;
+ closed = true;
+ nativeSession.close();
+ },
+ };
+}
+
+/**
+ * Keeps a FORMAT-v2 scene on the GPU between frames (the `cycles` kernel only). `render(renderOptions)` takes what
+ * `traceNative` takes (`width`, `height`, `samples`, `samplesPerDispatch`, `maxSeconds`, `denoise`, the sampling and filter
+ * options) and returns what it returns plus `pipelineReused`, `accelerationReused`, `filmReused` and `frameIndex`. A later frame
+ * with the same scene compiles no shader (while the specialized kernel text is unchanged) and builds no acceleration structure; a
+ * frame at the same size also keeps the film. `renderOptions.kernelParams` brings another camera of the same scene: the
+ * `kernelParams` of a second `buildNativeInputV2` call. `options` are defaults for every frame. `close()` frees the card.
+ * A frame equals the `traceNative` render of the same input and options byte for byte.
+ */
+export function createNativeSession(input, options = {}) {
+ const sessionInput = resolveSessionCreation(input, options);
+ const addon = loadAddon();
+ if (typeof addon.NativeCyclesSession !== 'function') {
+ throw new Error('The built native addon has no session support. Run `npm run build` in packages/render-native.');
+ }
+ return wrapNativeSession(new addon.NativeCyclesSession(sessionInput), sessionInput, options);
+}
diff --git a/packages/render-native/src/cycles/mod.rs b/packages/render-native/src/cycles/mod.rs
index 3ad73030..0911d905 100644
--- a/packages/render-native/src/cycles/mod.rs
+++ b/packages/render-native/src/cycles/mod.rs
@@ -164,9 +164,39 @@ pub(crate) fn check_counts_match_kernel_params(input: &NativeTraceInputV2) -> Re
Ok(())
}
-/// The compute entry point to run: `main`, or `light_tree_probe` when the input carries `KERNEL_FLAG_LIGHT_TREE_PROBE` (tests).
-pub(crate) fn trace_entry_point(input: &NativeTraceInputV2) -> &'static str {
- let kernel_flags = read_u32_le(&input.kernel_params, KP_KERNEL_FLAGS_BYTE);
+/// Checks that a frame's kernel parameters describe the scene the session holds: the seven record counts must equal the
+/// counts of the parameters the session was created with. Everything else (camera, bounces, seed, filter, flags) may change.
+pub(crate) fn check_frame_params_keep_scene_counts(session_kernel_params: &[u8], frame_kernel_params: &[u8]) -> Result<()> {
+ let counts = [
+ ("instanceCount", KP_INSTANCE_COUNT_BYTE),
+ ("triangleCount", KP_TRIANGLE_COUNT_BYTE),
+ ("materialCount", KP_MATERIAL_COUNT_BYTE),
+ ("emissiveTriangleCount", KP_EMISSIVE_TRIANGLE_COUNT_BYTE),
+ ("lightCount", KP_LIGHT_COUNT_BYTE),
+ ("lightTreeNodeCount", KP_LIGHT_TREE_NODE_COUNT_BYTE),
+ ("textureCount", KP_TEXTURE_COUNT_BYTE),
+ ];
+ for (name, byte_offset) in counts {
+ if session_kernel_params.len() < byte_offset + 4 || frame_kernel_params.len() < byte_offset + 4 {
+ return Err(failure(format!(
+ "kernelParams must hold the 320 byte KernelParamsV2 block to read {name} at byte {byte_offset}."
+ )));
+ }
+ let session_count = read_u32_le(session_kernel_params, byte_offset);
+ let frame_count = read_u32_le(frame_kernel_params, byte_offset);
+ if session_count != frame_count {
+ return Err(failure(format!(
+ "The kernelParams of this frame say {name} is {frame_count}, but the session scene has {session_count}. A session renders one scene; pack the frame from the same scene (only the camera and the render settings may differ) or create a new session."
+ )));
+ }
+ }
+ Ok(())
+}
+
+/// The compute entry point to run for a kernel parameter block: `main`, or `light_tree_probe` when it carries
+/// `KERNEL_FLAG_LIGHT_TREE_PROBE` (tests).
+pub(crate) fn trace_entry_point_for_params(kernel_params: &[u8]) -> &'static str {
+ let kernel_flags = read_u32_le(kernel_params, KP_KERNEL_FLAGS_BYTE);
if (kernel_flags & KERNEL_FLAG_LIGHT_TREE_PROBE) != 0 {
"light_tree_probe"
} else {
@@ -179,24 +209,40 @@ pub(crate) fn trace_entry_point(input: &NativeTraceInputV2) -> &'static str {
/// The sentinel pattern is `true` (conservative default) so the kernel compiles and renders
/// correctly even without specialization; specialization disables dead branches for performance.
///
-/// NOTE: Only replaces in `trace_scene_cycles` / `prepare_cycles_scene`. In `probe_cycles_lobe`
+/// NOTE: Only replaces in `trace_scene_cycles` / `CyclesSession`. In `probe_cycles_lobe`
/// all flags stay `true` (which is the unspecialized default).
+#[cfg(test)]
pub(crate) fn specialize_cycles_kernel(source: &str, input: &NativeTraceInputV2) -> String {
- let kp = &input.kernel_params;
+ specialize_kernel_source(source, &scan_scene_specialization(input), &input.kernel_params)
+}
+
+/// What the scene tables decide about the kernel's `SCENE_HAS_*` constants and lobe bounds. A session scans its scene once
+/// and combines the result with each frame's kernel parameters, so a frame does not walk the tables again.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub(crate) struct SceneSpecialization {
+ has_alpha_mask: bool,
+ has_transparent: bool,
+ has_glass: bool,
+ has_coat: bool,
+ has_sheen: bool,
+ has_anisotropy: bool,
+ has_thin_film: bool,
+ has_f82: bool,
+ has_normal_map: bool,
+ max_closure_lobes: u32,
+ max_closure_candidates: u32,
+ has_finite_lights: bool,
+ has_light_linking: bool,
+ has_emissive_triangles: bool,
+ has_analytic_lights: bool,
+ light_tree_node_count: u32,
+}
+
+/// Walks the materials, lights and instances of an input once.
+pub(crate) fn scan_scene_specialization(input: &NativeTraceInputV2) -> SceneSpecialization {
let mats = &input.materials;
let lights = &input.lights;
let instances = &input.instances;
-
- // --- KernelParamsV2 fields ---
- let kernel_flags = read_u32_le(kp, KP_KERNEL_FLAGS_BYTE);
- let volume_density = read_f32_le(kp, KP_VOLUME_DENSITY_BYTE);
- let env_width = read_u32_le(kp, KP_ENV_WIDTH_BYTE);
- let env_height = read_u32_le(kp, KP_ENV_HEIGHT_BYTE);
- let env_total_weight = read_f32_le(kp, KP_ENV_TOTAL_WEIGHT_BYTE);
-
- let has_volume = (kernel_flags & 2) != 0 && volume_density > 0.0;
- let has_env_importance = env_width > 0 && env_height > 0 && env_total_weight > 0.0;
- let has_light_tree = (kernel_flags & 1) != 0 && input.light_tree_node_count > 0;
let has_emissive_triangles = input.emissive_triangle_count > 0;
let has_analytic_lights = input.light_count > 0;
@@ -340,6 +386,57 @@ pub(crate) fn specialize_cycles_kernel(source: &str, input: &NativeTraceInputV2)
}
}
+ SceneSpecialization {
+ has_alpha_mask,
+ has_transparent,
+ has_glass,
+ has_coat,
+ has_sheen,
+ has_anisotropy,
+ has_thin_film,
+ has_f82,
+ has_normal_map,
+ max_closure_lobes,
+ max_closure_candidates,
+ has_finite_lights,
+ has_light_linking,
+ has_emissive_triangles,
+ has_analytic_lights,
+ light_tree_node_count: input.light_tree_node_count,
+ }
+}
+
+/// Replaces the `SCENE_HAS_*` sentinels of `source` with the scene scan and the frame's kernel parameters
+/// (kernel flags, fog density and environment table size).
+pub(crate) fn specialize_kernel_source(source: &str, scene: &SceneSpecialization, kp: &[u8]) -> String {
+ let kernel_flags = read_u32_le(kp, KP_KERNEL_FLAGS_BYTE);
+ let volume_density = read_f32_le(kp, KP_VOLUME_DENSITY_BYTE);
+ let env_width = read_u32_le(kp, KP_ENV_WIDTH_BYTE);
+ let env_height = read_u32_le(kp, KP_ENV_HEIGHT_BYTE);
+ let env_total_weight = read_f32_le(kp, KP_ENV_TOTAL_WEIGHT_BYTE);
+
+ let has_volume = (kernel_flags & 2) != 0 && volume_density > 0.0;
+ let has_env_importance = env_width > 0 && env_height > 0 && env_total_weight > 0.0;
+ let has_light_tree = (kernel_flags & 1) != 0 && scene.light_tree_node_count > 0;
+ let SceneSpecialization {
+ has_alpha_mask,
+ has_transparent,
+ has_glass,
+ has_coat,
+ has_sheen,
+ has_anisotropy,
+ has_thin_film,
+ has_f82,
+ has_normal_map,
+ max_closure_lobes,
+ max_closure_candidates,
+ has_finite_lights,
+ has_light_linking,
+ has_emissive_triangles,
+ has_analytic_lights,
+ ..
+ } = *scene;
+
// --- Apply replacements ---
// The sentinel pattern `const SCENE_HAS_*: bool = true;` is replaced with the computed value.
// If the pattern is absent (kernel not yet updated), the source is returned unchanged.
@@ -556,6 +653,66 @@ mod specialization_tests {
assert_eq!(result, source, "Source without markers should be unchanged");
}
+ const SESSION_TEST_SOURCE: &str = "const SCENE_HAS_VOLUME: bool = true;\nconst SCENE_HAS_GLASS: bool = true;\nconst SCENE_HAS_ENV_IMPORTANCE: bool = true;";
+
+ #[test]
+ fn a_scene_scan_combined_with_the_parameters_equals_the_one_step_specialization() {
+ let kp = make_kp(2, 1.0, 0, 0, 0.0);
+ let mat = make_mat(0.0, 0.0, 0.0, 0.0, 0.0, 0, 0, -1, -1);
+ let input = dummy_input(&kp, &mat, &make_default_light(), &make_default_inst());
+ let scene = scan_scene_specialization(&input);
+ assert_eq!(
+ specialize_kernel_source(SESSION_TEST_SOURCE, &scene, &kp),
+ specialize_cycles_kernel(SESSION_TEST_SOURCE, &input)
+ );
+ }
+
+ #[test]
+ fn a_frame_that_changes_only_the_camera_keeps_the_specialized_source() {
+ let kp = make_kp(2, 1.0, 0, 0, 0.0);
+ let mat = make_mat(0.0, 0.0, 0.0, 0.0, 0.0, 0, 0, -1, -1);
+ let input = dummy_input(&kp, &mat, &make_default_light(), &make_default_inst());
+ let scene = scan_scene_specialization(&input);
+ let mut moved_camera = kp.clone();
+ moved_camera[120..124].copy_from_slice(&3.5f32.to_bits().to_le_bytes());
+ assert_eq!(
+ specialize_kernel_source(SESSION_TEST_SOURCE, &scene, &kp),
+ specialize_kernel_source(SESSION_TEST_SOURCE, &scene, &moved_camera)
+ );
+ }
+
+ #[test]
+ fn a_frame_that_removes_the_fog_changes_the_specialized_source() {
+ let kp = make_kp(2, 1.0, 0, 0, 0.0);
+ let mat = make_mat(0.0, 0.0, 0.0, 0.0, 0.0, 0, 0, -1, -1);
+ let input = dummy_input(&kp, &mat, &make_default_light(), &make_default_inst());
+ let scene = scan_scene_specialization(&input);
+ let without_fog = make_kp(0, 0.0, 0, 0, 0.0);
+ let fogged = specialize_kernel_source(SESSION_TEST_SOURCE, &scene, &kp);
+ let clear = specialize_kernel_source(SESSION_TEST_SOURCE, &scene, &without_fog);
+ assert!(fogged.contains("const SCENE_HAS_VOLUME: bool = true;"));
+ assert!(clear.contains("const SCENE_HAS_VOLUME: bool = false;"));
+ }
+
+ #[test]
+ fn a_frame_must_keep_the_scene_record_counts_of_the_session() {
+ let session_params = make_kp(0, 0.0, 0, 0, 0.0);
+ let mut moved_camera = session_params.clone();
+ moved_camera[120..124].copy_from_slice(&1.0f32.to_bits().to_le_bytes());
+ assert!(check_frame_params_keep_scene_counts(&session_params, &moved_camera).is_ok());
+
+ let mut other_scene = session_params.clone();
+ other_scene[KP_MATERIAL_COUNT_BYTE..KP_MATERIAL_COUNT_BYTE + 4].copy_from_slice(&9u32.to_le_bytes());
+ let message = check_frame_params_keep_scene_counts(&session_params, &other_scene)
+ .expect_err("a different material count must be refused")
+ .to_string();
+ assert!(message.contains("materialCount"), "{message}");
+ assert!(message.contains("create a new session"), "{message}");
+
+ let truncated = &session_params[..64];
+ assert!(check_frame_params_keep_scene_counts(&session_params, truncated).is_err());
+ }
+
fn opaque_inputs(metallic: f32, transmission_weight: f32) -> BaseLayerInputs {
BaseLayerInputs {
metallic,
diff --git a/packages/render-native/src/host/cycles_session.rs b/packages/render-native/src/host/cycles_session.rs
new file mode 100644
index 00000000..4372421c
--- /dev/null
+++ b/packages/render-native/src/host/cycles_session.rs
@@ -0,0 +1,396 @@
+//! A persistent Cycles render session (issue 896). It owns what a render needs that does not change from one frame to
+//! the next: the device handle, the scene tables on the card, the acceleration structures, the compiled pipeline and the
+//! film with its bind group. A frame then only writes the kernel parameters (camera, image size, sample count), clears the
+//! film and dispatches. The one-shot `traceSceneCycles` is a session that renders once.
+
+use std::sync::atomic::Ordering;
+use std::time::Instant;
+
+use napi::Result;
+
+use crate::cycles::{
+ assemble_cycles_kernel_entry, check_counts_match_kernel_params, check_frame_params_keep_scene_counts,
+ scan_scene_specialization, specialize_kernel_source, trace_entry_point_for_params, SceneSpecialization,
+};
+use crate::host::accel::{build_cycles_acceleration_structure, CyclesAcceleration};
+use crate::host::device::failure;
+use crate::host::film::{image_accumulation_bytes, image_workgroups};
+use crate::host::session::{
+ create_cycles_bind_group, get_cycles_device_context, get_or_compile_cycles_pipeline_on, pipeline_key,
+ trace_cycles_samples, validate_cycles_input, validate_kernel_params_v2, validate_light_tree_flag_has_tables,
+ validate_render_extent, with_cycles_cache_on, CyclesDeviceContext, CyclesDispatchTarget, CyclesTrace, DispatchPlan,
+ PipelineKey,
+};
+use crate::host::textures::{create_cycles_film, create_cycles_parameters, upload_cycles_scene_tables};
+use crate::NativeTraceInputV2;
+
+const KERNEL_PARAMS_WIDTH_BYTE: usize = 8;
+const KERNEL_PARAMS_HEIGHT_BYTE: usize = 12;
+const KERNEL_PARAMS_TOTAL_SAMPLES_BYTE: usize = 24;
+/// A wall clock limit under this many seconds keeps one sample per dispatch so the limit is checked often.
+const TIGHT_TIME_LIMIT_SECONDS: f64 = 2.0;
+
+/// What one frame asks of a session.
+pub(crate) struct CyclesRenderRequest<'a> {
+ pub(crate) width: u32,
+ pub(crate) height: u32,
+ pub(crate) samples: u32,
+ pub(crate) samples_per_dispatch: Option<u32>,
+ pub(crate) max_seconds: Option<f64>,
+ pub(crate) bootstrap_kernel: bool,
+ /// A KernelParamsV2 block for this frame (another camera, seed or filter of the same scene); absent means the block
+ /// the session was created with.
+ pub(crate) kernel_params: Option<&'a [u8]>,
+}
+
+/// The per-phase seconds of one frame and what it reused. A frame that reuses something spends no time on it: the
+/// first frame of a session carries the setup, upload and acceleration build seconds of the creation.
+pub(crate) struct CyclesRenderReport {
+ pub(crate) setup_seconds: f64,
+ pub(crate) compile_seconds: f64,
+ pub(crate) upload_seconds: f64,
+ pub(crate) acceleration_build_seconds: f64,
+ /// The session already held the compiled pipeline this frame needed.
+ pub(crate) pipeline_reused: bool,
+ /// The acceleration structures were built by an earlier call, not for this frame.
+ pub(crate) acceleration_reused: bool,
+ /// The film and its bind group were kept from the previous frame (same image size).
+ pub(crate) film_reused: bool,
+ /// How many frames this session finished before this one.
+ pub(crate) frame_index: u32,
+}
+
+pub(crate) struct CyclesRender {
+ pub(crate) trace: CyclesTrace,
+ pub(crate) report: CyclesRenderReport,
+}
+
+/// What creating the session cost; the first frame reports it.
+struct CreationCosts {
+ setup_seconds: f64,
+ upload_seconds: f64,
+ acceleration_build_seconds: f64,
+}
+
+struct HeldPipeline {
+ key: PipelineKey,
+ pipeline: wgpu::ComputePipeline,
+}
+
+struct SessionFilm {
+ width: u32,
+ height: u32,
+ accumulation: wgpu::Buffer,
+ bind_group: wgpu::BindGroup,
+}
+
+/// Everything on the card. Dropping it frees the card, which is what `close` does.
+struct SessionGpuState {
+ scene_tables: Vec<wgpu::Buffer>,
+ acceleration: CyclesAcceleration,
+ parameters: wgpu::Buffer,
+ pipeline: Option<HeldPipeline>,
+ film: Option<SessionFilm>,
+}
+
+impl SessionGpuState {
+ fn film(&self) -> Result<&SessionFilm> {
+ self.film.as_ref().ok_or_else(|| failure("The session film is missing; this is a bug in the session."))
+ }
+
+ fn pipeline(&self) -> Result<&HeldPipeline> {
+ self.pipeline.as_ref().ok_or_else(|| failure("The session pipeline is missing; this is a bug in the session."))
+ }
+}
+
+pub(crate) struct CyclesSession {
+ context: CyclesDeviceContext,
+ /// The kernel parameters the session was created with, the default for a frame that brings none.
+ session_kernel_params: Vec<u8>,
+ scene_specialization: SceneSpecialization,
+ light_tree_node_count: u32,
+ has_light_tree_tables: bool,
+ creation_costs: Option<CreationCosts>,
+ renders_completed: u32,
+ /// `None` once the session is closed.
+ gpu: Option<SessionGpuState>,
+}
+
+/// The kernel parameters of one render: the frame's block with the image size and the total sample count written in.
+pub(crate) fn patch_render_parameters(kernel_params: &[u8], width: u32, height: u32, total_samples: u32) -> Vec<u8> {
+ let mut patched = kernel_params.to_vec();
+ patched[KERNEL_PARAMS_WIDTH_BYTE..KERNEL_PARAMS_WIDTH_BYTE + 4].copy_from_slice(&width.to_le_bytes());
+ patched[KERNEL_PARAMS_HEIGHT_BYTE..KERNEL_PARAMS_HEIGHT_BYTE + 4].copy_from_slice(&height.to_le_bytes());
+ patched[KERNEL_PARAMS_TOTAL_SAMPLES_BYTE..KERNEL_PARAMS_TOTAL_SAMPLES_BYTE + 4]
+ .copy_from_slice(&total_samples.to_le_bytes());
+ patched
+}
+
+/// Unless the caller fixes the batch, each dispatch is sized from the time of the last so none runs long enough for the
+/// driver to reset the device. A wall-clock limit under 2 s keeps one sample per dispatch for tight responsiveness.
+pub(crate) fn choose_dispatch_plan(samples: u32, samples_per_dispatch: Option<u32>, max_seconds: Option<f64>) -> DispatchPlan {
+ match samples_per_dispatch {
+ Some(samples_per_dispatch) => DispatchPlan::Fixed(samples_per_dispatch.max(1)),
+ None => match max_seconds {
+ Some(limit) if limit < TIGHT_TIME_LIMIT_SECONDS => DispatchPlan::Fixed(1),
+ _ => DispatchPlan::TimeBudget { largest_batch: samples.max(1) },
+ },
+ }
+}
+
+fn session_closed_failure() -> napi::Error {
+ failure("This native session is closed. Create a new one with createNativeSession(input) before rendering again.")
+}
+
+fn session_device_lost_failure(detail: &str) -> napi::Error {
+ let reported = if detail.is_empty() { "no detail from the driver" } else { detail };
+ failure(format!(
+ "The GPU device this session was created on was lost ({reported}). The session cannot render any more: call close() and create a new one with createNativeSession(input)."
+ ))
+}
+
+impl CyclesSession {
+ /// Validates the input, opens (or reuses) the device, uploads the scene tables and builds the acceleration structures.
+ pub(crate) fn create(input: &NativeTraceInputV2) -> Result<CyclesSession> {
+ let setup_started = Instant::now();
+ validate_cycles_input(input)?;
+ check_counts_match_kernel_params(input)?;
+ let context = get_cycles_device_context()?;
+ let scene_specialization = scan_scene_specialization(input);
+ let setup_seconds = setup_started.elapsed().as_secs_f64();
+
+ let upload_started = Instant::now();
+ let scene_tables = upload_cycles_scene_tables(&context.device, input);
+ let parameters = create_cycles_parameters(&context.device, &input.kernel_params);
+ let upload_seconds = upload_started.elapsed().as_secs_f64();
+
+ let build_started = Instant::now();
+ let acceleration = build_cycles_acceleration_structure(
+ &context.device,
+ &context.queue,
+ &input.instances,
+ input.instance_count as usize,
+ &input.triangles,
+ input.triangle_count as usize,
+ )?;
+ let acceleration_build_seconds = build_started.elapsed().as_secs_f64();
+
+ Ok(CyclesSession {
+ context,
+ session_kernel_params: input.kernel_params.to_vec(),
+ scene_specialization,
+ light_tree_node_count: input.light_tree_node_count,
+ has_light_tree_tables: input.light_tree_emitters.is_some(),
+ creation_costs: Some(CreationCosts { setup_seconds, upload_seconds, acceleration_build_seconds }),
+ renders_completed: 0,
+ gpu: Some(SessionGpuState {
+ scene_tables,
+ acceleration,
+ parameters,
+ pipeline: None,
+ film: None,
+ }),
+ })
+ }
+
+ pub(crate) fn device_context(&self) -> &CyclesDeviceContext {
+ &self.context
+ }
+
+ /// Frees the scene, the acceleration structures, the pipeline and the film. A closed session refuses to render.
+ pub(crate) fn close(&mut self) {
+ self.gpu = None;
+ }
+
+ fn fail_if_unusable(&self) -> Result<()> {
+ if self.gpu.is_none() {
+ return Err(session_closed_failure());
+ }
+ if self.context.device_lost.load(Ordering::SeqCst) {
+ let detail = self.context.device_error.lock().map(|stored| stored.clone()).unwrap_or_default();
+ return Err(session_device_lost_failure(&detail));
+ }
+ Ok(())
+ }
+
+ /// The kernel parameters of a frame: the ones it brings after checking they describe this scene, else the session's own.
+ fn frame_kernel_params(&self, requested: Option<&[u8]>) -> Result<Vec<u8>> {
+ let Some(requested_bytes) = requested else {
+ return Ok(self.session_kernel_params.clone());
+ };
+ validate_kernel_params_v2(requested_bytes)?;
+ check_frame_params_keep_scene_counts(&self.session_kernel_params, requested_bytes)?;
+ validate_light_tree_flag_has_tables(requested_bytes, self.light_tree_node_count, self.has_light_tree_tables)?;
+ Ok(requested_bytes.to_vec())
+ }
+
+ /// Renders one frame. The scene, the acceleration structures and (while the specialized kernel text and the image size
+ /// stay the same) the pipeline and the film are reused; the film is cleared, so a frame starts from zero as a one-shot does.
+ pub(crate) fn render(&mut self, request: &CyclesRenderRequest<'_>) -> Result<CyclesRender> {
+ self.fail_if_unusable()?;
+ validate_render_extent(request.width, request.height, request.samples)?;
+ let frame_kernel_params = self.frame_kernel_params(request.kernel_params)?;
+
+ let frame_index = self.renders_completed;
+ let creation_costs = self.creation_costs.take();
+ let acceleration_reused = creation_costs.is_none();
+ let context = &self.context;
+ let gpu = self.gpu.as_mut().ok_or_else(session_closed_failure)?;
+
+ let compile_started = Instant::now();
+ let pipeline_reused = ensure_pipeline(
+ context,
+ gpu,
+ &self.scene_specialization,
+ &frame_kernel_params,
+ request.bootstrap_kernel,
+ )?;
+ let compile_seconds = compile_started.elapsed().as_secs_f64();
+
+ let upload_started = Instant::now();
+ let film_reused = ensure_film(context, gpu, request.width, request.height)?;
+ let render_parameters =
+ patch_render_parameters(&frame_kernel_params, request.width, request.height, request.samples);
+ context.queue.write_buffer(&gpu.parameters, 0, &render_parameters);
+ if film_reused {
+ clear_film(context, gpu.film()?);
+ }
+ let upload_seconds = upload_started.elapsed().as_secs_f64();
+
+ let film = gpu.film()?;
+ let target = CyclesDispatchTarget {
+ device: &context.device,
+ queue: &context.queue,
+ pipeline: &gpu.pipeline()?.pipeline,
+ bind_group: &film.bind_group,
+ parameters: &gpu.parameters,
+ accumulation: &film.accumulation,
+ device_lost: &context.device_lost,
+ device_error: &context.device_error,
+ };
+ let plan = choose_dispatch_plan(request.samples, request.samples_per_dispatch, request.max_seconds);
+ let trace = trace_cycles_samples(
+ &target,
+ request.samples,
+ plan,
+ image_workgroups(request.width, request.height),
+ image_accumulation_bytes(request.width, request.height),
+ request.max_seconds,
+ )?;
+ self.renders_completed = frame_index + 1;
+
+ let report = CyclesRenderReport {
+ setup_seconds: creation_costs.as_ref().map_or(0.0, |costs| costs.setup_seconds),
+ compile_seconds,
+ upload_seconds: upload_seconds + creation_costs.as_ref().map_or(0.0, |costs| costs.upload_seconds),
+ acceleration_build_seconds: creation_costs.as_ref().map_or(0.0, |costs| costs.acceleration_build_seconds),
+ pipeline_reused,
+ acceleration_reused,
+ film_reused,
+ frame_index,
+ };
+ Ok(CyclesRender { trace, report })
+ }
+}
+
+/// Makes `gpu.pipeline` the pipeline for this frame's specialized kernel text; true when it already was.
+fn ensure_pipeline(
+ context: &CyclesDeviceContext,
+ gpu: &mut SessionGpuState,
+ scene: &SceneSpecialization,
+ frame_kernel_params: &[u8],
+ bootstrap_kernel: bool,
+) -> Result<bool> {
+ let assembled_source = assemble_cycles_kernel_entry("main", bootstrap_kernel)?;
+ let entry_point = trace_entry_point_for_params(frame_kernel_params);
+ let specialized_source = specialize_kernel_source(&assembled_source, scene, frame_kernel_params);
+ let key = pipeline_key(entry_point, &specialized_source);
+ if gpu.pipeline.as_ref().is_some_and(|held| held.key == key) {
+ return Ok(true);
+ }
+ let pipeline = get_or_compile_cycles_pipeline_on(Some(&context.device_lost), entry_point, specialized_source)?;
+ gpu.pipeline = Some(HeldPipeline { key, pipeline });
+ Ok(false)
+}
+
+/// Makes `gpu.film` a film of this size with a bind group over it; true when the previous frame's film was kept.
+fn ensure_film(context: &CyclesDeviceContext, gpu: &mut SessionGpuState, width: u32, height: u32) -> Result<bool> {
+ if gpu.film.as_ref().is_some_and(|film| film.width == width && film.height == height) {
+ return Ok(true);
+ }
+ let accumulation = create_cycles_film(&context.device, image_accumulation_bytes(width, height));
+ let bind_group = with_cycles_cache_on(Some(&context.device_lost), |device, _queue, layout, lut| {
+ create_cycles_bind_group(
+ device,
+ layout,
+ &gpu.parameters,
+ &gpu.acceleration.tlas,
+ &gpu.scene_tables,
+ &accumulation,
+ lut,
+ )
+ })?;
+ gpu.film = Some(SessionFilm { width, height, accumulation, bind_group });
+ Ok(false)
+}
+
+fn clear_film(context: &CyclesDeviceContext, film: &SessionFilm) {
+ let mut encoder = context.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("cycles film clear"),
+ });
+ encoder.clear_buffer(&film.accumulation, 0, None);
+ context.queue.submit(Some(encoder.finish()));
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn render_parameters_carry_the_image_size_and_the_sample_count_and_nothing_else() {
+ let mut frame = vec![0xABu8; 320];
+ frame[0..4].copy_from_slice(&0x36375054u32.to_le_bytes());
+ let patched = patch_render_parameters(&frame, 1920, 1080, 64);
+ assert_eq!(patched.len(), 320);
+ assert_eq!(&patched[8..12], &1920u32.to_le_bytes());
+ assert_eq!(&patched[12..16], &1080u32.to_le_bytes());
+ assert_eq!(&patched[24..28], &64u32.to_le_bytes());
+ let untouched = |index: &usize| !(8..16).contains(index) && !(24..28).contains(index);
+ assert!((0..320).filter(untouched).all(|index| patched[index] == frame[index]));
+ }
+
+ #[test]
+ fn a_fixed_batch_is_kept_and_never_zero() {
+ assert!(matches!(choose_dispatch_plan(64, Some(8), None), DispatchPlan::Fixed(8)));
+ assert!(matches!(choose_dispatch_plan(64, Some(0), None), DispatchPlan::Fixed(1)));
+ assert!(matches!(choose_dispatch_plan(64, Some(16), Some(0.5)), DispatchPlan::Fixed(16)));
+ }
+
+ #[test]
+ fn a_tight_time_limit_draws_one_sample_per_dispatch() {
+ assert!(matches!(choose_dispatch_plan(64, None, Some(1.5)), DispatchPlan::Fixed(1)));
+ assert!(matches!(choose_dispatch_plan(64, None, Some(2.0)), DispatchPlan::TimeBudget { largest_batch: 64 }));
+ }
+
+ #[test]
+ fn without_a_batch_or_limit_the_dispatches_are_sized_by_time() {
+ assert!(matches!(choose_dispatch_plan(256, None, None), DispatchPlan::TimeBudget { largest_batch: 256 }));
+ assert!(matches!(choose_dispatch_plan(0, None, None), DispatchPlan::TimeBudget { largest_batch: 1 }));
+ }
+
+ #[test]
+ fn a_closed_session_error_says_how_to_continue() {
+ let message = session_closed_failure().to_string();
+ assert!(message.contains("closed"), "{message}");
+ assert!(message.contains("createNativeSession"), "{message}");
+ }
+
+ #[test]
+ fn a_lost_device_error_names_the_driver_report_and_the_way_out() {
+ let with_detail = session_device_lost_failure("Unknown: TDR").to_string();
+ assert!(with_detail.contains("TDR"), "{with_detail}");
+ assert!(with_detail.contains("createNativeSession"), "{with_detail}");
+ let without_detail = session_device_lost_failure("").to_string();
+ assert!(without_detail.contains("no detail from the driver"), "{without_detail}");
+ }
+}
diff --git a/packages/render-native/src/host/mod.rs b/packages/render-native/src/host/mod.rs
index 6e4bc72d..4972a58f 100644
--- a/packages/render-native/src/host/mod.rs
+++ b/packages/render-native/src/host/mod.rs
@@ -3,5 +3,6 @@ pub(crate) mod denoise;
pub(crate) mod dispatch;
pub(crate) mod device;
pub(crate) mod film;
+pub(crate) mod cycles_session;
pub(crate) mod session;
pub(crate) mod textures;
diff --git a/packages/render-native/src/host/session.rs b/packages/render-native/src/host/session.rs
index 51d6b754..882e5721 100644
--- a/packages/render-native/src/host/session.rs
+++ b/packages/render-native/src/host/session.rs
@@ -8,16 +8,15 @@ use std::time::Instant;
use napi::Result;
use wgpu::util::DeviceExt;
-use crate::cycles::{check_counts_match_kernel_params, specialize_cycles_kernel, trace_entry_point, unit_filter_table_words, CYCLES_LUT_WORDS};
+use crate::cycles::{unit_filter_table_words, CYCLES_LUT_WORDS};
use crate::host::accel::{
- build_acceleration_structure, build_cycles_acceleration_structure, build_empty_cycles_acceleration,
- create_vertex_buffer, unpack_triangles, CyclesAcceleration, INSTANCE_RECORD_BYTES, TRIANGLE_FLOATS,
- TRIANGLE_RECORD_BYTES,
+ build_acceleration_structure, build_empty_cycles_acceleration, create_vertex_buffer, unpack_triangles,
+ INSTANCE_RECORD_BYTES, TRIANGLE_FLOATS, TRIANGLE_RECORD_BYTES,
};
use crate::host::dispatch::{DispatchPlanner, DISPATCH_BUDGET_SECONDS};
use crate::host::device::{failure, layout_entry, open_device, storage_buffer, storage_entry};
use crate::host::film::{image_accumulation_bytes, read_accumulation};
-use crate::host::textures::{upload_cycles_scene_buffers, upload_scene_buffers};
+use crate::host::textures::upload_scene_buffers;
use crate::{NativeTraceInput, NativeTraceInputV2, ProbeCyclesLobeOptions};
// ---- In-process device and pipeline cache ----
@@ -33,9 +32,9 @@ const MAX_CACHED_PIPELINES: usize = 32;
/// A pipeline cache key: the entry point plus a 64 bit hash of the specialized source, so the cache never
/// holds a second copy of a kernel text that is hundreds of kilobytes long.
-type PipelineKey = (String, u64);
+pub(crate) type PipelineKey = (String, u64);
-fn pipeline_key(entry_point: &str, specialized_source: &str) -> PipelineKey {
+pub(crate) fn pipeline_key(entry_point: &str, specialized_source: &str) -> PipelineKey {
let mut hasher = DefaultHasher::new();
specialized_source.hash(&mut hasher);
(entry_point.to_string(), hasher.finish())
@@ -183,15 +182,27 @@ fn cache_was_reset_failure() -> napi::Error {
/// Looks up or compiles and caches a Cycles `ComputePipeline` for `(entry_point, specialized_source)`.
fn get_or_compile_cycles_pipeline(entry_point: &str, specialized_source: String) -> Result<wgpu::ComputePipeline> {
+ get_or_compile_cycles_pipeline_on(None, entry_point, specialized_source)
+}
+
+/// As `get_or_compile_cycles_pipeline`, for a caller that holds buffers on one device. `expected_device` is that device's
+/// lost flag: when the cache has since moved to another device the call fails instead of returning a pipeline that
+/// does not belong to the caller's device.
+pub(crate) fn get_or_compile_cycles_pipeline_on(
+ expected_device: Option<&Arc<AtomicBool>>,
+ entry_point: &str,
+ specialized_source: String,
+) -> Result<wgpu::ComputePipeline> {
let key = pipeline_key(entry_point, &specialized_source);
{
let guard = lock_device_cache();
let cached = guard.as_ref().ok_or_else(cache_was_reset_failure)?;
+ check_same_device(cached, expected_device)?;
if let Some(existing) = cached.cycles_pipelines.get(&key) {
return Ok(existing);
}
}
- let compiled = with_cycles_cache(|device, _queue, layout, _lut| {
+ let compiled = with_cycles_cache_on(expected_device, |device, _queue, layout, _lut| {
compile_compute_pipeline(device, specialized_source, entry_point, layout)
})??;
let mut guard = lock_device_cache();
@@ -201,17 +212,53 @@ fn get_or_compile_cycles_pipeline(entry_point: &str, specialized_source: String)
Ok(compiled)
}
+fn check_same_device(cached: &CachedDevice, expected_device: Option<&Arc<AtomicBool>>) -> Result<()> {
+ match expected_device {
+ Some(expected) if !Arc::ptr_eq(&cached.device_lost, expected) => Err(failure(
+ "The GPU device this session was created on has been replaced. Close the session and create a new one.",
+ )),
+ _ => Ok(()),
+ }
+}
+
/// Returns the cached Cycles bind group layout and LUT buffer, with cloned device/queue.
/// Fails when the cache was reset since `get_cached_device` succeeded (device loss or a poisoned lock).
fn with_cycles_cache<F, T>(f: F) -> Result<T>
+where
+ F: FnOnce(&wgpu::Device, &wgpu::Queue, &wgpu::BindGroupLayout, &wgpu::Buffer) -> T,
+{
+ with_cycles_cache_on(None, f)
+}
+
+/// As `with_cycles_cache`, failing when the cache no longer holds the device whose lost flag is `expected_device`.
+pub(crate) fn with_cycles_cache_on<F, T>(expected_device: Option<&Arc<AtomicBool>>, f: F) -> Result<T>
where
F: FnOnce(&wgpu::Device, &wgpu::Queue, &wgpu::BindGroupLayout, &wgpu::Buffer) -> T,
{
let guard = lock_device_cache();
let cached = guard.as_ref().ok_or_else(cache_was_reset_failure)?;
+ check_same_device(cached, expected_device)?;
Ok(f(&cached.device, &cached.queue, &cached.cycles_bind_group_layout, &cached.lut_buffer))
}
+/// The cached device with everything a Cycles session needs to know about it. The loss flag identifies the device: two
+/// contexts with the same flag (`Arc::ptr_eq`) share one device.
+pub(crate) struct CyclesDeviceContext {
+ pub(crate) device: wgpu::Device,
+ pub(crate) queue: wgpu::Queue,
+ pub(crate) adapter_name: String,
+ pub(crate) backend_name: String,
+ pub(crate) features: String,
+ pub(crate) device_lost: Arc<AtomicBool>,
+ pub(crate) device_error: Arc<Mutex<String>>,
+}
+
+pub(crate) fn get_cycles_device_context() -> Result<CyclesDeviceContext> {
+ let (device, queue, adapter_name, backend_name, features) = get_cached_device()?;
+ let (device_lost, device_error) = cached_device_loss_state()?;
+ Ok(CyclesDeviceContext { device, queue, adapter_name, backend_name, features, device_lost, device_error })
+}
+
const PARAMETER_BYTES: usize = 16 * 16;
const VOLUME_DENSITY_BYTE_OFFSET: usize = 51 * 4;
const SUBSURFACE_OFFSET_BYTE_OFFSET: usize = 60 * 4;
@@ -253,24 +300,16 @@ pub(crate) struct PreparedScene {
pub(crate) _tlas: wgpu::Tlas,
}
-pub(crate) struct PreparedCyclesScene {
- pub(crate) device: wgpu::Device,
- pub(crate) queue: wgpu::Queue,
- pub(crate) pipeline: wgpu::ComputePipeline,
- pub(crate) bind_group: wgpu::BindGroup,
- pub(crate) accumulation: wgpu::Buffer,
- pub(crate) parameters: wgpu::Buffer,
- pub(crate) adapter_name: String,
- pub(crate) backend_name: String,
- pub(crate) features: String,
- pub(crate) device_lost: Arc<AtomicBool>,
- pub(crate) device_error: Arc<Mutex<String>>,
- pub(crate) setup_seconds: f64,
- pub(crate) compile_seconds: f64,
- pub(crate) upload_seconds: f64,
- pub(crate) acceleration_build_seconds: f64,
- pub(crate) _buffers: Vec<wgpu::Buffer>,
- pub(crate) _acceleration: CyclesAcceleration,
+/// Everything one run of Cycles dispatches touches, borrowed from the session that owns it.
+pub(crate) struct CyclesDispatchTarget<'a> {
+ pub(crate) device: &'a wgpu::Device,
+ pub(crate) queue: &'a wgpu::Queue,
+ pub(crate) pipeline: &'a wgpu::ComputePipeline,
+ pub(crate) bind_group: &'a wgpu::BindGroup,
+ pub(crate) parameters: &'a wgpu::Buffer,
+ pub(crate) accumulation: &'a wgpu::Buffer,
+ pub(crate) device_lost: &'a AtomicBool,
+ pub(crate) device_error: &'a Mutex<String>,
}
/// What one kind of job adds to the shared scene setup: the kernel text, its entry point, the accumulation size and the
@@ -407,7 +446,7 @@ fn create_scene_bind_group(
})
}
-fn create_cycles_bind_group(
+pub(crate) fn create_cycles_bind_group(
device: &wgpu::Device,
bind_group_layout: &wgpu::BindGroupLayout,
parameters: &wgpu::Buffer,
@@ -560,7 +599,7 @@ pub(crate) fn trace_samples(
Ok((sums, trace_started.elapsed().as_secs_f64()))
}
-fn validate_kernel_params_v2(parameter_bytes: &[u8]) -> Result<()> {
+pub(crate) fn validate_kernel_params_v2(parameter_bytes: &[u8]) -> Result<()> {
if parameter_bytes.len() != KERNEL_PARAMS_V2_BYTES {
return Err(failure(format!(
"KernelParamsV2 must be {KERNEL_PARAMS_V2_BYTES} bytes, got {}.",
@@ -597,6 +636,24 @@ fn validate_record_buffer(label: &str, bytes: &[u8], count: u32, stride: usize)
const KERNEL_PARAMS_KERNEL_FLAGS_BYTE: usize = 32;
const KERNEL_FLAG_USE_LIGHT_TREE: u32 = 1;
+/// Refuses kernel parameters that switch the light tree on for an input that carries tree nodes but no emitter tables.
+pub(crate) fn validate_light_tree_flag_has_tables(
+ kernel_params: &[u8],
+ light_tree_node_count: u32,
+ has_emitter_tables: bool,
+) -> Result<()> {
+ let tree_flag_set = kernel_params
+ .get(KERNEL_PARAMS_KERNEL_FLAGS_BYTE..KERNEL_PARAMS_KERNEL_FLAGS_BYTE + 4)
+ .map(|bytes| u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) & KERNEL_FLAG_USE_LIGHT_TREE != 0)
+ .unwrap_or(false);
+ if tree_flag_set && light_tree_node_count > 0 && !has_emitter_tables {
+ return Err(failure(
+ "The light-tree kernel flag is set and the input has light tree nodes, but lightTreeEmitters, lightTreeEmitterCount and lightToTree are missing. Repack the scene with buildNativeInputV2.",
+ ));
+ }
+ Ok(())
+}
+
/// The emitter table and the emitter-to-slot table come together or not at all, and the slot table must cover
/// every analytic light and emissive triangle of the input.
pub(crate) fn validate_light_tree_tables(input: &NativeTraceInputV2) -> Result<()> {
@@ -606,17 +663,7 @@ pub(crate) fn validate_light_tree_tables(input: &NativeTraceInputV2) -> Result<(
&input.light_to_tree,
) {
(None, None, None) => {
- let tree_flag_set = input
- .kernel_params
- .get(KERNEL_PARAMS_KERNEL_FLAGS_BYTE..KERNEL_PARAMS_KERNEL_FLAGS_BYTE + 4)
- .map(|bytes| u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) & KERNEL_FLAG_USE_LIGHT_TREE != 0)
- .unwrap_or(false);
- if tree_flag_set && input.light_tree_node_count > 0 {
- return Err(failure(
- "The light-tree kernel flag is set and the input has light tree nodes, but lightTreeEmitters, lightTreeEmitterCount and lightToTree are missing. Repack the scene with buildNativeInputV2.",
- ));
- }
- return Ok(());
+ return validate_light_tree_flag_has_tables(&input.kernel_params, input.light_tree_node_count, false);
}
(Some(emitters), Some(emitter_count), Some(light_to_tree)) => (emitters, emitter_count, light_to_tree),
_ => {
@@ -641,21 +688,19 @@ pub(crate) fn validate_light_tree_tables(input: &NativeTraceInputV2) -> Result<(
Ok(())
}
-pub(crate) fn prepare_cycles_scene(
- input: &NativeTraceInputV2,
- shader_source: String,
- width: u32,
- height: u32,
- total_samples: u32,
- accumulation_bytes: u64,
-) -> Result<PreparedCyclesScene> {
- let setup_started = Instant::now();
+/// Refuses a render size or sample count the kernel cannot run.
+pub(crate) fn validate_render_extent(width: u32, height: u32, total_samples: u32) -> Result<()> {
if width == 0 || height == 0 {
return Err(failure("Trace width and height must both be >= 1."));
}
if total_samples == 0 {
return Err(failure("Trace samples must be >= 1."));
}
+ Ok(())
+}
+
+/// Checks a FORMAT-v2 input before a session uploads it: schema, parameter block and the size of every table.
+pub(crate) fn validate_cycles_input(input: &NativeTraceInputV2) -> Result<()> {
if input.schema_version != FORMAT_V2_VERSION {
return Err(failure(format!(
"Invalid FORMAT-v2 input schemaVersion {}: expected {FORMAT_V2_VERSION}.",
@@ -685,66 +730,7 @@ pub(crate) fn prepare_cycles_scene(
input.texture_count,
TEXTURE_DESCRIPTOR_BYTES,
)?;
- validate_light_tree_tables(input)?;
-
- // Use cached device; open once per process.
- let (device, queue, adapter_name, backend_name, features) = get_cached_device()?;
- let (device_lost, device_error) = cached_device_loss_state()?;
- let setup_seconds = setup_started.elapsed().as_secs_f64();
-
- let compile_started = Instant::now();
- // Specialise the kernel source for this scene (replaces SCENE_HAS_* sentinels).
- check_counts_match_kernel_params(input)?;
- let specialized_source = specialize_cycles_kernel(&shader_source, input);
- let pipeline = get_or_compile_cycles_pipeline(trace_entry_point(input), specialized_source)?;
- let compile_seconds = compile_started.elapsed().as_secs_f64();
-
- let upload_started = Instant::now();
- let uploaded = upload_cycles_scene_buffers(&device, input, width, height, total_samples, accumulation_bytes);
- let upload_seconds = upload_started.elapsed().as_secs_f64();
-
- let build_started = Instant::now();
- let acceleration = build_cycles_acceleration_structure(
- &device,
- &queue,
- &input.instances,
- input.instance_count as usize,
- &input.triangles,
- input.triangle_count as usize,
- )?;
- let acceleration_build_seconds = build_started.elapsed().as_secs_f64();
-
- // Bind group: take layout and LUT reference under a brief lock, build the group, then release.
- let bind_group = with_cycles_cache(|device, _queue, layout, lut| {
- create_cycles_bind_group(
- device,
- layout,
- &uploaded.parameters,
- &acceleration.tlas,
- &uploaded.buffers,
- &uploaded.accumulation,
- lut,
- )
- })?;
- Ok(PreparedCyclesScene {
- device,
- queue,
- pipeline,
- bind_group,
- accumulation: uploaded.accumulation,
- parameters: uploaded.parameters,
- adapter_name,
- backend_name,
- features,
- device_lost,
- device_error,
- setup_seconds,
- compile_seconds,
- upload_seconds,
- acceleration_build_seconds,
- _buffers: uploaded.buffers,
- _acceleration: acceleration,
- })
+ validate_light_tree_tables(input)
}
/// How `trace_cycles_samples` splits the samples into dispatches.
@@ -767,15 +753,15 @@ pub(crate) struct CyclesTrace {
/// Raises the error for a lost device, naming the dispatch that was running and how to lower the work per dispatch.
fn fail_if_device_lost(
- prepared: &PreparedCyclesScene,
+ target: &CyclesDispatchTarget<'_>,
sample_offset: u32,
batch_samples: u32,
samples: u32,
) -> Result<()> {
- if !prepared.device_lost.load(Ordering::SeqCst) {
+ if !target.device_lost.load(Ordering::SeqCst) {
return Ok(());
}
- let detail = prepared.device_error.lock().map(|stored| stored.clone()).unwrap_or_default();
+ let detail = target.device_error.lock().map(|stored| stored.clone()).unwrap_or_default();
let smaller_batch = (batch_samples / 2).max(1);
Err(failure(format!(
"The GPU device was lost during the render, while drawing samples {sample_offset} to {} of {samples} in one dispatch of \
@@ -788,7 +774,7 @@ fn fail_if_device_lost(
}
pub(crate) fn trace_cycles_samples(
- prepared: &PreparedCyclesScene,
+ target: &CyclesDispatchTarget<'_>,
samples: u32,
plan: DispatchPlan,
groups: (u32, u32),
@@ -796,8 +782,8 @@ pub(crate) fn trace_cycles_samples(
max_seconds: Option<f64>,
) -> Result<CyclesTrace> {
let trace_started = Instant::now();
- let device = &prepared.device;
- let queue = &prepared.queue;
+ let device = target.device;
+ let queue = target.queue;
let mut planner = match plan {
DispatchPlan::TimeBudget { largest_batch } => Some(DispatchPlanner::new(DISPATCH_BUDGET_SECONDS, largest_batch)),
DispatchPlan::Fixed(_) => None,
@@ -819,7 +805,7 @@ pub(crate) fn trace_cycles_samples(
let mut dispatch_words = [0u8; 8];
dispatch_words[0..4].copy_from_slice(&sample_offset.to_le_bytes());
dispatch_words[4..8].copy_from_slice(&batch_samples.to_le_bytes());
- queue.write_buffer(&prepared.parameters, CYCLES_SAMPLE_OFFSET_BYTE_OFFSET, &dispatch_words);
+ queue.write_buffer(target.parameters, CYCLES_SAMPLE_OFFSET_BYTE_OFFSET, &dispatch_words);
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("cycles sample batch"),
@@ -829,8 +815,8 @@ pub(crate) fn trace_cycles_samples(
label: None,
timestamp_writes: None,
});
- pass.set_pipeline(&prepared.pipeline);
- pass.set_bind_group(0, &prepared.bind_group, &[]);
+ pass.set_pipeline(target.pipeline);
+ pass.set_bind_group(0, target.bind_group, &[]);
pass.dispatch_workgroups(groups.0, groups.1, 1);
}
queue.submit(Some(encoder.finish()));
@@ -850,7 +836,7 @@ pub(crate) fn trace_cycles_samples(
};
if should_poll {
let _ = device.poll(wgpu::PollType::wait_indefinitely());
- fail_if_device_lost(prepared, dispatch_offset, batch_samples, samples)?;
+ fail_if_device_lost(target, dispatch_offset, batch_samples, samples)?;
if let Some(planner) = planner.as_mut() {
let dispatch_seconds = dispatch_started.elapsed().as_secs_f64();
planner.record(batch_samples, dispatch_seconds);
@@ -866,8 +852,8 @@ pub(crate) fn trace_cycles_samples(
}
}
- let sums = read_accumulation(device, queue, &prepared.accumulation, accumulation_bytes);
- fail_if_device_lost(prepared, samples.saturating_sub(largest_batch), largest_batch, samples)?;
+ let sums = read_accumulation(device, queue, target.accumulation, accumulation_bytes);
+ fail_if_device_lost(target, samples.saturating_sub(largest_batch), largest_batch, samples)?;
Ok(CyclesTrace {
sums: sums?,
traced_seconds: trace_started.elapsed().as_secs_f64(),
@@ -1033,4 +1019,43 @@ mod tests {
*lock_resetting_when_poisoned(&cache) = Some(9);
assert_eq!(*lock_resetting_when_poisoned(&cache), Some(9));
}
+
+ fn kernel_params_with_flags(kernel_flags: u32) -> Vec<u8> {
+ let mut kernel_params = vec![0u8; KERNEL_PARAMS_V2_BYTES];
+ kernel_params[0..4].copy_from_slice(&FORMAT_V2_MAGIC.to_le_bytes());
+ kernel_params[4..8].copy_from_slice(&FORMAT_V2_VERSION.to_le_bytes());
+ kernel_params[KERNEL_PARAMS_KERNEL_FLAGS_BYTE..KERNEL_PARAMS_KERNEL_FLAGS_BYTE + 4]
+ .copy_from_slice(&kernel_flags.to_le_bytes());
+ kernel_params
+ }
+
+ #[test]
+ fn a_frame_may_switch_the_light_tree_on_only_when_the_session_holds_the_emitter_tables() {
+ let tree_on = kernel_params_with_flags(KERNEL_FLAG_USE_LIGHT_TREE);
+ let tree_off = kernel_params_with_flags(0);
+ assert!(validate_light_tree_flag_has_tables(&tree_on, 3, true).is_ok());
+ assert!(validate_light_tree_flag_has_tables(&tree_on, 0, false).is_ok());
+ assert!(validate_light_tree_flag_has_tables(&tree_off, 3, false).is_ok());
+ let message = validate_light_tree_flag_has_tables(&tree_on, 3, false)
+ .expect_err("the tree flag without emitter tables must be refused")
+ .to_string();
+ assert!(message.contains("buildNativeInputV2"), "{message}");
+ }
+
+ #[test]
+ fn a_frame_kernel_params_block_must_be_the_v2_block() {
+ assert!(validate_kernel_params_v2(&kernel_params_with_flags(0)).is_ok());
+ assert!(validate_kernel_params_v2(&[0u8; 12]).is_err());
+ let mut wrong_version = kernel_params_with_flags(0);
+ wrong_version[4..8].copy_from_slice(&1u32.to_le_bytes());
+ assert!(validate_kernel_params_v2(&wrong_version).is_err());
+ }
+
+ #[test]
+ fn an_image_of_zero_pixels_or_zero_samples_is_refused() {
+ assert!(validate_render_extent(16, 16, 1).is_ok());
+ assert!(validate_render_extent(0, 16, 1).is_err());
+ assert!(validate_render_extent(16, 0, 1).is_err());
+ assert!(validate_render_extent(16, 16, 0).is_err());
+ }
}
\ No newline at end of file
diff --git a/packages/render-native/src/host/textures.rs b/packages/render-native/src/host/textures.rs
index 8881f7c1..e2198c7b 100644
--- a/packages/render-native/src/host/textures.rs
+++ b/packages/render-native/src/host/textures.rs
@@ -89,21 +89,10 @@ fn light_to_tree_words(input: &NativeTraceInputV2) -> &[u32] {
}
}
-pub(crate) fn upload_cycles_scene_buffers(
- device: &wgpu::Device,
- input: &NativeTraceInputV2,
- width: u32,
- height: u32,
- total_samples: u32,
- accumulation_bytes: u64,
-) -> UploadedSceneBuffers {
- let mut parameter_bytes = input.kernel_params.to_vec();
- parameter_bytes[8..12].copy_from_slice(&width.to_le_bytes());
- parameter_bytes[12..16].copy_from_slice(&height.to_le_bytes());
- parameter_bytes[24..28].copy_from_slice(&total_samples.to_le_bytes());
-
- // Bindings 2..=10 in FORMAT-v2 order, then the light tree tables for bindings 13 and 14.
- let buffers = vec![
+/// The scene tables in FORMAT-v2 order: bindings 2..=10, then the light tree tables bound at 13 and 14 by
+/// `create_cycles_bind_group`. These stay on the card for as long as a session lives.
+pub(crate) fn upload_cycles_scene_tables(device: &wgpu::Device, input: &NativeTraceInputV2) -> Vec<wgpu::Buffer> {
+ vec![
storage_buffer(device, "cycles instances", &input.instances),
storage_buffer(device, "cycles triangles", &input.triangles),
storage_buffer(device, "cycles materials", &input.materials),
@@ -116,21 +105,23 @@ pub(crate) fn upload_cycles_scene_buffers(
// Bound at 13 and 14 by `create_cycles_bind_group`: the light tree emitters and the emitter-to-slot table.
storage_buffer(device, "cycles light tree emitters", light_tree_emitter_bytes(input)),
storage_buffer(device, "cycles light to tree", bytemuck::cast_slice(light_to_tree_words(input))),
- ];
- let accumulation = device.create_buffer(&wgpu::BufferDescriptor {
+ ]
+}
+
+/// A zeroed film. `COPY_DST` lets a session clear it between renders.
+pub(crate) fn create_cycles_film(device: &wgpu::Device, accumulation_bytes: u64) -> wgpu::Buffer {
+ device.create_buffer(&wgpu::BufferDescriptor {
label: Some("cycles film accumulation"),
size: accumulation_bytes,
- usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
+ usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
- });
- let parameters = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ })
+}
+
+pub(crate) fn create_cycles_parameters(device: &wgpu::Device, kernel_params: &[u8]) -> wgpu::Buffer {
+ device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("cycles kernel params"),
- contents: &parameter_bytes,
+ contents: kernel_params,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
- });
- UploadedSceneBuffers {
- buffers,
- accumulation,
- parameters,
- }
+ })
}
diff --git a/packages/render-native/src/lib.rs b/packages/render-native/src/lib.rs
index 204f0522..5b74f1c3 100644
--- a/packages/render-native/src/lib.rs
+++ b/packages/render-native/src/lib.rs
@@ -14,9 +14,8 @@ use crate::host::film::{
image_accumulation_bytes, image_workgroups, pad_texel_vectors, resolve_image, resolve_texels,
texel_accumulation_bytes, texel_workgroups,
};
-use crate::host::session::{
- get_cached_device, DispatchPlan, prepare_cycles_scene, prepare_scene, run_cycles_lobe_probe, trace_cycles_samples, trace_samples, JobShape,
-};
+use crate::host::cycles_session::{CyclesRenderRequest, CyclesSession};
+use crate::host::session::{get_cached_device, prepare_scene, run_cycles_lobe_probe, trace_samples, JobShape};
const KERNEL_SOURCE: &str = include_str!("kernel.wgsl");
/// The texel entry point of the light bake, appended to the kernel for a bake only.
@@ -86,6 +85,9 @@ pub struct NativeCyclesTraceOptions {
pub bootstrap_kernel: Option<bool>,
/// `"none"` (default) or `"atrous"`: also filter the image with the edge-avoiding a-trous wavelet filter.
pub denoise: Option<String>,
+ /// A KernelParamsV2 block for this render (a session frame with another camera or render settings of the same scene);
+ /// absent means the block of the input.
+ pub kernel_params: Option<Uint8Array>,
}
#[napi(object)]
@@ -260,45 +262,48 @@ pub fn trace_scene(input: NativeTraceInput, options: NativeTraceOptions) -> Resu
})
}
-/// Traces a packed `FORMAT-v2` scene on the GPU using the assembled Cycles-parity WGSL kernel.
-#[napi]
-pub fn trace_scene_cycles(input: NativeTraceInputV2, options: NativeCyclesTraceOptions) -> Result<NativeTraceResult> {
+/// The frame bookkeeping of a session render: what was reused instead of rebuilt.
+#[napi(object)]
+pub struct NativeSessionReport {
+ /// The session already held the compiled pipeline this frame needed (no shader compile).
+ pub pipeline_reused: bool,
+ /// The acceleration structures were built by an earlier call (no build for this frame).
+ pub acceleration_reused: bool,
+ /// The film and its bind group were kept from the previous frame (same image size).
+ pub film_reused: bool,
+ /// How many frames the session finished before this one.
+ pub frame_index: u32,
+}
+
+#[napi(object)]
+pub struct NativeSessionRenderResult {
+ pub trace: NativeTraceResult,
+ pub session: NativeSessionReport,
+}
+
+/// Renders one frame on a session and resolves the film into the result object.
+fn render_session_frame(
+ session: &mut CyclesSession,
+ options: &NativeCyclesTraceOptions,
+) -> Result<NativeSessionRenderResult> {
let use_atrous_filter = parse_denoise_option(options.denoise.as_deref())?;
- let source = cycles::assemble_cycles_kernel_entry("main", options.bootstrap_kernel.unwrap_or(false))?;
- let pixel_count = options.width as u64 * options.height as u64;
- let accumulation_bytes = image_accumulation_bytes(options.width, options.height);
- let prepared = prepare_cycles_scene(
- &input,
- source,
- options.width,
- options.height,
- options.samples,
- accumulation_bytes,
- )?;
- let groups = image_workgroups(options.width, options.height);
- // Unless the caller fixes the batch, each dispatch is sized from the time of the last so none runs long enough for the
- // driver to reset the device. A wall-clock limit under 2 s keeps one sample per dispatch for tight responsiveness.
- let plan = match options.samples_per_dispatch {
- Some(samples_per_dispatch) => DispatchPlan::Fixed(samples_per_dispatch.max(1)),
- None => match options.max_seconds {
- Some(limit) if limit < 2.0 => DispatchPlan::Fixed(1),
- _ => DispatchPlan::TimeBudget { largest_batch: options.samples.max(1) },
- },
+ let request = CyclesRenderRequest {
+ width: options.width,
+ height: options.height,
+ samples: options.samples,
+ samples_per_dispatch: options.samples_per_dispatch,
+ max_seconds: options.max_seconds,
+ bootstrap_kernel: options.bootstrap_kernel.unwrap_or(false),
+ kernel_params: options.kernel_params.as_deref(),
};
- let trace = trace_cycles_samples(
- &prepared,
- options.samples,
- plan,
- groups,
- accumulation_bytes,
- options.max_seconds,
- )?;
- let (sums, traced_seconds, samples_per_dispatch) = (trace.sums, trace.traced_seconds, trace.largest_batch);
- let resolved = resolve_image(&sums, pixel_count);
+ let render = session.render(&request)?;
+ let pixel_count = options.width as u64 * options.height as u64;
+ let resolved = resolve_image(&render.trace.sums, pixel_count);
+ let context = session.device_context();
let filtered = if use_atrous_filter {
Some(atrous_denoise(
- &prepared.device,
- &prepared.queue,
+ &context.device,
+ &context.queue,
&DenoiseInput {
width: options.width,
height: options.height,
@@ -315,7 +320,7 @@ pub fn trace_scene_cycles(input: NativeTraceInputV2, options: NativeCyclesTraceO
let denoise_seconds = filtered.as_ref().map(|output| output.upload_seconds + output.gpu_seconds + output.readback_seconds);
let denoise_gpu_seconds = filtered.as_ref().map(|output| output.gpu_seconds);
let denoise_compile_seconds = filtered.as_ref().map(|output| output.compile_seconds);
- Ok(NativeTraceResult {
+ let trace = NativeTraceResult {
rgba: Float32Array::new(resolved.rgba),
denoised_rgba: filtered.map(|output| Float32Array::new(output.rgba)),
denoise_seconds,
@@ -326,17 +331,60 @@ pub fn trace_scene_cycles(input: NativeTraceInputV2, options: NativeCyclesTraceO
depth: Float32Array::new(resolved.depth),
variance: Float32Array::new(resolved.variance),
average_samples: resolved.average_samples,
- samples_per_dispatch: Some(samples_per_dispatch),
- longest_dispatch_seconds: trace.longest_dispatch_seconds,
- adapter: prepared.adapter_name,
- backend: prepared.backend_name,
- features: prepared.features,
- setup_seconds: prepared.setup_seconds,
- compile_seconds: prepared.compile_seconds,
- upload_seconds: prepared.upload_seconds,
- acceleration_build_seconds: prepared.acceleration_build_seconds,
- traced_seconds,
- })
+ samples_per_dispatch: Some(render.trace.largest_batch),
+ longest_dispatch_seconds: render.trace.longest_dispatch_seconds,
+ adapter: context.adapter_name.clone(),
+ backend: context.backend_name.clone(),
+ features: context.features.clone(),
+ setup_seconds: render.report.setup_seconds,
+ compile_seconds: render.report.compile_seconds,
+ upload_seconds: render.report.upload_seconds,
+ acceleration_build_seconds: render.report.acceleration_build_seconds,
+ traced_seconds: render.trace.traced_seconds,
+ };
+ let session_report = NativeSessionReport {
+ pipeline_reused: render.report.pipeline_reused,
+ acceleration_reused: render.report.acceleration_reused,
+ film_reused: render.report.film_reused,
+ frame_index: render.report.frame_index,
+ };
+ Ok(NativeSessionRenderResult { trace, session: session_report })
+}
+
+/// Traces a packed `FORMAT-v2` scene on the GPU using the assembled Cycles-parity WGSL kernel: a session that renders once.
+#[napi]
+pub fn trace_scene_cycles(input: NativeTraceInputV2, options: NativeCyclesTraceOptions) -> Result<NativeTraceResult> {
+ parse_denoise_option(options.denoise.as_deref())?;
+ let mut session = CyclesSession::create(&input)?;
+ let rendered = render_session_frame(&mut session, &options)?;
+ Ok(rendered.trace)
+}
+
+/// A scene kept on the GPU between frames (issue 896): the device handle, the scene tables, the acceleration structures,
+/// the compiled pipeline and the film. `createNativeSession` in index.mjs is the way to make one.
+#[napi]
+pub struct NativeCyclesSession {
+ session: CyclesSession,
+}
+
+#[napi]
+impl NativeCyclesSession {
+ #[napi(constructor)]
+ pub fn new(input: NativeTraceInputV2) -> Result<Self> {
+ Ok(NativeCyclesSession { session: CyclesSession::create(&input)? })
+ }
+
+ /// Renders one frame of the session's scene. `options.kernelParams` may bring another camera or render settings of the same scene.
+ #[napi]
+ pub fn render(&mut self, options: NativeCyclesTraceOptions) -> Result<NativeSessionRenderResult> {
+ render_session_frame(&mut self.session, &options)
+ }
+
+ /// Frees the card; every later `render` fails.
+ #[napi]
+ pub fn close(&mut self) {
+ self.session.close();
+ }
}
/// Filters a traced image with the edge-avoiding a-trous wavelet filter on the GPU (spatial only; the result is biased).
diff --git a/tests/native-session.test.js b/tests/native-session.test.js
new file mode 100644
index 00000000..6d564358
--- /dev/null
+++ b/tests/native-session.test.js
@@ -0,0 +1,328 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import {
+ buildNativeInputV2,
+ createNativeSession,
+ findNativeAddon,
+ resolveSessionCreation,
+ resolveSessionFrame,
+ traceNative,
+ wrapNativeSession,
+ KERNEL_PARAMS_V2_FILTER_GLOSSY_BYTE_OFFSET,
+} from '../packages/render-native/index.mjs';
+import { KERNEL_FLAG_WHITE_NOISE_SAMPLER, KERNEL_PARAMS_V2_KERNEL_FLAGS_BYTE_OFFSET } from '../packages/render-native/pack-input-v2.mjs';
+import { createCamera } from '../src/path-tracer.js';
+
+const addonIsBuilt = findNativeAddon() !== null;
+const skipWithoutAddon = addonIsBuilt ? false : 'the native addon is not built';
+const skipWithAddon = addonIsBuilt ? 'the addon is built; this test covers the missing addon' : false;
+
+const UNIT_QUAD = {
+ positions: new Float32Array([-1, -1, 0, 1, -1, 0, 1, 1, 0, -1, 1, 0]),
+ normals: new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]),
+ uvs: new Float32Array([0, 1, 1, 1, 1, 0, 0, 0]),
+ colors: new Float32Array(12).fill(1),
+ indices: new Uint32Array([0, 1, 2, 0, 2, 3]),
+};
+
+const IMAGE_OPTIONS = { width: 24, height: 16, samples: 32, bounces: 3, seed: 11 };
+const RESULT_PLANES = ['rgba', 'albedo', 'normal', 'depth', 'variance'];
+const MATERIAL_COUNT_BYTE_OFFSET = 92;
+
+function horizontalQuadMatrix(scale, height, facesUp) {
+ const upOrDown = facesUp ? 1 : -1;
+ return [scale, 0, 0, 0, 0, 0, -upOrDown * scale, 0, 0, upOrDown * scale, 0, 0, 0, height, 0, 1];
+}
+
+// A lit floor with two emissive ceiling quads, so light picking and several bounces take part.
+function buildRoomScene() {
+ return {
+ materials: [{ color: [0.6, 0.6, 0.6], roughness: 0.8 }, { color: [1, 0.95, 0.9], emission: 5, roughness: 1 }],
+ instances: [
+ { geometry: UNIT_QUAD, matrix: horizontalQuadMatrix(8, 0, true), materialIndex: 0 },
+ { geometry: UNIT_QUAD, matrix: horizontalQuadMatrix(2, 3, false), materialOverride: 1 },
+ { geometry: UNIT_QUAD, matrix: horizontalQuadMatrix(1, 2, false), materialOverride: 1 },
+ ],
+ };
+}
+
+function roomInput(eye, options = IMAGE_OPTIONS) {
+ const camera = createCamera({ eye, target: [0, 0.5, 0], fov: 45 }, options.width, options.height);
+ return buildNativeInputV2(buildRoomScene(), camera, options);
+}
+
+function bytesOf(result, plane) {
+ const values = result[plane];
+ return Buffer.from(values.buffer, values.byteOffset, values.byteLength);
+}
+
+function assertSameBytes(first, second, message) {
+ for (const plane of RESULT_PLANES) {
+ assert.ok(bytesOf(first, plane).equals(bytesOf(second, plane)), `${message}: the ${plane} plane differs`);
+ }
+}
+
+function readKernelFlags(kernelParams) {
+ return new DataView(kernelParams.buffer, kernelParams.byteOffset, kernelParams.byteLength).getUint32(KERNEL_PARAMS_V2_KERNEL_FLAGS_BYTE_OFFSET, true);
+}
+
+// ---- Argument checks: these run without the addon ----
+
+test('createNativeSession refuses an input that is not FORMAT-v2', () => {
+ assert.throws(() => createNativeSession(undefined), { name: 'TypeError', message: /FORMAT-v2 input object/ });
+ assert.throws(() => createNativeSession(null), { name: 'TypeError' });
+ assert.throws(() => createNativeSession({ schemaVersion: 1 }), { name: 'TypeError', message: /schemaVersion.*must be 2/ });
+ assert.throws(() => createNativeSession({ triangles: new Float32Array(36), triangleCount: 1 }), { name: 'TypeError', message: /schemaVersion/ });
+});
+
+test('createNativeSession refuses a kernel parameter block of the wrong size', () => {
+ const input = roomInput([0, 2.2, 6]);
+ assert.throws(
+ () => createNativeSession({ ...input, kernelParams: new Uint8Array(12) }),
+ { name: 'TypeError', message: /320 bytes/ }
+ );
+ assert.throws(() => createNativeSession({ ...input, kernelParams: undefined }), { name: 'TypeError', message: /kernelParams/ });
+});
+
+test('createNativeSession runs the cycles kernel only', () => {
+ const input = roomInput([0, 2.2, 6]);
+ assert.throws(() => createNativeSession(input, { kernel: 'legacy' }), { name: 'TypeError', message: /"cycles" kernel only/ });
+ assert.throws(() => createNativeSession(input, { kernel: 'nonsense' }), { message: /Invalid native kernel/ });
+ assert.throws(() => createNativeSession(input, null), { name: 'TypeError', message: /options/ });
+});
+
+test('createNativeSession checks its default options like traceNative does', () => {
+ const input = roomInput([0, 2.2, 6]);
+ assert.throws(() => createNativeSession(input, { samples: 0 }), { name: 'RangeError', message: /samples/ });
+ assert.throws(() => createNativeSession(input, { sampler: 'nonsense' }), { message: /sampler/ });
+ assert.throws(() => createNativeSession(input, { pathRegeneration: 'yes' }), { name: 'TypeError', message: /pathRegeneration/ });
+ assert.throws(() => createNativeSession(input, { maxSeconds: -1 }), { name: 'RangeError', message: /maxSeconds/ });
+});
+
+test('createNativeSession without the built addon says how to build it', { skip: skipWithAddon }, () => {
+ assert.throws(() => createNativeSession(roomInput([0, 2.2, 6])), { message: /not built/ });
+});
+
+test('a session input carries the kernel parameters patched by the default options', () => {
+ const input = roomInput([0, 2.2, 6]);
+ const unpatchedFlags = readKernelFlags(input.kernelParams);
+ assert.equal(unpatchedFlags & KERNEL_FLAG_WHITE_NOISE_SAMPLER, 0, 'the packed input uses the blue-noise sampler');
+ const sessionInput = resolveSessionCreation(input, { sampler: 'white' });
+ assert.notEqual(readKernelFlags(sessionInput.kernelParams) & KERNEL_FLAG_WHITE_NOISE_SAMPLER, 0);
+ assert.equal(readKernelFlags(input.kernelParams), unpatchedFlags, 'the caller input is not modified');
+});
+
+test('a frame needs the size and the samples, from the defaults or from the call', () => {
+ const sessionInput = resolveSessionCreation(roomInput([0, 2.2, 6]), { width: 24, height: 16 });
+ assert.throws(
+ () => resolveSessionFrame(sessionInput, { width: 24, height: 16 }, {}),
+ { name: 'TypeError', message: /samples/ }
+ );
+ const frame = resolveSessionFrame(sessionInput, { width: 24, height: 16 }, { samples: 8 });
+ assert.equal(frame.width, 24);
+ assert.equal(frame.height, 16);
+ assert.equal(frame.samples, 8);
+ assert.equal(frame.kernelParams.byteLength, 320);
+});
+
+test('a frame option replaces the default and an undefined one does not', () => {
+ const sessionInput = resolveSessionCreation(roomInput([0, 2.2, 6]), {});
+ const defaults = { width: 24, height: 16, samples: 32 };
+ const frame = resolveSessionFrame(sessionInput, defaults, { samples: 64, width: undefined });
+ assert.equal(frame.samples, 64);
+ assert.equal(frame.width, 24);
+});
+
+test('a frame patches the sampler flag on its own copy of the parameters', () => {
+ const sessionInput = resolveSessionCreation(roomInput([0, 2.2, 6]), {});
+ const defaults = { width: 24, height: 16, samples: 4 };
+ const white = resolveSessionFrame(sessionInput, defaults, { sampler: 'white' });
+ const blueNoise = resolveSessionFrame(sessionInput, defaults, { sampler: 'sobol-burley' });
+ assert.notEqual(readKernelFlags(white.kernelParams) & KERNEL_FLAG_WHITE_NOISE_SAMPLER, 0);
+ assert.equal(readKernelFlags(blueNoise.kernelParams) & KERNEL_FLAG_WHITE_NOISE_SAMPLER, 0);
+ assert.equal(readKernelFlags(sessionInput.kernelParams) & KERNEL_FLAG_WHITE_NOISE_SAMPLER, 0);
+});
+
+test('a frame patches the glossy filter into the parameters it was given', () => {
+ const sessionInput = resolveSessionCreation(roomInput([0, 2.2, 6]), {});
+ const defaults = { width: 24, height: 16, samples: 4 };
+ const frame = resolveSessionFrame(sessionInput, defaults, { filterGlossy: 0 });
+ const view = new DataView(frame.kernelParams.buffer, frame.kernelParams.byteOffset, frame.kernelParams.byteLength);
+ assert.equal(view.getFloat32(KERNEL_PARAMS_V2_FILTER_GLOSSY_BYTE_OFFSET, true), 0);
+});
+
+test('a frame takes the camera of another packing through kernelParams', () => {
+ const first = roomInput([0, 2.2, 6]);
+ const second = roomInput([1.5, 2.2, 5]);
+ assert.notDeepEqual(first.kernelParams, second.kernelParams);
+ const sessionInput = resolveSessionCreation(first, {});
+ const defaults = { width: 24, height: 16, samples: 4 };
+ const frame = resolveSessionFrame(sessionInput, defaults, { kernelParams: second.kernelParams });
+ assert.deepEqual(frame.kernelParams, second.kernelParams);
+ assert.throws(
+ () => resolveSessionFrame(sessionInput, defaults, { kernelParams: new Uint8Array(8) }),
+ { name: 'TypeError', message: /320 bytes/ }
+ );
+});
+
+test('a frame refuses the legacy kernel, bad options and a bad options object', () => {
+ const sessionInput = resolveSessionCreation(roomInput([0, 2.2, 6]), {});
+ const defaults = { width: 24, height: 16, samples: 4 };
+ assert.throws(() => resolveSessionFrame(sessionInput, defaults, { kernel: 'legacy' }), { name: 'TypeError', message: /"cycles" kernel only/ });
+ assert.throws(() => resolveSessionFrame(sessionInput, defaults, { samples: 1.5 }), { name: 'RangeError', message: /integer/ });
+ assert.throws(() => resolveSessionFrame(sessionInput, defaults, null), { name: 'TypeError', message: /renderOptions/ });
+});
+
+test('a wrapped session passes the frame to the addon and joins the reuse flags to the result', () => {
+ const sessionInput = resolveSessionCreation(roomInput([0, 2.2, 6]), {});
+ const calls = [];
+ const nativeSession = {
+ render(frame) {
+ calls.push(frame);
+ return { trace: { rgba: new Float32Array(4), tracedSeconds: 0.5 }, session: { pipelineReused: calls.length > 1, frameIndex: calls.length - 1 } };
+ },
+ close() {
+ calls.push('closed');
+ },
+ };
+ const session = wrapNativeSession(nativeSession, sessionInput, { width: 24, height: 16 });
+ const first = session.render({ samples: 4 });
+ const second = session.render({ samples: 8 });
+ assert.equal(calls[0].samples, 4);
+ assert.equal(calls[1].samples, 8);
+ assert.equal(first.pipelineReused, false);
+ assert.equal(second.pipelineReused, true);
+ assert.equal(second.frameIndex, 1);
+ assert.equal(second.tracedSeconds, 0.5);
+ assert.equal(session.closed, false);
+});
+
+test('a closed session refuses to render and closing twice frees the card once', () => {
+ const sessionInput = resolveSessionCreation(roomInput([0, 2.2, 6]), {});
+ const calls = [];
+ const nativeSession = {
+ render() {
+ calls.push('render');
+ return { trace: {}, session: {} };
+ },
+ close() {
+ calls.push('close');
+ },
+ };
+ const session = wrapNativeSession(nativeSession, sessionInput, {});
+ session.close();
+ session.close();
+ assert.equal(session.closed, true);
+ assert.throws(() => session.render({ width: 24, height: 16, samples: 4 }), { message: /closed/ });
+ assert.deepEqual(calls, ['close']);
+});
+
+// ---- Renders on the GPU ----
+
+test('a session render equals the one-shot render byte for byte and the second frame reuses the setup', { skip: skipWithoutAddon }, () => {
+ const input = roomInput([0, 2.2, 6]);
+ const options = { ...IMAGE_OPTIONS, kernel: 'cycles' };
+ const oneShot = traceNative(input, options);
+ const session = createNativeSession(input);
+ try {
+ const first = session.render(options);
+ assertSameBytes(oneShot, first, 'the first session frame against the one-shot render');
+ assert.equal(first.frameIndex, 0);
+ assert.equal(first.accelerationReused, false);
+ assert.equal(first.pipelineReused, false);
+ assert.equal(first.filmReused, false);
+
+ const second = session.render(options);
+ assertSameBytes(oneShot, second, 'the second session frame against the one-shot render');
+ assert.equal(second.frameIndex, 1);
+ assert.equal(second.accelerationReused, true);
+ assert.equal(second.pipelineReused, true);
+ assert.equal(second.filmReused, true);
+ assert.equal(second.accelerationBuildSeconds, 0);
+ assert.equal(second.setupSeconds, 0);
+ } finally {
+ session.close();
+ }
+});
+
+test('a frame that changes only the camera equals a fresh one-shot render of that camera', { skip: skipWithoutAddon }, () => {
+ const firstInput = roomInput([0, 2.2, 6]);
+ const secondInput = roomInput([1.5, 2.2, 5]);
+ const options = { ...IMAGE_OPTIONS, kernel: 'cycles' };
+ const session = createNativeSession(firstInput);
+ try {
+ const firstFrame = session.render(options);
+ const movedFrame = session.render({ ...options, kernelParams: secondInput.kernelParams });
+ assertSameBytes(traceNative(secondInput, options), movedFrame, 'the moved camera against a one-shot render of it');
+ assert.ok(!bytesOf(firstFrame, 'rgba').equals(bytesOf(movedFrame, 'rgba')), 'the two cameras must give different images');
+ assert.equal(movedFrame.accelerationReused, true);
+ assert.equal(movedFrame.pipelineReused, true);
+ assert.equal(movedFrame.accelerationBuildSeconds, 0);
+ const backFrame = session.render(options);
+ assertSameBytes(firstFrame, backFrame, 'the first camera again');
+ } finally {
+ session.close();
+ }
+});
+
+test('a frame with another sample count or image size equals the one-shot render and keeps what it can', { skip: skipWithoutAddon }, () => {
+ const input = roomInput([0, 2.2, 6]);
+ const options = { ...IMAGE_OPTIONS, kernel: 'cycles' };
+ const session = createNativeSession(input);
+ try {
+ session.render(options);
+ const moreSamples = session.render({ ...options, samples: 48 });
+ assertSameBytes(traceNative(input, { ...options, samples: 48 }), moreSamples, 'another sample count');
+ assert.equal(moreSamples.filmReused, true);
+ assert.equal(moreSamples.pipelineReused, true);
+
+ const larger = session.render({ ...options, width: 32, height: 20 });
+ assertSameBytes(traceNative(input, { ...options, width: 32, height: 20 }), larger, 'another image size');
+ assert.equal(larger.filmReused, false);
+ assert.equal(larger.pipelineReused, true);
+ assert.equal(larger.accelerationReused, true);
+ assert.equal(larger.rgba.length, 32 * 20 * 4);
+ } finally {
+ session.close();
+ }
+});
+
+test('a session takes its default options and a frame option overrides them', { skip: skipWithoutAddon }, () => {
+ const input = roomInput([0, 2.2, 6]);
+ const options = { ...IMAGE_OPTIONS, kernel: 'cycles' };
+ const session = createNativeSession(input, { ...IMAGE_OPTIONS, sampler: 'white' });
+ try {
+ assertSameBytes(traceNative(input, { ...options, sampler: 'white' }), session.render({}), 'the default sampler');
+ assertSameBytes(traceNative(input, { ...options, sampler: 'sobol-burley' }), session.render({ sampler: 'sobol-burley' }), 'a frame sampler');
+ } finally {
+ session.close();
+ }
+});
+
+test('a frame of another scene is refused', { skip: skipWithoutAddon }, () => {
+ const input = roomInput([0, 2.2, 6]);
+ const session = createNativeSession(input);
+ try {
+ const otherScene = new Uint8Array(input.kernelParams);
+ new DataView(otherScene.buffer).setUint32(MATERIAL_COUNT_BYTE_OFFSET, 9, true);
+ assert.throws(() => session.render({ ...IMAGE_OPTIONS, kernelParams: otherScene }), { message: /materialCount/ });
+ assert.ok(session.render(IMAGE_OPTIONS).rgba.every(Number.isFinite), 'the session still renders after a refused frame');
+ } finally {
+ session.close();
+ }
+});
+
+test('rendering after close throws and the card is free for a new session', { skip: skipWithoutAddon }, () => {
+ const input = roomInput([0, 2.2, 6]);
+ const options = { ...IMAGE_OPTIONS, kernel: 'cycles' };
+ const session = createNativeSession(input);
+ session.render(options);
+ session.close();
+ assert.throws(() => session.render(options), { message: /closed/ });
+ const fresh = createNativeSession(input);
+ try {
+ assertSameBytes(traceNative(input, options), fresh.render(options), 'a new session after a close');
+ } finally {
+ fresh.close();
+ }
+});