use bitsy_parser::game::Game; use bitsy_parser::image::Image; use bitsy_parser::tile::Tile; use image::{GenericImageView, Pixel}; use wasm_bindgen::prelude::*; const SD: u32 = 8; #[wasm_bindgen] pub fn load_default_game_data() { let window = web_sys::window().expect("no global `window` exists"); let document = window.document().expect("should have a document on window"); let game_data_input = document.get_element_by_id("game-data").expect("no game data input"); game_data_input.set_inner_html(&bitsy_parser::mock::game_default().to_string()); } fn tile_name(prefix: &str, index: &u32) -> Option { if prefix.len() > 0 { Some(format!("{} {}", prefix, index)) } else { None } } /// image is a base64-encoded string /// prefix will be ignored if empty #[wasm_bindgen] pub fn add_tiles(game_data: String, image: String, prefix: String) -> String { let mut game = Game::from(game_data) .expect("Couldn't parse game data"); let image: Vec<&str> = image.split("base64,").collect(); let image = image[1]; let image = base64::decode(image).unwrap(); let image = image::load_from_memory(image.as_ref()) .expect("Couldn't load image"); let width = image.width(); let height = image.height(); assert_eq!(width % 8, 0); assert_eq!(height % 8, 0); let columns = (width as f64 / 8.).floor() as u32; let rows = (height as f64 / 8.).floor() as u32; let mut tile_index = 1; for column in 0..columns { for row in 0..rows { let mut pixels = Vec::with_capacity(64); for y in (row * SD)..((row + 1) * SD) { for x in (column * SD)..((column + 1) * SD) { let pixel = image.get_pixel(x, y).to_rgb(); let total = pixel[0] as u32 + pixel[1] as u32 + pixel[2] as u32; // is each channel brighter than 128/255 on average? pixels.push(if total >= 384 {1} else {0}); } } game.add_tile(Tile { /// "0" will get overwritten to a new, safe tile ID id: "0".to_string(), name: tile_name(&prefix, &tile_index), wall: None, animation_frames: vec![Image { pixels }], colour_id: None }); tile_index += 1; } } game.dedupe_tiles(); game.to_string() } #[cfg(test)] mod test { use crate::add_tiles; #[test] fn example() { let game_data = bitsy_parser::mock::game_default().to_string(); let image = include_str!("test-resources/test.png.base64").to_string(); let output = add_tiles(game_data, image, "".to_string()); let expected = include_str!("test-resources/expected.bitsy"); assert_eq!(output, expected); } }