A WebGPU implementation based on the excellent wgpu crate.

Last update: May 5, 2022

node-wgpu

A WebGPU implementation based on the excellent wgpu crate.

Work in progress. Just far along enough to execute the following snippet:

[[builtin(position)]] vec4 { let x = f32(i32(in_vertex_index) - 1); let y = f32(i32(in_vertex_index & 1u) * 2 - 1); return vec4(x, y, 0.0, 1.0); } [[stage(fragment)]] fn fs_main() -> [[location(0)]] vec4 { return vec4(1.0, 0.0, 0.0, 1.0); } ` const shaderModule = device.createShaderModule({ code: shaderCode }) const pipelineLayout = device.createPipelineLayout({ bindGroupLayouts: [], }) const renderPipeline = device.createRenderPipeline({ layout: pipelineLayout, vertex: { module: shaderModule, entryPoint: "vs_main", }, fragment: { module: shaderModule, entryPoint: "fs_main", targets: [ { format: "rgba8unorm-srgb" }, ], }, }) const { texture, outputBuffer } = createCapture(device, dimensions) const encoder = device.createCommandEncoder() const renderPass = encoder.beginRenderPass({ colorAttachments: [{ view: texture.createView(), storeOp: "store", loadValue: [0, 1, 0, 1], }], }) renderPass.setPipeline(renderPipeline) renderPass.draw(3, 1) renderPass.end() function createCapture(device, dimensions) { const { padded } = getRowPadding(dimensions.width) const outputBuffer = device.createBuffer({ label: "Capture", size: padded * dimensions.height, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST, }) const texture = device.createTexture({ label: "Capture", size: dimensions, format: "rgba8unorm-srgb", usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC, }) return { outputBuffer, texture } } function getRowPadding(width) { // It is a webgpu requirement that BufferCopyView.layout.bytes_per_row % COPY_BYTES_PER_ROW_ALIGNMENT(256) == 0 // So we calculate padded_bytes_per_row by rounding unpadded_bytes_per_row // up to the next multiple of COPY_BYTES_PER_ROW_ALIGNMENT. // https://en.wikipedia.org/wiki/Data_structure_alignment#Computing_padding const bytesPerPixel = 4 const unpaddedBytesPerRow = width * bytesPerPixel const align = 256 const paddedBytesPerRowPadding = (align - unpaddedBytesPerRow % align) % align const paddedBytesPerRow = unpaddedBytesPerRow + paddedBytesPerRowPadding return { unpadded: unpaddedBytesPerRow, padded: paddedBytesPerRow, } }">
// Adapted from https://github.com/denoland/webgpu-examples/blob/main/hello-triangle/mod.ts
import gpu from "gpu"

const {
    GPUBufferUsage,
    GPUTextureUsage,
} = gpu

const adapter = await gpu.requestAdapter()
const device = await adapter?.requestDevice()

const shaderCode = `
    [[stage(vertex)]]
    fn vs_main([[builtin(vertex_index)]] in_vertex_index: u32) -> [[builtin(position)]] vec4 {
        let x = f32(i32(in_vertex_index) - 1);
        let y = f32(i32(in_vertex_index & 1u) * 2 - 1);
        return vec4(x, y, 0.0, 1.0);
    }

    [[stage(fragment)]]
    fn fs_main() -> [[location(0)]] vec4 {
        return vec4(1.0, 0.0, 0.0, 1.0);
    }
