Skip to content

feat: Allow passing raw wgsl implementation to shell à la template literal #1128

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 21 commits into from
Apr 11, 2025
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 30 additions & 22 deletions apps/typegpu-docs/src/content/docs/fundamentals/functions/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,27 @@ These functions can reference outside resources, like other user-defined or help
## Creating a function

Functions are constructed by first defining their shells, which specify their inputs and outputs.
Then the actual WGSL implementation is passed in as an argument to a shell invocation.
Then the actual WGSL implementation is passed in as an argument to a shell invocation. If the code string is a template literal, you can omit the parentheses, which may result in a more compact Biome/Prettier formatting.

The following code defines a function that accepts one argument and returns one value.

```ts
const getGradientColor = tgpu['~unstable']
.fn({ ratio: d.f32 }, d.vec4f)(`{
let color = mix(vec4f(0.769, 0.392, 1.0, 1), d.vec4f(0.114, 0.447, 0.941, 1), ratio);
.fn(
{ ratio: d.f32 },
d.vec4f,
)(`{
let color = mix(vec4f(0.769, 0.392, 1.0, 1), vec4f(0.114, 0.447, 0.941, 1), ratio);
return color;
}`)
.$name('getGradientColor');

// or

const getGradientColor = tgpu['~unstable'].fn({ ratio: d.f32 }, d.vec4f)`{
let color = mix(vec4f(0.769, 0.392, 1.0, 1), vec4f(0.114, 0.447, 0.941, 1), ratio);
return color;
}`.$name('getGradientColor');
```

If you're using Visual Studio Code, you can use an [extension](https://marketplace.visualstudio.com/items?itemName=ggsimm.wgsl-literal) that brings syntax highlighting to the code fragments marked with `/* wgsl */` comments.
Expand All @@ -40,18 +50,16 @@ Functions can use external resources passed inside a record via the `$uses` meth
Externals can be any value or TypeGPU resource that can be resolved to WGSL (functions, buffer usages, slots, accessors, constants, variables, declarations, vectors, matrices, textures, samplers etc.).

```ts
const getBlue = tgpu['~unstable']
.fn({}, d.vec4f)(`{
return vec4f(0.114, 0.447, 0.941, 1);
}`);
const getBlue = tgpu['~unstable'].fn({}, d.vec4f)`{
return vec4f(0.114, 0.447, 0.941, 1);
}`;

const purple = d.vec4f(0.769, 0.392, 1.0, 1);

const getGradientColor = tgpu['~unstable']
.fn({ ratio: d.f32 }, d.vec4f)(`{
let color = mix(purple, getBlue(), ratio);
return color;
}`)
const getGradientColor = tgpu['~unstable'].fn({ ratio: d.f32 }, d.vec4f)`{
let color = mix(purple, getBlue(), ratio);
return color;
}`
.$uses({ purple, getBlue })
.$name('getGradientColor');
```
Expand Down Expand Up @@ -79,11 +87,10 @@ Defining entry functions is similar to regular ones, but is done through dedicat
They can be passed to root-defined pipelines and they accept special arguments like builtins (`d.builtin`) and decorated data (`d.location`).

```ts
const mainVertex = tgpu['~unstable']
.vertexFn({
in: { vertexIndex: d.builtin.vertexIndex },
out: { outPos: d.builtin.position, uv: d.vec2f },
})(/* wgsl */ `{
const mainVertex = tgpu['~unstable'].vertexFn({
in: { vertexIndex: d.builtin.vertexIndex },
out: { outPos: d.builtin.position, uv: d.vec2f },
}) /* wgsl */`{
var pos = array<vec2f, 3>(
vec2(0.0, 0.5),
vec2(-0.5, -0.5),
Expand All @@ -97,13 +104,14 @@ const mainVertex = tgpu['~unstable']
);

return Out(vec4f(pos[in.vertexIndex], 0.0, 1.0), uv[in.vertexIndex]);
}`);
}`;

const mainFragment = tgpu['~unstable']
.fragmentFn({ in: { uv: d.vec2f }, out: d.vec4f })(/* wgsl */ `{
const mainFragment = tgpu['~unstable'].fragmentFn({
in: { uv: d.vec2f },
out: d.vec4f,
}) /* wgsl */`{
return getGradientColor((in.uv[0] + in.uv[1]) / 2);
}`)
.$uses({ getGradientColor });
}`.$uses({ getGradientColor });
```

When entry function inputs or outputs are specified as objects containing builtins and inter-stage variables, the WGSL implementations need to access these arguments as passed in via structs.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,13 +86,12 @@ export const vertexShader = tgpu['~unstable']
})
.$name('vertexShader');

const sampleTexture = tgpu['~unstable']
.fn(
{ uv: d.vec2f },
d.vec4f,
)(/* wgsl */ `{
const sampleTexture = tgpu['~unstable'].fn(
{ uv: d.vec2f },
d.vec4f,
) /* wgsl */`{
return textureSample(layout.$.modelTexture, layout.$.sampler, uv);
}`)
}`
.$uses({ layout })
.$name('sampleTexture');

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,11 +106,10 @@ const renderBindGroup = root.createBindGroup(renderLayout, {

// functions

const getBoxIntersection = tgpu['~unstable']
.fn(
{ boundMin: d.vec3f, boundMax: d.vec3f, ray: RayStruct },
IntersectionStruct,
)(/* wgsl */ `{
const getBoxIntersection = tgpu['~unstable'].fn(
{ boundMin: d.vec3f, boundMax: d.vec3f, ray: RayStruct },
IntersectionStruct,
) /* wgsl */`{
var tMin: f32;
var tMax: f32;
var tMinY: f32;
Expand Down Expand Up @@ -167,15 +166,14 @@ const getBoxIntersection = tgpu['~unstable']
}

return IntersectionStruct(tMin > 0 && tMax > 0, tMin, tMax);
}`)
}`
.$uses({ IntersectionStruct })
.$name('box_intersection');

const vertexFunction = tgpu['~unstable']
.vertexFn({
in: { vertexIndex: d.builtin.vertexIndex },
out: { outPos: d.builtin.position },
})(/* wgsl */ `{
const vertexFunction = tgpu['~unstable'].vertexFn({
in: { vertexIndex: d.builtin.vertexIndex },
out: { outPos: d.builtin.position },
}) /* wgsl */`{
var pos = array<vec2f, 6>(
vec2<f32>( 1, 1),
vec2<f32>( 1, -1),
Expand All @@ -186,17 +184,15 @@ const vertexFunction = tgpu['~unstable']
);

return Out(vec4f(pos[in.vertexIndex], 0, 1));
}`)
.$name('vertex_main');
}`.$name('vertex_main');

const boxSizeAccessor = tgpu['~unstable'].accessor(d.u32);
const canvasDimsAccessor = tgpu['~unstable'].accessor(CanvasDimsStruct);

const fragmentFunction = tgpu['~unstable']
.fragmentFn({
in: { position: d.builtin.position },
out: d.vec4f,
})(/* wgsl */ `{
const fragmentFunction = tgpu['~unstable'].fragmentFn({
in: { position: d.builtin.position },
out: d.vec4f,
}) /* wgsl */`{
let minDim = f32(min(canvasDims.width, canvasDims.height));

var ray: RayStruct;
Expand Down Expand Up @@ -246,7 +242,7 @@ const fragmentFunction = tgpu['~unstable']
}

return color;
}`)
}`
.$uses({
...renderLayout.bound,
RayStruct,
Expand All @@ -266,12 +262,9 @@ const fragmentFunction = tgpu['~unstable']
const pipeline = root['~unstable']
.with(
boxSizeAccessor,
tgpu['~unstable']
.fn(
[],
d.u32,
)('() -> u32 { return boxSize; }')
.$uses({ boxSize: boxSizeUniform }),
tgpu['~unstable'].fn([], d.u32)`() -> u32 { return boxSize; }`.$uses({
boxSize: boxSizeUniform,
}),
)
.with(canvasDimsAccessor, canvasDimsUniform)
.withVertex(vertexFunction, {})
Expand Down
27 changes: 12 additions & 15 deletions apps/typegpu-docs/src/content/examples/simple/triangle/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,21 +16,20 @@ context.configure({
alphaMode: 'premultiplied',
});

const getGradientColor = tgpu['~unstable']
.fn(
{ ratio: d.f32 },
d.vec4f,
)(/* wgsl */ `{
const getGradientColor = tgpu['~unstable'].fn(
{ ratio: d.f32 },
d.vec4f,
) /* wgsl */`{
let color = mix(purple, blue, ratio);
return color;
}`)
}`
.$uses({ purple, blue })
.$name('getGradientColor');

const mainVertex = tgpu['~unstable'].vertexFn({
in: { vertexIndex: d.builtin.vertexIndex },
out: { outPos: d.builtin.position, uv: d.vec2f },
})(/* wgsl */ `{
}) /* wgsl */`{
var pos = array<vec2f, 3>(
vec2(0.0, 0.5),
vec2(-0.5, -0.5),
Expand All @@ -44,16 +43,14 @@ const mainVertex = tgpu['~unstable'].vertexFn({
);

return Out(vec4f(pos[in.vertexIndex], 0.0, 1.0), uv[in.vertexIndex]);
}`);
}`;

const mainFragment = tgpu['~unstable']
.fragmentFn({
in: { uv: d.vec2f },
out: d.vec4f,
})(/* wgsl */ `{
const mainFragment = tgpu['~unstable'].fragmentFn({
in: { uv: d.vec2f },
out: d.vec4f,
}) /* wgsl */`{
return getGradientColor((in.uv[0] + in.uv[1]) / 2);
}`)
.$uses({ getGradientColor });
}`.$uses({ getGradientColor });

const pipeline = root['~unstable']
.withVertex(mainVertex, {})
Expand Down
62 changes: 27 additions & 35 deletions apps/typegpu-docs/src/content/examples/simulation/confetti/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,28 +90,25 @@ const dataLayout = tgpu
const rotate = tgpu['~unstable'].fn(
{ v: d.vec2f, angle: d.f32 },
d.vec2f,
)(/* wgsl */ `{
) /* wgsl */`{
let pos = vec2(
(v.x * cos(angle)) - (v.y * sin(angle)),
(v.x * sin(angle)) + (v.y * cos(angle))
);

return pos;
}
`);

