Google codelab WebGPU入门教程源码<6> - 使用计算着色器实现计算元胞自动机之生命游戏模拟过程(源码)

news2025/1/20 12:08:49

对应的教程文章: 

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

对应的源码执行效果:

对应的教程源码: 

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

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 WGPUSimulation {

	private mRVertices: Float32Array = null;
	private mRPipeline: any | null = null;
	private mRSimulationPipeline: 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;
	private mShdWorkGroupSize = 8;
	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): any {
		// 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);

		// Create the bind group layout and pipeline layout.
		const bindGroupLayout = device.createBindGroupLayout({
			label: "Cell Bind Group Layout",
			entries: [{
				binding: 0,
				visibility: GPUShaderStage.FRAGMENT | GPUShaderStage.VERTEX | GPUShaderStage.COMPUTE,
				buffer: {} // Grid uniform buffer
			}, {
				binding: 1,
				visibility: GPUShaderStage.VERTEX | GPUShaderStage.COMPUTE,
				buffer: { type: "read-only-storage"} // Cell state input buffer
			}, {
				binding: 2,
				visibility: GPUShaderStage.COMPUTE,
				buffer: { type: "storage"} // Cell state output buffer
			}]
		});
		const bindGroups = [
			device.createBindGroup({
				label: "Cell renderer bind group A",
				layout: bindGroupLayout,
				entries: [
					{
						binding: 0,
						resource: { buffer: uniformBuffer }
					}, {
						binding: 1,
						resource: { buffer: cellStateStorage[0] }
					}, {
						binding: 2,
						resource: { buffer: cellStateStorage[1] }
					}
				],
			}),
			device.createBindGroup({
				label: "Cell renderer bind group B",
				layout: bindGroupLayout,
				entries: [
					{
						binding: 0,
						resource: { buffer: uniformBuffer }
					}, {
						binding: 1,
						resource: { buffer: cellStateStorage[1] }
					}, {
						binding: 2,
						resource: { buffer: cellStateStorage[0] }
					}
				],
			})
		];

		this.mUniformBindGroups = bindGroups;

		const obj = this.mUniformObj;
		obj.uniformArray = uniformArray;
		obj.uniformBuffer = uniformBuffer;

		return bindGroupLayout;
	}
	private mStep = 0;
	private createComputeShader(device: any): any {
		let sgs = this.mShdWorkGroupSize;
		// Create the compute shader that will process the simulation.
		const simulationShaderModule = device.createShaderModule({
			label: "Game of Life simulation shader",
			code: `
			@group(0) @binding(0) var<uniform> grid: vec2f;

			@group(0) @binding(1) var<storage> cellStateIn: array<u32>;
			@group(0) @binding(2) var<storage, read_write> cellStateOut: array<u32>;

			fn cellIndex(cell: vec2u) -> u32 {
				return cell.y * u32(grid.x) + cell.x;
			}

			@compute @workgroup_size(${sgs}, ${sgs})
			fn computeMain(@builtin(global_invocation_id) cell: vec3u) {
				if (cellStateIn[cellIndex(cell.xy)] == 1) {
					cellStateOut[cellIndex(cell.xy)] = 0;
				} else {
					cellStateOut[cellIndex(cell.xy)] = 1;
				}
			}`
		});

		return simulationShaderModule;
	}
	private createRectGeometryData(device: any, pass: any, computePass: any): void {

		let vertices = this.mRVertices;
		let vertexBuffer = this.mVtxBuffer;
		let cellPipeline = this.mRPipeline;
		let simulationPipeline = this.mRSimulationPipeline;
		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>;

			@vertex
			fn 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;
			}

			@fragment
			fn 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 bindGroupLayout = this.createUniform(device);
			const pipelineLayout = device.createPipelineLayout({
				label: "Cell Pipeline Layout",
				bindGroupLayouts: [ bindGroupLayout ],
			});
			const cellShaderModule = device.createShaderModule({
				label: "Cell shader",
				code: shaderCodes
				});
			cellPipeline = device.createRenderPipeline({
				label: "Cell pipeline",
				layout: pipelineLayout,
				vertex: {
					module: cellShaderModule,
					entryPoint: "vertexMain",
					buffers: [vertexBufferLayout]
				},
				fragment: {
					module: cellShaderModule,
					entryPoint: "fragmentMain",
					targets: [{
						format: this.mCanvasFormat
					}]
				},
			});

			const simulationShaderModule = this.createComputeShader( device );
			// Create a compute pipeline that updates the game state.
			simulationPipeline = device.createComputePipeline({
					label: "Simulation pipeline",
					layout: pipelineLayout,
					compute: {
					module: simulationShaderModule,
					entryPoint: "computeMain",
				}
			});
			this.mRVertices = vertices;
			this.mVtxBuffer = vertexBuffer;
			this.mRPipeline = cellPipeline;
			this.mRSimulationPipeline = simulationPipeline;
		}
		const bindGroups = this.mUniformBindGroups;

		computePass.setPipeline(simulationPipeline),
		computePass.setBindGroup(0, bindGroups[this.mStep % 2]);
		const workgroupCount = Math.ceil(this.mGridSize / this.mShdWorkGroupSize);
		computePass.dispatchWorkgroups(workgroupCount, workgroupCount);

		pass.setPipeline(cellPipeline);
		pass.setVertexBuffer(0, vertexBuffer);
		// pass.setBindGroup(0, this.mUniformBindGroup);
		pass.setBindGroup(0, bindGroups[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], // yes
					view: context.getCurrentTexture().createView(),
					loadOp: "clear",
					storeOp: "store"
				}
			]
		};

		const encoder = device.createCommandEncoder();
		const pass = encoder.beginRenderPass( rpassParam );

		const computeEncoder = device.createCommandEncoder();
		const computePass = computeEncoder.beginComputePass()

		this.createRectGeometryData(device, pass, computePass);

		pass.end();
		computePass.end();

		device.queue.submit([ encoder.finish() ]);
		device.queue.submit([ computeEncoder.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.coloradmin.cn/o/1215262.html

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

相关文章

Mysql 索引优化——Explain

文章目录 Explain 简介Explain 概念Explain 示例 Explain 中列的含义idselect_typetabletypepossible_keyskeykey_lenrefrowExtra 索引最佳实践1.全值匹配2.最左前缀原则3.避免计算、函数、类型转换导致索引失效4.范围条件右边的索引列失效5.尽量使用覆盖索引 Explain 简介 Ex…

基于SSM的校园服务平台管理系统设计与实现

末尾获取源码 开发语言&#xff1a;Java Java开发工具&#xff1a;JDK1.8 后端框架&#xff1a;SSM 前端&#xff1a;采用JSP技术开发 数据库&#xff1a;MySQL5.7和Navicat管理工具结合 服务器&#xff1a;Tomcat8.5 开发软件&#xff1a;IDEA / Eclipse 是否Maven项目&#x…

利用vscode连接远程服务器进行代码调试

文章目录 一、vscode下载二、连接服务器1. 安装remote development套件2. 配置ssh3. 连接服务器4. 打开服务器文件路径 三、X11安装1. 安装插件2. 安装xserver服务3. Remote X11连接服务器All configured authentication methods failed问题 四、使用上常见一些问题1. 代码中文…

前端js,reduce归并操作图解

// 数组reduce方法// arr.reduce(function(上一次值, 当前值){}, 初始值)const arr [1, 5, 8]// 1. 没有初始值 // const total arr.reduce(function (prev, current) {// return prev current// })// console.log(total)// 2. 有初始值// const total arr.reduce(functi…

rabbit的扇出模式(fanout发布订阅)的生产者与消费者使用案例

扇出模式 fanout 发布订阅模式 生产者 生产者发送消息到交换机&#xff08;logs&#xff09;,控制台输入消息作为生产者的消息发送 package com.esint.rabbitmq.work03;import com.esint.rabbitmq.RabbitMQUtils; import com.rabbitmq.client.Channel;import java.util.Scanne…

Find My婴儿车|苹果Find My技术与婴儿车结合,智能防丢,全球定位

婴儿车是一种为婴儿户外活动提供便利而设计的工具车&#xff0c;是宝宝最喜爱的散步交通工具&#xff0c;更是妈妈带宝宝上街购物时的必须品。随着现在三胎的放开&#xff0c;婴儿车市场已经迎来上升的趋势。 在智能化加持下&#xff0c;防丢功能的加入使得人们日益关心物品的…

SpringCloud Alibaba组件入门全方面汇总(上):注册中心-nacos、负载均衡-ribbon、远程调用-feign

文章目录 NacosRibbonFeignFeign拓展 Nacos 概念&#xff1a;Nacos是阿里巴巴推出的一款新开源项目&#xff0c;它是一个更易于构建云原生应用的动态服务发现、配置管理和服务管理平台。Nacos致力于帮助用户发现、配置和管理微服务&#xff0c;它提供了一组简单易用的特性集&am…

Vue3 使用教程

目录 一、创建vue3工程1. 使用vue-cli创建2.使用 vite 创建 二、setup使用三、ref函数四、reactive函数五、计算属性与监视属性5.1 computed函数5.2 watch函数5.3 watchEffect函数 六、自定义hook函数七、toRef函数八、shallowReactive 与 shallowRef九、readonly 与 shallowRe…

ROS 学习应用篇(六)参数的使用与编程

node可能不在一个电脑里但是这些服务的参数信息是共享的&#xff0c;因为话题Topic是异步的所以只有服务Service有实时参数信息可以调用。 接下来将演示服务参数信息的调用与修改。 创建功能包(工作空间src文件夹下) catkin_create_pkg learning_parameter roscpp rospy std…

第九章认识Express模板

基本概述 Express模板是指Express框架中用于渲染视图的文件&#xff0c;可以包含HTML、CSS、JavaScript等内容&#xff0c;用于构建Web应用程序的用户界面。 使用Express模板可以快速、方便地创建Web应用程序&#xff0c;并且可以轻松地将动态数据注入到模板中&#xff0c;以…

Netty实战专栏 | NIO详解

✅作者简介&#xff1a;大家好&#xff0c;我是Leo&#xff0c;热爱Java后端开发者&#xff0c;一个想要与大家共同进步的男人&#x1f609;&#x1f609; &#x1f34e;个人主页&#xff1a;Leo的博客 &#x1f49e;当前专栏&#xff1a; Netty实战专栏 ✨特色专栏&#xff1a…

实验室LIMS系统 asp.net源码 lims系统源码

LIMS系统是以实验室为中心&#xff0c;将人员、仪器、试剂、方法、环境、文件等影响分析数据的因素有机结合&#xff0c;针对实验室的要求&#xff0c;遵循ISO 17025准则&#xff0c;采用先进的计算机网络技术、数据存储技术、快速和强大的数据处理技术来对实验室进行全面管理的…

【23真题】魔都高校真题!刷一刷!

今天分享的是23年上海海事大学806的信号与系统试题及解析。 本套试卷难度分析&#xff1a;22年上海海事大学806考研真题&#xff0c;我也发布过&#xff0c;若有需要&#xff0c;戳这里自取&#xff01;本套试题内容难度适中&#xff0c;题量适中&#xff0c;考察的知识点不难…

还有医学生不知道这个免费好用的在线样本量计算器吗?

相信很多小伙伴都有过这样的经历&#xff1a;做科研设计、撰写论文&#xff0c;设计好主题后摆在眼前的是你最头痛的问题——样本量计算。事实上&#xff0c;样本量计算往往是临床医生做临床研究设计的一大障碍&#xff0c;是临床研究设计、临床知识经验以及统计学知识的结合。…

前端 / 小程序——第三方字体库压缩(压缩率80%)

文章目录 前言压缩字体总结 前言 在做微信小程序时&#xff0c;需要使用第三方字体库&#xff0c;但是该字体库有30MB大小&#xff0c;导致微信使用wx.loadFontFace一直报错。网速很慢的话&#xff0c;极其影响用户体验&#xff0c;小的字体库没有问题&#xff0c;所以是字体库…

[读论文]DiT Scalable Diffusion Models with Transformers

论文翻译Scalable Diffusion Models with Transformers-CSDN博客 论文地址&#xff1a;https://arxiv.org/pdf/2212.09748.pdf 项目地址&#xff1a;GitHub - facebookresearch/DiT: Official PyTorch Implementation of "Scalable Diffusion Models with Transformers&qu…

个推用户运营全新上线用户生命周期管理功能,助力APP快速实现用户精细化运营

近期&#xff0c;个推用户运营上线了APP用户生命周期管理功能。该功能可以帮助APP多维度洞察⽤户所处的⽣命周期分布&#xff0c;旨在帮助运营人员快速全面地了解用户&#xff0c;从而基于用户生命周期针对性地做出用户运营策略调整&#xff0c;提升用户价值和运营指标。 个推如…

【LeetCode:2760. 最长奇偶子数组 | 模拟 双指针】

&#x1f680; 算法题 &#x1f680; &#x1f332; 算法刷题专栏 | 面试必备算法 | 面试高频算法 &#x1f340; &#x1f332; 越难的东西,越要努力坚持&#xff0c;因为它具有很高的价值&#xff0c;算法就是这样✨ &#x1f332; 作者简介&#xff1a;硕风和炜&#xff0c;…

(C++)把字符串转换成整数

把字符串转换成整数_牛客题霸_牛客网 愿所有美好如期而遇 思路 看到这个题目我们首先应该想到的就是去处理第一个字符&#xff0c;但是第一个字符也可能是数字字符&#xff0c;所以我们需要对他单独处理&#xff0c;如果他不符合条件&#xff0c;直接return&#xff0c;符合条…

QGIS之二十三矢量线融合

效果 步骤 1、准备数据 现有线分段太多&#xff0c;需要将部分线按照某个字段融合起来 2、融合 运行 3、结果 线已经融合了 线相交处也添加了线的节点