bitperm 0.1.0

Bit permutations and bit-packed polycube/grid structures in Rust
Documentation
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
use std::fmt;
use std::ops::*;

use flowscad::*;

use crate::bitlib::*;
// use crate::bitlib::BC3_FULL;
// use crate::bitlib::swap_mask_shift_u32;
// TODO: Remove
use crate::bitcube4::BitCube4;

// use itertools::Itertools;

// -----------------------------------------------------------------
// 3x3x3 cube space represented by 27 bits of a u32
// -----------------------------------------------------------------
// Position at (x,y,z) = x + 3*y + 9*z
// Rotations will happen from the center of the cube

#[derive(Copy, Clone, PartialEq)]
pub struct BitCube3(pub u32);

impl From<u32> for BitCube3 {
    fn from(x: u32) -> BitCube3 {
        BitCube3(x & BC3_FULL)
    }
}

/* TODO remove
/// Embedding a BitCube4 into a BitCube3 by truncated the 4-cube indices
/// larger than 3. Does not check for lost bits.
impl From<BitCube4> for BitCube3 {
    fn from(bc4: BitCube4) -> BitCube3 {
        let mut x = bc4.0;
        // Shift the row start index from 0,4,8 to 0,3,6
        x = (x & 0x700070007) ^ ((x>>1) & 0x3800380038) ^ ((x>>2) & 0x01c001c001c0);
        // Shift the plane start index from 0,16,32 to 0,9,18
        x = (x & 0o777) ^ ((x>>7) & 0o777000) ^ ((x>>14) & 0o777000000);
        BitCube3(x as u32)
    }
}
*/

/* TODO: How should TryFrom<BitCube4> for BitCube3 work?
impl TryFrom<u64> for BitCube3 {
    type Error = ();

    fn try_from(bc4: u64) -> Result<BitCube3, Self::Error> {
        let mut x = bc4;
        if x == x & 0x77707770777 {
            // Shift the row start index from 0,4,8 to 0,3,6
            x = (x & 0x700070007) ^ ((x>>1) & 0x3800380038) ^ ((x>>2) & 0x01c001c001c0);
            // Shift the plane start index from 0,16,32 to 0,9,18
            x = (x & 0o777) ^ ((x>>7) & 0o777000) ^ ((x>>14) & 0o777000000);
            Ok(BitCube3(x as u32))
        } else {
            Err(())
        }
    }
}
*/

impl From<BitCube3> for D3 {
    fn from(val: BitCube3) -> Self {
        let block = D3::cube(1.0);
        (0..27)
            .filter(|ii| (val.0 >> ii) & 1 == 1)
            .map(|ii| v3(ii % 3, (ii / 3) % 3, ii / 9))
            .map(|xyz| block.clone().translate(xyz))
            .union()
            // .translate(v3(-1,-1,-1))
            .scale(10)
            .color(ColorEnum::Red)
    }
}

/// 3x3x3 layout of u32 0b00000qponmlkjihgfedcba9876543210
/// 678 | fgh | opq
/// 345 | cde | lmn
/// 012 | 9ab | ijk
/// (x,y,z) at x+3*y+9*z
impl BitCube3 {
    /// Count the number of cubes (ones) in the BitCube
    pub fn count_cubes(self) -> u32 {
        self.0.count_ones()
    }

    /// Easiest to visualize as a z-rotation, but same idea
    pub fn rotate_x(self) -> Self {
        let mut cube = self.0;
        // Swap vertical
        swap_mask_shift_u32(&mut cube, 0o777_u32, 18);
        // Swap main diagonal
        swap_mask_shift_u32(&mut cube, 0o700_u32, 12);
        // Swap outer diagonals
        swap_mask_shift_u32(&mut cube, 0o700_070_u32, 6);
        BitCube3(cube)
    }

