1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
//! Functions and datatypes to work with world coordinates

use crate::MAPBLOCK_LENGTH;
use num_integer::div_floor;
#[cfg(any(feature = "postgres"))]
use sqlx::postgres::PgRow;
#[cfg(any(feature = "sqlite"))]
use sqlx::sqlite::SqliteRow;
#[cfg(any(feature = "sqlite", feature = "postgres"))]
use sqlx::{FromRow, Row};
use std::ops::{Add, Rem};

/// A point location within the world
///
/// This type is used for addressing one of the following:
/// * voxels ([nodes](`crate::Node`), node timers, metadata, ...).
/// * [MapBlocks](`crate::MapBlock`). In this case, all three dimensions are divided by the
/// MapBlock [side length](`crate::MAPBLOCK_LENGTH`).
///
/// A voxel position may either be absolute or relative to a mapblock root.
#[derive(Debug, PartialEq, Copy, Clone, Eq, Hash)]
pub struct Position {
    /// "East direction". The direction in which the sun rises.
    pub x: i16,
    /// "Up" direction
    pub y: i16,
    /// "North" direction. 90° left from the direction the sun rises.
    pub z: i16,
}

impl std::ops::Add for Position {
    type Output = Self;

    fn add(self, other: Self) -> Self {
        Position {
            x: self.x + other.x,
            y: self.y + other.y,
            z: self.z + other.z,
        }
    }
}

impl std::ops::Sub for Position {
    type Output = Self;

    fn sub(self, rhs: Self) -> Self::Output {
        Position {
            x: self.x - rhs.x,
            y: self.y - rhs.y,
            z: self.z - rhs.z,
        }
    }
}

impl std::ops::Mul<i16> for Position {
    type Output = Self;

    fn mul(self, rhs: i16) -> Self {
        Position {
            x: self.x * rhs,
            y: self.y * rhs,
            z: self.z * rhs,
        }
    }
}

#[cfg(feature = "sqlite")]
impl FromRow<'_, SqliteRow> for Position {
    fn from_row(row: &SqliteRow) -> sqlx::Result<Self> {
        Ok(Position::from_database_key(row.try_get("pos")?))
    }
}

#[cfg(feature = "postgres")]
impl FromRow<'_, PgRow> for Position {
    fn from_row(row: &PgRow) -> sqlx::Result<Self> {
        Ok(Position {
            x: row.try_get("posx")?,
            y: row.try_get("posy")?,
            z: row.try_get("posz")?,
        })
    }
}

/// While there is no modulo operator in rust, we'll use the remainder operator (%) to build one.
pub fn modulo<I>(a: I, b: I) -> I
where
    I: Copy + Add<Output = I> + Rem<Output = I>,
{
    (a % b + b) % b
}

impl Position {
    /// Create a new position value from its components
    pub fn new<I: Into<i16>>(x: I, y: I, z: I) -> Self {
        Position {
            x: x.into(),
            y: y.into(),
            z: z.into(),
        }
    }

    /// Convert a mapblock database index into coordinates
    pub(crate) fn from_database_key(i: i64) -> Position {
        fn unsigned_to_signed(i: i64, max_positive: i64) -> i64 {
            if i < max_positive {
                i
            } else {
                i - 2 * max_positive
            }
        }

        let x = unsigned_to_signed(modulo(i, 4096), 2048) as i16;
        let mut i = (i - x as i64) / 4096;
        let y = unsigned_to_signed(modulo(i, 4096), 2048) as i16;
        i = (i - y as i64) / 4096;
        let z = unsigned_to_signed(modulo(i, 4096), 2048) as i16;
        Position { x, y, z }
    }

    /// Convert a map block position to an integer
    ///
    /// This integer is used as primary key in the sqlite and redis backends.
    pub(crate) fn as_database_key(&self) -> i64 {
        self.x as i64 + self.y as i64 * 4096 + self.z as i64 * 16777216
    }

    /// Convert a nodex index (used in flat 16·16·16 arrays) into a node position
    ///
    /// The node position will be relative to the map block.
    pub(crate) fn from_node_index(node_index: u16) -> Position {
        let x = node_index % 16;
        let i = node_index / 16;
        let y = i % 16;
        let i = node_index / 16;
        let z = i % 16;
        Position {
            x: x as i16,
            y: y as i16,
            z: z as i16,
        }
    }

    /// Convert a MapBlock-relative node position into a flat array index
    pub(crate) fn as_node_index(&self) -> u16 {
        self.x as u16 + 16 * self.y as u16 + 256 * self.z as u16
    }

    /// Return the mapblock position corresponding to this node position
    pub fn mapblock_at(&self) -> Position {
        Position {
            x: div_floor(self.x, MAPBLOCK_LENGTH.into()),
            y: div_floor(self.y, MAPBLOCK_LENGTH.into()),
            z: div_floor(self.z, MAPBLOCK_LENGTH.into()),
        }
    }

    /// Split this node position into a mapblock position and a relative node position
    pub fn split_at_block(&self) -> (Position, Position) {
        let blockpos = self.mapblock_at();
        let relative_pos = *self - blockpos * MAPBLOCK_LENGTH as i16;
        (blockpos, relative_pos)
    }
}