`

const shaderModule = device.createShaderModule({ code: shaderCode })

const pipelineLayout = device.createPipelineLayout({
    bindGroupLayouts: [],
})

const renderPipeline = device.createRenderPipeline({
    layout: pipelineLayout,
    vertex: {
        module: shaderModule,
        entryPoint: "vs_main",
    },
    fragment: {
        module: shaderModule,
        entryPoint: "fs_main",
        targets: [
            { format: "rgba8unorm-srgb" },
        ],
    },
})

const { texture, outputBuffer } = createCapture(device, dimensions)

const encoder = device.createCommandEncoder()

const renderPass = encoder.beginRenderPass({
    colorAttachments: [{
        view: texture.createView(),
        storeOp: "store",
        loadValue: [0, 1, 0, 1],
    }],
})
renderPass.setPipeline(renderPipeline)
renderPass.draw(3, 1)
renderPass.end()

function createCapture(device, dimensions) {
    const { padded } = getRowPadding(dimensions.width)
    const outputBuffer = device.createBuffer({
        label: "Capture",
        size: padded * dimensions.height,
        usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,
    })
    const texture = device.createTexture({
        label: "Capture",
        size: dimensions,
        format: "rgba8unorm-srgb",
        usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
    })
    return { outputBuffer, texture }
}

function getRowPadding(width) {
    // It is a webgpu requirement that BufferCopyView.layout.bytes_per_row % COPY_BYTES_PER_ROW_ALIGNMENT(256) == 0
    // So we calculate padded_bytes_per_row by rounding unpadded_bytes_per_row
    // up to the next multiple of COPY_BYTES_PER_ROW_ALIGNMENT.
    // https://en.wikipedia.org/wiki/Data_structure_alignment#Computing_padding
    const bytesPerPixel = 4
    const unpaddedBytesPerRow = width * bytesPerPixel
    const align = 256
    const paddedBytesPerRowPadding = (align - unpaddedBytesPerRow % align) % align
    const paddedBytesPerRow = unpaddedBytesPerRow + paddedBytesPerRowPadding

    return {
        unpadded: unpaddedBytesPerRow,
        padded: paddedBytesPerRow,
    }
}

GitHub

https://github.com/bnoordhuis/node-wgpu
You might also like...

An implementation of the callbag spec

callbag-rs An implementation of the callbag spec License Licensed under either of Apache License, Version 2.0, (LICENSE-APACHE or https://www.apache.o

May 22, 2022

Reference implementation of a full-stack Rust application

Reference implementation of a full-stack Rust application

Full-stack Rust with WebAssembly Look Ma, No JavaScript !!! My very first Rust project (implementation of the "Connect 5" game), I used as a learning

May 17, 2022

Implementation of the RealWorld backend API spec in Actix, Rust's powerful actor system and most fun web framework.

Implementation of the RealWorld backend API spec in Actix, Rust's powerful actor system and most fun web framework.

Actix codebase containing real world examples (CRUD, auth, advanced patterns, etc) that adheres to the RealWorld spec and API. ❗ (2021/05/13) This cod

May 18, 2022

A minimalistic implementation of Refal.

Refal A minimalistic implementation of Refal. It is based on the following (in Russian) papers by Sergei Romanenko: С.А.Романенко. Машинно-независимый

Apr 7, 2022

A brief implementation of a simple hello world program in rust since they said it couldn't be done.

rust-hello-world A brief blazingly fast 🚀 implementation of a simple hello world program in rust since they said it couldn't be done. 🚀 fast 🚀 Also

Apr 16, 2022

Native WebGPU implementation based on gfx-hal

Native WebGPU implementation based on gfx-hal

This is an active GitHub mirror of the WebGPU implementation in Rust, which now lives in "gfx/wgpu" of Mozilla-central. Issues and pull requests are a

May 20, 2022

A high level, easy to use gpgpu crate based on wgpu

A high level, easy to use gpgpu crate based on wgpu. It is made for very large computations on powerful gpus

Mar 29, 2022

RTS game/engine in Rust and WebGPU

RTS game/engine in Rust and WebGPU

What is this? A real time strategy game/engine written with Rust and WebGPU. Eventually it will be able to run in a web browser thanks to WebGPU. This

May 19, 2022

Windowing support for Deno WebGPU.

Windowing support for Deno WebGPU.

deno_desktop Windowing support for Deno WebGPU. In very early stages at the moment. Usage const win = Deno.createWindow({ title: "Deno Desktop", w

May 14, 2022

wgpugd: A WebGPU Graphics Device for R

wgpugd: A WebGPU Graphics Device for R

wgpugd: A WebGPU Graphics Device for R Overview What is WebGPU? WebGPU is an API that exposes the capabilities of GPU hardware. What is wgpu? As the n

May 15, 2022

Rustification of the excellent GD Script Action RPG Tutorial by youtuber HeartBeast

Rustification of the excellent GD Script Action RPG Tutorial by youtuber HeartBeast

Godot Action RPG w/Rust A GDNative implementation in Rust of youtuber HeartBeast 's great step-by-step turoial series creating a Godot Action RPG, usi

Apr 14, 2022

This is a tool for solving the excellent Wordle puzzle

Wordle Tool This is a tool for solving the excellent Wordle puzzle. It mainly exists as an exercise to learn the (by all accounts) equally excellent R

Jan 17, 2022

xh is a friendly and fast tool for sending HTTP requests. It reimplements as much as possible of HTTPie's excellent design, with a focus on improved performance.

xh is a friendly and fast tool for sending HTTP requests. It reimplements as much as possible of HTTPie's excellent design, with a focus on improved performance.

xh is a friendly and fast tool for sending HTTP requests. It reimplements as much as possible of HTTPie's excellent design, with a focus on improved performance

May 24, 2022

A reimplementation of the excellent word game Wordle by Josh Wardle.

Paudle A reimplementation of the excellent word game Wordle by Josh Wardle. This version was created using Yew and Rust. I cribbed the colors and layo

Mar 28, 2022

A linear algebra library with excellent type safety

Static L.A. (Linear Algebra) A fast minimal ultra type safe linear algebra library. While ndarray offers no compile time type checking on dimensionali

Feb 21, 2022

Apprentice-vscode - a port of @romainl’s excellent Apprentice Vim colour scheme to VS Code

Apprentice-vscode - a port of @romainl’s excellent Apprentice Vim colour scheme to VS Code

Apprentice for VS Code apprentice-vscode is a port of @romainl’s excellent Apprentice Vim colour scheme to VS Code. The theme is available in two vari

May 24, 2022

A modern 3D/2D game engine that uses wgpu.

A modern 3D/2D game engine that uses wgpu.

Harmony A modern 3D/2D game engine that uses wgpu and is designed to work out of the box with minimal effort. It uses legion for handling game/renderi

Mar 27, 2022

A curated list of wgpu code and resources.

Awesome wgpu A curated list of wgpu code and resources. PRs welcome. About wgpu https://github.com/gfx-rs/wgpu-rs matrix chat https://matrix.to/#/#wgp

May 21, 2022

Simple profiler scopes for wgpu using timer queries

wgpu-profiler Simple profiler scopes for wgpu using timer queries Features Easy to use profiler scopes Allows nesting! Can be disabled by runtime flag

May 25, 2022
A Blog & RSS system written in Rust based on Luke Smith's LB.
A Blog & RSS system written in Rust based on Luke Smith's LB.

OB - Oliver's Blog Script A Blog and RSS system written in Rust. Features Converts blog entries written in Markdown into HTML. ✍?? Keeps a rolling blo

May 11, 2022
A minimal and flexible blog generator based on GitHub Gists.
A minimal and flexible blog generator based on GitHub Gists.

gisture Utilizing GitHub Gists as a Blogging Platform A minimal and flexible blog generator based on GitHub Gists with SEO, Templating, Syntax Highlig

Apr 21, 2022
A web application to configuration Caddy based on MoonZoon.

Cream A web application to configuration Caddy based on MoonZoon. MoonZoon is a Rust Fullstack Framework. Live demo Run on a local machine Check you'v

May 16, 2022
📝 Web-based, reactive Datalog notebooks for data analysis and visualization
📝 Web-based, reactive Datalog notebooks for data analysis and visualization

Percival is a declarative data query and visualization language. It provides a reactive, web-based notebook environment for exploring complex datasets, producing interactive graphics, and sharing results.

May 23, 2022
A GUI frontend in Rust based on web-view
A GUI frontend in Rust based on web-view

neutrino I am not working anymore on this project. If you want to become a maintainer of neutrino, please answer to this issue. Preamble Docs | Repo |

May 2, 2022
JLM: A research compiler based on the RVSDG IR

JLM: A research compiler based on the RVSDG IR Jlm is an experimental compiler/optimizer that consumes and produces LLVM IR. It uses the Regionalized

May 3, 2022
Based on the Book Computer Graphics from Scratch
Based on the Book Computer Graphics from Scratch

raytracing_basic v1 Description Based on the Book Computer Graphics from Scratch Dependencies Good Web Game Build and run cargo build --release

Jan 28, 2022
puppy is an example implementation of a tiny Web browser for educational purposes.
puppy is an example implementation of a tiny Web browser for educational purposes.

An example implementation of a tiny Web browser for educational purposes.

May 18, 2022
Rust implementation of the `URLPattern` web API

urlpattern This crate implements the URLPattern web API in Rust. We aim to follow the specification as closely as possible. Contributing We appreciate

May 7, 2022
A pure Rust implementation of the Web Local Storage API, for use in non-browser contexts

Rust Web Local Storage API A Rust implementation of the Web LocalStorage API, for use in non-browser contexts About the Web Local Storage API MDN docs

Mar 22, 2022