Skip to content

feat: Add @typegpu/three package and Three.js integration example #1453

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

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all 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
3 changes: 3 additions & 0 deletions apps/typegpu-docs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
"@tailwindcss/vite": "^4.1.6",
"@typegpu/color": "workspace:*",
"@typegpu/noise": "workspace:*",
"@typegpu/three": "workspace:*",
"three": "^0.178.0",
"@types/dom-mediacapture-transform": "^0.1.9",
"@types/react": "^19.0.10",
"@types/react-dom": "^19.0.4",
Expand Down Expand Up @@ -59,6 +61,7 @@
"@types/babel__template": "^7.4.4",
"@types/babel__traverse": "^7.20.7",
"@types/node": "^24.0.3",
"@types/three": "catalog:types",
"@webgpu/types": "catalog:types",
"astro-vtbot": "^2.0.6",
"autoprefixer": "^10.4.21",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<canvas></canvas>
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import tgpu from 'typegpu';
import * as THREE from 'three/webgpu';
import * as t from '@typegpu/three';
import * as d from 'typegpu/data';
import { uv } from 'three/tsl';

const canvas = document.querySelector('canvas') as HTMLCanvasElement;

const tgpuMaterial = new t.TypeGPUMaterial(
tgpu.fn([d.vec2f], d.vec4f)((uv) => {
return d.vec4f(uv.x, uv.y, 0.5, 1);
}),
[uv()],
);

const renderer = new THREE.WebGPURenderer({ canvas });
await renderer.init();

renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(canvas.clientWidth, canvas.clientHeight, false);

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000,
);
camera.position.z = 5;

const mesh = new THREE.Mesh(
new THREE.BoxGeometry(1, 1, 1),
tgpuMaterial,
);
scene.add(mesh);

const resizeObserver = new ResizeObserver((entries) => {
for (const entry of entries) {
const width = entry.contentRect.width;
const height = entry.contentRect.height;
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
});
resizeObserver.observe(canvas);

renderer.setAnimationLoop(() => {
mesh.rotation.x += 0.01;
mesh.rotation.y += 0.01;
renderer.render(scene, camera);
});

export function onCleanup() {
renderer.dispose();
resizeObserver.disconnect();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"title": "Three.js",
"category": "rendering",
"tags": ["experimental"]
}
9 changes: 9 additions & 0 deletions packages/typegpu-three/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<div align="center">

# @typegpu/three

🚧 **Under Construction** 🚧

</div>

A helper library for using TypeGPU with Three.js.
12 changes: 12 additions & 0 deletions packages/typegpu-three/build.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { type BuildConfig, defineBuildConfig } from 'unbuild';
import typegpu from 'unplugin-typegpu/rollup';

const Config: BuildConfig[] = defineBuildConfig({
hooks: {
'rollup:options': (_options, config) => {
config.plugins.push(typegpu({ include: [/\.ts$/] }));
},
},
});

export default Config;
7 changes: 7 additions & 0 deletions packages/typegpu-three/deno.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"exclude": ["."],
"fmt": {
"exclude": ["!."],
"singleQuote": true
}
}
46 changes: 46 additions & 0 deletions packages/typegpu-three/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
{
"name": "@typegpu/three",
"type": "module",
"version": "0.0.0",
"description": "Utilities for integrating TypeGPU with Three.js",
"exports": {
".": "./src/index.ts",
"./package.json": "./package.json"
},
"publishConfig": {
"directory": "dist",
"linkDirectory": false,
"main": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"exports": {
"./package.json": "./dist/package.json",
".": {
"types": "./dist/index.d.ts",
"module": "./dist/index.mjs",
"import": "./dist/index.mjs",
"default": "./dist/index.cjs"
}
}
},
"sideEffects": false,
"scripts": {
"build": "unbuild",
"test:types": "pnpm tsc --p ./tsconfig.json --noEmit",
"prepublishOnly": "tgpu-dev-cli prepack"
},
"keywords": [],
"license": "MIT",
"peerDependencies": {
"typegpu": "^0.5.9",
"three": ">0.126.0"
},
"devDependencies": {
"@typegpu/tgpu-dev-cli": "workspace:*",
"@webgpu/types": "catalog:types",
"@types/three": "catalog:types",
"typegpu": "workspace:*",
"typescript": "catalog:types",
"unbuild": "catalog:build",
"unplugin-typegpu": "workspace:*"
}
}
1 change: 1 addition & 0 deletions packages/typegpu-three/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './tgpuThree.ts';
105 changes: 105 additions & 0 deletions packages/typegpu-three/src/tgpuThree.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import * as THREE from 'three/webgpu';
import tgpu, { type TgpuFn } from 'typegpu';

class FragmentNode extends THREE.CodeNode {
private tgslFn: TgpuFn;
private functionName: string | null | undefined;
private threeVars: THREE.TSL.ShaderNodeObject<THREE.Node>[] | undefined;
private argNames: string[] | undefined;

constructor(
tgslFn: TgpuFn,
threeRequirements?: THREE.TSL.ShaderNodeObject<THREE.Node>[] | undefined,
) {
const resolved = tgpu.resolve({
template: '___ID___ fnName',
externals: { fnName: tgslFn },
});
const [code, functionName] = resolved.split('___ID___').map((s) =>
s.trim()
);
let counter = 0;
const args = tgslFn.shell.argTypes.map((type) =>
`TGPUArg${counter++}_${type.type}`
);
const threeArgs = threeRequirements
? threeRequirements.map((node, i) => node.toVar(args[i]))
: [];

super(code, [...threeArgs], 'wgsl');

this.functionName = functionName;
this.threeVars = threeArgs;
this.argNames = args;
this.tgslFn = tgslFn;
}

static get type() {
return 'FunctionNode';
}

getNodeType(builder: THREE.NodeBuilder) {
return this.getNodeFunction(builder).type;
}

getInputs(builder: THREE.NodeBuilder) {
return this.getNodeFunction(builder).inputs;
}

getNodeFunction(builder: THREE.NodeBuilder) {
const nodeData = builder.getDataFromNode(this);

// @ts-expect-error <- Three.js types suck
let nodeFunction = nodeData.nodeFunction;

if (nodeFunction === undefined) {
nodeFunction = builder.parser.parseFunction(this.code);
// @ts-expect-error <- Three.js types suck
nodeData.nodeFunction = nodeFunction;
}

return nodeFunction;
}

generate(
builder: THREE.NodeBuilder,
output: string | null | undefined,
): string | null | undefined {
super.generate(builder);

const nodeFunction = this.getNodeFunction(builder);

const name = nodeFunction.name;
const type = nodeFunction.type;

const nodeCode = builder.getCodeFromNode(this, type);

if (name !== '') {
// @ts-expect-error <- Three.js types suck
nodeCode.name = name;
}

// @ts-expect-error <- Three.js types suck
const propertyName = builder.getPropertyName(nodeCode, 'fragment');

const code = this.getNodeFunction(builder).getCode(propertyName);
// @ts-expect-error <- Three.js types suck
nodeCode.code = `${code}\n`;

if (output === 'property') {
return this.functionName;
}
return `${this.functionName}(${this.argNames?.join(', ')})`;
}
}

export class TypeGPUMaterial extends THREE.NodeMaterial {
constructor(
fragmentFn: TgpuFn,
threeRequirements?: THREE.TSL.ShaderNodeObject<THREE.Node>[] | undefined,
) {
super();

this.fragmentNode = new FragmentNode(fragmentFn, threeRequirements);
}
}
5 changes: 5 additions & 0 deletions packages/typegpu-three/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"extends": "../../tsconfig.base.json",
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
Loading