    /// Easiest to visualize as a z-rotation, but same idea
    pub fn rotate_y(self) -> Self {
        let mut cube = self.0;
        // Swap vertical
        swap_mask_shift_u32(&mut cube, 0o777_u32, 18);
        // Swap main diagonal
        swap_mask_shift_u32(&mut cube, 0o444_u32, 16);
        // Swap outer diagonals
        swap_mask_shift_u32(&mut cube, 0o444_222_u32, 8);
        BitCube3(cube)
    }

    /// z-rotation done by two swaps
    /// abc      bc.
    /// ... then a.c
    /// abc      .ab
    pub fn rotate_z(self) -> Self {
        let mut cube = self.0;
        // Swap vertical
        swap_mask_shift_u32(&mut cube, 0o007_007_007_u32, 6);
        // Swap main diagonal
        swap_mask_shift_u32(&mut cube, 0o004_004_004_u32, 4);
        // Swap outer diagonals
        swap_mask_shift_u32(&mut cube, 0o042_042_042_u32, 2);
        BitCube3(cube)
    }

    /// Rotate 120 degrees about the diagonal through the origin and center of the cube.
    /// TODO: Figure out a faster way than using BitCube4
    pub fn rotate_d(self) -> Self {
        Self::from(BitCube4::from(self).rotate_d())
    }

    pub fn shift_x(self, shift: i8) -> Self {
        match shift {
            0 => self,
            1 => Self((self.0.unbounded_shl(1)) & 0o666_666_666_u32),
            2 => Self((self.0.unbounded_shl(2)) & 0o444_444_444_u32),
            -1 => Self((self.0.unbounded_shl(1)) & 0o333_333_333_u32),
            -2 => Self((self.0.unbounded_shl(2)) & 0o111_111_111_u32),
            _ => Self(0),
        }
    }

    /// Return none if the x-shift would move part of the polycube past an edge.
    pub fn bounded_shift_x(self, shift: i8) -> Option<Self> {
        let shifted = self.shift_x(shift);
        if self.count_cubes() == shifted.count_cubes() {
            Some(shifted)
        } else {
            None
        }
    }

    pub fn shift_y(self, shift: i8) -> Self {
        match shift {
            0 => self,
            1 => Self((self.0.unbounded_shl(3)) & 0o770_770_770_u32),
            2 => Self((self.0.unbounded_shl(6)) & 0o700_700_700_u32),
            -1 => Self((self.0.unbounded_shr(3)) & 0o077_077_077_u32),
            -2 => Self((self.0.unbounded_shr(6)) & 0o007_007_007_u32),
            _ => Self(0),
        }
    }

    /// Return none if the y-shift would move part of the polycube past an edge.
    pub fn bounded_shift_y(self, shift: i8) -> Option<Self> {
        let shifted = self.shift_y(shift);
        if self.count_cubes() == shifted.count_cubes() {
            Some(shifted)
        } else {
            None
        }
    }

    pub fn shift_z(self, shift: i8) -> Self {
        match shift {
            0 => self,
            1 => Self((self.0.unbounded_shl(9)) & 0o777_777_000_u32),
            2 => Self((self.0.unbounded_shl(18)) & 0o777_000_000_u32),
            -1 => Self((self.0.unbounded_shr(9)) & 0o000_777_777_u32),
            -2 => Self((self.0.unbounded_shr(18)) & 0o000_000_777_u32),
            _ => Self(0),
        }
    }

    /// Return none if the z-shift would move part of the polycube past an edge.
    pub fn bounded_shift_z(self, shift: i8) -> Option<Self> {
        let shifted = self.shift_z(shift);
        if self.count_cubes() == shifted.count_cubes() {
            Some(shifted)
        } else {
            None
        }
    }

