深入理解WebGPU

WebGPU 培訓

WebGPU是什麼? 它是一個在瀏覽器中實現低級圖形渲染的API,可以讓Web開發人員利用GPU提高渲染性能。WebGPU支持多種GPU,並允許Web應用程序通過JavaScript,WebAssembly或HLSL代碼與GPU通信。

WebGPU可與WebGL和WebXR等其他Web圖形API配合使用,但它是更先進和更靈活的API,提供了更多的控制權和更好的性能,從而更適合處理複雜和大型3D場景。

要使用WebGPU,需要使用最新的Web瀏覽器(如Chrome)和支持WebGPU的GPU。

  const adapter = await navigator.gpu.requestAdapter();
  const device = await adapter.requestDevice();

使用WebGPU,我們需要獲取GPU的適配器(adapter)和設備(device),並將其存儲在變數中,以便我們可以在GPU上執行操作。

實用WebGPU

1. 使用WebGPU渲染三角形

在使用WebGPU渲染三角形之前,需要進行一些準備工作。我們需要編寫代碼來創建窗口、初始化WebGPU並定義渲染器所需的常量和資源。在這裡,我們使用了GLSL作為著色語言。

  let vertexShader =
  `
  #version 450
  layout(location = 0) in vec3 pos;
  void main() {
        gl_Position = vec4(pos, 1.0);
  }
  `;
  let fragmentShader =
  `
  #version 450
  layout(location = 0) out vec4 outColor;
  void main() {
        outColor = vec4(1.0, 1.0, 1.0, 1.0);
  }
  `;
  async function main() {
        // Step 1: Create a window to render into.
        const canvas = document.createElement('canvas');
        document.body.appendChild(canvas);
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
      
        // Step 2: Initialize WebGPU and create the "context".
        const adapter = await navigator.gpu.requestAdapter();
        const device = await adapter.requestDevice();
        const context = canvas.getContext('gpupresent');
      
        // Step 3: Define the shader modules (i.e. the shader code).
        const shaderModule =
              device.createShaderModule({
                    code: vertexShader
              });
      
        const fragModule = device.createShaderModule({
              code: fragmentShader
        });
      
        // Step 4: Define the pipeline layout. This specifies the vertex input
        // format, and any other inputs we will be using in our shaders.
        const layout = device.createPipelineLayout({
              bindGroupLayouts: []
        });
      
        // Step 5: Define the render pipeline. This specifies the shaders to use,
        // as well as the pipeline layout from step 4.
        const pipeline = device.createRenderPipeline({
              layout,
              vertex: {
                  module: shaderModule,
                  entryPoint: 'main',
                  buffers: [{
                        arrayStride: 12,
                        attributes: [{
                              shaderLocation: 0,
                              offset: 0,
                              format: 'float3'
                        }]
                  }]
              },
              fragment: {
                  module: fragModule,
                  entryPoint: 'main',
                  targets: [{
                        format: 'rgba8unorm'
                  }]
              },
              primitive: {
                  topology: 'triangle-list',
                  stripIndexFormat: undefined,
                  frontFace: 'ccw',
                  cullMode: 'none',
                  clampDepth: false
              },
              depthStencil: {
                  format: undefined,
                  depthWriteEnabled: false,
                  depthCompare: 'always',
                  stencilFront: {
                        compare: 'always',
                        failOp: 'keep',
                        passOp: 'keep',
                        depthFailOp: 'keep'
                  },
                  stencilBack: {
                        compare: 'always',
                        failOp: 'keep',
                        passOp: 'keep',
                        depthFailOp: 'keep'
                  },
                  stencilReadMask: 0xff,
                  stencilWriteMask: 0xff
              }
        });
      
        // Step 6: Define the uniform buffer.
        const uniformBuffer = device.createBuffer({
              size: 16,
              usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
        });
        const uniformBindGroup = device.createBindGroup({
              layout: pipeline.getBindGroupLayout(0),
              entries: [{
                    binding: 0,
                    resource: {
                          buffer: uniformBuffer
                    }
              }]
        });
      
        // Step 7: Define the render loop.
        function update() {
              const renderPassDescriptor = {
                    colorAttachments: [{
                          attachment: context.getCurrentTexture().createView(),
                          loadValue: [0, 0, 0, 1],
                          storeOp: 'store'
                    }]
              };
        
              const commandEncoder = device.createCommandEncoder();
              const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
              passEncoder.setPipeline(pipeline);
              passEncoder.setBindGroup(0, uniformBindGroup);
              passEncoder.draw(3, 1, 0, 0);
              passEncoder.endPass();
        
              device.queue.submit([commandEncoder.finish()]);
              requestAnimationFrame(update);
        }
      
        requestAnimationFrame(update);
  }
  main();

