> 开发分支文档 — commit c5a119d39ba4c149dc90ed5711c4e76759080b41
> 包版本: @zenfg/webgpu 0.2.0, @zenfg/snapshot 0.1.1, @zenfg/inspector 0.2.0, zenfg 0.2.0, zenfg-snapshot 0.1.1
> Source: https://github.com/uinosoft/zenfg/blob/c5a119d39ba4c149dc90ed5711c4e76759080b41/packages/webgpu/examples/persistent-state.ts

# webgpu: persistent-state

此页展示完整、经过编译检查的包内示例。设备和应用状态由调用方管理。代码保留英文。

```ts
/**
 * Source: Original ZenFG package recipe.
 * Demonstrates: Defined contents and state carried between frames.
 * Flow: Import persistent buffers, record updates and retain them with a persistent-state root.
 * The caller owns the device and native inputs; ZenFG owns graph execution.
 * Read next: README.md for inputs and related recipes. The Examples adapter
 * and recipeHost.ts provide browser setup and snapshot capture.
 */
import { FrameGraph, type FrameGraphRecording } from '@zenfg/webgpu';

export type PersistentStateRecordOptions = {
	readonly recorder: FrameGraphRecording;
	readonly historyTexture: GPUTexture;
	readonly hasPreviousValue: boolean;
	readonly encodeUpdate: (pass: GPURenderPassEncoder) => undefined;
};

export type PersistentStateOptions = {
	readonly graph: FrameGraph;
	readonly historyTexture: GPUTexture;
	readonly hasPreviousValue: boolean;
	readonly frameIndex: number;
	readonly encodeUpdate: (pass: GPURenderPassEncoder) => undefined;
};

/** Declares an update of caller-owned state without compiling it. */
export function recordPersistentStateUpdate(options: PersistentStateRecordOptions): void {
	const history = options.recorder.importTexture(options.historyTexture, {
		label: 'temporal-history',
		initialContents: options.hasPreviousValue ? 'defined' : 'undefined',
	});

	options.recorder.render({
		label: 'update-history',
		colorAttachments: [{
			target: history,
			loadOp: options.hasPreviousValue ? 'load' : 'clear',
			storeOp: 'store',
			clearValue: { r: 0, g: 0, b: 0, a: 0 },
		}],
		encode({ pass }) {
			return options.encodeUpdate(pass);
		},
	});

	options.recorder.markPersistentState(history);
}

/** Updates a caller-owned history texture and retains its final producer. */
export function updatePersistentState(options: PersistentStateOptions): void {
	const recorder = options.graph.beginFrame();
	recordPersistentStateUpdate({
		recorder,
		historyTexture: options.historyTexture,
		hasPreviousValue: options.hasPreviousValue,
		encodeUpdate: options.encodeUpdate,
	});
	recorder.compile().execute({ frameIndex: options.frameIndex });
}

```
