screeps/objects/impls/
structure_portal.rs

1use js_sys::JsString;
2use wasm_bindgen::prelude::*;
3
4use crate::{
5    local::{Position, RoomName},
6    objects::{RoomObject, RoomPosition, Structure},
7    prelude::*,
8};
9
10#[wasm_bindgen]
11extern "C" {
12    /// An object representing a [`StructurePortal`], which allows movement
13    /// between remote locations or other shards.
14    ///
15    /// [Screeps documentation](https://docs.screeps.com/api/#StructurePortal)
16    #[wasm_bindgen(extends = RoomObject, extends = Structure)]
17    #[derive(Clone, Debug)]
18    pub type StructurePortal;
19
20    #[wasm_bindgen(method, getter = destination)]
21    fn destination_internal(this: &StructurePortal) -> JsValue;
22
23    /// The number of ticks until the portal will decay, if it's unstable, or 0
24    /// if it's stable.
25    ///
26    /// [Screeps documentation](https://docs.screeps.com/api/#StructurePortal.ticksToDecay)
27    #[wasm_bindgen(method, getter = ticksToDecay)]
28    pub fn ticks_to_decay(this: &StructurePortal) -> u32;
29}
30
31impl StructurePortal {
32    pub fn destination(&self) -> PortalDestination {
33        let dest = Self::destination_internal(self);
34        match dest.dyn_ref::<RoomPosition>() {
35            Some(room_pos) => PortalDestination::InterRoom(room_pos.into()),
36            None => PortalDestination::InterShard(dest.unchecked_into()),
37        }
38    }
39}
40
41impl CanDecay for StructurePortal {
42    fn ticks_to_decay(&self) -> u32 {
43        Self::ticks_to_decay(self)
44    }
45}
46
47pub enum PortalDestination {
48    InterRoom(Position),
49    InterShard(InterShardPortalDestination),
50}
51
52#[wasm_bindgen]
53extern "C" {
54    /// An object which contains the destination shard and room of an
55    /// inter-shard portal.
56    ///
57    /// [Screeps documentation](https://docs.screeps.com/api/#StructurePortal.destination)
58    #[wasm_bindgen]
59    pub type InterShardPortalDestination;
60
61    #[wasm_bindgen(method, getter = room)]
62    fn room_internal(this: &InterShardPortalDestination) -> JsString;
63
64    #[wasm_bindgen(method, getter)]
65    pub fn shard(this: &InterShardPortalDestination) -> String;
66}
67
68impl InterShardPortalDestination {
69    pub fn room(&self) -> RoomName {
70        Self::room_internal(self)
71            .try_into()
72            .expect("expected parseable room name")
73    }
74}