WebGPU React

使用WebGPU與React結合使用可以快速創建高性能的3D應用程序。下面的示例代碼演示了如何在React中使用Jaspr和WebGPU來渲染一個簡單的3D場景。

1. 在React中使用WebGPU渲染3D場景

  import * as THREE from 'three';
import {
  useResource,
  useFrame,
  Canvas,
} from 'react-three-fiber';
import Jaspr from 'jaspr';

function TriangleMesh(props) {
  const geometry = new THREE.Geometry();
  geometry.vertices.push(
    new THREE.Vector3(-1, 0, 0),
    new THREE.Vector3(0, 1, 0),
    new THREE.Vector3(1, 0, 0),
  );
  geometry.faces.push(new THREE.Face3(0, 1, 2));
  const [meshRef] = useResource();
  useFrame(({ clock }) => {
    meshRef.rotation.x = clock.getElapsedTime() * 0.5;
    meshRef.rotation.y = clock.getElapsedTime() * 0.8;
  });
  return (
    
      
         v.toArray())}
          itemSize={3}
        />
      
      
    
  );
}

function Scene() {
  return (
    
      
    
  );
}

function App() {
  return (
     {
        gl.getContext().makeCurrent();
      }}
    >
      
    
  );
}

export default App;

2. WebGPU 渲染動畫

下面是一個簡單的示例代碼,演示如何在WebGPU上渲染動畫。

  async function main() {
        // Step 1: Create a window to render into.
        const canvas = document.createElement('canvas');
        document.body.appendChild(canvas);
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
      
        // Step 2: Initialize WebGPU and create the "context".
        const adapter = await navigator.gpu.requestAdapter();
        const device = await adapter.requestDevice();
        const context = canvas.getContext('gpupresent');
      
        // Step 3: Define the shader modules (i.e. the shader code).
        const shaderModule =
              device.createShaderModule({
                    code: vertexShader
              });
      
        const fragModule = device.createShaderModule({
              code: fragmentShader
        });
      
        // Step 4: Define the pipeline layout.
        const layout = device.createPipelineLayout({
              bindGroupLayouts: []
        });
      
        // Step 5: Define the render pipeline.
        const pipeline = device.createRenderPipeline({
              layout,
              vertex: {
                  module: shaderModule,
                  entryPoint: 'main',
                  buffers: [{
                        arrayStride: 12,
                        attributes: [{
                              shaderLocation: 0,
                              offset: 0,
                              format: 'float3'
                        }]
                  }]
              },
              fragment: {
                  module: fragModule,
                  entryPoint: 'main',
                  targets: [{
                        format: 'rgba8unorm'
                  }]
              },
              primitive: {
                  topology: 'triangle-list',
                  stripIndexFormat: undefined,
                  frontFace: 'ccw',
                  cullMode: 'none',
                  clampDepth: false
              },
              depthStencil: {
                  format: undefined,
                  depthWriteEnabled: false,
                  depthCompare: 'always',
                  stencilFront: {
                        compare: 'always',
                        failOp: 'keep',
                        passOp: 'keep',
                        depthFailOp: 'keep'
                  },
                  stencilBack: {
                        compare: 'always',
                        failOp: 'keep',
                        passOp: 'keep',
                        depthFailOp: 'keep'
                  },
                  stencilReadMask: 0xff,
                  stencilWriteMask: 0xff
              }
        });
      
        // Step 6: Define the uniform buffer.
        const uniformBuffer = device.createBuffer({
              size: 16,
              usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
        });
        const uniformBindGroup = device.createBindGroup({
              layout: pipeline.getBindGroupLayout(0),
              entries: [{
                    binding: 0,
                    resource: {
                          buffer: uniformBuffer
                    }
              }]
        });
      
        // Step 7: Define the render loop.
        let time = 0;
        function update() {
              const t = performance.now() / 1000.0;
              const delta = t - time;
              time = t;
      
              const renderPassDescriptor = {
                    colorAttachments: [{
                          attachment: context.getCurrentTexture().createView(),
                          loadValue: [0, 0, 0, 1],
                          storeOp: 'store'
                    }]
              };
        
              const commandEncoder = device.createCommandEncoder();
              const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
              passEncoder.setPipeline(pipeline);
              passEncoder.setBindGroup(0, uniformBindGroup);
              passEncoder.draw(3, 1, 0, 0);
              passEncoder.endPass();
        
              device.queue.submit([commandEncoder.finish()]);
              requestAnimationFrame(update);
        }
        update();
  }
  main();

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/245345.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-12 13:08
下一篇 2024-12-12 13:08

