当前位置: 首页 > news >正文

简洁轻便的wordpress主题廊坊关键词优化报价

简洁轻便的wordpress主题,廊坊关键词优化报价,汕头建设银行电话,临沂做商城网站文章目录 WebAssembly简介WebGPU简介Wasm WebGPU 在游戏开发中的优势创建一个简单的WebAssembly模块使用WebGPU绘制一个三角形WebAssembly 的高级特性内存管理异步加载与多线程 WebGPU 的高级特性着色器编程计算着色器 实战案例:创建一个简单的 2D 游戏游戏逻辑设计…

文章目录

      • WebAssembly简介
      • WebGPU简介
      • Wasm + WebGPU 在游戏开发中的优势
      • 创建一个简单的WebAssembly模块
      • 使用WebGPU绘制一个三角形
      • WebAssembly 的高级特性
        • 内存管理
        • 异步加载与多线程
      • WebGPU 的高级特性
        • 着色器编程
        • 计算着色器
      • 实战案例:创建一个简单的 2D 游戏
        • 游戏逻辑设计
        • 结合 WebAssembly

WebAssembly简介

  • 定义: WebAssembly是一种二进制指令格式,旨在为高性能应用程序提供一种可移植的目标平台。
  • 特点:
    • 小而快加载
    • 运行速度快
    • 支持多种编程语言编译
  • 用途: 主要用于加速网页应用性能,特别是在计算密集型任务上。

WebGPU简介

  • 定义: WebGPU API 是一个用于访问现代图形和计算硬件的新 JavaScript API。
  • 特点:
    • 基于现代图形API (如DirectX 12, Metal)
    • 提供低级别访问GPU的能力
    • 支持并行计算
  • 用途: 适用于复杂3D渲染、物理模拟等高性能需求场景。

Wasm + WebGPU 在游戏开发中的优势

  • 高性能: 利用Wasm的高效执行环境结合WebGPU对GPU的直接控制,可以实现接近原生应用的性能表现。
  • 跨平台: 由于Wasm本身的设计就是跨平台的,加上WebGPU也支持多种硬件后端,使得游戏能够更容易地部署到不同设备上。
  • 易维护与更新: 基于Web技术栈,开发者可以利用现有的工具链进行开发、调试及维护。

创建一个简单的WebAssembly模块

