without bundle

This commit is contained in:
klangner 2020-09-12 14:44:37 +02:00
parent 90010f287a
commit 259006ce56
8 changed files with 111 additions and 220 deletions

1
.gitignore vendored
View File

@ -2,3 +2,4 @@
/demo/target /demo/target
Cargo.lock Cargo.lock
.vscode/ .vscode/
pkg/

View File

@ -4,13 +4,18 @@ version = "0.1.1"
authors = ["Krzysztof Langner <klangner@gmail.com>"] authors = ["Krzysztof Langner <klangner@gmail.com>"]
edition = "2018" edition = "2018"
[dependencies] [lib]
rand = "0.7" crate-type = ["cdylib"]
amethyst = {version = "0.15", features = ["tiles", "no-slow-safety-checks"]}
log = { version = "0.4.8", features = ["serde"] }
mapgen = {path=".."}
[features] [dependencies]
default = ["metal"] wasm-bindgen = "0.2.68"
metal = ["amethyst/metal"]
vulkan = ["amethyst/vulkan"] [dependencies.web-sys]
version = "0.3.4"
features = [
'Document',
'Element',
'HtmlElement',
'Node',
'Window',
]

View File

@ -1,4 +0,0 @@
(
title: "mapgen demo",
dimensions: Some((840, 520)),
)

View File

@ -1,27 +0,0 @@
(
axes: {
"camera_x": Emulated(
pos: Key(D),
neg: Key(A),
),
"camera_y": Emulated(
pos: Key(W),
neg: Key(S),
),
"camera_scale": Emulated(
pos: Key(E),
neg: Key(Q),
),
"camera_z": Emulated(
pos: Key(R),
neg: Key(F),
),
},
actions: {
"camera_switch": [[Key(Space)]],
"select": [[Mouse(Left)]],
"toggle_rotation": [[Key(Y)]],
"toggle_translation": [[Key(T)]],
},
)

59
demo/index.html Normal file
View File

@ -0,0 +1,59 @@
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type" />
</head>
<body>
<!-- Note the usage of `type=module` here as this is an ES6 module -->
<script type="module">
// Use ES module import syntax to import functionality from the module
// that we have compiled.
//
// Note that the `default` import is an initialization function which
// will "boot" the module and make it ready to use. Currently browsers
// don't support natively imported WebAssembly as an ES module, but
// eventually the manual initialization won't be required!
import init, { add } from './pkg/mapgen_demo.js';
async function run() {
// First up we need to actually load the wasm file, so we use the
// default export to inform it where the wasm file is located on the
// server, and then we wait on the returned promise to wait for the
// wasm to be loaded.
//
// It may look like this: `await init('./pkg/without_a_bundler_bg.wasm');`,
// but there is also a handy default inside `init` function, which uses
// `import.meta` to locate the wasm file relatively to js file.
//
// Note that instead of a string you can also pass in any of the
// following things:
//
// * `WebAssembly.Module`
//
// * `ArrayBuffer`
//
// * `Response`
//
// * `Promise` which returns any of the above, e.g. `fetch("./path/to/wasm")`
//
// This gives you complete control over how the module is loaded
// and compiled.
//
// Also note that the promise, when resolved, yields the wasm module's
// exports which is the same as importing the `*_bg` module in other
// modes
await init();
// And afterwards we can use all the functionality defined in wasm.
const result = add(1, 2);
console.log(`1 + 2 = ${result}`);
if (result !== 3)
throw new Error("wasm addition doesn't work!");
}
run();
</script>
</body>
</html>

24
demo/src/lib.rs Normal file
View File

@ -0,0 +1,24 @@
use wasm_bindgen::prelude::*;
// Called when the wasm module is instantiated
#[wasm_bindgen(start)]
pub fn main() -> Result<(), JsValue> {
// Use `web_sys`'s global `window` function to get a handle on the global
// window object.
let window = web_sys::window().expect("no global `window` exists");
let document = window.document().expect("should have a document on window");
let body = document.body().expect("document should have a body");
// Manufacture the element we're gonna append
let val = document.create_element("p")?;
val.set_inner_html("Hello from Rust!");
body.append_child(&val)?;
Ok(())
}
#[wasm_bindgen]
pub fn add(a: u32, b: u32) -> u32 {
a + b
}

View File

