JSFiddle - React, Tailwind, and code Playground

by emadurandal

HTML

<canvas id="world" width="400" height="400"></canvas>

TypeScript

(async()=>{

const quadVertexSize = 4 * 8; // Byte size of one vertex.
const quadPositionOffset = 4 * 0;
const quadColorOffset = 4 * 4; // Byte offset of cube vertex color attribute.
const quadVertexCount = 4;

const quadVertexArray = new Float32Array([
  // float4 position, float4 color
  -1,  1, 0, 1,   0, 1, 0, 1,
  -1, -1, 0, 1,   0, 0, 0, 1,
   1, -1, 0, 1,   1, 0, 0, 1,
   1,  1, 0, 1,   1, 1, 0, 1,
]);

const quadIndexArray = new Uint16Array([0, 1, 2, 0, 2, 3]);

const vertWGSL = `
struct VertexOutput {
  @builtin(position) Position : vec4<f32>,
  @location(0) fragColor : vec4<f32>,
}

@vertex
fn main(
  @location(0) position: vec4<f32>,
  @location(1) color: vec4<f32>
) -> VertexOutput {

	var output : VertexOutput;
  output.Position = position;
  output.fragColor = color;
  
  return output;
}
`;

const fragWGSL = `
@fragment
fn main(
  @location(0) fragColor: vec4<f32>,
) -> @location(0) vec4<f32> {
  return fragColor;
}
`;

const g_adapter = await navigator.gpu.requestAdapter();
const g_device = await g_adapter!.requestDevice();

async function init(canvas: HTMLCanvasElement): Promise<{context: GPUCanvasContext, pipeline: GPURenderPipeline, verticesBuffer: GPUBuffer, indicesBuffer: GPUBuffer}> {

  const context = canvas.getContext('webgpu') as GPUCanvasContext;

  const presentationFormat = navigator.gpu.getPreferredCanvasFormat();
  context.configure({
    device: g_device,
    format: presentationFormat,
    alphaMode: 'opaque',
  });

  // create a render pipeline
  const pipeline = g_device.createRenderPipeline({
    layout: 'auto',
    vertex: {
      module: g_device.createShaderModule({
        code: vertWGSL,
      }),
      entryPoint: 'main',
      buffers: [
        {
          // 配列の要素間の距離をバイト単位で指定します。
          arrayStride: quadVertexSize,

          // 頂点バッファの属性を指定します。
          attributes: [
            {
              // position
              shaderLocation: 0, // @location(0) in vertex shader
              offset:...