This commit is contained in:
klangner 2020-09-14 11:46:48 +02:00
parent 7c99187b03
commit 62cc50dbc0
9 changed files with 226 additions and 16 deletions

View File

@ -1,6 +1,5 @@
use wasm_bindgen::prelude::*;
use rand::prelude::*;
use js_sys::Date;
use mapgen::dungeon::{
MapBuilder,
map::TileType,
@ -11,24 +10,33 @@ use mapgen::dungeon::{
};
#[wasm_bindgen]
#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Cell {
Floor = 0,
Wall = 1,
}
#[wasm_bindgen]
pub struct World {
width: u32,
height: u32,
tiles: Vec<bool>,
tiles: Vec<Cell>,
}
#[wasm_bindgen]
impl World {
pub fn new(width: u32, height: u32) -> World {
let seed = Date::new_0().get_time() as u64;
let mut rng = StdRng::seed_from_u64(seed);
pub fn new_cellular_automata(width: u32, height: u32, seed: u32) -> World {
let mut rng = StdRng::seed_from_u64(seed as u64);
let map = MapBuilder::new(Box::new(CellularAutomataGen::new(width as usize, height as usize)))
.with(AreaStartingPosition::new(XStart::CENTER, YStart::CENTER))
.with(CullUnreachable::new())
.with(DistantExit::new())
.build_map_with_rng(&mut rng);
let tiles = (0..map.tiles.len()).map(|i| map.tiles[i] == TileType::Floor).collect();
let tiles = (0..map.tiles.len())
.map(|i| if map.tiles[i] == TileType::Floor {Cell::Floor} else {Cell::Wall})
.collect();
World {
width,
height,
@ -43,14 +51,7 @@ impl World {
self.height
}
pub fn tiles(&self) -> *const bool {
pub fn tiles(&self) -> *const Cell {
self.tiles.as_ptr()
}
}
// Called when the wasm module is instantiated
// #[wasm_bindgen(start)]
// pub fn main() -> Result<(), JsValue> {
// Ok(())
// }
}

@ -1 +0,0 @@
Subproject commit 9ac3dff9ebea4675e5c478bcdcbc0fd547d1529f

4
demo/www2/.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
node_modules
dist
.bin/
package-lock.json

5
demo/www2/bootstrap.js vendored Normal file
View File

@ -0,0 +1,5 @@
// A dependency graph that contains any wasm must all be imported
// asynchronously. This `bootstrap.js` file does the single async import, so
// that no one else needs to worry about it again.
import("./index.js")
.catch(e => console.error("Error importing `index.js`:", e));

BIN
demo/www2/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

49
demo/www2/index.html Normal file
View File

@ -0,0 +1,49 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Mapgen demo</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<style>
body {
background-color: lightgrey;
}
</style>
<script src="./bootstrap.js"></script>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Mapgen demo</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">
Select generator
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#" id="cellular-automata-option">Cellular Automata</a>
<a class="dropdown-item" id="simple-rooms-option">Simple Rooms</a>
</div>
</li>
</ul>
</div>
</nav>
<canvas id="mapgen-canvas"></canvas>
<div id="map-info"></div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"
integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
</body>
</html>

98
demo/www2/index.js Normal file
View File

@ -0,0 +1,98 @@
import {Cell, World} from "mapgen-demo";
import { memory } from "mapgen-demo/mapgen_demo_bg";
const CELL_SIZE = 12;
const GRID_COLOR = "#CCCCCC";
const DEAD_COLOR = "#FFFFFF";
const ALIVE_COLOR = "#000000";
var world = null;
const width = 80;
const height = 50;
const infoDiv = document.getElementById('map-info');
// Give the canvas room for all of our cells and a 1px border
// around each of them.
const canvas = document.getElementById("mapgen-canvas");
canvas.height = (CELL_SIZE + 1) * height + 1;
canvas.width = (CELL_SIZE + 1) * width + 1;
const ctx = canvas.getContext('2d');
// Map generators
function newCellularAutomata() {
var seed = Date.now();
world = World.new_cellular_automata(width, height, seed);
drawGrid();
drawCells();
requestAnimationFrame(renderLoop);
infoDiv.textContent = "Cellular automata with the seed: " + seed;
}
function newSimpleRooms() {
console.log("Simple rooms")
}
const renderLoop = () => {
// universe.tick();
drawGrid();
drawCells();
requestAnimationFrame(renderLoop);
};
const 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();
};
const getIndex = (row, column) => {
return row * width + column;
};
const drawCells = () => {
const tilesPtr = world.tiles();
const tiles = new Uint8Array(memory.buffer, tilesPtr, 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 = tiles[idx] == Cell.Floor
? DEAD_COLOR
: ALIVE_COLOR;
ctx.fillRect(
col * (CELL_SIZE + 1) + 1,
row * (CELL_SIZE + 1) + 1,
CELL_SIZE,
CELL_SIZE
);
}
}
ctx.stroke();
};
newCellularAutomata();
// Connect UI element
document.getElementById('cellular-automata-option').addEventListener('click', newCellularAutomata);
document.getElementById('simple-rooms-option').addEventListener('click', newSimpleRooms);

40
demo/www2/package.json Normal file
View File

@ -0,0 +1,40 @@
{
"name": "create-wasm-app",
"version": "0.1.0",
"description": "create an app to consume rust-generated wasm packages",
"main": "index.js",
"bin": {
"create-wasm-app": ".bin/create-wasm-app.js"
},
"scripts": {
"build": "webpack --config webpack.config.js",
"start": "webpack-dev-server",
"deploy": "gh-pages -d dist"
},
"repository": {
"type": "git",
"url": "git+https://github.com/rustwasm/create-wasm-app.git"
},
"keywords": [
"webassembly",
"wasm",
"rust",
"webpack"
],
"author": "Ashley Williams <ashley666ashley@gmail.com>",
"license": "(MIT OR Apache-2.0)",
"bugs": {
"url": "https://github.com/rustwasm/create-wasm-app/issues"
},
"homepage": "https://github.com/rustwasm/create-wasm-app#readme",
"dependencies": {
"mapgen-demo": "file:../pkg"
},
"devDependencies": {
"hello-wasm-pack": "^0.1.0",
"webpack": "^4.29.3",
"webpack-cli": "^3.1.0",
"webpack-dev-server": "^3.1.5",
"copy-webpack-plugin": "^5.0.0"
}
}

View File

@ -0,0 +1,14 @@
const CopyWebpackPlugin = require("copy-webpack-plugin");
const path = require('path');
module.exports = {
entry: "./bootstrap.js",
output: {
path: path.resolve(__dirname, "../../docs"),
filename: "bootstrap.js",
},
mode: "development",
plugins: [
new CopyWebpackPlugin(['index.html', 'favicon.ico'])
],
};