Struct screeps::Position [−][src]
Represents a position in a particular room in Screeps.
Note: This is analogous to the RoomPosition
JavaScript type.
We've renamed this type to Position
in screeps-game-api
to reflect the
fact that it's implemented entirely as a local type, and does represent a
position located within an entire shard, not only within a single room.
This should be a very efficient type to use in most if not all situations.
It's represented by a single u32
, all math operations are implemented in
pure-Rust code, and uploading to / downloading from JavaScript only requires
transferring a single i32
.
Using Position
You can retrieve a Position
by getting the position of a game object using
HasPosition::pos
, or by creating one from coordinates with
Position::new
.
You can use any of the math methods available on this page to manipulate
Position
, and you can pass it to any game methods expecting a position
or something with a position.
Serialization
Position
implements both serde::Serialize
and
serde::Deserialize
.
When serializing, it will use the format {roomName: String, x: u32, y: u32}
in "human readable" formats like JSON, and will serialize as a single
i32
in "non-human readable" formats like bincode
.
You can also pass Position
into JavaScript using the js!{}
macro provided by stdweb
, or helper methods using the same code like
MemoryReference::set
. It will be
serialized the same as in JSON, as an object with roomName
, x
and y
properties.
Note: serializing using js!{}
or MemoryReference::set
will not
create a JavaScript RoomPosition
, only something with the same properties.
If you need a reference to a RoomPosition
in JavaScript to use manually,
you have two options:
-
Use
.remote()
to get astdweb::Reference
, and then use that reference in JavaScript -
Convert the room position to an integer with
Position::packed_repr
, send that to JS, and use thepos_from_packed
JavaScript function provided by this library:use stdweb::js; use screeps::Position; let pos = Position::new(20, 21, "E5N6".parse().unwrap()); let result = js! { let pos = pos_from_packed(@{pos.packed_repr()}); pos.roomName };
Deserialization
Position
implements TryFrom<Value>
, allowing conversion from values
retrieved from JavaScript. The implementation is fairly lenient, and will
try to accept the value as any of the following things, in order:
- an integer representing the packedPos
- this can be produced by retrieving the
__packedPos
field of aRoomPosition
- this can be produced by retrieving the
- an object with a
__packedPos
property- this allows converting from a JavaScript
RoomPosition
to aPosition
without referencing__packedPos
manually, but is less efficient since it requires an extra callback into JavaScript to grab that field from within the conversion code
- this allows converting from a JavaScript
- an object with
x
,y
androomName
properties- this is mainly intended to decode
Position
s which were previously sent to JavaScript using@{}
injs!{}
, or serialized using [serde::Serialize
] - this will also understand
RoomPosition
s in private servers versions3.2.1
and below, prior to when__packedPos
was added
- this is mainly intended to decode
World vs. in-room coordinates
When converting Position
to integer x/y coordinates, there are two main
methods. The first is to use x
/y
as "in room" coordinates, which are
bounded within 0..=49
. These coordinates only identify the location within
a given room name. These are used by Position::x
, Position::y
,
Position::new
as well as Position::coords
,
Position::coords_signed
and the various implementations of Into<([ui*], [ui*])>
for Position
.
The second is to use x
/y
as "world" coordinates, which are coordinates
spread across the world. To ensures they agree with in-room coordinates,
south is positive y
, north is negative y
, east is positive x
and west
is negative x
. One way to think of them is as extending the room
coordinates of the room E0S0
throughout the entire map.
World coordinates are used by Position::world_x
, Position::world_y
,
Position::world_coords
, Position::from_world_coords
, and by all
implementations which allow adding or subtracting positions (see Addition
and subtraction).
Method Behavior
While this corresponds with the JavaScript RoomPosition
type, it is not
identical. In particular, all "calculation" methods which take in another
position are re-implemented in pure Rust code, and some behave slightly
different.
For instance, Position::get_range_to
operates on positions as world
coordinates, and will return accurate distances for positions in different
rooms. This is in contrast to RoomPosition.getRangeTo
in JavaScript, which
will return Infinity
for positions from different rooms.
Position::in_range_to
has a similar difference.
Besides extending behavior to work between rooms, we've tried to keep methods as in-sync with the JavaScript versions as possible. Everything will "just work", and there should be some speed advantage because of not having to call into JavaScript to perform calculations.
Addition and subtraction
Position
implements Add<(i32, i32)>
, Sub<(i32, i32)>
and
Sub<Position>
. All of these implementations work on positions as world
positions, and will treat positions from different rooms just as if they're
further apart.
The Add
implementation can be used to add an offset to a position:
let pos1 = Position::new(0, 0, "E1N1".parse().unwrap()); let pos2 = Position::new(40, 20, "E1N1".parse().unwrap()); assert_eq!(pos1 + (40, 20), pos2);
And the Sub
implementation can be used to get the offset between two
positions:
let pos1 = Position::new(4, 20, "E20S21".parse().unwrap()); let pos2 = Position::new(4, 30, "E20S22".parse().unwrap()); assert_eq!(pos2 - pos1, (0, 60)); let pos3 = Position::new(0, 0, "E20S21".parse().unwrap()); assert_eq!(pos3 - pos1, (-4, -20));
Ordering
To facilitate use as a key in a BTreeMap
or other similar data
structures, Position
implements PartialOrd
and Ord
.
Position
s are ordered first by ascending world y
position, then by
ascending world x
position. World x
and y
here simply extend the x,y
coords within the room E0S0
throughout the map.
Looking at positions as tuples (world_x, world_y)
, the sorting obeys rules
such as:
(a, 0) < (b, 1)
for anya
,b
(0, c) < (1, c)
for anyc
This follows left-to-right reading order when looking at the Screeps map from above.
Implementations
impl Position
[src]
pub fn towards<T: ?Sized>(
self,
target: &T,
distance_towards_target: i32
) -> Position where
T: HasPosition,
[src]
self,
target: &T,
distance_towards_target: i32
) -> Position where
T: HasPosition,
Calculates an approximate midpoint between this point and the target.
In case of a tie, rounds towards this point.
If distance_towards_target
is bigger than the distance to the target,
the target is returned.
pub fn between<T: ?Sized>(
self,
target: &T,
distance_from_target: i32
) -> Position where
T: HasPosition,
[src]
self,
target: &T,
distance_from_target: i32
) -> Position where
T: HasPosition,
Calculates an approximate midpoint between this point and the target.
In case of a tie, rounds towards the target.
If distance_from_target
is bigger than the distance to the target,
this position is returned.
pub fn midpoint_between<T: ?Sized>(self, target: &T) -> Position where
T: HasPosition,
[src]
T: HasPosition,
Calculates an approximate midpoint between this point and the target.
In case of a tie, rounds towards the target.
impl Position
[src]
pub fn offset(&mut self, x: i32, y: i32)
[src]
Returns a new position offset from this position by the specified x coords and y coords.
This function operates on world coordinates, and will wrap between rooms if necessary.
To return a new position rather than modifying in place, use pos + (x, y)
. See the implementation of Add<(i32, i32)>
for
Position
further down on this page.
Panics
Will panic if the new position overflows the world. See
Position::from_world_coords
.
Example
use screeps::Position; let e21s21 = "E21S21".parse().unwrap(); let e21s22 = "E21S22".parse().unwrap(); let mut pos = Position::new(21, 21, e21s21); pos.offset(5, 5); assert_eq!(pos, Position::new(26, 26, e21s21)); pos.offset(0, 49); assert_eq!(pos, Position::new(26, 25, e21s22));
impl Position
[src]
pub fn get_direction_to<T: ?Sized>(self, target: &T) -> Option<Direction> where
T: HasPosition,
[src]
T: HasPosition,
Gets linear direction to the specified position.
Note that this chooses between Top
/Bottom
/Left
/Right
and
TopLeft
/TopRight
/BottomLeft
/BottomRight
by the magnitude in both
directions. For instance, Direction::Top
can be returned even
if the target has a slightly different x
coordinate.
pub fn get_range_to<T: ?Sized>(self, target: &T) -> u32 where
T: HasPosition,
[src]
T: HasPosition,
Gets linear range to the specified position.
This operates on positions as "world positions", and will return an
accurate range for positions in different rooms. Note that the
corresponding JavaScript method, RoomPosition.getRangeTo
returns
Infinity
if given positions in different rooms.
pub fn in_range_to<T: ?Sized>(self, target: &T, range: u32) -> bool where
T: HasPosition,
[src]
T: HasPosition,
Checks whether this position is in the given range of another position.
This operates on positions as "world positions", and may return true for
positions in different rooms which are still within the given range.
Note that the corresponding JavaScript method, RoomPosition.inRangeTo
,
will always return false
for positions from different rooms.
pub fn is_equal_to<T: ?Sized>(self, target: &T) -> bool where
T: HasPosition,
[src]
T: HasPosition,
Checks whether this position is the same as the specified position.
Note that this is equivalent to this_pos == target.pos()
.
pub fn is_near_to<T: ?Sized>(self, target: &T) -> bool where
T: HasPosition,
[src]
T: HasPosition,
True if this position is in the same room as the target, and the range is at most 1.
impl Position
[src]
pub fn create_construction_site(self, ty: StructureType) -> ReturnCode
[src]
pub fn create_named_construction_site(
self,
ty: StructureType,
name: &str
) -> ReturnCode
[src]
self,
ty: StructureType,
name: &str
) -> ReturnCode
pub fn create_flag(
self,
name: &str,
main_color: Color,
secondary_color: Color
) -> Result<String, ReturnCode>
[src]
self,
name: &str,
main_color: Color,
secondary_color: Color
) -> Result<String, ReturnCode>
pub fn find_closest_by_range<T>(self, ty: T) -> Option<T::Item> where
T: FindConstant,
[src]
T: FindConstant,
pub fn find_in_range<T>(self, ty: T, range: u32) -> Vec<T::Item> where
T: FindConstant,
[src]
T: FindConstant,
pub fn find_path_to<'a, F, T: ?Sized>(
self,
target: &T,
opts: FindOptions<'a, F, SingleRoomCostResult<'a>>
) -> Path where
F: Fn(RoomName, CostMatrix<'a>) -> SingleRoomCostResult<'a> + 'a,
T: HasPosition,
[src]
self,
target: &T,
opts: FindOptions<'a, F, SingleRoomCostResult<'a>>
) -> Path where
F: Fn(RoomName, CostMatrix<'a>) -> SingleRoomCostResult<'a> + 'a,
T: HasPosition,
pub fn find_path_to_xy<'a, F>(
self,
x: u32,
y: u32,
opts: FindOptions<'a, F, SingleRoomCostResult<'a>>
) -> Path where
F: Fn(RoomName, CostMatrix<'a>) -> SingleRoomCostResult<'a> + 'a,
[src]
self,
x: u32,
y: u32,
opts: FindOptions<'a, F, SingleRoomCostResult<'a>>
) -> Path where
F: Fn(RoomName, CostMatrix<'a>) -> SingleRoomCostResult<'a> + 'a,
pub fn look(self) -> Vec<LookResult>
[src]
pub fn look_for<T>(self, ty: T) -> Vec<T::Item> where
T: LookConstant,
[src]
T: LookConstant,
impl Position
[src]
pub fn coords(&self) -> (u32, u32)
[src]
Returns this position's in-room coordinates as a pair of unsigned integers.
pub fn coords_signed(&self) -> (i32, i32)
[src]
Returns this position's in-room coordinates as a pair of signed integers.
impl Position
[src]
pub fn world_x(self) -> i32
[src]
Returns this position's horizontal "world coordinate".
The value is equal to 50 * room_x + x
, where room_x
is defined as
room_x = -xx - 1
for Wxx
rooms and as room_x = xx
for Exx
rooms.
pub fn world_y(self) -> i32
[src]
Returns this position's vertical "world coordinate".
The value is equal to 50 * room_y + y
, where room_y
is defined as
room_y = -yy - 1
for Nyy
rooms and as room_y = yy
for Syy
rooms.
pub fn world_coords(self) -> (i32, i32)
[src]
Returns this position's "world coordinates".
The first value is equal to 50 * room_x + x
, where room_x
is defined
as room_x = -xx - 1
for Wxx
rooms and as room_x = xx
for Exx
rooms.
The second value is equal to 50 * room_y + y
, where room_y
is
defined as room_y = -yy - 1
for Nyy
rooms and as room_y = yy
for Syy
rooms.
See also Position::world_x
and
Position::world_y
.
pub fn from_world_coords(x: i32, y: i32) -> Self
[src]
Creates a room position from world coords.
Panics
Panics if either x or y is out of the range -128 * 50 .. +128 * 50
.
impl Position
[src]
impl Position
[src]
pub fn new(x: u32, y: u32, room_name: RoomName) -> Self
[src]
Create a new Position
Panics
Will panic if either x
or y
is larger than 49, or if room_name
is
outside of the range E127N127 - W127S127
.
pub fn packed_repr(self) -> i32
[src]
pub fn from_packed(packed: i32) -> Self
[src]
pub fn x(self) -> u32
[src]
Gets this position's in-room x coordinate.
pub fn y(self) -> u32
[src]
Gets this position's in-room y coordinate.
pub fn room_name(self) -> RoomName
[src]
pub fn set_x(&mut self, x: u32)
[src]
pub fn set_y(&mut self, y: u32)
[src]
pub fn set_room_name(&mut self, room_name: RoomName)
[src]
pub fn with_x(mut self: Self, x: u32) -> Self
[src]
pub fn with_y(mut self: Self, y: u32) -> Self
[src]
pub fn with_room_name(mut self: Self, room_name: RoomName) -> Self
[src]
Trait Implementations
impl Add<(i32, i32)> for Position
[src]
type Output = Position
The resulting type after applying the +
operator.
fn add(self, (x, y): (i32, i32)) -> Self
[src]
Adds an (x, y)
pair to this room position's world coordinates.
Will change rooms if necessary.
Panics
Will panic if the new position's room is outside bounds. See
Position::from_world_coords
.
Example
use screeps::Position; let w5s6 = "W5S6".parse().unwrap(); let w5s5 = "W5S5".parse().unwrap(); let pos1 = Position::new(42, 42, w5s6); let pos2 = pos1 + (7, 7); assert_eq!(pos2, Position::new(49, 49, w5s6)); let pos3 = pos2 + (0, -59); assert_eq!(pos3, Position::new(49, 40, w5s5)); let pos4 = pos3 - (49, 0); assert_eq!(pos4, Position::new(0, 40, w5s5));
impl Clone for Position
[src]
impl Copy for Position
[src]
impl Debug for Position
[src]
impl<'de> Deserialize<'de> for Position
[src]
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where
D: Deserializer<'de>,
[src]
D: Deserializer<'de>,
impl Display for Position
[src]
impl Eq for Position
[src]
impl FromExpectedType<Reference> for Position
[src]
fn from_expected_type(reference: Reference) -> Result<Self, ConversionError>
[src]
impl HasPosition for Position
[src]
impl Hash for Position
[src]
fn hash<__H: Hasher>(&self, state: &mut __H)
[src]
pub fn hash_slice<H>(data: &[Self], state: &mut H) where
H: Hasher,
1.3.0[src]
H: Hasher,
impl Into<(i16, i16)> for Position
[src]
fn into(self) -> (i16, i16)
[src]
Turns this positions's in-room coordinates into a pair of i16
values.
impl Into<(i32, i32)> for Position
[src]
fn into(self) -> (i32, i32)
[src]
Turns this positions's in-room coordinates into a pair of i32
values.
impl Into<(i64, i64)> for Position
[src]
fn into(self) -> (i64, i64)
[src]
Turns this positions's in-room coordinates into a pair of i64
values.
impl Into<(i8, i8)> for Position
[src]
impl Into<(u16, u16)> for Position
[src]
fn into(self) -> (u16, u16)
[src]
Turns this positions's in-room coordinates into a pair of u16
values.
impl Into<(u32, u32)> for Position
[src]
fn into(self) -> (u32, u32)
[src]
Turns this positions's in-room coordinates into a pair of u32
values.
impl Into<(u64, u64)> for Position
[src]
fn into(self) -> (u64, u64)
[src]
Turns this positions's in-room coordinates into a pair of u64
values.
impl Into<(u8, u8)> for Position
[src]
impl JsSerialize for Position
[src]
impl JsSerializeOwned for Position
[src]
fn into_js_owned<'_a>(value: &'_a mut Option<Self>) -> SerializedValue<'_a>
[src]
impl<'_r> JsSerializeOwned for &'_r Position
[src]
fn into_js_owned<'_a>(value: &'_a mut Option<Self>) -> SerializedValue<'_a>
[src]
impl Ord for Position
[src]
fn cmp(&self, other: &Self) -> Ordering
[src]
#[must_use]pub fn max(self, other: Self) -> Self
1.21.0[src]
#[must_use]pub fn min(self, other: Self) -> Self
1.21.0[src]
#[must_use]pub fn clamp(self, min: Self, max: Self) -> Self
1.50.0[src]
impl PartialEq<Position> for Position
[src]
impl PartialOrd<Position> for Position
[src]
fn partial_cmp(&self, other: &Position) -> Option<Ordering>
[src]
#[must_use]pub fn lt(&self, other: &Rhs) -> bool
1.0.0[src]
#[must_use]pub fn le(&self, other: &Rhs) -> bool
1.0.0[src]
#[must_use]pub fn gt(&self, other: &Rhs) -> bool
1.0.0[src]
#[must_use]pub fn ge(&self, other: &Rhs) -> bool
1.0.0[src]
impl Serialize for Position
[src]
impl StructuralEq for Position
[src]
impl StructuralPartialEq for Position
[src]
impl Sub<(i32, i32)> for Position
[src]
type Output = Position
The resulting type after applying the -
operator.
fn sub(self, (x, y): (i32, i32)) -> Self
[src]
See the implementation of Add<(i32, i32)>
for Position
.
impl Sub<Position> for Position
[src]
type Output = (i32, i32)
The resulting type after applying the -
operator.
fn sub(self, other: Position) -> (i32, i32)
[src]
Subtracts the other room position from this one, extracting the difference as the output.
Example
use screeps::Position; let e5n5 = "E5N5".parse().unwrap(); let e5n6 = "E5N6".parse().unwrap(); let pos1 = Position::new(40, 40, e5n5); let pos2 = Position::new(0, 20, e5n6); assert_eq!(pos1 - pos2, (40, 70));
impl<'_a> TryFrom<&'_a Position> for Value
[src]
type Error = ConversionError
The type returned in the event of a conversion error.
fn try_from(value: &'_a Position) -> Result<Self, Self::Error>
[src]
impl<'_a> TryFrom<&'_a mut Position> for Value
[src]
type Error = ConversionError
The type returned in the event of a conversion error.
fn try_from(value: &'_a mut Position) -> Result<Self, Self::Error>
[src]
impl TryFrom<Position> for Value
[src]
type Error = ConversionError
The type returned in the event of a conversion error.
fn try_from(value: Position) -> Result<Self, Self::Error>
[src]
impl TryFrom<Value> for Position
[src]
Auto Trait Implementations
impl RefUnwindSafe for Position
[src]
impl Send for Position
[src]
impl Sync for Position
[src]
impl Unpin for Position
[src]
impl UnwindSafe for Position
[src]
Blanket Implementations
impl<T> Any for T where
T: 'static + ?Sized,
[src]
T: 'static + ?Sized,
impl<T> Borrow<T> for T where
T: ?Sized,
[src]
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
[src]
T: ?Sized,
pub fn borrow_mut(&mut self) -> &mut T
[src]
impl<T> DeserializeOwned for T where
T: for<'de> Deserialize<'de>,
[src]
T: for<'de> Deserialize<'de>,
impl<T> From<T> for T
[src]
impl<T> FromExpectedType<Value> for T where
T: FromExpectedType<Reference>,
[src]
T: FromExpectedType<Reference>,
pub fn from_expected_type(Value) -> Result<T, ConversionError>
[src]
impl<T, U> Into<U> for T where
U: From<T>,
[src]
U: From<T>,
impl<T, U> IntoExpectedType<U> for T where
U: FromExpectedType<T>,
[src]
U: FromExpectedType<T>,
pub fn into_expected_type(Self) -> Result<U, ConversionError>
[src]
impl<T> ToOwned for T where
T: Clone,
[src]
T: Clone,
type Owned = T
The resulting type after obtaining ownership.
pub fn to_owned(&self) -> T
[src]
pub fn clone_into(&self, target: &mut T)
[src]
impl<T> ToString for T where
T: Display + ?Sized,
[src]
T: Display + ?Sized,
impl<T, U> TryFrom<U> for T where
U: Into<T>,
[src]
U: Into<T>,
type Error = Infallible
The type returned in the event of a conversion error.
pub fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
[src]
impl<T, U> TryInto<U> for T where
U: TryFrom<T>,
[src]
U: TryFrom<T>,
type Error = <U as TryFrom<T>>::Error
The type returned in the event of a conversion error.
pub fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>
[src]
impl<T, U> TryInto<U> for T where
U: TryFrom<T>,
[src]
U: TryFrom<T>,