Google codelab WebGPU入门教程源码<5> - 使用Storage类型对象给着色器传数据(源码)

对应的教程文章: 

https://codelabs.developers.google.com/your-first-webgpu-app?hl=zh-cn#5

对应的源码执行效果:

对应的教程源码: 

此处源码和教程本身提供的部分代码可能存在一点差异。运行的时候,点击画面可以切换效果。

class Color4 {r: number;g: number;b: number;a: number;constructor(pr = 1.0, pg = 1.0, pb = 1.0, pa = 1.0) {this.r = pr;this.g = pg;this.b = pb;this.a = pa;}
}export class WGPURStorage2 {private mRVertices: Float32Array = null;private mRPipeline: any | null = null;private mVtxBuffer: any | null = null;private mCanvasFormat: any | null = null;private mWGPUDevice: any | null = null;private mWGPUContext: any | null = null;private mUniformBindGroups: any | null = null;private mGridSize = 32;constructor() {}initialize(): void {const canvas = document.createElement("canvas");canvas.width = 512;canvas.height = 512;document.body.appendChild(canvas);console.log("ready init webgpu ...");this.initWebGPU(canvas).then(() => {console.log("webgpu initialization finish ...");this.updateWGPUCanvas();});document.onmousedown = (evt):void => {this.updateWGPUCanvas( new Color4(0.05, 0.05, 0.1) );}}private mUniformObj: any = {uniformArray: null, uniformBuffer: null};private createStorage(device: any): any {// Create an array representing the active state of each cell.const cellStateArray = new Uint32Array(this.mGridSize * this.mGridSize);// Create two storage buffers to hold the cell state.const cellStateStorage = [device.createBuffer({label: "Cell State A",size: cellStateArray.byteLength,usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,}),device.createBuffer({label: "Cell State B",size: cellStateArray.byteLength,usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,})];// Mark every third cell of the first grid as active.for (let i = 0; i < cellStateArray.length; i+=3) {cellStateArray[i] = 1;}device.queue.writeBuffer(cellStateStorage[0], 0, cellStateArray);// Mark every other cell of the second grid as active.for (let i = 0; i < cellStateArray.length; i++) {cellStateArray[i] = i % 2;}device.queue.writeBuffer(cellStateStorage[1], 0, cellStateArray);return cellStateStorage;}private createUniform(device: any, pipeline: any): void {// Create a uniform buffer that describes the grid.const uniformArray = new Float32Array([this.mGridSize, this.mGridSize]);const uniformBuffer = device.createBuffer({label: "Grid Uniforms",size: uniformArray.byteLength,usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,});device.queue.writeBuffer(uniformBuffer, 0, uniformArray);const cellStateStorage = this.createStorage(device);const bindGroups = [device.createBindGroup({label: "Cell renderer bind group A",layout: pipeline.getBindGroupLayout(0),entries: [{binding: 0,resource: { buffer: uniformBuffer }}, {binding: 1,resource: { buffer: cellStateStorage[0] }}],}),device.createBindGroup({label: "Cell renderer bind group B",layout: pipeline.getBindGroupLayout(0),entries: [{binding: 0,resource: { buffer: uniformBuffer }}, {binding: 1,resource: { buffer: cellStateStorage[1] }}],})];this.mUniformBindGroups = bindGroups;const obj = this.mUniformObj;obj.uniformArray = uniformArray;obj.uniformBuffer = uniformBuffer;}private mStep = 0;private createRectGeometryData(device: any, pass: any): void {let vertices = this.mRVertices;let vertexBuffer = this.mVtxBuffer;let cellPipeline = this.mRPipeline;if(!cellPipeline) {let hsize = 0.8;vertices = new Float32Array([//   X,    Y,-hsize, -hsize, // Triangle 1 (Blue)hsize, -hsize,hsize,  hsize,-hsize, -hsize, // Triangle 2 (Red)hsize,  hsize,-hsize,  hsize,]);vertexBuffer = device.createBuffer({label: "Cell vertices",size: vertices.byteLength,usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,});device.queue.writeBuffer(vertexBuffer, /*bufferOffset=*/0, vertices);const vertexBufferLayout = {arrayStride: 8,attributes: [{format: "float32x2",offset: 0,shaderLocation: 0, // Position, see vertex shader}],};const shaderCodes = `struct VertexInput {@location(0) pos: vec2f,@builtin(instance_index) instance: u32,};struct VertexOutput {@builtin(position) pos: vec4f,@location(0) cell: vec2f,};@group(0) @binding(0) var<uniform> grid: vec2f;@group(0) @binding(1) var<storage> cellState: array<u32>;@vertexfn vertexMain(input: VertexInput) -> VertexOutput  {let i = f32(input.instance);let cell = vec2f(i % grid.x, floor(i / grid.x));let cellOffset = cell / grid * 2;let state = f32(cellState[input.instance]);let gridPos = (input.pos * state + 1) / grid - 1 + cellOffset;var output: VertexOutput;output.pos = vec4f(gridPos, 0, 1);output.cell = cell;return output;}@fragmentfn fragmentMain(input: VertexOutput) -> @location(0) vec4f {// return vec4f(input.cell, 0, 1);let c = input.cell/grid;return vec4f(c, 1.0 - c.x, 1);}`;const cellShaderModule = device.createShaderModule({label: "Cell shader",code: shaderCodes});cellPipeline = device.createRenderPipeline({label: "Cell pipeline",layout: "auto",vertex: {module: cellShaderModule,entryPoint: "vertexMain",buffers: [vertexBufferLayout]},fragment: {module: cellShaderModule,entryPoint: "fragmentMain",targets: [{format: this.mCanvasFormat}]},});this.mRVertices = vertices;this.mVtxBuffer = vertexBuffer;this.mRPipeline = cellPipeline;this.createUniform(device, cellPipeline);}pass.setPipeline(cellPipeline);pass.setVertexBuffer(0, vertexBuffer);// pass.setBindGroup(0, this.mUniformBindGroup);pass.setBindGroup(0, this.mUniformBindGroups[this.mStep % 2]);pass.draw(vertices.length / 2, this.mGridSize * this.mGridSize);this.mStep ++;}private updateWGPUCanvas(clearColor: Color4 = null): void {clearColor = clearColor ? clearColor : new Color4(0.05, 0.05, 0.1);const device = this.mWGPUDevice;const context = this.mWGPUContext;const rpassParam = {colorAttachments: [{clearValue: clearColor,// clearValue: [0.3,0.7,0.5,1.0], // yesview: context.getCurrentTexture().createView(),loadOp: "clear",storeOp: "store"}]};const encoder = device.createCommandEncoder();const pass = encoder.beginRenderPass( rpassParam );this.createRectGeometryData(device, pass);pass.end();device.queue.submit([ encoder.finish() ]);}private async initWebGPU(canvas: HTMLCanvasElement) {const gpu = (navigator as any).gpu;if (gpu) {console.log("WebGPU supported on this browser.");const adapter = await gpu.requestAdapter();if (adapter) {console.log("Appropriate GPUAdapter found.");const device = await adapter.requestDevice();if (device) {this.mWGPUDevice = device;console.log("Appropriate GPUDevice found.");const context = canvas.getContext("webgpu") as any;const canvasFormat = gpu.getPreferredCanvasFormat();this.mWGPUContext = context;this.mCanvasFormat = canvasFormat;console.log("canvasFormat: ", canvasFormat);context.configure({device: device,format: canvasFormat,alphaMode: "premultiplied"});} else {throw new Error("No appropriate GPUDevice found.");}} else {throw new Error("No appropriate GPUAdapter found.");}} else {throw new Error("WebGPU not supported on this browser.");}}run(): void {}
}

切换后的效果:

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/144191.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

ceph 14.2.10 aarch64 非集群内 客户端 挂载块设备

集群上的机器测试 706 ceph pool create block-pool 64 64 707 ceph osd pool create block-pool 64 64 708 ceph osd pool application enable block-pool rbd 709 rbd create vdisk1 --size 4G --pool block-pool --image-format 2 --image-feature layering 7…

@postmapping 定义formdata传参方式

背景&#xff1a;feign声明接口&#xff0c;传对象&#xff0c; 但是对象那边没有用requestBody接收&#xff1b; 前端调它也是走的formdata&#xff0c;所以不改变源代码&#xff0c;以及补新接口的情况下&#xff0c;我也需要formdata传参&#xff1b; 不然数据传不过去会为空…

GDS 命令的使用 srvctl service TAF application continuity

文档中prim and stdy在同一台机器上&#xff0c;不同机器需要添加address list TAF ENABLED GLOBAL SERVICE in GDS ENVIRONMNET 12C. (Doc ID 2283193.1)​编辑To Bottom In this Document Goal Solution APPLIES TO: Oracle Database - Enterprise Edition - Version 12.1.…

漏电继电器 LLJ-250HT AC220V 50-500ma 面板安装

系列型号&#xff1a; LLJ-10H(S)漏电继电器LLJ-15H(S)漏电继电器LLJ-16H(S)漏电继电器 LLJ-25H(S)漏电继电器LLJ-30H(S)漏电继电器LLJ-32H(S)漏电继电器 LLJ-60H(S)漏电继电器LLJ-63H(S)漏电继电器LLJ-80H(S)漏电继电器 LLJ-100H(S)漏电继电器LLJ-120H(S)漏电继电器LLJ-125H(…

优思学院|新版ISO9001:2015质量体系的优势(一)高阶结构

在全球商业环境中&#xff0c;不断提高产品和服务的质量至关重要。因此&#xff0c;国际标准组织&#xff08;ISO&#xff09;于2015年发布了更新的ISO 9001标准&#xff0c;即ISO 9001:2015质量体系标准。这一更新旨在适应不断变化的商业需求和挑战&#xff0c;为组织提供更强…

Idea 编译SpringBoot项目Kotlin报错/Idea重新编译

原因应该是一次性修改了大量的文件, SpringBoot项目启动Kotlin报错, Build Project也是同样的结果, 报错如下 Error:Kotlin: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.9.0, expected version is 1.1.13. Build-&…

多svn仓库一键更新脚本分享

之前分享过多git仓库一键更新脚本&#xff0c;本期就分享下svn仓库的一键更新脚本 1、首先需要设置svn为可执行命令行 打开SVN安装程序&#xff0c;选择modify&#xff0c;然后点击 command client tools&#xff0c;安装命令行工具 2、update脚本 echo 开始更新SVN目录&…

qt+opengl 着色器VAO、VBO、EBO(四)

文章目录 一、顶点着色器和片段着色器代码分析1. 着色器12. 顶点着色器2 二、使用步骤1. 使用着色器12. 使用着色器23. 在着色器2中使用EBO 三、完整代码 一、顶点着色器和片段着色器代码分析 1. 着色器1 用到的坐标矩阵, 四个四边形顶点坐标 float vertices_data[36] {// 所…

mybatis之主键返回

1.在mybatis的xml中加入 <insert id"insertUser" keyProperty"id" useGeneratedKeys"true" parameterType"com.UserAndOrder"> insert into Tuser(userName,passWord) values (#{userName},#{passWord} ) </insert&…

多维时序 | MATLAB实现PSO-BiLSTM-Attention粒子群优化双向长短期记忆神经网络融合注意力机制的多变量时间序列预测

多维时序 | MATLAB实现PSO-BiLSTM-Attention粒子群优化双向长短期记忆神经网络融合注意力机制的多变量时间序列预测 目录 多维时序 | MATLAB实现PSO-BiLSTM-Attention粒子群优化双向长短期记忆神经网络融合注意力机制的多变量时间序列预测预测效果基本介绍模型描述程序设计参考…

国产高云FPGA开发软件Gowin的下载、安装、Licence共享,按照我的方案保证立马能用,不能用你铲我耳屎

目录 1、前言2、GOWIN简介3、GOWIN下载4、GOWIN安装5、Licence共享方案&#xff0c;立马就能用6、网盘福利领取 1、前言 “苟利国家生死以&#xff0c;岂因祸福避趋之&#xff01;”大洋彼岸的我优秀地下档员&#xff0c;敏锐地洞察到祖国的短板在于高精尖半导体的制造领域&am…

WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!

WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! 解决方案 解决方案 ssh-keygen -f "/home/oyk/.ssh/known_hosts" -R "[192.168.30.125]:6004"再重连就行

使用IDEA 将Eclipse java工程转为maven格式

使用IDEA 将Eclipse java工程转为maven格式 ①使用idea打开项目&#xff0c;在项目根目录下右键选择 Add Framework Support 选择 maven &#xff0c;引入maven ②找到项目中的.classpath文件或者lib目录 根据.classpath文件或者lib目录中列举的jar包名&#xff0c;将其依次手…

Redis 配置文件信息中文翻译版

前言 Redis 配置文件信息中文翻译版&#xff0c;方便大家阅读和理解对应参数信息及配置参数信息 # Redis configuration file example# Note on units: when memory size is needed, it is possible to specify # it in the usual form of 1k 5GB 4M and so forth: # 注意:当…

信息检索与数据挖掘 | 【实验】检索评价指标MAP、MRR、NDCG

文章目录 &#x1f4da;实验内容&#x1f4da;知识梳理&#x1f4da;实验步骤&#x1f407;前情提要&#x1f407;MAP评价指标函数&#x1f407;MRR 评价指标函数&#x1f407;NDCG评价指标函数&#x1f407;调试结果 &#x1f4da;实验内容 实现以下指标评价&#xff0c;并对…

锐捷EG易网关login.php以及其后台cli.php/branch_passw.php RCE漏洞复现 [附POC]

文章目录 锐捷EG易网关login.php以及其后台cli.php/branch_passw.php远程代码执行漏洞复现 [附POC]0x01 前言0x02 漏洞描述0x03 影响版本0x04 漏洞环境0x05 漏洞复现1.访问漏洞环境2.构造POC3.复现 锐捷EG易网关login.php以及其后台cli.php/branch_passw.php远程代码执行漏洞复…

【Java 进阶篇】JQuery 案例:下拉列表选中条目左右移动,打破选择的边界

在前端的舞台上&#xff0c;下拉列表是常见的用户交互元素&#xff0c;但有时候我们想要更多的交互体验。通过巧妙运用 JQuery&#xff0c;我们可以实现下拉列表中选中条目的左右移动功能&#xff0c;为用户提供更加灵活的选择方式。本篇博客将深入研究 JQuery 中实现这一功能的…

操作系统(二 )| 进程控制 进程状态 进程描述 进程控制 进程同步互斥

文章目录 1 进程和程序区别2 进程状态2.1 进程的5种基本状态2.2 进程状态之间转换2.3 七状态模型 3 进程描述3.1 进程控制块 PCB3.2 进程块组织方式 4 进程控制5 进程同步 互斥5.1 区分进程互斥和同步5.2 核心方案5.3 其他方案方案1 设置锁变量方案2 严格轮转法方案3 Peterson解…

post 和get参数 请求

json参数 post请求格式 RestController public class HelloController { //json参数 post 请求RequestMapping("/jsonParam")public String jsonParam(RequestBody User user){System.out.println(user);return "OK";} } postman 接口测试工具…

服务器数据恢复—服务器发生故障导致数据丢失如何恢复服务器数据?

服务器常见故障&#xff1a; 硬件故障&#xff1a;磁盘、板卡、电源故障等。 软件故障&#xff1a;操作系统崩溃、程序运行错误等。 入侵破坏&#xff1a;加密、删除服务数据等。 不可控力&#xff1a;浸水、火烧、倒塌等。 误操作&#xff1a;格式化、删除、覆盖等。 如何减少…