首页 > 其他分享 >004 Web Assembly康威游戏之优化

004 Web Assembly康威游戏之优化

时间:2022-11-07 10:33:34浏览次数:44  
标签:Web const 康威 ctx CELL game wasm Assembly SIZE


0 介绍

视频地址:https://www.bilibili.com/video/BV1eg411g7c8
相关源码:https://github.com/anonymousGiga/Rust-and-Web-Assembly

1 说明

在上一节的实现中,我们是在Rust中实现了填充的内容,然后让wasm bindgen转换为一个有效的js字符串,这样就产生了不必要的副本。因为js代码已经知道宇宙的宽度和高度,因此可以直接读取构成cell的web assembly内存。另外我们将切换到Canvas API,而不是直接使用unicode文本。

本节直接上一节的内容之上进行修改。

2 实现

在wasm-game-of-life/www/index.html中的body标签内容修改为如下:

<body>
<!--canvas标签是表示图像或图表-->
<canvas id="game-of-life-canvas"></canvas>
<script src='./bootstrap.js'></script>
</body>

接下来,我们在wasm-game-of-life/src/lib.rs中添加如下代码:

#![allow(unused_variables)]
fn main() {
/// Public methods, exported to JavaScript.
#[wasm_bindgen]
impl Universe {
// ...

pub fn width(&self) -> u32 {
self.width
}

pub fn height(&self) -> u32 {
self.height
}

pub fn cells(&self) -> *const Cell {
self.cells.as_ptr()
}
}
}

修改wasm-game-of-life/www/index.js中的代码如下:

//import { Universe } from "wasm-game-of-life";
import { Universe, Cell } from "wasm-game-of-life";
import { memory } from "wasm-game-of-life/wasm_game_of_life_bg";

const CELL_SIZE = 5; // px
const GRID_COLOR = "#CCCCCC";
const DEAD_COLOR = "#FFFFFF";
const ALIVE_COLOR = "#000000";

const universe = Universe.new();
const width = universe.width();
const height = universe.height();

const canvas = document.getElementById("game-of-life-canvas");
canvas.height = (CELL_SIZE + 1) * height + 1;
canvas.width = (CELL_SIZE + 1) * width + 1;

const ctx = canvas.getContext('2d');

function renderLoop() {
universe.tick();

drawGrid();
drawCells();

window.requestAnimationFrame(renderLoop);
}

function drawGrid() {
ctx.beginPath();
ctx.strokeStyle = GRID_COLOR;

// Vertical lines.
for (let i = 0; i <= width; i++) {
ctx.moveTo(i * (CELL_SIZE + 1) + 1, 0);
ctx.lineTo(i * (CELL_SIZE + 1) + 1, (CELL_SIZE + 1) * height + 1);
}

// Horizontal lines.
for (let j = 0; j <= height; j++) {
ctx.moveTo(0, j * (CELL_SIZE + 1) + 1);
ctx.lineTo((CELL_SIZE + 1) * width + 1, j * (CELL_SIZE + 1) + 1);
}

ctx.stroke();
}

function getIndex(row, column) {
return row * width + column;
}

function drawCells() {
const cellsPtr = universe.cells();
const cells = new Uint8Array(memory.buffer, cellsPtr, width * height);

ctx.beginPath();

for (let row = 0; row < height; row++) {
for (let col = 0; col < width; col++) {
const idx = getIndex(row, col);

ctx.fillStyle = cells[idx] === Cell.Dead
? DEAD_COLOR
: ALIVE_COLOR;

ctx.fillRect(
col * (CELL_SIZE + 1) + 1,
row * (CELL_SIZE + 1) + 1,
CELL_SIZE,
CELL_SIZE
);
}
}

ctx.stroke();
}

window.requestAnimationFrame(renderLoop);

3 编译运行

在wasm-game-of-life目录下执行:

wasm-pack build

编译rust代码。

在wasm-game-of-life/www目录下执行:

npm run start

在浏览器中输入:

127.0.0.1:8080


标签:Web,const,康威,ctx,CELL,game,wasm,Assembly,SIZE
From: https://blog.51cto.com/u_15862521/5828084

相关文章