Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

8.7 KB
Raw Blame
// tools/dump.py's JSON -> src/gen: Blender's whole Python API as TypeScript types. Run by tools/gen.sh:
//   bun tools/gen/main.ts DUMP.json
// src/gen is replaced: enums.ts, rna/ (bpy.types, a file per first letter), ops/ (a file per bpy.ops module),
// py/ (a file per module outside RNA), api/bpy.ts (bpy itself: data, context, ops, types, app) and the barrels.
import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { emitContext } from "./context";
import type { Dump, Op } from "./dump";
import { jsdoc, key, modId, Names } from "./names";
import { emitOpModule } from "./ops";
import { emitApp, emitBpyStruct, emitModule, registerClasses } from "./pymod";
import { emitRefine } from "./refine";
import { emitStructs } from "./rna";

const HEAD = "// Generated by tools/gen.sh from Blender's own API (tools/dump.py). Don't edit: regenerate.\n";
const IMPORTS = `import type * as H from "../../types";\nimport type * as M from "../../mathutils";\nimport type * as R from "../rna";\nimport type * as E from "../enums";\nimport type * as P from "../py";\n\n`;

const dumpPath = process.argv[2];
if (!dumpPath) throw new Error("usage: bun tools/gen/main.ts DUMP.json");
const d = JSON.parse(readFileSync(dumpPath, "utf8")) as Dump;
// BL34: the enums whose items Blender works out at the time (tools/itemf.json, read from its source by tools/itemf.sh)
const itemf = JSON.parse(readFileSync(join(dirname(new URL(import.meta.url).pathname), "../itemf.json"), "utf8")) as { blender: string; itemf: string[] };
if (itemf.blender !== d.blender) console.warn(`gen: tools/itemf.json is Blender ${itemf.blender}'s, the dump ${d.blender}'s: run tools/itemf.sh ${d.blender}`);
const atTheTime = new Set(itemf.itemf);
for (const s of d.structs) {
  for (const p of s.props) if (p.type === "enum" && atTheTime.has(`${s.id}.${p.id}`)) p.itemf = true;
  for (const f of s.funcs) for (const a of f.args) if (a.type === "enum" && atTheTime.has(`${s.id}.${f.id}(${a.id})`)) a.itemf = true;
}
// BL22: what C methods and properties return where their docstrings don't say (tools/cret.json, read from the
// bindings' C source by tools/cret.sh), by family of bindings; one written in Python (`py`, or a Python property, which
// has `ro`) or with an :rtype: or :type: keeps its own
type Family = { methods: Record<string, string>; getters: Record<string, string> };
const cret = JSON.parse(readFileSync(join(dirname(new URL(import.meta.url).pathname), "../cret.json"), "utf8")) as { blender: string; families: Record<string, Family> };
if (cret.blender !== d.blender) console.warn(`gen: tools/cret.json is Blender ${cret.blender}'s, the dump ${d.blender}'s: run tools/cret.sh ${d.blender}`);
const FAMILY: Record<string, string> = { bmesh: "bmesh", gpu: "gpu", mathutils: "mathutils", aud: "aud", bpy: "bpy", idprop: "generic", imbuf: "generic", bl_math: "generic" };
type Member = { id: string; doc: string; kind?: string; py?: boolean; ro?: boolean; none?: boolean; ret?: string; members?: Member[] };
const has = (o: object, k: string) => Object.hasOwn(o, k);
const markC = (fam: Family | undefined, m: Member) => {
  if (!fam || m.py || m.none || /:rtype:/.test(m.doc) || !has(fam.methods, m.id)) return;
  if (fam.methods[m.id] === "None") m.none = true;
  else m.ret = fam.methods[m.id];
};
const markAll = (fam: Family | undefined, ms: Member[]) => {
  for (const m of ms) {
    if (m.kind === "function" || m.kind === "method") markC(fam, m);
    else if (m.kind === "property" && fam && m.ro === undefined && !/:type:/.test(m.doc) && has(fam.getters, m.id) && fam.getters[m.id] !== "None") m.ret = fam.getters[m.id];
    else if (m.kind === "class" || m.kind === "module") markAll(fam, m.members ?? []);
  }
};
for (const [mod, data] of Object.entries(d.modules)) markAll(cret.families[FAMILY[mod.split(".")[0]] ?? ""], data.members);
markAll(cret.families.bpy, [d.bpy_struct, ...d.app]);
for (const s of d.structs) for (const c of s.cfuncs ?? []) markC(cret.families.bpy, c);
const root = join(dirname(new URL(import.meta.url).pathname), "../../src/gen");
rmSync(root, { recursive: true, force: true });
const files = new Map<string, string>();
const put = (rel: string, text: string) => files.set(rel, text);

const n = new Names(d);
// mathutils' own classes are the local ones (src/mathutils); its submodules are Blender's
const modules = Object.fromEntries(Object.entries(d.modules).filter(([m]) => m !== "mathutils"));
registerClasses({ ...d, modules }, n);
const all = new Set(Object.keys(modules));

