Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html lang="ja">
- <head>
- <meta charset="utf-8">
- <meta name="viewport" content="height=device-height, width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
- <title>GPGPU</title>
- </head>
- <body>
- <div id="result"></div>
- </body>
- <script id="shader" type="x-shader/x-compute">
- #version 310 es
- layout (local_size_x = 128, local_size_y = 1, local_size_z = 1) in;
- layout (std430, binding = 0) buffer SSBO {
- float data[];
- } ssbo;
- void main(){
- uint threadIndex = gl_GlobalInvocationID.x;
- ssbo.data[threadIndex] = float(threadIndex);
- }
- </script>
- <script>
- class GPGPU{
- ctx;
- program;
- constructor(src){
- this.ctx = new OffscreenCanvas(0, 0).getContext("webgl2-compute");
- this.program = this.ctx.createProgram();
- const shader = this.ctx.createShader(this.ctx.COMPUTE_SHADER);
- this.ctx.shaderSource(shader, src);
- this.ctx.compileShader(shader);
- if(!this.ctx.getShaderParameter(shader, this.ctx.COMPILE_STATUS)){
- console.log(this.ctx.getShaderInfoLog(shader));
- return;
- }
- this.ctx.attachShader(this.program, shader);
- this.ctx.linkProgram(this.program);
- if(!this.ctx.getProgramParameter(this.program, this.ctx.LINK_STATUS)){
- console.log(this.ctx.getProgramInfoLog(this.program));
- return;
- }
- }
- compute(input){
- const ssbo = this.ctx.createBuffer();
- this.ctx.bindBuffer(this.ctx.SHADER_STORAGE_BUFFER, ssbo);
- this.ctx.bufferData(this.ctx.SHADER_STORAGE_BUFFER, input, this.ctx.DYNAMIC_COPY);
- this.ctx.bindBufferBase(this.ctx.SHADER_STORAGE_BUFFER, 0, ssbo);
- this.ctx.useProgram(this.program);
- this.ctx.dispatchCompute(1, 1, 1);
- const result = new Float32Array(input.length);
- this.ctx.getBufferSubData(this.ctx.SHADER_STORAGE_BUFFER, 0, result);
- return result;
- }
- }
- const gpgpu = new GPGPU(document.getElementById("shader").textContent.trim());
- document.getElementById("result").textContent = gpgpu.compute(new Float32Array(8));
- </script>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement