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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
//! Representations of positions of various things in Minecraft.
//!
//! The most common ones are [`Vec3`] and [`BlockPos`], which are usually used
//! for entity positions and block positions, respectively.

use azalea_buf::{BufReadError, McBuf, McBufReadable, McBufWritable};
use std::{
    fmt,
    hash::Hash,
    io::{Cursor, Write},
    ops::{Add, AddAssign, Mul, Rem, Sub},
};

use crate::resource_location::ResourceLocation;

macro_rules! vec3_impl {
    ($name:ident, $type:ty) => {
        impl $name {
            #[inline]
            pub fn new(x: $type, y: $type, z: $type) -> Self {
                Self { x, y, z }
            }

            /// Get the distance of this vector to the origin by doing `x^2 + y^2 +
            /// z^2`.
            #[inline]
            pub fn length_sqr(&self) -> $type {
                self.x * self.x + self.y * self.y + self.z * self.z
            }

            /// Get the squared distance from this position to another position.
            /// Equivalent to `(self - other).length_sqr()`.
            #[inline]
            pub fn distance_to_sqr(&self, other: &Self) -> $type {
                (self - other).length_sqr()
            }

            #[inline]
            pub fn horizontal_distance_sqr(&self) -> $type {
                self.x * self.x + self.z * self.z
            }

            #[inline]
            pub fn horizontal_distance_to_sqr(&self, other: &Self) -> $type {
                (self - other).horizontal_distance_sqr()
            }

            /// Return a new instance of this position with the y coordinate
            /// decreased by the given number.
            #[inline]
            pub fn down(&self, y: $type) -> Self {
                Self {
                    x: self.x,
                    y: self.y - y,
                    z: self.z,
                }
            }
            /// Return a new instance of this position with the y coordinate
            /// increased by the given number.
            #[inline]
            pub fn up(&self, y: $type) -> Self {
                Self {
                    x: self.x,
                    y: self.y + y,
                    z: self.z,
                }
            }

            /// Return a new instance of this position with the z coordinate subtracted
            /// by the given number.
            pub fn north(&self, z: $type) -> Self {
                Self {
                    x: self.x,
                    y: self.y,
                    z: self.z - z,
                }
            }
            /// Return a new instance of this position with the x coordinate increased
            /// by the given number.
            pub fn east(&self, x: $type) -> Self {
                Self {
                    x: self.x + x,
                    y: self.y,
                    z: self.z,
                }
            }
            /// Return a new instance of this position with the z coordinate increased
            /// by the given number.
            pub fn south(&self, z: $type) -> Self {
                Self {
                    x: self.x,
                    y: self.y,
                    z: self.z + z,
                }
            }
            /// Return a new instance of this position with the x coordinate subtracted
            /// by the given number.
            pub fn west(&self, x: $type) -> Self {
                Self {
                    x: self.x - x,
                    y: self.y,
                    z: self.z,
                }
            }

            #[inline]
            pub fn dot(&self, other: Self) -> $type {
                self.x * other.x + self.y * other.y + self.z * other.z
            }
        }

        impl Add for &$name {
            type Output = $name;

            #[inline]
            fn add(self, rhs: Self) -> Self::Output {
                $name {
                    x: self.x + rhs.x,
                    y: self.y + rhs.y,
                    z: self.z + rhs.z,
                }
            }
        }

        impl Add for $name {
            type Output = $name;

            #[inline]
            fn add(self, rhs: Self) -> Self::Output {
                (&self).add(&rhs)
            }
        }

        impl AddAssign for $name {
            #[inline]
            fn add_assign(&mut self, rhs: Self) {
                self.x += rhs.x;
                self.y += rhs.y;
                self.z += rhs.z;
            }
        }
        impl Rem<$type> for $name {
            type Output = Self;

            #[inline]
            fn rem(self, rhs: $type) -> Self::Output {
                Self {
                    x: self.x % rhs,
                    y: self.y % rhs,
                    z: self.z % rhs,
                }
            }
        }

        impl Sub for &$name {
            type Output = $name;

            /// Find the difference between two positions.
            #[inline]
            fn sub(self, other: Self) -> Self::Output {
                Self::Output {
                    x: self.x - other.x,
                    y: self.y - other.y,
                    z: self.z - other.z,
                }
            }
        }
        impl Sub for $name {
            type Output = Self;

            #[inline]
            fn sub(self, other: Self) -> Self::Output {
                (&self).sub(&other)
            }
        }

        impl Mul<$type> for $name {
            type Output = Self;

            #[inline]
            fn mul(self, multiplier: $type) -> Self::Output {
                Self {
                    x: self.x * multiplier,
                    y: self.y * multiplier,
                    z: self.z * multiplier,
                }
            }
        }

        impl From<($type, $type, $type)> for $name {
            #[inline]
            fn from(pos: ($type, $type, $type)) -> Self {
                Self::new(pos.0, pos.1, pos.2)
            }
        }
        impl From<&($type, $type, $type)> for $name {
            #[inline]
            fn from(pos: &($type, $type, $type)) -> Self {
                Self::new(pos.0, pos.1, pos.2)
            }
        }
        impl From<$name> for ($type, $type, $type) {
            #[inline]
            fn from(pos: $name) -> Self {
                (pos.x, pos.y, pos.z)
            }
        }
    };
}

