1. 引言

WebGPU是什么?

WebGPU与WebGL的对比?

2. 快速体验

参考:Orillusion | 专业WebGPU社区 | WebGPU小白入门(一): 零基础创建第一个WebGPU项目

# Clone the repo
git clone https://github.com/Orillusion/orillusion-webgpu-samples.git # Go inside the folder
cd orillusion-webgpu-samples # Start installing dependencies
npm install #or yarn add # Run project at localhost:3000
npm run dev #or yarn run dev

Chrome 浏览器(版本100+) 中打开localhost:3000,即可看到运行结果:

注意

  • 目前(2022年7月)WebGPU未正式发布,接口代码变更较快

  • WebGPU未正式发布,各个浏览器支持程度不同,本文使用Chrome版本号为:105.0.5153.0(正式版本)canary (64 位),下载地址:开发者专用的 Chrome Canary 版功能 - Google Chrome

部署别人写的代码终究是少了点感觉,接下来将编写一个入手案例

3. Hello Triangle

3.1 环境准备

浏览器:Chrome Canary版,版本号为:105.0.5153.0(正式版本)canary (64 位)

将Chrome开启WebGPU功能:

在地址栏输入 chrome://flags/ 搜索 WebGPU,将WebGPU的功能打开

3.2 基础代码

创建一个HTML文件,设置基础代码,另外,WebGPU是借助HTML中的canvas元素实现的,所以创建一个canvas元素

index.html:

<!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Basic Triangle</title>
<style>
html,
body {
margin: 0;
width: 100%;
height: 100%;
background: #000;
color: #fff;
display: flex;
text-align: center;
flex-direction: column;
justify-content: center;
} canvas {
width: 100%;
height: 100%;
}
</style>
</head> <body>
<canvas></canvas>
<script src="./index.js"></script>
</body> </html>

3.3 主要代码

同一目录下创建一个index.js文件,代码内容如下,流程讲解在下一节

index.js:

// initialize webgpu device & config canvas context
async function initWebGPU(canvas) {
if(!navigator.gpu)
throw new Error('Not Support WebGPU')
const adapter = await navigator.gpu.requestAdapter({
powerPreference: 'high-performance'
// powerPreference: 'low-power'
})
if (!adapter)
throw new Error('No Adapter Found')
const device = await adapter.requestDevice()
const context = canvas.getContext('webgpu')
const format = navigator.gpu.getPreferredCanvasFormat ? navigator.gpu.getPreferredCanvasFormat() : context.getPreferredFormat(adapter)
const devicePixelRatio = window.devicePixelRatio || 1
canvas.width = canvas.clientWidth * devicePixelRatio
canvas.height = canvas.clientHeight * devicePixelRatio
const size = {width: canvas.width, height: canvas.height}
context.configure({
// json specific format when key and value are the same
device, format,
// prevent chrome warning
alphaMode: 'opaque'
})
return {device, context, format, size}
} // create a simple pipiline
async function initPipeline(device, format){
const descriptor = {
layout: 'auto',
vertex: {
module: device.createShaderModule({
code: `@vertex
fn main(@builtin(vertex_index) VertexIndex : u32) -> @builtin(position) vec4<f32> {
var pos = array<vec2<f32>, 3>(
vec2<f32>(0.0, 0.5),
vec2<f32>(-0.5, -0.5),
vec2<f32>(0.5, -0.5)
);
return vec4<f32>(pos[VertexIndex], 0.0, 1.0);
}`
}),
entryPoint: 'main'
},
primitive: {
topology: 'triangle-list' // try point-list, line-list, line-strip, triangle-strip?
},
fragment: {
module: device.createShaderModule({
code: `@fragment
fn main() -> @location(0) vec4<f32> {
return vec4<f32>(1.0, 0.0, 0.0, 1.0);
}`
}),
entryPoint: 'main',
targets: [
{
format: format
}
]
}
}
return await device.createRenderPipelineAsync(descriptor)
}
// create & submit device commands
function draw(device, context, pipeline) {
const commandEncoder = device.createCommandEncoder()
const view = context.getCurrentTexture().createView()
const renderPassDescriptor = {
colorAttachments: [
{
view: view,
clearValue: { r: 0, g: 0, b: 0, a: 1.0 },
loadOp: 'clear', // clear/load
storeOp: 'store' // store/discard
}
]
}
const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor)
passEncoder.setPipeline(pipeline)
// 3 vertex form a triangle
passEncoder.draw(3)
passEncoder.end()
// webgpu run in a separate process, all the commands will be executed after submit
device.queue.submit([commandEncoder.finish()])
} async function run(){
const canvas = document.querySelector('canvas')
if (!canvas)
throw new Error('No Canvas')
const {device, context, format} = await initWebGPU(canvas)
const pipeline = await initPipeline(device, format)
// start draw
draw(device, context, pipeline) // re-configure context on resize
window.addEventListener('resize', ()=>{
canvas.width = canvas.clientWidth * devicePixelRatio
canvas.height = canvas.clientHeight * devicePixelRatio
// don't need to recall context.configure() after v104
draw(device, context, pipeline)
})
}
run()

