feat(web): studio worlds, camera-view/offscreen environment parity, material and undo coverage
Some checks failed
M6 deployable RC / quick (push) Has been cancelled
M6 deployable RC / chromium (push) Has been cancelled
M6 deployable RC / release (push) Has been cancelled

Environment lighting:
- ship all eight desktop studiolights/world datasets (WBENV1 float32) and a
  shared loader used by both the main viewport and the offscreen worker
- add the N-panel "studio 环境" selector
- rotate the world background together with the environment
  (backgroundRotation/backgroundIntensity), so camera view and offscreen
  renders match the desktop Mapping-node behaviour

Verification (Chromium, OPFS, NOT_CLAIMED):
- environment lighting + 8 world pixel identity
- camera-view rotation correspondence (camera matrices, 207 samples)
- offscreen vs on-screen background parity after hiding geometry (1305 samples)
- metals case extended with material-field OPFS roundtrip
- material Principled edits and rename undo/redo
- eight studio worlds: pairwise frame differences + luminance rank correlation
- undo history depth capped at 64 steps and undo across OPFS save/reopen

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
mes123456
2026-11-23 09:27:47 +08:00
parent f96654b158
commit 63db6caf1f
325 changed files with 20004 additions and 762 deletions

View File

@@ -1,20 +1,20 @@
import { loadAssetCatalogIndexedDBSnapshot } from "../storage/asset-catalog-indexeddb";
import { openKvDatabase, type KvDatabase } from "../storage/opfs-kv";
const scope = self as unknown as {
onmessage: ((event: MessageEvent<{ databaseName: string }>) => void) | null;
onmessage: ((event: MessageEvent<{ databaseName: string; stores?: string[] }>) => void) | null;
postMessage: (value: unknown) => void;
};
function openDatabase(name: string): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
const request = indexedDB.open(name);
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error ?? new Error("Catalog restart database open failed"));
});
// Metadata lives in OPFS, so the restart probe opens the same store set the
// storage worker uses instead of a real IndexedDB database.
function openDatabase(name: string, stores: readonly string[]): Promise<KvDatabase> {
return openKvDatabase(name, stores);
}
scope.onmessage = (event): void => {
void openDatabase(event.data.databaseName).then(async (database) => {
const stores = event.data.stores ?? ["setting", "migration"];
void openDatabase(event.data.databaseName, stores).then(async (database) => {
try {
return await loadAssetCatalogIndexedDBSnapshot(database);
}

View File

@@ -0,0 +1,184 @@
import createAssimp from "../vendor/assimp/assimpjs.js";
import assimpWasmUrl from "../vendor/assimp/assimpjs.wasm?url";
type ConvertRequest = { id: number; name: string; buffer: ArrayBuffer };
type Assimp = {
HEAPU8: Uint8Array;
_ajs_alloc(size: number): number;
_ajs_free(pointer: number): void;
_ajs_convert(name: number, data: number, size: number, format: number): number;
_ajs_success(handle: number): number;
_ajs_file_count(handle: number): number;
_ajs_file_data(handle: number, index: number): number;
_ajs_file_size(handle: number, index: number): number;
_ajs_error(handle: number): number;
_ajs_result_free(handle: number): void;
};
const GLB_MAGIC = 0x46546c67;
const JSON_CHUNK = 0x4e4f534a;
const BIN_CHUNK = 0x004e4942;
let factoryPromise: Promise<Assimp> | null = null;
function loadAssimp(): Promise<Assimp> {
if (!factoryPromise) {
factoryPromise = (createAssimp as unknown as (options?: Record<string, unknown>) => Promise<Assimp>)({
locateFile: () => assimpWasmUrl,
});
}
return factoryPromise;
}
function parseGlb(bytes: Uint8Array): { json: any; bin: Uint8Array | null } {
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
if (view.getUint32(0, true) !== GLB_MAGIC) throw new Error("GLB_MAGIC_INVALID");
const total = view.getUint32(8, true);
let offset = 12;
let json: any = null;
let bin: Uint8Array | null = null;
while (offset + 8 <= total) {
const length = view.getUint32(offset, true);
const type = view.getUint32(offset + 4, true);
const chunk = bytes.subarray(offset + 8, offset + 8 + length);
if (type === JSON_CHUNK) json = JSON.parse(new TextDecoder().decode(chunk));
else if (type === BIN_CHUNK) bin = chunk;
offset += 8 + length;
}
if (!json) throw new Error("GLB_JSON_MISSING");
return { json, bin };
}
function encodeGlb(json: any, bin: Uint8Array | null): Uint8Array {
const text = new TextEncoder().encode(JSON.stringify(json));
const jsonLength = Math.ceil(text.length / 4) * 4;
const binLength = bin ? Math.ceil(bin.length / 4) * 4 : 0;
const total = 12 + 8 + jsonLength + (bin ? 8 + binLength : 0);
const out = new Uint8Array(total);
const view = new DataView(out.buffer);
view.setUint32(0, GLB_MAGIC, true);
view.setUint32(4, 2, true);
view.setUint32(8, total, true);
view.setUint32(12, jsonLength, true);
view.setUint32(16, JSON_CHUNK, true);
out.set(text, 20);
out.fill(0x20, 20 + text.length, 20 + jsonLength);
if (bin) {
const binOffset = 20 + jsonLength;
view.setUint32(binOffset, binLength, true);
view.setUint32(binOffset + 4, BIN_CHUNK, true);
out.set(bin, binOffset + 8);
}
return out;
}
/**
* Assimp exports a Collada node with N geometries as one glTF mesh holding N
* primitives, which Blender imports as a single object. The assjson pass keeps
* the source geometry names, so split the primitive run back into one child
* node per geometry. This is a pure JSON restructure; accessors and buffer
* views are shared, no geometry is recomputed.
*/
function splitMeshByGeometry(json: any, names: string[]): number {
const nodes: any[] = json.nodes ?? [];
if (names.length < 2) return 1;
const nodeIndex = nodes.findIndex((node: any) =>
Number.isInteger(node.mesh) && json.meshes?.[node.mesh]?.primitives?.length === names.length);
if (nodeIndex < 0) return 1;
const node = nodes[nodeIndex];
if (node.children?.length) return 1;
const meshIndex: number = node.mesh;
const mergedMesh = json.meshes[meshIndex];
const primitives = mergedMesh.primitives as unknown[];
const groups: { name: string; start: number; end: number }[] = [];
let start = 0;
for (let index = 1; index <= names.length; index++) {
if (index === names.length || names[index] !== names[start]) {
groups.push({ name: names[start], start, end: index });
start = index;
}
}
if (groups.length < 2) return 1;
json.meshes.splice(meshIndex, 1);
for (const other of nodes) if (Number.isInteger(other.mesh) && other.mesh > meshIndex) other.mesh--;
/* The merged mesh no longer exists; leaving the stale index on the node would make the
* native glTF importer turn the parent empty into a duplicate mesh object. */
delete node.mesh;
const children: number[] = [];
for (const group of groups) {
json.meshes.push({ ...mergedMesh, name: group.name, primitives: primitives.slice(group.start, group.end) });
nodes.push({ name: group.name, mesh: json.meshes.length - 1 });
children.push(nodes.length - 1);
}
node.children = children;
return groups.length;
}
self.onmessage = async (event: MessageEvent<ConvertRequest>) => {
const { id, name, buffer } = event.data;
try {
const ajs = await loadAssimp();
/* The rebuild exports plain C functions instead of embind: embind compiles each invoker
* with `new Function` (craftInvokerFunction), which the app CSP rejects. Data crosses the
* boundary through HEAPU8 only. */
const encoder = new TextEncoder();
const decoder = new TextDecoder();
const writeString = (text: string): number => {
const bytes = encoder.encode(`${text}\0`);
const pointer = ajs._ajs_alloc(bytes.byteLength);
ajs.HEAPU8.set(bytes, pointer);
return pointer;
};
const readString = (pointer: number): string => {
let end = pointer;
while (ajs.HEAPU8[end] !== 0) end++;
return decoder.decode(ajs.HEAPU8.subarray(pointer, end));
};
const convert = (format: string): Uint8Array => {
const namePointer = writeString(name);
const formatPointer = writeString(format);
const inputPointer = ajs._ajs_alloc(buffer.byteLength);
ajs.HEAPU8.set(new Uint8Array(buffer), inputPointer);
let handle = -1;
try {
handle = ajs._ajs_convert(namePointer, inputPointer, buffer.byteLength, formatPointer);
}
finally {
ajs._ajs_free(inputPointer);
ajs._ajs_free(formatPointer);
ajs._ajs_free(namePointer);
}
const error = readString(ajs._ajs_error(handle));
const succeeded = ajs._ajs_success(handle) === 1 && ajs._ajs_file_count(handle) > 0;
let output = new Uint8Array(0);
if (succeeded) {
const size = ajs._ajs_file_size(handle, 0);
const pointer = ajs._ajs_file_data(handle, 0);
output = new Uint8Array(ajs.HEAPU8.subarray(pointer, pointer + size));
}
ajs._ajs_result_free(handle);
if (!succeeded || output.byteLength === 0) {
const code = format === "assjson" ? "COLLADA_PARSE_FAILED" : "COLLADA_CONVERT_FAILED";
throw new Error(`${code}: ${error || "unknown error"}`);
}
return output;
};
const sceneJson = JSON.parse(decoder.decode(convert("assjson"))) as { meshes?: { name?: string }[] };
const names = (sceneJson.meshes ?? []).map((mesh) => mesh.name ?? "");
const bytes = convert("glb2");
const { json, bin } = parseGlb(bytes);
const objects = splitMeshByGeometry(json, names);
const output = objects > 1 ? encodeGlb(json, bin) : bytes;
self.postMessage({
id,
ok: true,
glb: output.buffer,
stats: { objects, meshes: json.meshes?.length ?? 0, primitives: names.length, bytes: output.byteLength },
}, { transfer: [output.buffer] } as unknown as StructuredSerializeOptions);
}
catch (error) {
/* The status bar shows this text verbatim; a stack trace belongs in diagnostics. */
self.postMessage({ id, ok: false, error: error instanceof Error ? error.message : String(error) });
}
};

View File

@@ -3,8 +3,9 @@ import { normalizeProjectAssetPath } from "../../../protocol/asset-path";
import { isEditorResourcePath } from '../../../protocol/editor-resource-path';
import { parseLODCacheRecord, type LODCacheRecord } from "../../../protocol/lod";
import { planSimulationCacheLRU, selectSimulationCacheFrame, simulationCacheKey, SimulationCacheValidationError, verifySimulationCacheCancellable, verifySimulationCacheFrame, verifySimulationCacheRevisionBinding, type SimulationCacheManifestIR } from "../../../protocol/simulation-cache";
import { STORAGE_DATABASE_NAME, STORAGE_SCHEMA_VERSION, STORAGE_STORES, upgradeStorageSchema } from "../storage/migrations";
import { deleteContentAsset, deleteLodCache, deleteProjectSnapshot, ensureProjectLayout, measureProjectVDBBytes, projectLayout, readContentAsset, readContentAssetRange, readLodCache, readProjectBlend, readProjectSnapshot, recoverProjectBlend, removeOrphanContentAssets, validateSha256, writeContentAsset, writeLodCache, writeProjectBlend, writeProjectSnapshot, type ProjectSaveFault } from "../storage/opfs-files";
import { STORAGE_DATABASE_NAME, STORAGE_SCHEMA_VERSION, STORAGE_STORES } from "../storage/migrations";
import { deleteContentAsset, deleteLodCache, deleteProjectSnapshot, ensureProjectLayout, measureProjectVDBBytes, projectLayout, readContentAsset, readContentAssetRange, readLodCache, readProjectBlend, readProjectSnapshot, recoverProjectBlend, removeOrphanContentAssets, validateSha256, writeContentAsset, writeLodCache, writeProjectBlend, writeProjectSnapshot, type OpfsProjectLayout, type ProjectSaveFault } from "../storage/opfs-files";
import { openKvDatabase, type KvDatabase, type KvTransaction } from "../storage/opfs-kv";
import { classifyRecentProjectIdentity, createRecentProjectIndex, parseRecentProjectIndex, parseRecentProjectRecord, removeRecentProject, upsertRecentProject, type RecentProjectIdentity, type RecentProjectIndex, type RecentProjectIssue, type RecentProjectRecord } from "../../../protocol/recent-projects";
import { createStorageBudget } from "../../../protocol/storage-budget";
import { applyUdimTilePatch } from "../../../protocol/paint";
@@ -64,21 +65,34 @@ interface WorkerLockManager {
request<T>(name: string, callback: () => Promise<T>): Promise<T>;
}
async function useOpfsForProject(projectId: string): Promise<boolean> {
if (opfsUsable !== undefined) return opfsUsable;
const OPFS_REQUIRED = "OPFS is unavailable: Web Blender keeps every work file in OPFS";
// Every project file lives in OPFS, so a missing `getDirectory` is a hard
// error rather than a reason to fall back to another backend.
//
// Only success is cached. A cache of the failure would turn one transient
// error (a quota blip, a half-written layout) into every later storage call in
// this worker failing until the Worker restarts; with no fallback behind it
// that is a far worse trade than re-probing the two cheap calls above.
async function requireProjectLayout(projectId: string): Promise<OpfsProjectLayout> {
if (opfsUsable === false) throw storageError("STORAGE_TRANSACTION", OPFS_REQUIRED);
const workerNavigator = (self as unknown as { navigator?: Navigator }).navigator;
if (!workerNavigator?.storage || typeof (workerNavigator.storage as StorageManager & { getDirectory?: unknown }).getDirectory !== "function") {
opfsUsable = false;
return false;
throw storageError("STORAGE_TRANSACTION", OPFS_REQUIRED);
}
try {
await ensureProjectLayout(projectId);
const layout = await ensureProjectLayout(projectId);
opfsUsable = true;
return layout;
}
catch {
opfsUsable = false;
catch (error) {
if (error instanceof Error && error.message === "OPFS is unavailable") {
opfsUsable = false;
throw storageError("STORAGE_TRANSACTION", OPFS_REQUIRED);
}
throw error;
}
return opfsUsable;
}
async function withProjectTransaction<T>(projectId: string, operation: () => Promise<T>): Promise<T> {
@@ -107,20 +121,19 @@ async function withRecentProjectsTransaction<T>(operation: () => Promise<T>): Pr
return result;
}
function openDatabase(): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
const request = indexedDB.open(STORAGE_DATABASE_NAME, STORAGE_SCHEMA_VERSION);
request.onupgradeneeded = (event) => upgradeStorageSchema(request.result, request.transaction!, (event as IDBVersionChangeEvent).oldVersion);
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error ?? new Error("IndexedDB open failed"));
});
// Metadata rows (project index, snapshots, operation log, asset index, LOD and
// simulation manifests) live in OPFS, not IndexedDB: the project rule is that
// every work file lives in OPFS. `openKvDatabase` reproduces the small IDB
// surface these call sites use, so the row logic below stays as written.
function openDatabase(): Promise<KvDatabase> {
return openKvDatabase(STORAGE_DATABASE_NAME, STORAGE_STORES);
}
function storeNames(db: IDBDatabase): string[] {
function storeNames(db: KvDatabase): string[] {
return [...STORAGE_STORES].filter((name) => db.objectStoreNames.contains(name));
}
async function withDatabase<T>(operation: (db: IDBDatabase) => Promise<T>): Promise<T> {
async function withDatabase<T>(operation: (db: KvDatabase) => Promise<T>): Promise<T> {
const db = await openDatabase();
try {
return await operation(db);
@@ -134,7 +147,7 @@ async function info(): Promise<StorageInfoResult> {
const db = await openDatabase();
const workerNavigator = (self as unknown as { navigator?: Navigator }).navigator;
const result = {
backend: "indexeddb" as const,
backend: "opfs" as const,
opfsAvailable: Boolean(workerNavigator?.storage && "getDirectory" in workerNavigator.storage),
schemaVersion: STORAGE_SCHEMA_VERSION,
stores: storeNames(db),
@@ -143,12 +156,12 @@ async function info(): Promise<StorageInfoResult> {
return result;
}
function transactionComplete(transaction: IDBTransaction): Promise<void> {
return new Promise((resolve, reject) => {
transaction.oncomplete = () => resolve();
transaction.onerror = () => reject(transaction.error ?? new Error("IndexedDB transaction failed"));
transaction.onabort = () => reject(transaction.error ?? new Error("IndexedDB transaction aborted"));
});
async function transactionComplete(transaction: KvTransaction): Promise<void> {
// `done` settles when every operation queued on the transaction has landed.
// Per-request failures still surface through each request's `onerror`, so a
// caller that awaited only this would miss them; callers here await both.
try { await transaction.done; }
catch (error) { throw transaction.error ?? (error instanceof Error ? error : new Error("Storage transaction failed")); }
}
interface LODManifestRow {
@@ -183,8 +196,7 @@ interface ProjectRow {
sha256: string;
updatedAt: string;
scenePath: string;
backend: "opfs" | "indexeddb";
buffer?: ArrayBuffer;
backend: "opfs";
}
interface SettingRow {
@@ -221,13 +233,7 @@ async function writeRecentProjectIndex(index: RecentProjectIndex): Promise<void>
db.close();
}
async function readCommittedProjectIdentity(projectId: string, row: ProjectRow): Promise<RecentProjectIdentity | undefined> {
if (row.backend === "indexeddb") {
if (!row.buffer || row.buffer.byteLength !== row.bytes) return undefined;
const sha256 = await sha256Hex(row.buffer);
return { revision: row.revision, bytes: row.bytes, sha256 };
}
if (!await useOpfsForProject(projectId)) return { revision: row.revision, bytes: row.bytes, sha256: row.sha256 };
async function readCommittedProjectIdentity(projectId: string): Promise<RecentProjectIdentity | undefined> {
const recovery = await recoverProjectBlend(projectId);
if (!recovery.manifest) return undefined;
return { revision: recovery.manifest.revision, bytes: recovery.manifest.bytes, sha256: recovery.manifest.sha256 };
@@ -240,7 +246,7 @@ async function inspectRecentProject(project: RecentProjectRecord): Promise<Recen
const row = await readProjectRow(project.projectId);
if (!row) return { project, code: "MISSING" };
const rowIdentity = { revision: row.revision, bytes: row.bytes, sha256: row.sha256 };
const committed = await readCommittedProjectIdentity(project.projectId, row);
const committed = await readCommittedProjectIdentity(project.projectId);
const metadataIssue = classifyRecentProjectIdentity(rowIdentity, committed);
if (metadataIssue) return { project, code: metadataIssue };
const issue = classifyRecentProjectIdentity(project, committed);
@@ -391,7 +397,7 @@ async function smoke() {
const value = await new Promise<{ id: number; value: string } | undefined>((resolve, reject) => {
const request = read.objectStore("smoke").get(1);
request.onsuccess = () => resolve(request.result as { id: number; value: string } | undefined);
request.onerror = () => reject(request.error ?? new Error("IndexedDB read failed"));
request.onerror = () => reject(request.error ?? new Error("Storage read failed"));
});
await transactionComplete(read);
const stores = storeNames(db);
@@ -399,7 +405,7 @@ async function smoke() {
const workerNavigator = (self as unknown as { navigator?: Navigator }).navigator;
return {
backend: "indexeddb" as const,
backend: "opfs" as const,
opfsAvailable: Boolean(workerNavigator?.storage && "getDirectory" in workerNavigator.storage),
rowCount: value?.value === "ready" ? 1 : 0,
persisted: value?.value === "ready",
@@ -409,8 +415,7 @@ async function smoke() {
}
async function ensureProject(projectId: string): Promise<StorageProjectResult> {
const useOpfs = await useOpfsForProject(projectId);
const layout = useOpfs ? await ensureProjectLayout(projectId) : projectLayout(projectId);
const layout = await requireProjectLayout(projectId);
return {
projectId: layout.projectId,
scenePath: layout.scenePath,
@@ -420,8 +425,7 @@ async function ensureProject(projectId: string): Promise<StorageProjectResult> {
async function saveProject(projectId: string, revision: number, buffer: ArrayBuffer, faultAt?: ProjectSaveFault | "before-metadata-commit" | "quota"): Promise<StorageSaveResult> {
if (faultAt === "quota") throw new Error("QuotaExceededError: injected OPFS quota exhaustion");
const useOpfs = await useOpfsForProject(projectId);
const layout = useOpfs ? await ensureProjectLayout(projectId) : projectLayout(projectId);
const layout = await requireProjectLayout(projectId);
const sha256 = await sha256Hex(buffer);
const existing = await readProjectRow(projectId);
if (existing && existing.revision > revision) {
@@ -431,47 +435,37 @@ async function saveProject(projectId: string, revision: number, buffer: ArrayBuf
if (existing.bytes !== buffer.byteLength || existing.sha256 !== sha256) {
throw new Error(`PROJECT_REVISION_CONFLICT: revision ${revision} already has different content`);
}
if (existing.backend === "opfs" && useOpfs) {
const recovered = await recoverProjectBlend(projectId);
if (!recovered.manifest || recovered.manifest.revision !== revision || recovered.manifest.bytes !== existing.bytes || recovered.manifest.sha256 !== sha256) {
throw new Error(`PROJECT_REVISION_CONFLICT: revision ${revision} metadata does not match the OPFS commit`);
}
}
else if (existing.backend !== "indexeddb" || useOpfs || !existing.buffer || await sha256Hex(existing.buffer) !== sha256) {
throw new Error(`PROJECT_REVISION_CONFLICT: revision ${revision} backend does not match the committed project`);
const recovered = await recoverProjectBlend(projectId);
if (!recovered.manifest || recovered.manifest.revision !== revision || recovered.manifest.bytes !== existing.bytes || recovered.manifest.sha256 !== sha256) {
throw new Error(`PROJECT_REVISION_CONFLICT: revision ${revision} metadata does not match the OPFS commit`);
}
return {
projectId,
bytes: existing.bytes,
revision,
persisted: true,
backend: existing.backend,
backend: "opfs" as const,
scenePath: existing.scenePath,
sha256,
};
}
if (useOpfs) {
const previousBuffer = faultAt && existing ? await readProjectBlend(projectId) : undefined;
try {
const opfsFault = faultAt === "after-stage" || faultAt === "after-scene-commit" ? faultAt : undefined;
const committed = await writeProjectBlend(projectId, revision, buffer, undefined, opfsFault);
if (committed.manifest.sha256 !== sha256) throw new Error("Project commit digest mismatch");
if (faultAt === "before-metadata-commit") {
throw new Error("PROJECT_SAVE_FAULT_INJECTED: before-metadata-commit");
}
}
catch (error) {
if (faultAt && existing && previousBuffer) {
const rollback = await writeProjectBlend(projectId, existing.revision, previousBuffer);
if (rollback.manifest.sha256 !== existing.sha256) {
throw new Error("PROJECT_SAVE_ROLLBACK_FAILED: old committed hash was not restored", { cause: error });
}
}
throw error;
const previousBuffer = faultAt && existing ? await readProjectBlend(projectId) : undefined;
try {
const opfsFault = faultAt === "after-stage" || faultAt === "after-scene-commit" ? faultAt : undefined;
const committed = await writeProjectBlend(projectId, revision, buffer, undefined, opfsFault);
if (committed.manifest.sha256 !== sha256) throw new Error("Project commit digest mismatch");
if (faultAt === "before-metadata-commit") {
throw new Error("PROJECT_SAVE_FAULT_INJECTED: before-metadata-commit");
}
}
else if (faultAt) {
throw new Error("PROJECT_SAVE_FAULT_UNAVAILABLE: IndexedDB commits are already transactional");
catch (error) {
if (faultAt && existing && previousBuffer) {
const rollback = await writeProjectBlend(projectId, existing.revision, previousBuffer);
if (rollback.manifest.sha256 !== existing.sha256) {
throw new Error("PROJECT_SAVE_ROLLBACK_FAILED: old committed hash was not restored", { cause: error });
}
}
throw error;
}
await writeProjectRow({
@@ -481,35 +475,21 @@ async function saveProject(projectId: string, revision: number, buffer: ArrayBuf
sha256,
updatedAt: new Date().toISOString(),
scenePath: layout.scenePath,
backend: useOpfs ? "opfs" : "indexeddb",
buffer: useOpfs ? undefined : buffer.slice(0),
backend: "opfs",
});
return {
projectId,
bytes: buffer.byteLength,
revision,
persisted: true,
backend: useOpfs ? "opfs" : "indexeddb",
backend: "opfs" as const,
scenePath: layout.scenePath,
sha256,
};
}
async function recoverProject(projectId: string): Promise<StorageRecoveryResult> {
const useOpfs = await useOpfsForProject(projectId);
if (!useOpfs) {
const row = await readProjectRow(projectId);
return row ? {
projectId,
status: "clean",
recovered: false,
backend: "indexeddb",
revision: row.revision,
bytes: row.bytes,
sha256: row.sha256,
} : { projectId, status: "missing", recovered: false, backend: "indexeddb" };
}
await requireProjectLayout(projectId);
const recovery = await recoverProjectBlend(projectId);
if (!recovery.manifest) {
return { projectId, status: "missing", recovered: false, backend: "opfs" };
@@ -541,8 +521,7 @@ async function readProject(projectId: string): Promise<StorageProjectReadResult>
recovery.bytes === undefined || recovery.sha256 === undefined) {
throw new Error("Project has no committed blend");
}
const row = await readProjectRow(projectId);
const buffer = recovery.backend === "opfs" ? await readProjectBlend(projectId) : row?.buffer?.slice(0);
const buffer = await readProjectBlend(projectId);
if (!buffer || buffer.byteLength !== recovery.bytes || await sha256Hex(buffer) !== recovery.sha256) {
throw new Error("Project blend integrity check failed");
}
@@ -592,7 +571,7 @@ async function listOperations(projectId: string, afterRevision: number): Promise
const read = db.transaction("operation_log", "readonly");
const rows = await new Promise<unknown[]>((resolve, reject) => {
const request = read.objectStore("operation_log").getAll();
request.onsuccess = () => resolve(request.result);
request.onsuccess = () => resolve(request.result as unknown[]);
request.onerror = () => reject(request.error ?? new Error("Operation log scan failed"));
});
await transactionComplete(read);
@@ -635,9 +614,8 @@ async function pruneOperations(projectId: string, throughRevision: number): Prom
interface SnapshotRow extends StorageSnapshotResult {
id: string;
backend?: "indexeddb" | "opfs";
backend?: "opfs";
path?: string;
buffer?: ArrayBuffer;
}
async function saveSnapshot(projectId: string, revision: number, buffer: ArrayBuffer, maxCount = 5, maxBytes = 268_435_456): Promise<StorageSnapshotResult> {
@@ -658,16 +636,14 @@ async function saveSnapshot(projectId: string, revision: number, buffer: ArrayBu
const existing = rows.find((candidate) => candidate.revision === revision);
if (existing?.bytes === buffer.byteLength && existing.sha256 === sha256) {
const existingBuffer = existing.backend === "opfs"
? await readProjectSnapshot(projectId, revision)
: existing.buffer;
const existingBuffer = await readProjectSnapshot(projectId, revision);
if (existingBuffer?.byteLength === existing.bytes && await sha256Hex(existingBuffer) === sha256) {
return { projectId, revision, bytes: existing.bytes, sha256, createdAt: existing.createdAt, persisted: true };
}
}
const useOpfs = await useOpfsForProject(projectId);
const opfs = useOpfs ? await writeProjectSnapshot(projectId, revision, buffer) : undefined;
await requireProjectLayout(projectId);
const opfs = await writeProjectSnapshot(projectId, revision, buffer);
const createdAt = new Date().toISOString();
const row: SnapshotRow = {
id: `${projectId}:${revision}`,
@@ -677,9 +653,8 @@ async function saveSnapshot(projectId: string, revision: number, buffer: ArrayBu
sha256,
createdAt,
persisted: true,
backend: useOpfs ? "opfs" : "indexeddb",
path: opfs?.path,
buffer: useOpfs ? undefined : buffer.slice(0),
backend: "opfs",
path: opfs.path,
};
const retained = [...rows.filter((candidate) => candidate.revision !== revision), row].sort((left, right) => right.revision - left.revision);
let total = 0;
@@ -728,14 +703,12 @@ async function readSnapshot(projectId: string, revision: number): Promise<Storag
await transactionComplete(transaction);
db.close();
if (!row) throw new Error("Snapshot integrity check failed");
const buffer = row.backend === "opfs" ? await readProjectSnapshot(projectId, revision) : row.buffer;
const buffer = await readProjectSnapshot(projectId, revision);
if (!buffer || buffer.byteLength !== row.bytes || await sha256Hex(buffer) !== row.sha256) throw new Error("Snapshot integrity check failed");
return { projectId, revision, bytes: row.bytes, sha256: row.sha256, createdAt: row.createdAt, buffer: buffer.slice(0) };
}
interface AssetRow extends StorageAssetRecord {
buffer?: ArrayBuffer;
}
type AssetRow = StorageAssetRecord;
function assetRecord(row: AssetRow): StorageAssetRecord {
return {
@@ -777,18 +750,13 @@ async function putAsset(projectId: string, data: ArrayBuffer, mimeType: string,
if (!/^[A-Za-z0-9.+-]+\/[A-Za-z0-9.+-]+$/.test(mimeType)) throw new Error("Invalid asset MIME type");
const normalizedSourcePath = sourcePath === undefined ? undefined : normalizeProjectAssetPath(sourcePath);
const sha256 = await sha256Hex(data);
const useOpfs = await useOpfsForProject(projectId);
const existing = await readAssetRow(projectId, sha256);
let path = `indexeddb:${projectId}:${sha256}`;
let deduplicated = Boolean(existing);
if (useOpfs) {
const written = await writeContentAsset(projectId, sha256, data);
path = written.path;
deduplicated = written.deduplicated;
const verified = await readContentAsset(projectId, sha256);
if (verified.byteLength !== data.byteLength || await sha256Hex(verified) !== sha256) {
throw new Error("Content-addressed asset verification failed");
}
const written = await writeContentAsset(projectId, sha256, data);
const path = written.path;
const deduplicated = written.deduplicated;
const verified = await readContentAsset(projectId, sha256);
if (verified.byteLength !== data.byteLength || await sha256Hex(verified) !== sha256) {
throw new Error("Content-addressed asset verification failed");
}
const now = new Date().toISOString();
const row: AssetRow = {
@@ -804,7 +772,6 @@ async function putAsset(projectId: string, data: ArrayBuffer, mimeType: string,
path,
createdAt: existing?.createdAt ?? now,
lastAccessAt: now,
buffer: useOpfs ? undefined : data.slice(0),
};
const db = await openDatabase();
const transaction = db.transaction("asset", "readwrite");
@@ -812,7 +779,7 @@ async function putAsset(projectId: string, data: ArrayBuffer, mimeType: string,
if (isEditorResourcePath(normalizedSourcePath) && (normalizedSourcePath.split('/')[2] === 'shader' || /\.(?:osl|oso)$/i.test(normalizedSourcePath))) {
const lookup = store.openCursor();
lookup.onsuccess = () => {
const cursor = lookup.result;
const cursor = lookup.result as IDBCursorWithValue | null;
if (!cursor) { store.put({ ...row, id: `${projectId}:${sha256}` }); return; }
const previous = cursor.value as AssetRow & { id: string };
if (previous.projectId === projectId) {
@@ -835,7 +802,7 @@ async function readAsset(projectId: string, sha256: string): Promise<StorageAsse
if (!row) throw storageError("NON_MESH_RESOURCE_MISSING", "content-addressed asset metadata is missing");
let data: ArrayBuffer;
try {
data = row.buffer ? row.buffer.slice(0) : await readContentAsset(projectId, sha256);
data = await readContentAsset(projectId, sha256);
}
catch (error) {
if (error instanceof DOMException && error.name === "NotFoundError") {
@@ -1306,9 +1273,7 @@ async function readSimulationCacheFrame(projectId: string, cacheKey: string, fra
throw new SimulationCacheValidationError("SIMULATION_CACHE_MISSING", "Simulation cache payload is missing or truncated");
}
throwIfCancelled(requestId);
data = asset.buffer ?
asset.buffer.slice(selected.byteOffset, selected.byteOffset + selected.byteLength) :
await readContentAssetRange(projectId, manifest.cacheSha256, selected.byteOffset, selected.byteLength, manifest.byteLength);
data = await readContentAssetRange(projectId, manifest.cacheSha256, selected.byteOffset, selected.byteLength, manifest.byteLength);
throwIfCancelled(requestId);
await verifySimulationCacheFrame(manifest, frame, data);
}
@@ -1575,7 +1540,7 @@ async function handleRequest(event: MessageEvent<StorageRequest>): Promise<void>
scope.postMessage({
requestId: event.data.requestId,
ok: false,
error: error instanceof Error ? error.message : "IndexedDB initialization failed",
error: error instanceof Error ? error.message : "Storage initialization failed",
errorCode: error && typeof error === "object" && "code" in error ? (error as { code: StorageResponse["errorCode"] }).code : undefined,
});
}

View File

@@ -16,6 +16,7 @@ import {
Raycaster,
Scene,
Uint32BufferAttribute,
Matrix3,
Vector2,
Vector3,
WebGLRenderer,
@@ -27,6 +28,10 @@ import type { GPUTextureAsset } from "../../../protocol/render-assets";
import type { MeshElementMode, MeshGeometryBuffer } from "../../../protocol/web-engine";
import type { NonMeshGeometryChunk } from "../../../protocol/nonmesh-binary";
import type { OffscreenTextureStatus, OffscreenViewportRequest, OffscreenViewportResponse } from "../three-adapter/offscreen-viewport-protocol";
import { applyStudioShading, usesStudioMaterial, type SolidShadingOptions } from "../three-adapter/studio-light";
import { createStudioWorldTexture, fetchStudioWorld, STUDIO_WORLD_DEFAULT } from "../three-adapter/studio-environment";
import { WorkbenchPost } from "../three-adapter/workbench-post";
import { pickSurface, projectBrushRing } from "../three-adapter/viewport-surface-math";
import type { NonMeshElementKind } from "../three-adapter/nonmesh";
import type { CurveGizmoFrameIR, CurveGizmoScreenFrameIR } from "../../../protocol/nonmesh-interaction";
import type { NanoVDBViewportAssetIR, NanoVDBViewportRenderResultIR } from "../volume/nanovdb-viewport";
@@ -64,6 +69,8 @@ const workerScope = self as unknown as {
postMessage(message: OffscreenViewportResponse, transfer?: Transferable[]): void;
};
let renderer: WebGLRenderer | null = null;
/* Screen-space cavity/curvature, shared with the main-thread renderer. */
const workbenchPost = new WorkbenchPost();
let scene: Scene | null = null;
let camera: PerspectiveCamera|OrthographicCamera | null = null;
let navigationCamera=false;
@@ -76,6 +83,11 @@ let appliedTextureRevision = -1;
let contextLost = false;
let width = 1;
let height = 1;
let shadingMode: "WIREFRAME" | "SOLID" | "MATERIAL" | "RENDERED" = "MATERIAL";
let xray = false;
let workerSelectedIds: ReadonlySet<string> = new Set();
let solidShading: SolidShadingOptions = {};
let navigationOptions: import("../../../protocol/viewport-camera").OrbitDeltaOptions = {};
let orbit: ViewportOrbitState = { ...VIEWPORT_DEFAULT_ORBIT, target: [...VIEWPORT_DEFAULT_ORBIT.target] as [number, number, number] };
let viewPreset: "SCENE_CAMERA" | "COMPARISON" = "SCENE_CAMERA";
let editMode = false;
@@ -99,10 +111,21 @@ function post(message: OffscreenViewportResponse, transfer?: Transferable[]): vo
workerScope.postMessage(message, transfer);
}
/** Applies the shading mode in the worker; shares the main-thread helper so the
* two render paths cannot drift. */
function applyWorkerShadingMode(): void {
if (!root) return;
applyStudioShading(root, shadingMode, xray, workerSelectedIds, solidShading);
}
function render(): void {
if (contextLost || !renderer || !scene || !camera) return;
if (!navigationCamera) applyViewPresetPose(camera);
renderer.render(scene, camera);
/* Same post pass as the main thread; disabled it returns without drawing. */
const cavity = solidShading.cavity;
/* Solid shading only; see the note in the main-thread render loop. */
workbenchPost.setOptions({ ...cavity, enabled: usesStudioMaterial(shadingMode) && Boolean(cavity?.enabled) });
if (!workbenchPost.render(renderer, scene, camera)) renderer.render(scene, camera);
publishCurveGizmoFrame();
const gl = renderer.getContext();
const sampleWidth = Math.min(16, gl.drawingBufferWidth);
@@ -503,11 +526,36 @@ async function refreshVolumes(): Promise<void> {
}
}
let previewStudioLight: string = STUDIO_WORLD_DEFAULT;
let studioWorldAppliedName = "";
/* Material Preview studio world (`studiolights/world/*.exr`), shared with the
* main-thread viewport loader so both backends show identical lighting. */
function applyStudioEnvironment(renderer: WebGLRenderer): void {
const name = previewStudioLight;
if (studioWorldAppliedName === name) return;
studioWorldAppliedName = name;
void (async () => {
const world = await fetchStudioWorld(name).catch(() => null);
if (!world || !scene || name !== previewStudioLight) return;
scene.environment = createStudioWorldTexture(renderer, world);
scene.environmentIntensity = 1;
scene.environmentRotation.set(0, 0, 0);
render();
})();
}
function reapplyCurrentTextures(): void {
if (!currentSnapshot || !root) return;
textureStore.applySnapshotMaterials(root, currentSnapshot);
const world = currentSnapshot.worlds.find((candidate) => candidate.id === currentSnapshot?.scenes[0]?.worldId) ?? currentSnapshot.worlds[0];
if (!scene || !renderer) return;
/* Material Preview without Scene World is lit by the studio world, exactly
* like the desktop studiolight; do not overwrite it with the scene world. */
if (shadingMode === "MATERIAL" && !solidShading.useSceneWorld) {
applyStudioEnvironment(renderer);
return;
}
// Never replace an applied HDRI background with the flat world color.
const background = Boolean(world?.environmentImageId);
void textureStore.applyEnvironment(scene, renderer, world, background).then((applied) => {
@@ -802,6 +850,22 @@ function meshBoxSelect(requestId: string, x0: number, y0: number, x1: number, y1
post({ type: "meshBoxSelected", requestId, meshId, mode: selectionMode, indices: [...indices].sort((left, right) => left - right) });
}
/* Sculpt surface queries. Both always answer, even when there is nothing to hit:
* the main thread keeps a request pending against a timeout, and a silent drop
* would make the brush ring freeze on stale coordinates. */
function pickSurfacePoint(requestId: string, x: number, y: number): void {
if (!root || !camera) { post({ type: "surfacePicked", requestId, pick: null }); return; }
post({ type: "surfacePicked", requestId, pick: pickSurface(raycaster, camera, root, x, y) });
}
function projectBrushCursor(requestId: string, x: number, y: number, radius: number, cssWidth: number, cssHeight: number): void {
if (!root || !camera) { post({ type: "brushCursorRing", requestId, ring: null }); return; }
/* `Vector3.project` reads `matrixWorldInverse`, which only the render loop
* normally refreshes; a ring query can land between frames. */
camera.updateMatrixWorld(true);
post({ type: "brushCursorRing", requestId, ring: projectBrushRing(raycaster, camera, root, x, y, radius, cssWidth, cssHeight) });
}
function pick(x: number, y: number, mode: "REPLACE" | "ADD" | "SUBTRACT", baseSelectionRevision: number): void {
if (!root || !camera) return;
raycaster.setFromCamera(new Vector2(x, y), camera);
@@ -936,6 +1000,10 @@ workerScope.onmessage = (event): void => {
light.shadow.bias = -0.0005;
light.shadow.normalBias = 0.03;
grid = new GridHelper(20, 20, 0x60656e, 0x383b42);
/* Overlay semantics: desktop draws the grid in the overlay engine, which
* runs after workbench has consumed its depth buffer, so the cavity pass
* never sees it. Keep it out of the web cavity depth texture as well. */
grid.material.depthWrite = false;
scene.add(light, light.target, grid, root, importedLights);
resize(message.width, message.height, message.pixelRatio);
post({ type: "ready" });
@@ -969,7 +1037,12 @@ workerScope.onmessage = (event): void => {
void refreshVolumes();
}
else if (message.type === "resize") resize(message.width, message.height, message.pixelRatio);
else if (message.type === "selection") setSelection(message.objectIds, message.elements, message.greasePencilPoints, message.greasePencilSelectionRevision);
else if (message.type === "selection") {
workerSelectedIds = new Set(message.objectIds);
setSelection(message.objectIds, message.elements, message.greasePencilPoints, message.greasePencilSelectionRevision);
if (shadingMode === "SOLID" || shadingMode === "WIREFRAME") applyWorkerShadingMode();
render();
}
else if (message.type === "interaction") {
editMode = message.editMode;
selectionMode = message.selectionMode;
@@ -991,10 +1064,48 @@ workerScope.onmessage = (event): void => {
render();
}
else if (message.type === "orbit") {
orbit = applyOrbitDelta(orbit, message.deltaX, message.deltaY, message.zoom);
orbit = applyOrbitDelta(orbit, message.deltaX, message.deltaY, message.zoom, navigationOptions);
render();
}
else if (message.type === "navigationPrefs") {
navigationOptions = {
rotateSensitivity: message.orbitSensitivity,
zoomSensitivity: message.zoomSensitivity,
invertZoom: message.invertZoom,
};
}
else if (message.type === "display") {
if (shadingMode === message.shadingMode && xray === message.xray) return;
shadingMode = message.shadingMode;
xray = message.xray;
applyWorkerShadingMode();
/* Switching into Material Preview swaps the studio world in; switching
* back re-applies the scene world (colour, image, strength, rotation). */
if (scene && renderer && shadingMode === "MATERIAL" && !solidShading.useSceneWorld) {
studioWorldAppliedName = "";
applyStudioEnvironment(renderer);
}
else reapplyCurrentTextures();
render();
}
else if (message.type === "solidShading") {
/* The rig/matcap/shadow settings travel separately from `display` so a
* preset change does not have to restate the shading mode. */
solidShading = { ...solidShading, ...message.options };
if (shadingMode === "SOLID" || shadingMode === "WIREFRAME") {
applyWorkerShadingMode();
render();
}
else if (message.options.useSceneWorld !== undefined) reapplyCurrentTextures();
}
else if (message.type === "studioLight") {
previewStudioLight = message.name;
studioWorldAppliedName = "";
if (scene && renderer && shadingMode === "MATERIAL" && !solidShading.useSceneWorld) applyStudioEnvironment(renderer);
}
else if (message.type === "pick") pick(message.x, message.y, message.mode, message.baseSelectionRevision);
else if (message.type === "pickSurface") pickSurfacePoint(message.requestId, message.x, message.y);
else if (message.type === "projectBrushCursor") projectBrushCursor(message.requestId, message.x, message.y, message.radius, message.cssWidth, message.cssHeight);
else if (message.type === "boxSelect") boxSelect(message.requestId, message.x0, message.y0, message.x1, message.y1);
else if (message.type === "meshBoxSelect") meshBoxSelect(message.requestId, message.x0, message.y0, message.x1, message.y1);
else if (message.type === "greasePencilMarquee") {
@@ -1010,6 +1121,7 @@ workerScope.onmessage = (event): void => {
volumeRenderGeneration++;
volumeRenderCache.clear();
volumeRenderSession.dispose();
workbenchPost.dispose();
clearLights();
renderer?.dispose();
textureStore.dispose();

View File

@@ -1,4 +1,5 @@
import { commitNativeSessionRecovery, restoreNativeSessionRecovery } from "../storage/native-session-opfs";
import { persistBrowserFS, populateBrowserFS, type BrowserFSLike } from "../storage/opfs-browser-fs";
import type { ErrorReport } from "../../../protocol/error";
import { installGPUComputeHost } from "../engine-client/gpu-compute-host";
import { NativeAudioTransport } from "../engine-client/native-audio-transport";
@@ -51,7 +52,6 @@ import { parseServerOperatorJobRequest } from "../../../protocol/server-operator
import { withCameraPresets } from '../storage/camera-presets';
type WasmModule = {
IDBFS?: unknown;
FS?: {
mount?(type: unknown, opts: Record<string, unknown>, path: string): void;
syncfs?(populate: boolean, callback: (error?: unknown) => void): void;
@@ -185,8 +185,12 @@ const cancelledOpenRequests = new Set<string>();
const queuedOpenRequests = new Set<string>();
const activeOpenResources = new Map<string, { liveInputBytes: number; liveNativeHandles: number; liveStagingFiles: number; cleanup?: () => void }>();
const paintStrokeSessions = new PaintStrokeSessionStore();
function mountBrowserFS(target: WasmModule): void { const fs = target.FS; if (!fs?.mount || !fs.syncfs || !target.IDBFS) throw report('CAPABILITY_MISSING', 'Native persistent filesystem requires the IDBFS-enabled build'); if (browserFSModules.has(target)) return; fs.mkdirTree('/browser'); fs.mount(target.IDBFS, {}, '/browser'); browserFSModules.add(target); }
async function syncBrowserFS(populate: boolean, target = module): Promise<void> { if (!target) return; mountBrowserFS(target); try { await new Promise<void>((resolve, reject) => target.FS!.syncfs!(populate, error => error ? reject(error) : resolve())); } catch (error) { throw report('WASM_INIT_FAILED', `${populate ? 'NATIVE_FILES_RESTORE_FAILED' : 'NATIVE_FILES_PERSISTENCE_PENDING'}: ${String(error)}; ${populate ? 'stored files were not replaced' : 'live files remain in memory; retry or download a backup before closing'}`); } }
// `/browser` stays a plain directory on the MEMFS root that Emscripten mounts at
// `/`, so Blender sees exactly the same in-memory tree as before. Only the
// persistence behind it changes: OPFS instead of IDBFS. There is no IDBFS
// fallback — all product files must live in OPFS.
function mountBrowserFS(target: WasmModule): void { const fs = target.FS; if (!fs?.mkdirTree) throw report('CAPABILITY_MISSING', 'Native filesystem is unavailable'); if (browserFSModules.has(target)) return; fs.mkdirTree('/browser'); browserFSModules.add(target); }
async function syncBrowserFS(populate: boolean, target = module): Promise<void> { if (!target) return; mountBrowserFS(target); const fs = target.FS as unknown as BrowserFSLike | undefined; if (!fs) return; try { if (populate) await populateBrowserFS(fs); else await persistBrowserFS(fs); } catch (error) { throw report('WASM_INIT_FAILED', `${populate ? 'NATIVE_FILES_RESTORE_FAILED' : 'NATIVE_FILES_PERSISTENCE_PENDING'}: ${String(error)}; ${populate ? 'stored files were not replaced' : 'live files remain in memory; retry or download a backup before closing'}`); } }
let gpuSurface: { session: string; canvas: OffscreenCanvas; width: number; height: number; pixelRatio: number;
ownerGeneration: number; nativeInputEpoch?: number; bound: boolean; contextLost: boolean; resetPending: boolean; listeners: AbortController; cursorRevision?: number } | null = null;
@@ -2681,10 +2685,12 @@ function assertFutureCapability(payload: Extract<WebEngineRequest["command"], {
case "setWorldProperties": {
const world = currentSnapshot?.worlds.find((candidate) => candidate.id === payload.dataId);
const properties = payload.properties;
if (!world || !validPropertyKeys(properties, ["color", "exposure", "environmentStrength", "ambientOcclusionDistance", "ambientOcclusionEnergy", "sunThreshold", "sunAngle", "sunShadowMaximumResolution", "sunShadowJitterOverblur", "sunShadowFilterRadius", "probeResolution", "useSunShadow", "useSunShadowJitter", "mist"])) throw report("RENDER_PROPERTY_INVALID", "World target or properties are invalid");
if (!world || !validPropertyKeys(properties, ["color", "exposure", "environmentStrength", "environmentImageId", "environmentRotation", "ambientOcclusionDistance", "ambientOcclusionEnergy", "sunThreshold", "sunAngle", "sunShadowMaximumResolution", "sunShadowJitterOverblur", "sunShadowFilterRadius", "probeResolution", "useSunShadow", "useSunShadowJitter", "mist"])) throw report("RENDER_PROPERTY_INVALID", "World target or properties are invalid");
if (properties.color !== undefined && (!Array.isArray(properties.color) || properties.color.length !== 3 || properties.color.some((value) => !boundedNumber(value, 0, 100)))) throw report("RENDER_PROPERTY_INVALID", "World color is invalid");
if (properties.exposure !== undefined && !boundedNumber(properties.exposure, -20, 20)) throw report("RENDER_PROPERTY_INVALID", "World exposure is invalid");
if (properties.environmentStrength !== undefined && !boundedNumber(properties.environmentStrength, 0, 1e9)) throw report("RENDER_PROPERTY_INVALID", "World environment strength is invalid");
if (properties.environmentImageId !== undefined && properties.environmentImageId !== null && typeof properties.environmentImageId !== "string") throw report("RENDER_PROPERTY_INVALID", "World environment image is invalid");
if (properties.environmentRotation !== undefined && !boundedNumber(properties.environmentRotation, -1e9, 1e9)) throw report("RENDER_PROPERTY_INVALID", "World environment rotation is invalid");
for (const [field, minimum, maximum] of [["ambientOcclusionDistance", 0, 1e9], ["ambientOcclusionEnergy", 0, 1e9], ["sunThreshold", 0, 1e9], ["sunAngle", 0, Math.PI], ["sunShadowMaximumResolution", 0.0000001, 1e9], ["sunShadowJitterOverblur", 0, 1e9], ["sunShadowFilterRadius", 0, 1e9]] as const) if (properties[field] !== undefined && !boundedNumber(properties[field], minimum, maximum)) throw report("RENDER_PROPERTY_INVALID", `World ${field} is outside the bounded range`);
if (properties.probeResolution !== undefined && (!Number.isSafeInteger(properties.probeResolution) || properties.probeResolution < 7 || properties.probeResolution > 12)) throw report("RENDER_PROPERTY_INVALID", "World probe resolution is invalid");
for (const field of ["useSunShadow", "useSunShadowJitter"] as const) if (properties[field] !== undefined && typeof properties[field] !== "boolean") throw report("RENDER_PROPERTY_INVALID", `World ${field} must be boolean`);
@@ -4421,7 +4427,10 @@ async function handleRequest(event: MessageEvent<WebEngineRequest>): Promise<voi
if (module && handle) {
const session = callUnifiedJson<{ written: boolean; path?: string }>('writeLastSession');
if (session.written) nativeRecoveryPath = session.path;
if (session.written && (typeof session.path !== 'string' || module.FS?.lookupPath?.(session.path, { follow: true }).node?.mount.mountpoint !== '/browser')) throw report('WASM_INIT_FAILED', `SESSION_RECOVERY_NOT_PERSISTENT: ${session.path}; select a temporary directory inside /browser before closing`);
// `/browser` is no longer its own mount point: it is a directory on the
// MEMFS root and OPFS is the persistence behind it, so the persisted
// test is path containment, not a mountpoint equality.
if (session.written && (typeof session.path !== 'string' || !session.path.startsWith('/browser/') || session.path.split('/').some(part => part === '.' || part === '..'))) throw report('WASM_INIT_FAILED', `SESSION_RECOVERY_NOT_PERSISTENT: ${session.path}; select a temporary directory inside /browser before closing`);
}
await syncBrowserFS(false);
if (nativeRecoveryPath) { try { await commitNativeSessionRecovery(nativeRecoveryPath, module!.FS!.readFile(nativeRecoveryPath)); } catch (error) { throw report('WASM_INIT_FAILED', `NATIVE_SESSION_OPFS_PERSISTENCE_PENDING: ${String(error)}; live Main and files remain available; retry or download a backup before closing`); } }