WebGPU Example Cube Texture Rotation transform camera no lighting var script document createElement script script type text javascript script async false script src https cdnjs cloudflare com ajax libs gl matrix 2 6 0 gl matrix min js document head appendChild script const canvas document createElement canvas document body appendChild canvas canvas width 400 canvas height 400 console log canvas width console log canvas height const gpu navigator gpu console log gpu const adapter await gpu requestAdapter const device await adapter requestDevice const context canvas getContext webgpu Set up WebGPU texture image const img document createElement img img src https notebook xbdev net var images food jpg await Promise all img decode context getPreferredFormat adapter no longer supported const presentationFormat navigator gpu getPreferredCanvasFormat context configure device format presentationFormat Create texture sampler and load data const imageCanvas document createElement canvas imageCanvas width img width imageCanvas height img height const imageCanvasContext imageCanvas getContext 2d imageCanvasContext drawImage img 0 0 img width img height const imageData imageCanvasContext getImageData 0 0 img width img height let textureData null const rowPitch Math ceil img width 4 256 256 if rowPitch img width 4 textureData imageData data else textureData new Uint8Array rowPitch img height for let y 0 y img height y for let x 0 x img width x let i x 4 y rowPitch textureData i imageData data i textureData i 1 imageData data i 1 textureData i 2 imageData data i 2 textureData i 3 imageData data i 3 console log textureData byteLength textureData byteLength const sampler device createSampler minFilter linear magFilter linear const texture device createTexture size img width img height 1 format rgba8unorm usage 0x4 0x2 GPUTextureUsage COPY_DST GPUTextureUsage TEXTURE_BINDING if typeof device queue writeTexture function console log device queue writeTexture supported device queue writeTexture texture textureData bytesPerRow img width 4 img width img height 1 else NOTE Fallback if Queue writeTexture isn t implemented const textureDataBuffer device createBuffer size textureData byteLength usage GPUBufferUsage COPY_DST GPUBufferUsage COPY_SRC device queue writeBuffer textureDataBuffer 0 textureData const textureLoadEncoder device createCommandEncoder textureLoadEncoder copyBufferToTexture buffer textureDataBuffer bytesPerRow img width 4 imageHeight img height texture img width img height 1 device queue submit textureLoadEncoder finish Create vertex buffers and load data function createCube options options options let dimensions options dimensions 1 1 1 let position options position dimensions 0 2 dimensions 1 2 dimensions 2 2 let x position 0 let y position 1 let z position 2 let width dimensions 0 let height dimensions 1 let depth dimensions 2 let fbl x x y y z z depth let fbr x x width y y z z depth let ftl x x y y height z z depth let ftr x x width y y height z z depth let bbl x x y y z z let bbr x x width y y z z let btl x x y y height z z let btr x x width y y height z z let positions new Float32Array front fbl x fbl y fbl z fbr x fbr y fbr z ftl x ftl y ftl z ftl x ftl y ftl z fbr x fbr y fbr z ftr x ftr y ftr z right fbr x fbr y fbr z bbr x bbr y bbr z ftr x ftr y ftr z ftr x ftr y ftr z bbr x bbr y bbr z btr x btr y btr z back fbr x bbr y bbr z bbl x bbl y bbl z btr x btr y btr z btr x btr y btr z bbl x bbl y bbl z btl x btl y btl z left bbl x bbl y bbl z fbl x fbl y fbl z btl x btl y btl z btl x btl y btl z fbl x fbl y fbl z ftl x ftl y ftl z top ftl x ftl y ftl z ftr x ftr y ftr z btl x btl y btl z btl x btl y btl z ftr x ftr y ftr z btr x btr y btr z bottom bbl x bbl y bbl z bbr x bbr y bbr z fbl x fbl y fbl z fbl x fbl y fbl z bbr x bbr y bbr z fbr x fbr y fbr z let uvs new Float32Array front 0 0 1 0 0 1 0 1 1 0 1 1 right 0 0 1 0 0 1 0 1 1 0 1 1 back 0 0 1 0 0 1 0 1 1 0 1 1 left 0 0 1 0 0 1 0 1 1 0 1 1 top 0 0 1 0 0 1 0 1 1 0 1 1 bottom 0 0 1 0 0 1 0 1 1 0 1 1 return positions uvs const cubeData createCube const numVertices cubeData positions length 3 const positionBuffer device createBuffer size cubeData positions byteLength usage GPUBufferUsage VERTEX GPUBufferUsage COPY_DST const uvBuffer device createBuffer size cubeData uvs byteLength usage GPUBufferUsage VERTEX GPUBufferUsage COPY_DST device queue writeBuffer positionBuffer 0 cubeData positions device queue writeBuffer uvBuffer 0 cubeData uvs Uniform data const projectionMatrix mat4 create const viewMatrix mat4 create const modelMatrix mat4 create const viewProjectionMatrix mat4 create const mvpMatrix mat4 create const rotation 0 0 0 mat4 perspective projectionMatrix Math PI 2 canvas width canvas height 0 1 10 0 mat4 lookAt viewMatrix 1 1 1 0 0 0 0 1 0 out eye center up mat4 multiply viewProjectionMatrix projectionMatrix viewMatrix Create uniform buffers and binding layout const vertexUniformBuffer device createBuffer size 64 usage GPUBufferUsage UNIFORM GPUBufferUsage COPY_DST device queue writeBuffer vertexUniformBuffer 0 viewProjectionMatrix const sceneUniformBindGroupLayout device createBindGroupLayout entries binding 0 visibility GPUShaderStage VERTEX buffer type uniform binding 1 visibility GPUShaderStage FRAGMENT sampler type filtering binding 2 visibility GPUShaderStage FRAGMENT texture sampleType float const sceneUniformBindGroup device createBindGroup layout sceneUniformBindGroupLayout entries binding 0 resource buffer vertexUniformBuffer binding 1 resource sampler binding 2 resource texture createView Create render pipeline let basicVertWGSL struct Uniforms modelViewProjectionMatrix mat4x4 f32 binding 0 group 0 var uniform uniforms Uniforms struct VertexOutput builtin position Position vec4 f32 location 0 fragUV vec2 f32 location 1 fragPosition vec4 f32 vertex fn main location 0 position vec4 f32 location 1 uv vec2 f32 VertexOutput var output VertexOutput output Position uniforms modelViewProjectionMatrix position output fragUV uv output fragPosition 0 5 position vec4 f32 1 0 1 0 1 0 1 0 return output let basicPixelWGSL group 0 binding 1 var mySampler sampler group 0 binding 2 var myTexture texture_2d f32 fragment fn main location 0 fragUV vec2 f32 location 1 fragPosition vec4 f32 location 0 vec4 f32 basic textured return textureSample myTexture mySampler fragUV if you want a retro color mixing in position return textureSample myTexture mySampler fragUV fragPosition if you want a constant color for the shape return vec4 f32 1 0 0 0 1 0 1 0 const pipeline device createRenderPipeline layout device createPipelineLayout bindGroupLayouts sceneUniformBindGroupLayout vertex module device createShaderModule code basicVertWGSL entryPoint main buffers arrayStride 12 attributes shaderLocation 0 format float32x3 offset 0 arrayStride 8 attributes shaderLocation 1 format float32x2 offset 0 fragment module device createShaderModule code basicPixelWGSL entryPoint main targets format presentationFormat primitive topology triangle list cullMode back depthStencil format depth24plus depthWriteEnabled true depthCompare less Render pass description const depthTexture device createTexture size canvas width canvas height 1 format depth24plus usage GPUTextureUsage RENDER_ATTACHMENT const renderPassDescription colorAttachments view context getCurrentTexture createView loadValue 0 1 0 1 clear screen to green loadOp clear clearValue 0 1 1 1 clear screen storeOp store depthStencilAttachment view depthTexture createView depthLoadOp clear depthClearValue 1 depthStoreOp store depthLoadValue 1 depthStoreOp store stencilLoadValue 0 stencilStoreOp store let translateMat mat4 create let rotateXMat mat4 create let rotateYMat mat4 create let rotateZMat mat4 create let scaleMat mat4 create function draw Update uniform buffer function xformMatrix xform translate rotate scale translate translate 0 0 0 rotate rotate 0 0 0 scale scale 1 1 1 mat4 fromTranslation translateMat translate mat4 fromXRotation rotateXMat rotate 0 mat4 fromYRotation rotateYMat rotate 1 mat4 fromZRotation rotateZMat rotate 2 mat4 fromScaling scaleMat scale mat4 multiply xform rotateXMat scaleMat mat4 multiply xform rotateYMat xform mat4 multiply xform rotateZMat xform mat4 multiply xform translateMat xform mat4 multiply xform viewMatrix xform mat4 multiply xform projectionMatrix xform rotation 0 0 01 rotation 2 0 005 xformMatrix modelMatrix null rotation null device queue writeBuffer vertexUniformBuffer 0 modelMatrix Swap framebuffer renderPassDescription colorAttachments 0 view context getCurrentTexture createView const commandEncoder device createCommandEncoder const renderPass commandEncoder beginRenderPass renderPassDescription renderPass setPipeline pipeline First argument here refers to array index in pipeline vertexState vertexBuffers renderPass setVertexBuffer 0 positionBuffer renderPass setVertexBuffer 1 uvBuffer First argument here refers to array index in pipeline layout bindGroupLayouts renderPass setBindGroup 0 sceneUniformBindGroup renderPass draw numVertices 1 0 0 renderPass endPass no longer supported renderPass end device queue submit commandEncoder finish requestAnimationFrame draw draw
ate const viewProjectionMatrix mat4 create const mvpMatrix mat4 create const rotation 0 0 0 mat4 perspective projectionMatrix Math PI 2 canvas width canvas height 0 1 10 0 mat4 lookAt viewMatrix 1 1 1 0 0 0 0 1 0 out eye center up mat4 multiply viewProjectionMatrix projectionMatrix viewMatrix Create uniform buffers and binding layout const vertexUniformBuffer device createBuffer size 64 usage GPUBufferUsage UNIFORM GPUBufferUsage COPY_DST device queue writeBuffer vertexUniformBuffer 0 viewProjectionMatrix const sceneUniformBindGroupLayout device createBindGroupLayout entries binding 0 visibility GPUShaderStage VERTEX buffer type uniform binding 1 visibility GPUShaderStage FRAGMENT sampler type filtering binding 2 visibility GPUShaderStage FRAGMENT texture sampleType float const sceneUniformBindGroup device createBindGroup layout sceneUniformBindGroupLayout entries binding 0 resource buffer vertexUniformBuffer binding 1 resource sampler binding 2 resource texture createView Create render pipeline let basicVertWGSL struct Uniforms modelViewProjectionMatrix mat4x4 f32 binding 0 group 0 var uniform uniforms Uniforms struct VertexOutput builtin position Position vec4 f32 location 0 fragUV vec2 f32 location 1 fragPosition vec4 f32 vertex fn main location 0 position vec4 f32 location 1 uv vec2 f32 VertexOutput var output VertexOutput output Position uniforms modelViewProjectionMatrix position output fragUV uv output fragPosition 0 5 position vec4 f32 1 0 1 0 1 0 1 0 return output let basicPixelWGSL group 0 binding 1 var mySampler sampler group 0 binding 2 var myTexture texture_2d f32 fragment fn main location 0 fragUV vec2 f32 location 1 fragPosition vec4 f32 location 0 vec4 f32 basic textured return textureSample myTexture mySampler fragUV if you want a retro color mixing in position return textureSample myTexture mySampler fragUV fragPosition if you want a constant color for the shape return vec4 f32 1 0 0 0 1 0 1 0 const pipeline device createRenderPipeline layout device createPipelineLayout bindGroupLayouts sceneUniformBindGroupLayout vertex module device createShaderModule code basicVertWGSL entryPoint main buffers arrayStride 12 attributes shaderLocation 0 format float32x3 offset 0 arrayStride 8 attributes shaderLocation 1 format float32x2 offset 0 fragment module device createShaderModule code basicPixelWGSL entryPoint main targets format presentationFormat primitive topology triangle list cullMode back depthStencil format depth24plus depthWriteEnabled true depthCompare less Render pass description const depthTexture device createTexture size canvas width canvas height 1 format depth24plus usage GPUTextureUsage RENDER_ATTACHMENT const renderPassDescription colorAttachments view context getCurrentTexture createView loadValue 0 1 0 1 clear screen to green loadOp clear clearValue 0 1 1 1 clear screen storeOp store depthStencilAttachment view depthTexture createView depthLoadOp clear depthClearValue 1 depthStoreOp store depthLoadValue 1 depthStoreOp store stencilLoadValue 0 stencilStoreOp store let translateMat mat4 create let rotateXMat mat4 create let rotateYMat mat4 create let rotateZMat mat4 create let scaleMat mat4 create function draw Update uniform buffer function xformMatrix xform translate rotate scale translate translate 0 0 0 rotate rotate 0 0 0 scale scale 1 1 1 mat4 fromTranslation translateMat translate mat4 fromXRotation rotateXMat rotate 0 mat4 fromYRotation rotateYMat rotate 1 mat4 fromZRotation rotateZMat rotate 2 mat4 fromScaling scaleMat scale mat4 multiply xform rotateXMat scaleMat mat4 multiply xform rotateYMat xform mat4 multiply xform rotateZMat xform mat4 multiply xform translateMat xform mat4 multiply xform viewMatrix xform mat4 multiply xform projectionMatrix xform rotation 0 0 01 rotation 2 0 005 xformMatrix modelMatrix null rotation null device queue writeBuffer vertexUniformBuffer 0 modelMatrix Swap framebuffer renderPassDescription colorAttachments 0 view context getCurrentTexture createView const commandEncoder device createCommandEncoder const renderPass commandEncoder beginRenderPass renderPassDescription renderPass setPipeline pipeline First argument here refers to array index in pipeline vertexState vertexBuffers renderPass setVertexBuffer 0 positionBuffer renderPass setVertexBuffer 1 uvBuffer First argument here refers to array index in pipeline layout bindGroupLayouts renderPass setBindGroup 0 sceneUniformBindGroup renderPass draw numVertices 1 0 0 renderPass endPass no longer supported renderPass end device queue submit commandEncoder finish requestAnimationFrame draw draw