Skip to content

3D engine that AI agents drive

2.3 KB
Raw Blame
// Committed default cameras for the benchmark scenes that are generated locally from Blender demo files
// (scripts/blender-demo-to-glb.py), whose own camera renders a flat frame (#2158). camera-overrides.json maps a scene name
// to the eye and target that show the scene; the sweep applies it to scene.json before it renders.
import { readFileSync, writeFileSync } from 'node:fs';
import { basename } from 'node:path';

const OVERRIDES_URL = new URL('./camera-overrides.json', import.meta.url);

export function loadCameraOverrides(overridesUrl = OVERRIDES_URL) {
  return JSON.parse(readFileSync(overridesUrl, 'utf8'));
}

function assertPoint(sceneName, field, point) {
  const valid = Array.isArray(point) && point.length === 3 && point.every(Number.isFinite);
  if (!valid) throw new Error(`Camera override "${sceneName}" needs ${field} as three finite numbers [x, y, z], got ${JSON.stringify(point)}.`);
}

// Returns the scene description with the override's eye and target, or the same description when the scene has no override.
export function applyCameraOverride(sceneName, description, overrides) {
  const override = overrides[sceneName];
  if (override === undefined) return description;
  assertPoint(sceneName, 'eye', override.eye);
  assertPoint(sceneName, 'target', override.target);
  return { ...description, eye: [...override.eye], target: [...override.target] };
}

// Reads the file once instead of checking for it first, so nothing can swap it between the check and the read.
function readSceneFile(scenePath, directory) {
  try {
    return readFileSync(scenePath, 'utf8');
  } catch (error) {
    if (error.code === 'ENOENT') throw new Error(`No scene.json in ${directory}. Pass a scene directory generated by scripts/blender-demo-to-glb.py.`);
    throw error;
  }
}

// Rewrites <directory>/scene.json in place and returns true when the override changed it.
export function applyCameraOverrideToDirectory(directory, overrides = loadCameraOverrides()) {
  const scenePath = `${directory}/scene.json`;
  const description = JSON.parse(readSceneFile(scenePath, directory));
  const updated = applyCameraOverride(description.id ?? basename(directory), description, overrides);
  if (updated === description) return false;
  writeFileSync(scenePath, `${JSON.stringify(updated, null, 2)}\n`);
  return true;
}