/// Used to represent an exact position in the world where an entity could be.
/// For blocks, [`BlockPos`] is used instead.
#[derive(Clone, Copy, Debug, Default, PartialEq, McBuf)]
pub struct Vec3 {
    pub x: f64,
    pub y: f64,
    pub z: f64,
}
vec3_impl!(Vec3, f64);

impl Vec3 {
    /// Get the distance of this vector to the origin by doing
    /// `sqrt(x^2 + y^2 + z^2)`.
    pub fn length(&self) -> f64 {
        f64::sqrt(self.x * self.x + self.y * self.y + self.z * self.z)
    }

    /// Get the distance from this position to another position.
    /// Equivalent to `(self - other).length()`.
    pub fn distance_to(&self, other: &Self) -> f64 {
        (self - other).length()
    }
}

/// The coordinates of a block in the world. For entities (if the coordinate
/// with decimals), use [`Vec3`] instead.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct BlockPos {
    pub x: i32,
    pub y: i32,
    pub z: i32,
}
vec3_impl!(BlockPos, i32);

impl BlockPos {
    /// Get the absolute center of a block position by adding 0.5 to each
    /// coordinate.
    pub fn center(&self) -> Vec3 {
        Vec3 {
            x: self.x as f64 + 0.5,
            y: self.y as f64 + 0.5,
            z: self.z as f64 + 0.5,
        }
    }

    /// Convert the block position into a Vec3 without centering it.
    pub fn to_vec3_floored(&self) -> Vec3 {
        Vec3 {
            x: self.x as f64,
            y: self.y as f64,
            z: self.z as f64,
        }
    }

    /// Get the distance of this vector from the origin by doing `x + y + z`.
    pub fn length_manhattan(&self) -> u32 {
        (self.x.abs() + self.y.abs() + self.z.abs()) as u32
    }
}

/// Chunk coordinates are used to represent where a chunk is in the world. You
/// can convert the x and z to block coordinates by multiplying them by 16.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ChunkPos {
    pub x: i32,
    pub z: i32,
}
impl ChunkPos {
    pub fn new(x: i32, z: i32) -> Self {
        ChunkPos { x, z }
    }
}
impl Add<ChunkPos> for ChunkPos {
    type Output = Self;

    fn add(self, rhs: Self) -> Self::Output {
        Self {
            x: self.x + rhs.x,
            z: self.z + rhs.z,
        }
    }
}

// reading ChunkPos is done in reverse, so z first and then x
// ........
// mojang why
impl From<ChunkPos> for u64 {
    #[inline]
    fn from(pos: ChunkPos) -> Self {
        (pos.x as u64) | ((pos.z as u64) << 32)
    }
}
impl From<u64> for ChunkPos {
    #[inline]
    fn from(pos: u64) -> Self {
        ChunkPos {
            x: (pos) as i32,
            z: (pos >> 32) as i32,
        }
    }
}
impl McBufReadable for ChunkPos {
    fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
        let long = u64::read_from(buf)?;
        Ok(ChunkPos::from(long))
    }
}
impl McBufWritable for ChunkPos {
    fn write_into(&self, buf: &mut impl Write) -> Result<(), std::io::Error> {
        u64::from(*self).write_into(buf)?;
        Ok(())
    }
}

