typegpu
Version:
A thin layer between JS and WebGPU/WGSL that improves development experience and allows for faster iteration.
41 lines (40 loc) • 1.47 kB
JavaScript
import { snip } from "../../data/snippet.js";
import { Void } from "../../data/wgslTypes.js";
import { $internal, $resolve } from "../../shared/symbols.js";
import { replaceExternalsInWgsl } from "../resolve/externals.js";
/**
* Allows defining extra declarations that shall be included in the final WGSL code,
* when resolving objects that use them.
*
* Using this API is generally discouraged, as it shouldn't be necessary in any common scenario.
* It was developed to ensure full compatibility of TypeGPU programs with current and future versions of WGSL.
*/
export function declare(declaration) {
return new TgpuDeclareImpl(declaration);
}
// --------------
// Implementation
// --------------
class TgpuDeclareImpl {
[$internal] = true;
#externals;
#declaration;
constructor(declaration) {
this.#declaration = declaration;
}
$uses(dependencyMap) {
if (this.#externals !== undefined) {
throw new Error("Cannot call '$uses' multiple times. If you wish to override dependencies, use slots or accessors instead.");
}
this.#externals = dependencyMap;
return this;
}
[$resolve](ctx) {
const replacedDeclaration = replaceExternalsInWgsl(ctx, this.#externals ?? {}, this.#declaration);
ctx.addDeclaration(replacedDeclaration);
return snip('', Void, /* origin */ 'constant');
}
toString() {
return `declare: ${this.#declaration}`;
}
}