相關推薦

  • 深入解析Vue3 defineExpose

    Vue 3在開發過程中引入了新的API `defineExpose`。在以前的版本中,我們經常使用 `$attrs` 和` $listeners` 實現父組件與子組件之間的通信,但…

    編程 2025-04-25
  • 深入理解byte轉int

    一、位元組與比特 在討論byte轉int之前,我們需要了解位元組和比特的概念。位元組是計算機存儲單位的一種,通常表示8個比特(bit),即1位元組=8比特。比特是計算機中最小的數據單位,是…

    編程 2025-04-25
  • 深入理解Flutter StreamBuilder

    一、什麼是Flutter StreamBuilder? Flutter StreamBuilder是Flutter框架中的一個內置小部件,它可以監測數據流(Stream)中數據的變…

    編程 2025-04-25
  • 深入探討OpenCV版本

    OpenCV是一個用於計算機視覺應用程序的開源庫。它是由英特爾公司創建的,現已由Willow Garage管理。OpenCV旨在提供一個易於使用的計算機視覺和機器學習基礎架構,以實…

    編程 2025-04-25
  • 深入了解scala-maven-plugin

    一、簡介 Scala-maven-plugin 是一個創造和管理 Scala 項目的maven插件,它可以自動生成基本項目結構、依賴配置、Scala文件等。使用它可以使我們專註於代…

    編程 2025-04-25
  • 深入了解LaTeX的腳註(latexfootnote)

    一、基本介紹 LaTeX作為一種排版軟體,具有各種各樣的功能,其中腳註(footnote)是一個十分重要的功能之一。在LaTeX中,腳註是用命令latexfootnote來實現的。…

    編程 2025-04-25
  • 深入探討馮諾依曼原理

    一、原理概述 馮諾依曼原理,又稱「存儲程序控制原理」,是指計算機的程序和數據都存儲在同一個存儲器中,並且通過一個統一的匯流排來傳輸數據。這個原理的提出,是計算機科學發展中的重大進展,…

    編程 2025-04-25
  • 深入理解Python字元串r

    一、r字元串的基本概念 r字元串(raw字元串)是指在Python中,以字母r為前綴的字元串。r字元串中的反斜杠(\)不會被轉義,而是被當作普通字元處理,這使得r字元串可以非常方便…

    編程 2025-04-25
  • 深入剖析MapStruct未生成實現類問題

    一、MapStruct簡介 MapStruct是一個Java bean映射器,它通過註解和代碼生成來在Java bean之間轉換成本類代碼,實現類型安全,簡單而不失靈活。 作為一個…

    編程 2025-04-25
  • 深入了解Python包

    一、包的概念 Python中一個程序就是一個模塊,而一個模塊可以引入另一個模塊,這樣就形成了包。包就是有多個模塊組成的一個大模塊,也可以看做是一個文件夾。包可以有效地組織代碼和數據…

    編程 2025-04-25

發表回復

登錄後才能評論