impl Hash for ChunkPos {
    #[inline]
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        // optimized hash that only calls hash once
        u64::from(*self).hash(state);
    }
}
/// nohash_hasher lets us have IntMap<ChunkPos, _> which is significantly faster
/// than a normal HashMap
impl nohash_hasher::IsEnabled for ChunkPos {}

/// The coordinates of a chunk section in the world.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
pub struct ChunkSectionPos {
    pub x: i32,
    pub y: i32,
    pub z: i32,
}
vec3_impl!(ChunkSectionPos, i32);

impl ChunkSectionPos {
    pub fn block_to_section_coord(block: i32) -> i32 {
        block >> 4
    }
}

/// The coordinates of a block inside a chunk.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ChunkBlockPos {
    pub x: u8,
    pub y: i32,
    pub z: u8,
}

impl ChunkBlockPos {
    pub fn new(x: u8, y: i32, z: u8) -> Self {
        ChunkBlockPos { x, y, z }
    }
}

impl Hash for ChunkBlockPos {
    // optimized hash that only calls hash once
    #[inline]
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        u64::from(*self).hash(state);
    }
}
impl From<ChunkBlockPos> for u64 {
    #[inline]
    fn from(pos: ChunkBlockPos) -> Self {
        // convert to u64
        let mut val: u64 = 0;
        // first 32 bits are y
        val |= pos.y as u64;
        // next 8 bits are z
        val |= (pos.z as u64) << 32;
        // last 8 bits are x
        val |= (pos.x as u64) << 40;
        val
    }
}
impl nohash_hasher::IsEnabled for ChunkBlockPos {}

/// The coordinates of a block inside a chunk section. Each coordinate must be
/// in the range [0, 15].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ChunkSectionBlockPos {
    pub x: u8,
    pub y: u8,
    pub z: u8,
}
vec3_impl!(ChunkSectionBlockPos, u8);

impl Add<ChunkSectionBlockPos> for ChunkSectionPos {
    type Output = BlockPos;

    fn add(self, rhs: ChunkSectionBlockPos) -> Self::Output {
        BlockPos::new(
            self.x * 16 + rhs.x as i32,
            self.y * 16 + rhs.y as i32,
            self.z * 16 + rhs.z as i32,
        )
    }
}
impl Hash for ChunkSectionBlockPos {
    // optimized hash that only calls hash once
    #[inline]
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        u16::from(*self).hash(state);
    }
}

impl From<ChunkSectionBlockPos> for u16 {
    #[inline]
    fn from(pos: ChunkSectionBlockPos) -> Self {
        // (pos.z as u16) | ((pos.y as u16) << 4) | ((pos.x as u16) << 8)
        ((((pos.y as u16) << 4) | pos.z as u16) << 4) | pos.x as u16
    }
}
impl nohash_hasher::IsEnabled for ChunkSectionBlockPos {}

/// A block pos with an attached world
#[derive(Debug, Clone, PartialEq)]
pub struct GlobalPos {
    // this is actually a ResourceKey in Minecraft, but i don't think it matters?
    pub world: ResourceLocation,
    pub pos: BlockPos,
}

impl From<&BlockPos> for ChunkPos {
    #[inline]
    fn from(pos: &BlockPos) -> Self {
        ChunkPos {
            x: pos.x >> 4,
            z: pos.z >> 4,
        }
    }
}
impl From<BlockPos> for ChunkPos {
    #[inline]
    fn from(pos: BlockPos) -> Self {
        ChunkPos {
            x: pos.x >> 4,
            z: pos.z >> 4,
        }
    }
}

impl From<BlockPos> for ChunkSectionPos {
    #[inline]
    fn from(pos: BlockPos) -> Self {
        ChunkSectionPos {
            x: pos.x >> 4,
            y: pos.y >> 4,
            z: pos.z >> 4,
        }
    }
}
impl From<&BlockPos> for ChunkSectionPos {
    #[inline]
    fn from(pos: &BlockPos) -> Self {
        ChunkSectionPos {
            x: pos.x >> 4,
            y: pos.y >> 4,
            z: pos.z >> 4,
        }
    }
}