const mainVert = tgpu['~unstable']
.vertexFn({
in: {
tilt: d.f32,
angle: d.f32,
color: d.vec4f,
center: d.vec2f,
index: d.builtin.vertexIndex,
},
out: VertexOutput,
})(
/* wgsl */ `{
}`;

const mainVert = tgpu['~unstable'].vertexFn({
in: {
tilt: d.f32,
angle: d.f32,
color: d.vec4f,
center: d.vec2f,
index: d.builtin.vertexIndex,
},
out: VertexOutput,
})`/* wgsl */ {
let width = in.tilt;
let height = in.tilt / 2;

Expand All @@ -129,36 +126,31 @@ const mainVert = tgpu['~unstable']
}

return Out(vec4f(pos, 0.0, 1.0), in.color);
}`,
)
.$uses({
rotate,
canvasAspectRatio: canvasAspectRatioUniform,
});
}`.$uses({
rotate,
canvasAspectRatio: canvasAspectRatioUniform,
});

const mainFrag = tgpu['~unstable'].fragmentFn({
in: VertexOutput,
out: d.vec4f,
})(/* wgsl */ `{
return in.color;
}`);
}) /* wgsl */`{ return in.color; }`;

const mainCompute = tgpu['~unstable']
.computeFn({ in: { gid: d.builtin.globalInvocationId }, workgroupSize: [1] })(
/* wgsl */ `{
const mainCompute = tgpu['~unstable'].computeFn({
in: { gid: d.builtin.globalInvocationId },
workgroupSize: [1],
})`/* wgsl */ {
let index = in.gid.x;
if index == 0 {
time += deltaTime;
}
let phase = (time / 300) + particleData[index].seed;
particleData[index].position += particleData[index].velocity * deltaTime / 20 + vec2f(sin(phase) / 600, cos(phase) / 500);
}`,
)
.$uses({
particleData: particleDataStorage,
deltaTime: deltaTimeUniform,
time: timeStorage,
});
}`.$uses({
particleData: particleDataStorage,
deltaTime: deltaTimeUniform,
time: timeStorage,
});

// pipelines

Expand Down
31 changes: 31 additions & 0 deletions packages/typegpu/src/core/function/templateUtils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import type { Implementation } from './fnTypes.ts';

export function stripTemplate(
arg: Implementation | TemplateStringsArray,
...values: unknown[]
): Implementation {
return isTemplateStringsArray(arg)
? templateLiteralIdentity(arg, ...values)
: arg;
}

function isTemplateStringsArray(value: unknown): value is TemplateStringsArray {
return (
Array.isArray(value) &&
'raw' in value &&
Array.isArray(value.raw) &&
value.raw.every((item) => typeof item === 'string')
);
}

function templateLiteralIdentity(
strings: TemplateStringsArray,
...values: unknown[]
): string {
return strings
.slice(1)
.reduce(
(acc, elem, index) => `${acc}${values[index]}${elem}`,
strings[0] as string,
);
}
Loading