    /*
    /// Given a piece in the 4-cube, shift it towards the origin so that it touches the x, y, and z
    /// planes
    pub fn shift_to_origin(self) -> Self {
        let mut shape = self.0;
        let z_shift = (shape.trailing_zeros() / 16) * 16;
        shape = shape.unbounded_shr(z_shift);
        let xy_proj = shape | shape.unbounded_shr(32);
        let xy_proj = xy_proj | xy_proj.unbounded_shr(16);
        let y_shift = (xy_proj.trailing_zeros() / 4) * 4;
        shape = shape.unbounded_shr(y_shift);
        let x_shift = xy_proj | xy_proj.unbounded_shr(8);
        let x_shift = x_shift | x_shift.unbounded_shr(4);
        shape = shape.unbounded_shr(x_shift.trailing_zeros());
        Self(shape)
    }
    */

    pub fn overlap(self, other: Self) -> bool {
        self.0 & other.0 != 0
    }
}

impl BitOr for BitCube3 {
    type Output = Self;

    fn bitor(self, other: Self) -> Self::Output {
        Self(self.0 | other.0)
    }
}

impl BitAnd for BitCube3 {
    type Output = Self;

    fn bitand(self, other: Self) -> Self::Output {
        Self(self.0 & other.0)
    }
}

impl Shl<u32> for BitCube3 {
    type Output = Self;

    fn shl(self, rhs: u32) -> Self::Output {
        Self(self.0.unbounded_shl(rhs))
    }
}

impl Shr<u32> for BitCube3 {
    type Output = Self;

    fn shr(self, rhs: u32) -> Self::Output {
        Self(self.0.unbounded_shr(rhs))
    }
}

impl fmt::Debug for BitCube3 {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "BitCube3({:#011o})\n{:}", self.0, self)
    }
}