// bpy.types, a file per first letter (stable across Blender versions: a new struct changes one file)
const structs = emitStructs(d, n);
const groups = new Map<string, string[]>();
const letter = (id: string) => (/^[A-Z]/.test(id) ? id[0] : "_misc");
for (const s of structs) groups.set(letter(s.id), [...(groups.get(letter(s.id)) ?? []), s.text]);
groups.set("_misc", [emitBpyStruct(d, n), ...(groups.get("_misc") ?? [])]);
for (const [g, texts] of groups) put(`rna/${g}.ts`, HEAD + IMPORTS + texts.join("\n"));
// what refined calls return per type value (tools/refine.py, tools/gen/refine.ts)
groups.set("_refine", []);
put("rna/_refine.ts", HEAD + IMPORTS + emitRefine(d, new Set(d.structs.map((s) => s.id))));
put("rna.ts", HEAD + [...groups.keys()].sort().map((g) => `export type * from "./rna/${g}";`).join("\n") + "\n");

// bpy.ops
const byMod = new Map<string, Op[]>();
for (const op of d.ops) byMod.set(op.mod, [...(byMod.get(op.mod) ?? []), op]);
for (const [mod, ops] of byMod) put(`ops/${mod}.ts`, emitOpModule(mod, ops, n));
const opMods = [...byMod.keys()].sort();
put("ops.ts", HEAD + opMods.map((m) => `import type * as o_${m} from "./ops/${m}";`).join("\n") +
  `\n\n${jsdoc("bpy.ops: every operator, by module.", "")}export interface Ops {\n${opMods.map((m) => `  readonly ${key(m)}: o_${m}.Ops;`).join("\n")}\n}\n`);

// the modules outside RNA
for (const [mod, data] of Object.entries(modules)) put(`py/${modId(mod)}.ts`, emitModule(mod, data, n, all));
put("py.ts", HEAD + [...all].sort().map((m) => `export type * as ${modId(m)} from "./py/${modId(m)}";`).join("\n") + "\n");

// bpy itself
const ctx = d.structs.find((s) => s.id === "Context")!;
const own = new Set([...ctx.props.map((p) => p.id), ...ctx.funcs.map((f) => f.id), ...(ctx.pyfuncs ?? []).map((f) => f.id),
  ...(ctx.cfuncs ?? []).map((f) => f.id), ...(d.bpy_struct.members ?? []).map((m) => m.id)]);
const mod = (m: string) => (all.has(m) ? `P.${modId(m)}.Api` : "any");
const types = d.structs.map((s) => `${jsdoc(s.desc)}  readonly ${key(s.id)}: any;`).join("\n");
put("api/bpy.ts", HEAD + IMPORTS.replace(`import type * as E from "../enums";\n`, "") + `import type * as O from "../ops";\n\n` +
  emitContext(d.context, own, n) + "\n" + emitApp(d, n) + "\n" +
  `${jsdoc("bpy.types: the classes (bpy.types.Object, ...), for isinstance, their bl_rna, and properties added to them (bpy.types.Object.my = bpy.props.FloatProperty()).", "")}export interface Types {\n${types}\n}\n\n` +
  `${jsdoc(`bpy: Blender ${d.version_string}'s Python API.`, "")}export interface Bpy {\n` +
  `  /** The open file's data: objects, meshes, materials, scenes, ... */\n  readonly data: H.Own<R.BlendData>;\n` +
  `  /** The current context: the scene, the view layer, the active and selected objects, the editor. */\n  readonly context: H.Own<Context>;\n` +
  `  /** Every operator, by module: bpy.ops.mesh.primitive_cube_add({ size: 2 }). */\n  readonly ops: O.Ops;\n` +
  `  readonly types: Types;\n  readonly app: App;\n  readonly utils: ${mod("bpy.utils")};\n  readonly path: ${mod("bpy.path")};\n` +
  `  readonly props: ${mod("bpy.props")};\n  readonly msgbus: ${mod("bpy.msgbus")};\n}\n`);

put("enums.ts", HEAD + [...n.enums.values()].join("\n"));
put("modules.ts", HEAD + `import type * as P from "./py";\n\nexport type { App, Bpy, Context, Types } from "./api/bpy";\nexport type { Ops } from "./ops";\n` +
  `export type Bmesh = ${all.has("bmesh") ? "P.bmesh.Api" : "any"};\nexport type BpyExtras = ${all.has("bpy_extras") ? "P.bpy_extras.Api" : "any"};\nexport type Gpu = ${all.has("gpu") ? "P.gpu.Api" : "any"};\n` +
  `export interface MathutilsModules {\n${["geometry", "noise", "bvhtree", "kdtree", "interpolate"].map((s) => `  readonly ${s}: ${mod(`mathutils.${s}`)};`).join("\n")}\n}\n` +
  `/** The Blender these types were made from. */\nexport const BLENDER_VERSION = ${JSON.stringify(d.blender)};\n`);

let bytes = 0;
for (const [rel, text] of files) {
  const p = join(root, rel);
  mkdirSync(dirname(p), { recursive: true });
  writeFileSync(p, text);
  bytes += text.length;
}
console.log(`gen: Blender ${d.blender}: ${d.structs.length} structs, ${d.ops.length} operators in ${byMod.size} modules, ` +
  `${all.size} Python modules, ${n.enums.size} shared enums -> ${files.size} files, ${(bytes / 1e6).toFixed(1)} MB in src/gen`);