@ -1,179 +0,0 @@
use amethyst::{
assets::{AssetStorage, Loader},
core::{
math::{Point3, Vector3},
Transform, TransformBundle,
},
ecs::Entity,
input::{is_close_requested, is_key_down, InputBundle, StringBindings},
prelude::*,
renderer::{
camera::Camera,
formats::texture::ImageFormat,
sprite::{SpriteSheet, SpriteSheetFormat, SpriteSheetHandle},
types::DefaultBackend,
RenderFlat2D, RenderToWindow, RenderingBundle, Texture,
palette::Srgba,
},
tiles::{MortonEncoder, RenderTiles2D, Tile, TileMap},
utils::application_root_dir,
window::ScreenDimensions,
winit,
};
use mapgen::dungeon::{
MapBuilder,
map::{Map, Point, TileType},
cellular_automata::CellularAutomataGen,
starting_point::{AreaStartingPosition, XStart, YStart},
cull_unreachable::CullUnreachable,
distant_exit::DistantExit,
};
#[derive(Default, Clone)]
struct MapTiles ;
impl Tile for MapTiles {
fn sprite(&self, p: Point3<u32>, world: &World) -> Option<usize> {
let map = world.read_resource::<Map>();
let pos = Point::new(p.x as usize, p.y as usize);
if map.starting_point == Some(pos) {
Some(160)
} else if map.exit_point == Some(pos) {
Some(12)
} else if map.at(p.x as usize, p.y as usize) == TileType::Wall {
Some(140)
} else {
Some(19)
}
}
fn tint(&self, p: Point3<u32>, world: &World) -> Srgba {
let map = world.read_resource::<Map>();
let pos = Some(Point::new(p.x as usize, p.y as usize));
if map.starting_point == pos || map.exit_point == pos {
Srgba::new(1.0, 1.0, 0.0, 1.0)
} else {
Srgba::new(1.0, 1.0, 1.0, 1.0)
}
}
}
fn load_tiles_sprite_sheet(world: &mut World, png_path: &str, ron_path: &str) -> SpriteSheetHandle {
let texture_handle = {
let loader = world.read_resource::<Loader>();
let texture_storage = world.read_resource::<AssetStorage<Texture>>();
loader.load(png_path, ImageFormat::default(), (), &texture_storage)
};
let loader = world.read_resource::<Loader>();
let sprite_sheet_store = world.read_resource::<AssetStorage<SpriteSheet>>();
loader.load(
ron_path,
SpriteSheetFormat(texture_handle),
(),
&sprite_sheet_store,
)
}
fn init_camera(world: &mut World, transform: Transform, camera: Camera) -> Entity {
world
.create_entity()
.with(transform)
.with(camera)
.named("camera")
.build()
}
fn init_map(world: &mut World) {
let map = MapBuilder::new(Box::new(CellularAutomataGen::new(80, 50)))
.with(AreaStartingPosition::new(XStart::CENTER, YStart::CENTER))
.with(CullUnreachable::new())
.with(DistantExit::new())
.build_map();
world.insert(map);
}
struct PlayState;
impl SimpleState for PlayState {
fn on_start(&mut self, data: StateData<'_, GameData<'_, '_>>) {
let mut world = data.world;
// Create map
init_map(&mut world);
let map_sprite_sheet_handle =
load_tiles_sprite_sheet(world, "texture/basic.png", "texture/basic.ron");
let (width, height) = {
let dim = world.read_resource::<ScreenDimensions>();
(dim.width(), dim.height())
};
let _camera = init_camera(
world,
Transform::from(Vector3::new(-10.0, 10.0, 1.1)),
Camera::standard_2d(width, height),
);
let tile_map = TileMap::<MapTiles, MortonEncoder>::new(
Vector3::new(80, 50, 1),
Vector3::new(20, 20, 1),
Some(map_sprite_sheet_handle),
);
let _map_entity = world
.create_entity()
.with(tile_map)
.with(Transform::default())
.build();
}
fn handle_event(
&mut self,
data: StateData<'_, GameData<'_, '_>>,
event: StateEvent,
) -> SimpleTrans {
let StateData { .. } = data;
if let StateEvent::Window(event) = &event {
if is_close_requested(&event) || is_key_down(&event, winit::VirtualKeyCode::Escape) {
Trans::Quit
} else {
Trans::None
}
} else {
Trans::None
}
}
}
fn main() -> amethyst::Result<()> {
amethyst::Logger::from_config(Default::default())
.level_for("demo", log::LevelFilter::Warn)
.start();
let app_root = application_root_dir()?;
let assets_directory = app_root.join("assets");
let display_config_path = app_root.join("config/display.ron");
let game_data = GameDataBuilder::default()
.with_bundle(TransformBundle::new())?
.with_bundle(
InputBundle::<StringBindings>::new()
.with_bindings_from_file("config/input.ron")?,
)?
.with_bundle(
RenderingBundle::<DefaultBackend>::new()
.with_plugin(
RenderToWindow::from_config_path(display_config_path)?
.with_clear([0.0, 0.0, 0.0, 1.0]),
)
.with_plugin(RenderFlat2D::default())
.with_plugin(RenderTiles2D::<MapTiles, MortonEncoder>::default()),
)?;
let mut game = Application::build(assets_directory, PlayState)?.build(game_data)?;
game.run();
Ok(())
}

12
demo/src/utils.rs Normal file
View File

@ -0,0 +1,12 @@
pub fn set_panic_hook() {
// When the `console_error_panic_hook` feature is enabled, we can call the
// `set_panic_hook` function at least once during initialization, and then
// we will get better error messages if our code ever panics.
//
// For more details see
// https://github.com/rustwasm/console_error_panic_hook#readme
#[cfg(feature = "console_error_panic_hook")]
console_error_panic_hook::set_once();
}