impl fmt::Display for BitCube3 {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{}",
            (0..3)
                .map(|x| {
                    let x = self.0 >> (3 * (2 - x));
                    (0..3)
                        .map(|y| format!("{:03b}", (x >> (9 * y)) & 0x7))
                        .map(|s| s.chars().rev().collect())
                        .collect::<Vec<String>>()
                        .join(" ")
                })
                .collect::<Vec<String>>()
                .join("\n")
        )
    }
}

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

    #[test]
    fn test_debug() {
        assert_eq!(
            format!("{:?}", BitCube3::from(BC3_ORDER)),
            "BitCube3(0o076543210)\n010 101 000\n100 001 111\n000 110 011"
        );
    }

    #[test]
    fn test_display() {
        assert_eq!(
            format!("{:}", BitCube3::from(BC3_ORDER)),
            "010 101 000\n100 001 111\n000 110 011"
        );
    }

    #[test]
    fn test_bitor() {
        assert_eq!(
            BitCube3::from(BC3_FULL) | BitCube3::from(BC3_FULL),
            BitCube3::from(BC3_FULL)
        );
        assert_eq!(
            BitCube3::from(BC3_CENTER_X)
                | BitCube3::from(BC3_CENTER_Y)
                | BitCube3::from(BC3_CENTER_Z),
            BitCube3::from(BC3_CENTER_ALL)
        );
    }

    #[test]
    fn test_bitand() {
        assert_eq!(
            BitCube3::from(BC3_FULL) & BitCube3::from(BC3_FULL),
            BitCube3::from(BC3_FULL)
        );
        assert_eq!(
            BitCube3::from(BC3_CENTER_X)
                & BitCube3::from(BC3_CENTER_Y)
                & BitCube3::from(BC3_CENTER_Z),
            BitCube3(0o020_000_u32)
        );
    }

    #[test]
    fn test_shift_x() {
        assert_eq!(
            BitCube3::from(BC3_FULL).shift_x(1),
            BitCube3(0o666_666_666_u32)
        );
        assert_eq!(
            BitCube3::from(BC3_FULL).shift_x(2),
            BitCube3(0o444_444_444_u32)
        );
    }

    #[test]
    fn test_bounded_shift_x() {
        assert_eq!(BitCube3::from(BC3_FULL).bounded_shift_x(1), None);
        assert_eq!(BitCube3::from(BC3_CENTER_X).bounded_shift_x(1), None);
        assert_eq!(
            BitCube3::from(BC3_CENTER_Y).bounded_shift_x(1),
            Some(BitCube3(0o444000))
        );
        assert_eq!(
            BitCube3::from(BC3_CENTER_Z).bounded_shift_x(1),
            Some(BitCube3(0o040040040))
        );
        assert_eq!(BitCube3::from(BC3_CENTER_Y) << 1, BitCube3(0o444000));
        assert_eq!(BitCube3::from(BC3_CENTER_Z) << 1, BitCube3(0o040040040));
    }

    #[test]
    fn test_shift_y() {
        assert_eq!(
            BitCube3::from(BC3_FULL).shift_y(1),
            BitCube3(0o770_770_770_u32)
        );
        assert_eq!(
            BitCube3::from(BC3_FULL).shift_y(-2),
            BitCube3(0o007_007_007_u32)
        );
        assert_eq!(BitCube3::from(BC3_CENTER_Z) >> 3, BitCube3(0o002002002));
    }

    #[test]
    fn test_bounded_shift_y() {
        assert_eq!(BitCube3::from(BC3_FULL).bounded_shift_y(1), None);
        assert_eq!(
            BitCube3::from(BC3_CENTER_X).bounded_shift_y(1),
            Some(BitCube3(0o700000))
        );
        assert_eq!(BitCube3::from(BC3_CENTER_Y).bounded_shift_y(1), None);
        assert_eq!(
            BitCube3::from(BC3_CENTER_Z).bounded_shift_y(1),
            Some(BitCube3(0o200200200))
        );
    }

    #[test]
    fn test_shift_z() {
        assert_eq!(
            BitCube3::from(BC3_FULL).shift_z(1),
            BitCube3(0o777_777_000_u32)
        );
        assert_eq!(
            BitCube3::from(BC3_FULL).shift_z(-2),
            BitCube3(0o000_000_777_u32)
        );
    }

    #[test]
    fn test_bounded_shift_z() {
        assert_eq!(BitCube3::from(BC3_FULL).bounded_shift_z(1), None);
        assert_eq!(
            BitCube3::from(BC3_CENTER_X).bounded_shift_z(1),
            Some(BitCube3(0o070000000))
        );
        assert_eq!(
            BitCube3::from(BC3_CENTER_Y).bounded_shift_z(1),
            Some(BitCube3(0o222000000))
        );
        assert_eq!(BitCube3::from(BC3_CENTER_Z).bounded_shift_z(1), None);
    }

    // #[test]
    // fn test_shift_to_origin() {
    // assert_eq!(BitCube3::from(BC3_FULL).shift_to_origin(), BitCube3::from(BC3_FULL));
    // assert_eq!((BitCube3::from(BC3_CENTER_X) | BitCube3::from(BC3_CENTER_Y)).shift_to_origin(), BitCube4(0x0000_0000_6ff6_6ff6));
    // }

    #[test]
    fn test_rotate_x() {
        assert_eq!(
            BitCube3::from(BC3_FULL).rotate_x(),
            BitCube3::from(BC3_FULL)
        );
        assert_eq!(
            BitCube3::from(BC3_CENTER).rotate_x(),
            BitCube3::from(BC3_CENTER)
        );
        assert_eq!(
            BitCube3::from(BC3_CENTER_X).rotate_x(),
            BitCube3::from(BC3_CENTER_X)
        );
        assert_eq!(
            BitCube3::from(BC3_CENTER_Y).rotate_x(),
            BitCube3::from(BC3_CENTER_Z)
        );
        assert_eq!(
            BitCube3::from(BC3_CENTER_Z).rotate_x(),
            BitCube3::from(BC3_CENTER_Y)
        );
        assert_eq!(BitCube3(0o7).rotate_x(), BitCube3(0o700));
        assert_eq!(BitCube3(0o4017).rotate_x(), BitCube3(0o100740));
    }

    #[test]
    fn test_rotate_y() {
        assert_eq!(
            BitCube3::from(BC3_FULL).rotate_y(),
            BitCube3::from(BC3_FULL)
        );
        assert_eq!(
            BitCube3::from(BC3_CENTER).rotate_y(),
            BitCube3::from(BC3_CENTER)
        );
        assert_eq!(
            BitCube3::from(BC3_CENTER_X).rotate_y(),
            BitCube3::from(BC3_CENTER_Z)
        );
        assert_eq!(
            BitCube3::from(BC3_CENTER_Y).rotate_y(),
            BitCube3::from(BC3_CENTER_Y)
        );
        assert_eq!(
            BitCube3::from(BC3_CENTER_Z).rotate_y(),
            BitCube3::from(BC3_CENTER_X)
        );
        assert_eq!(BitCube3(0o7).rotate_y(), BitCube3(0o4004004));
        assert_eq!(BitCube3(0o4017).rotate_y(), BitCube3(0o6004044));
    }

    #[test]
    fn test_rotate_z() {
        assert_eq!(
            BitCube3::from(BC3_FULL).rotate_z(),
            BitCube3::from(BC3_FULL)
        );
        assert_eq!(
            BitCube3::from(BC3_CENTER).rotate_z(),
            BitCube3::from(BC3_CENTER)
        );
        assert_eq!(
            BitCube3::from(BC3_CENTER_X).rotate_z(),
            BitCube3::from(BC3_CENTER_Y)
        );
        assert_eq!(
            BitCube3::from(BC3_CENTER_Y).rotate_z(),
            BitCube3::from(BC3_CENTER_X)
        );
        assert_eq!(
            BitCube3::from(BC3_CENTER_Z).rotate_z(),
            BitCube3::from(BC3_CENTER_Z)
        );
        assert_eq!(BitCube3(0o7).rotate_z(), BitCube3(0o444));
        assert_eq!(BitCube3(0o4017).rotate_z(), BitCube3(0o400446));
    }

    #[test]
    fn test_rotate_d() {
        assert_eq!(
            BitCube3::from(BC3_FULL).rotate_d(),
            BitCube3::from(BC3_FULL)
        );
        assert_eq!(
            BitCube3::from(BC3_CENTER_X).rotate_d(),
            BitCube3::from(BC3_CENTER_Y)
        );
        assert_eq!(
            BitCube3::from(BC3_CENTER_Y).rotate_d(),
            BitCube3::from(BC3_CENTER_Z)
        );
        assert_eq!(
            BitCube3::from(BC3_CENTER_Z).rotate_d(),
            BitCube3::from(BC3_CENTER_X)
        );
        assert_eq!(BitCube3(0o1047).rotate_d(), BitCube3(0o100113));
    }

    #[test]
    fn test_overlap() {
        assert!(BitCube3::from(BC3_CENTER_X).overlap(BitCube3::from(BC3_CENTER_Y)));
    }

    #[test]
    fn test_from_bitperm4() {
        assert_eq!(
            BitCube3::from(BitCube4(0x77707770777)),
            BitCube3(0o777777777)
        );
        assert_eq!(
            BitCube3::from(BitCube4(0x70000000000)),
            BitCube3(0o700000000)
        );
        assert_eq!(BitCube3::from(BitCube4(0x7605430210)), BitCube3(0o76543210));
    }

    // TODO: TryFrom at a future point?
    // #[test]
    // fn test_tryfrom_bitcube4() {
    // assert_eq!(BitCube3::try_from(BitCube4(0x77707770777)).ok(), Some(BitCube3(0o777777777)));
    // assert_eq!(BitCube3::try_from(BitCube4(0x77707770777077f)).ok(), Some(BitCube3(0o777777777)));
    // assert_eq!(BitCube3::from(BitCube4(0x70000000000)), BitCube3(0o700000000));
    // assert_eq!(BitCube3::from(BitCube4(0x7605430210)), BitCube3(0o76543210));
    // }
}