// 定义Wasm模块接口
const importObject = {env: {memoryBase: 0,tableBase: 0,memory: new WebAssembly.Memory({initial: 1}),table: new WebAssembly.Table({initial: 0, element: 'anyfunc'}),}
};// 加载Wasm模块
fetch('example.wasm').then(response => response.arrayBuffer()).then(bytes => WebAssembly.instantiate(bytes, importObject)).then(results => {const instance = results.instance;// 调用Wasm模块中的函数instance.exports.add(1, 2); // 假设该函数接收两个参数并返回它们的和});

使用WebGPU绘制一个三角形

// 获取WebGPU设备
navigator.gpu.requestAdapter().then(adapter => {return adapter.requestDevice();
}).then(device => {// 创建渲染管线const pipeline = device.createRenderPipeline({layout: device.createPipelineLayout({ bindGroupLayouts: [] }),vertexStage: {module: device.createShaderModule({code: `[[stage(vertex)]] fn main() -> [[builtin(position)]] vec4<f32> {var positions : array<vec2<f32>, 3> = array<vec2<f32>, 3>(vec2<f32>(-0.5, -0.5),vec2<f32>(0.5, -0.5),vec2<f32>(0.0, 0.5));var position = positions[0u]; // 简化起见,这里只取第一个顶点位置return vec4<f32>(position, 0.0, 1.0);}`,}),entryPoint: 'main',},primitiveTopology: 'triangle-list',colorStates: [{ format: 'bgra8unorm' }],});// 创建帧缓冲区const swapChain = device.createSwapChain(canvas, {usage: GPUTextureUsage.RENDER_ATTACHMENT,format: 'bgra8unorm',});// 渲染循环function render() {const context = device.getContext();const commandEncoder = device.createCommandEncoder();const textureView = swapChain.getCurrentTexture().createView();const renderPassDescriptor = {colorAttachments: [{attachment: textureView,loadValue: { r: 0.1, g: 0.2, b: 0.3, a: 1.0 },}],};const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);passEncoder.setPipeline(pipeline);passEncoder.draw(3, 1, 0, 0);passEncoder.endPass();device.queue.submit([commandEncoder.finish()]);requestAnimationFrame(render);}requestAnimationFrame(render);
});

WebAssembly 的高级特性

内存管理
  • 内存布局: WebAssembly 使用线性内存布局,可以通过 memory 对象进行访问。
  • 内存操作: 可以通过 get 和 set 方法读写内存。
  • 内存增长: 可以动态增加内存大小。
const memory = new WebAssembly.Memory({ initial: 1, maximum: 10 });
console.log(memory.buffer.byteLength); // 输出 65536 (1 MB)// 扩展内存
memory.grow(1);
console.log(memory.buffer.byteLength); // 输出 131072 (2 MB)
异步加载与多线程
  • 异步加载: 可以通过 fetch 或其他异步方法加载 Wasm 模块。
  • 多线程: 使用 WebAssembly.Threading API 支持多线程操作。
// 异步加载 Wasm 模块
fetch('example.wasm').then(response => response.arrayBuffer()).then(bytes => WebAssembly.compileAsync(bytes)).then(module => {WebAssembly.instantiate(module, importObject).then(results => {const instance = results.instance;// 调用 Wasm 函数instance.exports.add(1, 2);});});// 多线程支持
if ('workerGlobalScope' in self) {self.importScripts('wasm_worker.js');const worker = new Worker('wasm_worker.js');worker.postMessage({ type: 'run', data: [1, 2] });
}

WebGPU 的高级特性

着色器编程
  • 顶点着色器: 处理顶点数据。
  • 片段着色器: 处理像素颜色。
[[block]]
struct VertexInput {@builtin(position) pos: vec4<f32>,
};[[block]]
struct VertexOutput {@builtin(position) pos: vec4<f32>,
};[[stage(vertex)]]
fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput {var input: VertexInput = VertexInput(pos: vec4<f32>(0.0, 0.0, 0.0, 1.0));var output: VertexOutput = VertexOutput(pos: input.pos);return output;
}[[stage(fragment)]]
fn fs_main() -> @location(0) vec4<f32> {return vec4<f32>(1.0, 0.0, 0.0, 1.0);
}
计算着色器

计算着色器: 执行并行计算任务。

[[block]]
struct ComputeData {result: array<i32, 1>,
};[[group(0), binding(0)]]
var<storage, read_write> data: array<i32, 1>;[[stage(compute), workgroup_size(1)]]
fn cs_main([[builtin(global_invocation_id)]] global_id: vec3<u32>) {data[0] = global_id.x * global_id.y * global_id.z;
}

实战案例:创建一个简单的 2D 游戏

游戏逻辑设计
  • 状态管理: 使用对象或类来管理游戏状态。
  • 事件处理: 监听键盘和鼠标事件。
class Game {constructor(canvas) {this.canvas = canvas;this.context = canvas.getContext('2d');this.width = canvas.width;this.height = canvas.height;this.player = { x: 100, y: 100 };this.enemies = [];this.init();}init() {this.enemies.push({ x: 200, y: 200 });this.enemies.push({ x: 300, y: 300 });window.addEventListener('keydown', event => {if (event.key === 'ArrowUp') {this.player.y -= 10;} else if (event.key === 'ArrowDown') {this.player.y += 10;} else if (event.key === 'ArrowLeft') {this.player.x -= 10;} else if (event.key === 'ArrowRight') {this.player.x += 10;}});this.animate();}animate() {requestAnimationFrame(() => this.animate());this.update();this.render();}update() {// 更新敌人位置for (let enemy of this.enemies) {enemy.x += Math.random() * 10 - 5;enemy.y += Math.random() * 10 - 5;}}render() {this.context.clearRect(0, 0, this.width, this.height);this.context.fillStyle = 'blue';this.context.fillRect(this.player.x, this.player.y, 20, 20);this.context.fillStyle = 'red';for (let enemy of this.enemies) {this.context.fillRect(enemy.x, enemy.y, 20, 20);}}
}const canvas = document.getElementById('gameCanvas');
const game = new Game(canvas);
结合 WebAssembly
  • 加载 Wasm 模块: 在游戏初始化时加载 Wasm 模块。
  • 调用 Wasm 函数: 在游戏更新和渲染过程中调用 Wasm 函数。
class Game {constructor(canvas) {this.canvas = canvas;this.context = canvas.getContext('2d');this.width = canvas.width;this.height = canvas.height;this.player = { x: 100, y: 100 };this.enemies = [];this.init();}async init() {const importObject = {env: {memoryBase: 0,tableBase: 0,memory: new WebAssembly.Memory({ initial: 1 }),table: new WebAssembly.Table({ initial: 0, element: 'anyfunc' }),}};const response = await fetch('game_wasm.wasm');const bytes = await response.arrayBuffer();const { instance } = await WebAssembly.instantiate(bytes, importObject);this.wasm = instance.exports;this.enemies.push({ x: 200, y: 200 });this.enemies.push({ x: 300, y: 300 });window.addEventListener('keydown', event => {if (event.key === 'ArrowUp') {this.player.y -= 10;} else if (event.key === 'ArrowDown') {this.player.y += 10;} else if (event.key === 'ArrowLeft') {this.player.x -= 10;} else if (event.key === 'ArrowRight') {this.player.x += 10;}});this.animate();}animate() {requestAnimationFrame(() => this.animate());this.update();this.render();}update() {// 更新敌人位置for (let enemy of this.enemies) {enemy.x += this.wasm.randomMove(10);enemy.y += this.wasm.randomMove(10);}}render() {this.context.clearRect(0, 0, this.width, this.height);this.context.fillStyle = 'blue';this.context.fillRect(this.player.x, this.player.y, 20, 20);this.context.fillStyle = 'red';for (let enemy of this.enemies) {this.context.fillRect(enemy.x, enemy.y, 20, 20);}}
}const canvas = document.getElementById('gameCanvas');
const game = new Game(canvas);
http://www.yidumall.com/news/29370.html

相关文章:

  • 厦门做网站的公司seo研究协会网app
  • 寺庙网站建设网站每天做100个外链
  • 网站建设需要c语言吗seo实战密码在线阅读
  • 酒店建设网站的优势有哪些百度电话号码查询平台
  • 网站建设服务哪家好自己做网站难吗
  • 东莞市住房建设局网站电商软文广告经典案例
  • 中国的卡在日本能用吗东莞seo网络优化
  • 泗阳县住房和城乡建设局网站搜索引擎优化实训心得
  • 个人注册网站怎么注册济南优化哪家好
  • 宜宾公司做网站seo的推广技巧
  • 天津南开做网站网站推广主要是做什么
  • wordpress建站系统互联网营销渠道有哪些
  • 深圳网站建设潮动九州竞价账户托管
  • 济南教育论坛网站建设产品的网络推广要点
  • 怎样用代码建设一个网站百度app官网下载安装
  • 东平可信的网站建设百度企业推广怎么收费
  • 网站建设趋势网上推广赚钱项目
  • 网站建设要用什么软件抖音推广渠道有哪些
  • 上海网站开发培训seo关键词库
  • 网站登陆口提交网站指定关键词seo报价
  • 做网站创业流程图全网营销推广怎么做
  • 大良网站建设市场免费行情网站app大全
  • 加盟网站模板百度云网站入口
  • 做网站和做小程序有什么不同seo短视频网页入口营销
  • 微信公众号是在哪个网站做的郑州网站制作公司
  • 成都市温江区建设局网站友链出售
  • 色系网站.赣州seo唐三
  • wordpress相关文章代码seo链接优化建议
  • 前段模板网站大型营销型网站制作
  • 石狮网站建设公司哪家好做百度推广需要什么条件