TypeGPU

TypeGPU: Typed Shader Code Without Hand-Written WGSL

TypeGPU 320,420 (software-mansion/TypeGPU (https://github.com/software-mansion/TypeGPU 3,241 ), MIT, 0.12.6) makes one schema describe data on both sides. d.struct() defines a type once; TypeGPU derives the WGSL struct, the byte layout with its padding (Arrays and Alignment's rules, which Shared Book Struct applied by hand), and the JavaScript reads and writes. Here BookNest's prices and ratings go up in a typed buffer, a compute shader writes sale prices (25% off books rated 4.5 or more, 10% off the rest), and they come back as objects:

demos/ch04/typegpu-sale.html: a typed buffer and compute shader with TypeGPUHTMLLive
<script type="module">
import { tgpu, d } from 'https://cdn.jsdelivr.net/npm/typegpu@0.12.6/+esm';
const Book = d.struct({ price: d.f32, rating: d.f32, sale: d.f32 }).$name('Book');
const root = await tgpu.init();                          // adapter, device, error handling
const books = root.createMutable(d.arrayOf(Book, 6), [[14.99, 4.6], [39.5, 4.3], [24, 4.8],
  [18.75, 4.1], [16.2, 4.5], [21.3, 4.4]].map(([price, rating]) => ({ price, rating, sale: 0 })));
const discount = tgpu.computeFn({ in: { id: d.builtin.globalInvocationId },
  workgroupSize: [64] })`{
    if (in.id.x >= 6) { return; }
    let off = select(0.10, 0.25, books[in.id.x].rating >= 4.5);   // better books, bigger sale
    books[in.id.x].sale = round(books[in.id.x].price * (1 - off) * 100) / 100;
  }`.$uses({ books });                                   // binds the buffer by name
root.createComputePipeline({ compute: discount }).dispatchWorkgroups(1);
const result = await books.read();                       // typed objects, not raw bytes
console.log(result.map((b) => `${b.price.toFixed(2)}->${b.sale.toFixed(2)}`).join(' '));
console.log(tgpu.resolve([discount]).split('\n').slice(0, 7).join('\n'));
window.__done = true;
</script>

The last lines are the WGSL TypeGPU generated: the struct and a binding you never declared. TypeGPU can also compile JavaScript functions marked 'use gpu' into WGSL, so one function runs on CPU and GPU, but that needs its build plugin, unplugin-typegpu, for Vite 25,978 , webpack 3,824 or Babel 41,624 : loaded straight from the CDN, such a function failed with "Missing metadata for tgpu.fn function body". Install with npm 2,036 install typegpu and add the plugin to use it.