impl From<ChunkSectionPos> for ChunkPos {
    fn from(pos: ChunkSectionPos) -> Self {
        ChunkPos { x: pos.x, z: pos.z }
    }
}

impl From<&BlockPos> for ChunkBlockPos {
    #[inline]
    fn from(pos: &BlockPos) -> Self {
        ChunkBlockPos {
            x: (pos.x & 0xF) as u8,
            y: pos.y,
            z: (pos.z & 0xF) as u8,
        }
    }
}
impl From<BlockPos> for ChunkBlockPos {
    #[inline]
    fn from(pos: BlockPos) -> Self {
        ChunkBlockPos {
            x: (pos.x & 0xF) as u8,
            y: pos.y,
            z: (pos.z & 0xF) as u8,
        }
    }
}

impl From<BlockPos> for ChunkSectionBlockPos {
    #[inline]
    fn from(pos: BlockPos) -> Self {
        ChunkSectionBlockPos {
            x: (pos.x & 0xF) as u8,
            y: (pos.y & 0xF) as u8,
            z: (pos.z & 0xF) as u8,
        }
    }
}

impl From<&ChunkBlockPos> for ChunkSectionBlockPos {
    #[inline]
    fn from(pos: &ChunkBlockPos) -> Self {
        ChunkSectionBlockPos {
            x: pos.x,
            y: (pos.y & 0xF) as u8,
            z: pos.z,
        }
    }
}
impl From<&Vec3> for BlockPos {
    #[inline]
    fn from(pos: &Vec3) -> Self {
        BlockPos {
            x: pos.x.floor() as i32,
            y: pos.y.floor() as i32,
            z: pos.z.floor() as i32,
        }
    }
}
impl From<Vec3> for BlockPos {
    #[inline]
    fn from(pos: Vec3) -> Self {
        BlockPos::from(&pos)
    }
}

impl From<&Vec3> for ChunkPos {
    fn from(pos: &Vec3) -> Self {
        ChunkPos::from(&BlockPos::from(pos))
    }
}
impl From<Vec3> for ChunkPos {
    fn from(pos: Vec3) -> Self {
        ChunkPos::from(&pos)
    }
}

impl From<&Vec3> for ChunkBlockPos {
    fn from(pos: &Vec3) -> Self {
        ChunkBlockPos::from(&BlockPos::from(pos))
    }
}
impl From<Vec3> for ChunkBlockPos {
    fn from(pos: Vec3) -> Self {
        ChunkBlockPos::from(&pos)
    }
}

impl fmt::Display for BlockPos {
    /// Display a block position as `x y z`.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} {} {}", self.x, self.y, self.z)
    }
}
impl fmt::Display for Vec3 {
    /// Display a position as `x y z`.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} {} {}", self.x, self.y, self.z)
    }
}

const PACKED_X_LENGTH: u64 = 1 + 25; // minecraft does something a bit more complicated to get this 25
const PACKED_Z_LENGTH: u64 = PACKED_X_LENGTH;
const PACKED_Y_LENGTH: u64 = 64 - PACKED_X_LENGTH - PACKED_Z_LENGTH;
const PACKED_X_MASK: u64 = (1 << PACKED_X_LENGTH) - 1;
const PACKED_Y_MASK: u64 = (1 << PACKED_Y_LENGTH) - 1;
const PACKED_Z_MASK: u64 = (1 << PACKED_Z_LENGTH) - 1;
const Z_OFFSET: u64 = PACKED_Y_LENGTH;
const X_OFFSET: u64 = PACKED_Y_LENGTH + PACKED_Z_LENGTH;

impl McBufReadable for BlockPos {
    fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
        let val = i64::read_from(buf)?;
        let x = (val << (64 - X_OFFSET - PACKED_X_LENGTH) >> (64 - PACKED_X_LENGTH)) as i32;
        let y = (val << (64 - PACKED_Y_LENGTH) >> (64 - PACKED_Y_LENGTH)) as i32;
        let z = (val << (64 - Z_OFFSET - PACKED_Z_LENGTH) >> (64 - PACKED_Z_LENGTH)) as i32;
        Ok(BlockPos { x, y, z })
    }
}

