Created
October 1, 2025 20:11
-
-
Save devsnek/6665fd92aded0feada41cd32cee97810 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const SHADER = `\ | |
| struct DataBuf { | |
| data: array<f32>, | |
| } | |
| @group(0) | |
| @binding(0) | |
| var<storage, read_write> v_indices: DataBuf; | |
| @compute | |
| @workgroup_size(64) | |
| fn main(@builtin(global_invocation_id) id: vec3<u32>) { | |
| v_indices.data[id.x] = sin(v_indices.data[id.x]); | |
| } | |
| `; | |
| const adapter = await navigator.gpu.requestAdapter(); | |
| const device = await adapter!.requestDevice(); | |
| const shaderModule = device.createShaderModule({ code: SHADER }); | |
| const bindGroupLayout = device.createBindGroupLayout({ | |
| entries: [{ | |
| binding: 0, | |
| visibility: GPUShaderStage.COMPUTE, | |
| buffer: { | |
| type: "storage", | |
| }, | |
| }], | |
| }); | |
| const computePipelineLayout = device.createPipelineLayout({ | |
| bindGroupLayouts: [bindGroupLayout], | |
| }); | |
| const pipeline = device.createComputePipeline({ | |
| layout: computePipelineLayout, | |
| compute: { | |
| entryPoint: "main", | |
| module: shaderModule, | |
| }, | |
| }); | |
| const SIZE = 256; | |
| const input = new Float32Array( | |
| Array.from({ length: SIZE }, (_, i) => i / (SIZE / (3.14 * 2))), | |
| ); | |
| const inputBuf = device.createBuffer({ | |
| size: input.byteLength, | |
| usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST, | |
| }); | |
| device.queue.writeBuffer(inputBuf, 0, input); | |
| const outputBuf = device.createBuffer({ | |
| size: input.byteLength, | |
| usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST, | |
| }); | |
| const bindGroup = device.createBindGroup({ | |
| layout: bindGroupLayout, | |
| entries: [{ | |
| binding: 0, | |
| resource: { buffer: inputBuf }, | |
| }], | |
| }); | |
| const encoder = device.createCommandEncoder(); | |
| const cpass = encoder.beginComputePass(); | |
| cpass.setPipeline(pipeline); | |
| cpass.setBindGroup(0, bindGroup); | |
| cpass.dispatchWorkgroups(input.length / 64, 1, 1); | |
| cpass.end(); | |
| encoder.copyBufferToBuffer(inputBuf, 0, outputBuf, 0, input.byteLength); | |
| device.queue.submit([encoder.finish()]); | |
| await outputBuf.mapAsync(GPUMapMode.READ); | |
| const data = new Float32Array(outputBuf.getMappedRange()); | |
| import asciichart from "npm:asciichart"; | |
| console.log(asciichart.plot(data, { height: 30 })); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment