screeps/objects/impls/room_terrain.rs
1use js_sys::{JsString, Uint8Array};
2use wasm_bindgen::prelude::*;
3
4use crate::{
5 constants::{ErrorCode, Terrain},
6 local::{RoomName, RoomXY},
7 prelude::*,
8};
9
10#[wasm_bindgen]
11extern "C" {
12 /// A matrix representing the terrain of a room, held in the JavaScript
13 /// heap.
14 ///
15 /// Use [`LocalRoomTerrain`] to store and access the same data in Rust
16 /// memory.
17 ///
18 /// [Screeps documentation](https://docs.screeps.com/api/#Room-Terrain)
19 #[wasm_bindgen(js_namespace = Room, js_name = Terrain)]
20 pub type RoomTerrain;
21
22 #[wasm_bindgen(constructor, js_namespace = Room, js_class = Terrain, catch)]
23 fn new_internal(room_name: &JsString) -> Result<RoomTerrain, JsValue>;
24
25 /// Get the type of terrain at given coordinates.
26 ///
27 /// [Screeps documentation](https://docs.screeps.com/api/#Room.Terrain.get)
28 #[wasm_bindgen(method)]
29 pub fn get(this: &RoomTerrain, x: u8, y: u8) -> Terrain;
30
31 // when called without a destination array, can't fail - no error code possible
32 #[wasm_bindgen(method, js_name = getRawBuffer)]
33 fn get_raw_buffer_internal(this: &RoomTerrain) -> Uint8Array;
34
35 // and when called with a destination, it can only ever return a return code int
36 #[wasm_bindgen(method, js_name = getRawBuffer)]
37 fn get_raw_buffer_to_array_internal(this: &RoomTerrain, destination: &Uint8Array) -> JsValue;
38}
39
40impl RoomTerrain {
41 /// Gets the terrain for any room by name, regardless of current visibility
42 /// of the room.
43 ///
44 /// [Screeps documentation](https://docs.screeps.com/api/#Room.Terrain.constructor)
45 pub fn new(room_name: RoomName) -> Option<RoomTerrain> {
46 let name = room_name.into();
47
48 Self::new_internal(&name).ok()
49 }
50
51 /// Get a copy of the underlying Uint8Array with the data about the room's
52 /// terrain.
53 ///
54 /// [Screeps documentation](https://docs.screeps.com/api/#Room.Terrain.getRawBuffer)
55 #[inline]
56 pub fn get_raw_buffer(&self) -> Uint8Array {
57 self.get_raw_buffer_internal()
58 }
59
60 /// Copy the data about the room's terrain into an existing [`Uint8Array`].
61 ///
62 /// [Screeps documentation](https://docs.screeps.com/api/#Room.Terrain.getRawBuffer)
63 #[inline]
64 pub fn get_raw_buffer_to_array(&self, destination: &Uint8Array) -> Result<(), ErrorCode> {
65 let val = self.get_raw_buffer_to_array_internal(destination);
66
67 // val is integer if error; if object it's another reference to the Uint8Array;
68 // function was successful in that case
69 match val.as_f64() {
70 Some(n) => ErrorCode::result_from_i8(n as i8),
71 None => Ok(()),
72 }
73 }
74
75 /// Get the type of terrain at the given [`RoomXY`].
76 #[inline]
77 pub fn get_xy(&mut self, xy: RoomXY) -> Terrain {
78 self.get(xy.x.u8(), xy.y.u8())
79 }
80}