impl McBufReadable for GlobalPos {
    fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
        Ok(GlobalPos {
            world: ResourceLocation::read_from(buf)?,
            pos: BlockPos::read_from(buf)?,
        })
    }
}

impl McBufReadable for ChunkSectionPos {
    fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
        let long = i64::read_from(buf)?;
        Ok(ChunkSectionPos {
            x: (long >> 42) as i32,
            y: (long << 44 >> 44) as i32,
            z: (long << 22 >> 42) as i32,
        })
    }
}

impl McBufWritable for BlockPos {
    fn write_into(&self, buf: &mut impl Write) -> Result<(), std::io::Error> {
        let mut val: u64 = 0;
        val |= ((self.x as u64) & PACKED_X_MASK) << X_OFFSET;
        val |= (self.y as u64) & PACKED_Y_MASK;
        val |= ((self.z as u64) & PACKED_Z_MASK) << Z_OFFSET;
        val.write_into(buf)
    }
}

impl McBufWritable for GlobalPos {
    fn write_into(&self, buf: &mut impl Write) -> Result<(), std::io::Error> {
        ResourceLocation::write_into(&self.world, buf)?;
        BlockPos::write_into(&self.pos, buf)?;

        Ok(())
    }
}

impl McBufWritable for ChunkSectionPos {
    fn write_into(&self, buf: &mut impl Write) -> Result<(), std::io::Error> {
        let long = (((self.x & 0x3FFFFF) as i64) << 42)
            | (self.y & 0xFFFFF) as i64
            | (((self.z & 0x3FFFFF) as i64) << 20);
        long.write_into(buf)?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_from_block_pos_to_chunk_pos() {
        let block_pos = BlockPos::new(5, 78, -2);
        let chunk_pos = ChunkPos::from(&block_pos);
        assert_eq!(chunk_pos, ChunkPos::new(0, -1));
    }

    #[test]
    fn test_from_block_pos_to_chunk_block_pos() {
        let block_pos = BlockPos::new(5, 78, -2);
        let chunk_block_pos = ChunkBlockPos::from(&block_pos);
        assert_eq!(chunk_block_pos, ChunkBlockPos::new(5, 78, 14));
    }

    #[test]
    fn test_from_entity_pos_to_block_pos() {
        let entity_pos = Vec3 {
            x: 31.5,
            y: 80.0,
            z: -16.1,
        };
        let block_pos = BlockPos::from(&entity_pos);
        assert_eq!(block_pos, BlockPos::new(31, 80, -17));
    }

    #[test]
    fn test_from_entity_pos_to_chunk_pos() {
        let entity_pos = Vec3 {
            x: 31.5,
            y: 80.0,
            z: -16.1,
        };
        let chunk_pos = ChunkPos::from(&entity_pos);
        assert_eq!(chunk_pos, ChunkPos::new(1, -2));
    }

    #[test]
    fn test_read_blockpos_from() {
        let mut buf = Vec::new();
        13743895338965u64.write_into(&mut buf).unwrap();
        let mut buf = Cursor::new(&buf[..]);
        let block_pos = BlockPos::read_from(&mut buf).unwrap();
        assert_eq!(block_pos, BlockPos::new(49, -43, -3));
    }

    #[test]
    fn test_into_chunk_section_block_pos() {
        let block_pos = BlockPos::new(0, -60, 0);
        assert_eq!(
            ChunkSectionBlockPos::from(block_pos),
            ChunkSectionBlockPos::new(0, 4, 0)
        );
    }

    #[test]
    fn test_read_chunk_pos_from() {
        let mut buf = Vec::new();
        ChunkPos::new(2, -1).write_into(&mut buf).unwrap();
        let mut buf = Cursor::new(&buf[..]);
        let chunk_pos = ChunkPos::from(u64::read_from(&mut buf).unwrap());
        assert_eq!(chunk_pos, ChunkPos::new(2, -1));
    }
}