software-mansion / TypeGPU

TypeScript library that enhances the WebGPU API, allowing resource management in a type-safe, declarative way.
http://typegpu.com
MIT License
157 stars 4 forks source link

tgpu.resolve API #522

Closed iwoplaza closed 4 days ago

iwoplaza commented 2 weeks ago

The tgpu.resolve function generates a WGSL code string that is representative of all inputs (+ extra dependencies).

Expected signature:

function resolve(
  input: string | TgpuResolvable | (string | TgpuResolvable)[],
  extraDependencies?: Record<string, TgpuResolvable>
): string;

Example uses

Adding dependencies to a plain code string.

const Gradient = struct({
  from: vec3f,
  to: vec3f,
});

const foo0 = tgpu.resolve('fn foo() { var v: Gradient; }', { Gradient });

console.log(foo0); // struct Gradient_1 { from: vec3f, to: vec3f, } fn foo() { var v: Gradient_1; }

Resolving two entry functions to get one shader code string

const { intensity } = tgpu
  .bindGroupLayout({
    intensity: { uniform: f32 },
  }).bound;

const vertex = tgpu
  .vertexFn({}, {})
  .does(() => {
    const v = intensity.value;
  });

const fragment = tgpu
  .fragmentFn({}, vec4f)
  .does(() => vec4f(intensity.value, 0, 0, 1));

// Deduplicates dependencies
const foo0 = tgpu.resolve([vertex, fragment]);

console.log(foo0);
// @group(0) @binding(0) var<uniform> intensity_1: f32;
//
// @vertex
// fn vertex_main() {
//   let v = intensity_1;
// }
//
// @fragment
// fn fragment_main() {
//   return vec4f(intensity_1, 0.0, 0.0, 1.0);
// }