运行代码(笔者这里使用VS Code和Live Server插件),使用Chrome打开,顺利的话即可看到三角形:

4. 运行流程

5. 参考资料

[1]WebGPU 到底是什么? - 知乎 (zhihu.com)

[2]WebGPU学习系列目录 - Wonder-YYC - 博客园 (cnblogs.com)

[3]WebGPU性能测试分析 - Wonder-YYC - 博客园 (cnblogs.com)

[4]WebGL 与 WebGPU 比对 前奏 - 四季留歌 - 博客园 (cnblogs.com)

[5]WebGPU (orillusion.com)

[6]orillusion-webgpu-samples/basicTriangle.ts at main · Orillusion/orillusion-webgpu-samples (github.com)

[7]Orillusion | 专业WebGPU社区 | WebGPU小白入门(一): 零基础创建第一个WebGPU项目

[8]WebGPU小白入门(二):绘制简单三角形——1.认识渲染流程_哔哩哔哩_bilibili

WebGPU 01之Hello Triangle的更多相关文章

  1. OpenGL 学习笔记 01 环境配置

    以下教程仅适用于Mac下的Xcode编程环境!其他的我也不会搞. 推荐教程:opengl-tutorial  本项目Github网址       OpenGL太可怕了...必需得把学的记下来,不然绝壁 ...

  2. 1043 - Triangle Partitioning(数学)

    1043 - Triangle Partitioning   PDF (English) Statistics Forum Time Limit: 0.5 second(s) Memory Limit ...

  3. C博客01——分支,顺序结构

    C博客01--分支,顺序结构 1. 本章学习总结 1.1 思维导图 请以思维导图总结本周的学习内容. 1.2 本章学习体会及代码量体会 1.2.1 学习体会 对于C语言课程的理解,我有点吃力,不是说老 ...

  4. Category Theory: 01 One Structured Family of Structures

    Category Theory: 01 One Structured Family of Structures 这次看来要放弃了.看了大概三分之一.似乎不能够让注意力集中了.先更新吧. 群的定义 \( ...

  5. Triangle leetcode java

    题目: Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjace ...

  6. 一个由正则表达式引发的血案 vs2017使用rdlc实现批量打印 vs2017使用rdlc [asp.net core 源码分析] 01 - Session SignalR sql for xml path用法 MemCahe C# 操作Excel图形——绘制、读取、隐藏、删除图形 IOC,DIP,DI,IoC容器

    1. 血案由来 近期我在为Lazada卖家中心做一个自助注册的项目,其中的shop name校验规则较为复杂,要求:1. 英文字母大小写2. 数字3. 越南文4. 一些特殊字符,如“&”,“- ...

  7. WebGPU学习(五): 现代图形API技术要点和WebGPU支持情况调研

    大家好,本文整理了现代图形API的技术要点,重点研究了并行和GPU Driven Render Pipeline相关的知识点,调查了WebGPU的相关支持情况. 另外,本文对实时光线追踪也进行了简要的 ...

  8. WebGPU学习(六):学习“rotatingCube”示例

    大家好,本文学习Chrome->webgpu-samplers->rotatingCube示例. 上一篇博文: WebGPU学习(五): 现代图形API技术要点和WebGPU支持情况调研 ...

  9. [译]Vulkan教程(01)入门

    [译]Vulkan教程(01)入门 接下来我将翻译(https://vulkan-tutorial.com)上的Vulkan教程.这可能是我学习Vulkan的最好方式,但不是最理想的方式. 我会用“d ...

  10. WebGPU学习(九):学习“fractalCube”示例

    大家好,本文学习Chrome->webgpu-samplers->fractalCube示例. 上一篇博文: WebGPU学习(八):学习"texturedCube"示 ...

随机推荐

  1. Jmeter 之 jp@gc - Stepping Thread Group

    jp@gc - Stepping Thread Group 自定义线程组,根据业务需要进行设计用户增加间隔时间等 1.  下载jmeter-plugins-manager-1.3.jar插件放入lib ...

  2. 正确理解和使用JAVA中的字符串常量池

    前言 研究表明,Java堆中对象占据最大比重的就是字符串对象,所以弄清楚字符串知识很重要,本文主要重点聊聊字符串常量池.Java中的字符串常量池是Java堆中的一块特殊存储区域,用于存储字符串.它的实 ...

  3. win7安装Anaconda+TensorFlow(cpu版)+配置PyCharm

    本着不折腾不舒服斯基,好久没安装软件玩了.今天趁天气不错,安装下TensorFlow(cpu版)(因为没钱上GPU),首先在网上搜了下教程,原文出处: https://blog.csdn.net/u0 ...

  4. [R语言] 基于R语言实现树形图的绘制

    树状图(或树形图)是一种网络结构.它由一个根节点组成,根节点产生由边或分支连接的多个节点.层次结构的最后一个节点称为叶.本文主要基于R语言实现树形图的绘制.关于python实现树形图的绘制见:基于ma ...

  5. xpath解析数据的方法

    1 功能描述 2 1.实例化一个etree对象,且需要将被解析的页面源码数据加载到该对象中 3 2.调用etree对象中的XPath表达式实现标签的定位和内容捕获 4 3.环境安装 pip insta ...

  6. VUEX state 的使用学习二

    转载请注明出处: state 提供唯一的数据资源,所有的共享的数据都要统一放到store 中的state中进行存储; 状态state用于存储所有组件的数据. 管理数据 // 初始化vuex对象 con ...

  7. Axure 环境进度条

    步骤一:拖拉摆放好相关控件 1.4个半圆环,一个白色上半圆环 (上白),一个白色下半圆环 (下白),一个灰色上半圆环 (上灰),一个灰色下半圆环 (下灰),排放层次为: 下灰<下白<上灰& ...

  8. Java入门与进阶 P-1.9+P-1.10

    计算机的优先级 所有的数学运算都认为是从左向右运算的,Java 语言中大部分运算符也是从左向右结合的,只有单目运算符.赋值运算符和三目运算符例外,其中,单目运算符.赋值运算符和三目运算符是从右向左结合 ...

  9. 如何又快又好实现 Catalog 系统搜索能力?火山引擎 DataLeap 这样做

      摘要 DataLeap 是火山引擎数智平台 VeDI 旗下的大数据研发治理套件产品,帮助用户快速完成数据集成.开发.运维.治理.资产.安全等全套数据中台建设,降低工作成本和数据维护成本.挖掘数据价 ...

  10. git拉项目出现的小问题

    问题描述 在IDEA中拉代码事报错. 点击查看报错信息 error: unable to read askpass response from 'C:\Users\霍亚龙\AppData\Local\ ...