forked from feather-rs/feather
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathchunk.rs
More file actions
1356 lines (1147 loc) · 41.3 KB
/
chunk.rs
File metadata and controls
1356 lines (1147 loc) · 41.3 KB
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
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::Biome;
use crate::{Block, BlockExt, ChunkPosition};
use bitflags::bitflags;
use multimap::MultiMap;
/// The number of bits used for each block
/// in the global palette.
pub const GLOBAL_BITS_PER_BLOCK: u8 = 14;
/// The minimum bits per block allowed when
/// using a section palette.
/// Bits per block values lower than this
/// value will be offsetted to this value.
pub const MIN_BITS_PER_BLOCK: u8 = 4;
/// The maximum number of bits per block
/// allowed when using a section palette.
/// Values above this will use the global palette
/// instead.
pub const MAX_BITS_PER_BLOCK: u8 = 8;
/// The height in blocks of a chunk column.
pub const CHUNK_HEIGHT: usize = 256;
/// The width in blocks of a chunk column.
pub const CHUNK_WIDTH: usize = 16;
/// The height in blocks of a chunk section.
pub const SECTION_HEIGHT: usize = 16;
/// The width in blocks of a chunk section.
pub const SECTION_WIDTH: usize = CHUNK_WIDTH;
/// The volume in blocks of a chunk section.
pub const SECTION_VOLUME: usize = (SECTION_HEIGHT * SECTION_WIDTH * SECTION_WIDTH) as usize;
/// The number of chunk sections in a column.
pub const NUM_SECTIONS: usize = 16;
/// A chunk column consisting
/// of a 16x256x16 section of blocks.
/// A chunk column maintains an array
/// of up to 16 chunk sections, each corresponding
/// to a 16x16x16 section of blocks in the chunk.
#[derive(Clone)]
pub struct Chunk {
/// The location of this chunk, in chunk
/// coordinates.
location: ChunkPosition,
/// An array of the sections in this chunk.
/// A section with Y value `y` can be found at
/// index `y` in this array.
/// When an entry in this array is set to `None`,
/// the section at the entry's Y coordinate
/// is assumed to empty, meaning that it consists
/// of only air.
sections: [Option<ChunkSection>; NUM_SECTIONS],
/// The biomes in this section, indexable by
/// ((z << 4) | x).
biomes: [Biome; SECTION_WIDTH * SECTION_WIDTH],
/// Whether this chunk has been modified since the most recent
/// call to `check_modified`().
modified: bool,
heightmaps: Box<[HeightMap]>,
}
#[derive(Clone, Copy, Default)]
pub struct HeightMap {
motion_blocking: u8,
motion_blocking_no_leaves: u8,
ocean_floor: u8,
ocean_floor_wg: u8,
world_surface: u8,
world_surface_wg: u8,
}
impl HeightMap {
/// The highest block that is solid or contains a fluid.
pub fn motion_blocking(self) -> u8 {
self.motion_blocking
}
pub fn set_motion_blocking(&mut self, motion_blocking: u8) {
self.motion_blocking = motion_blocking;
}
/// The highest block that is solid or contains a fluid and is not leaves.
pub fn motion_blocking_no_leaves(self) -> u8 {
self.motion_blocking_no_leaves
}
pub fn set_motion_blocking_no_leaves(&mut self, motion_blocking_no_leaves: u8) {
self.motion_blocking_no_leaves = motion_blocking_no_leaves;
}
/// The highest block that is solid.
pub fn ocean_floor(self) -> u8 {
self.ocean_floor
}
pub fn set_ocean_floor(&mut self, ocean_floor: u8) {
self.ocean_floor = ocean_floor;
}
/// The highest block that is solid for world generation.
pub fn ocean_floor_wg(self) -> u8 {
self.ocean_floor_wg
}
/// The highest block that is not air.
pub fn world_surface(self) -> u8 {
self.world_surface
}
pub fn set_world_surface(&mut self, world_surface: u8) {
self.world_surface = world_surface;
}
/// The highest block is not air for world generation.
pub fn world_surface_wg(self) -> u8 {
self.world_surface_wg
}
}
bitflags! {
struct HeightMapMask: u8 {
const MOTION_BLOCKING = 0b0000_0001;
const MOTION_BLOCKING_NO_LEAVES = 0b0000_0010;
const OCEAN_FLOOR = 0b0000_0100;
const OCEAN_FLOOR_WG = 0b0000_1000;
const WORLD_SURFACE = 0b0001_0000;
const WORLD_SURFACE_WG = 0b0010_0000;
}
}
impl Default for Chunk {
fn default() -> Self {
// Rust apparently forces you to implement
// `Copy` on types if you want to use the
// `[ChunkSection::new(); 16]` syntax,
// so I had to do this.
let sections = [
None, None, None, None, None, None, None, None, None, None, None, None, None, None,
None, None,
];
Self {
location: ChunkPosition::new(0, 0),
modified: true,
sections,
biomes: [Biome::Plains; SECTION_WIDTH * SECTION_WIDTH],
heightmaps: vec![HeightMap::default(); CHUNK_WIDTH * CHUNK_WIDTH].into_boxed_slice(),
}
}
}
impl Chunk {
/// Creates a new empty chunk
/// with the specified location.
pub fn new(location: ChunkPosition) -> Self {
Self {
location,
modified: true,
..Default::default()
}
}
/// Creates a new empty chunk
/// with the specified location,
/// and filling its biomes with
/// the provided `default_biome`.
pub fn new_with_default_biome(location: ChunkPosition, default_biome: Biome) -> Self {
Self {
location,
modified: true,
biomes: [default_biome; SECTION_WIDTH * SECTION_HEIGHT],
..Default::default()
}
}
/// Gets the block at the specified
/// position in this chunk. The position
/// is in the chunk's local coordinate
/// space.
///
/// The specified coordinates must be inside
/// this chunk, so the function will panic
/// if `x >= 16 || y >= 256 || z >= 16`.
pub fn block_at(&self, x: usize, y: usize, z: usize) -> Block {
Self::check_coords(x, y, z);
let chunk_section = &self.sections[(y / 16) as usize];
match chunk_section {
Some(section) => section.block_at(x, y % 16, z),
None => Block::Air,
}
}
/// Sets the block at the specified
/// position in this chunk. The position
/// is in the chunk's local coordinate
/// space.
///
/// The specified coordinates must be inside
/// this chunk, so the function will panic
/// if `x >= 16 || y >= 256 || z >= 16`.
pub fn set_block_at(&mut self, x: usize, y: usize, z: usize, block: Block) {
Self::check_coords(x, y, z);
self.modified = true;
let chunk_section = &mut self.sections[y / 16];
let section;
if let Some(sec) = chunk_section {
section = sec;
} else {
// The section is empty - create it
if block == Block::Air {
return; // Nothing to do - section already empty
}
let new_section = ChunkSection::default();
self.set_section_at(y / 16, Some(new_section));
section = self.section_mut(y / 16).unwrap();
}
section.set_block_at(x, y % 16, z, block);
self.update_heightmap(x, y, z, block);
}
pub fn heightmap(&self, x: usize, z: usize) -> &HeightMap {
Self::check_coords(x, 0, z);
&self.heightmaps[x + z * CHUNK_WIDTH]
}
pub fn heightmap_mut(&mut self, x: usize, z: usize) -> &mut HeightMap {
Self::check_coords(x, 0, z);
&mut self.heightmaps[x + z * CHUNK_WIDTH]
}
pub fn heightmaps(&self) -> &[HeightMap] {
&self.heightmaps
}
fn update_heightmap(&mut self, x: usize, y: usize, z: usize, block: Block) -> HeightMapMask {
let heightmap = self.heightmap_mut(x, z);
let mut mask: HeightMapMask = HeightMapMask::empty();
if (block.is_solid() || block.is_fluid()) && heightmap.motion_blocking() < y as u8 {
heightmap.set_motion_blocking(y as u8);
mask |= HeightMapMask::MOTION_BLOCKING;
}
if (block.is_solid() || block.is_fluid())
&& !block.is_leaves()
&& heightmap.motion_blocking_no_leaves() < y as u8
{
heightmap.set_motion_blocking_no_leaves(y as u8);
mask |= HeightMapMask::MOTION_BLOCKING_NO_LEAVES;
}
if block.is_solid() && heightmap.ocean_floor() < y as u8 {
heightmap.set_ocean_floor(y as u8);
mask |= HeightMapMask::OCEAN_FLOOR;
}
if !block.is_air() && heightmap.world_surface() < y as u8 {
heightmap.set_world_surface(y as u8);
mask |= HeightMapMask::WORLD_SURFACE;
}
mask
}
/// Recalculate the heightmap for the chunk
pub fn recalculate_heightmap(&mut self) {
// This function can be optimized, instead of
// fetching heightmap every time, and sections
for x in 0..CHUNK_WIDTH {
for z in 0..CHUNK_WIDTH {
let mut mask: HeightMapMask = HeightMapMask::empty();
for y in (0..CHUNK_HEIGHT).rev() {
if mask.is_all() {
break;
}
let block = self.block_at(x, y, z);
mask |= self.update_heightmap(x, y, z, block);
}
}
}
}
pub fn sky_light_at(&self, x: usize, y: usize, z: usize) -> u8 {
Self::check_coords(x, y, z);
let chunk_section = self.section_for_y(y);
match chunk_section {
Some(chunk_section) => chunk_section.sky_light_at(x, y % 16, z),
None => 0,
}
}
pub fn block_light_at(&self, x: usize, y: usize, z: usize) -> u8 {
Self::check_coords(x, y, z);
let chunk_section = self.section_for_y(y);
match chunk_section {
Some(chunk_section) => chunk_section.block_light_at(x, y % 16, z),
None => 0,
}
}
pub fn set_sky_light_at(&mut self, x: usize, y: usize, z: usize, value: u8) {
Self::check_coords(x, y, z);
let chunk_section = self.section_for_y_mut(y);
chunk_section.set_sky_light_at(x, y % 16, z, value);
}
pub fn set_block_light_at(&mut self, x: usize, y: usize, z: usize, value: u8) {
Self::check_coords(x, y, z);
let chunk_section = self.section_for_y_mut(y);
chunk_section.set_block_light_at(x, y % 16, z, value);
}
fn section_for_y(&self, y: usize) -> &Option<ChunkSection> {
&self.sections[y / 16]
}
fn section_for_y_mut(&mut self, y: usize) -> &mut ChunkSection {
self.sections[y / 16].get_or_insert_with(ChunkSection::default)
}
fn check_coords(x: usize, y: usize, z: usize) {
assert!(x < CHUNK_WIDTH);
assert!(y < CHUNK_HEIGHT);
assert!(z < CHUNK_WIDTH);
}
/// Returns a slice of the 16
/// chunk sections in the chunk.
pub fn sections(&self) -> Vec<Option<&ChunkSection>> {
self.sections.iter().map(|sec| sec.as_ref()).collect()
}
/// Returns a mutable slice of the 16 sections
/// in this chunk.
pub fn sections_mut(&mut self) -> Vec<Option<&mut ChunkSection>> {
self.modified = true;
self.sections.iter_mut().map(|sec| sec.as_mut()).collect()
}
/// Returns the position in chunk coordinates
/// of this chunk.
pub fn position(&self) -> ChunkPosition {
self.location
}
/// Sets the position of this chunk.
pub fn set_position(&mut self, pos: ChunkPosition) {
self.location = pos
}
/// Returns a reference to the chunk section at the given
/// Y offset. The Y offset must be between 0 and 15, inclusive;
/// each Y offset value corresponds to 16 blocks vertically.
///
/// If this function returns `None`, the section is assumed
/// to be empty, meaning it consists only of air.
pub fn section(&self, index: usize) -> Option<&ChunkSection> {
assert!(index < NUM_SECTIONS);
self.sections[index].as_ref()
}
/// Returns a mutable reference to the chunk section at the given
/// Y offset. The Y offset must be between 0 and 15, inclusive;
/// each Y offset value corresponds to 16 blocks vertically.
///
/// If this function returns `None`, the section is assumed
/// to be empty, meaning it consists only of air.
pub fn section_mut(&mut self, index: usize) -> Option<&mut ChunkSection> {
assert!(index < NUM_SECTIONS);
self.modified = true;
self.sections[index].as_mut()
}
/// Sets the section at the given section index.
pub fn set_section_at(&mut self, index: usize, section: Option<ChunkSection>) {
assert!(index < NUM_SECTIONS);
self.sections[index] = section;
self.modified = true;
}
/// Optimizes each section in this chunk.
///
/// Returns the number of sections which were actually
/// optimized - sections which have not been
/// modified since the last time they were optimized
/// are not optimized.
pub fn optimize(&mut self) -> u32 {
let modified = self.modified;
let mut count = 0;
let mut to_remove = vec![];
for (i, s) in self.sections.iter_mut().enumerate() {
if let Some(section) = s {
if section.optimize() {
// Section was optimized - increment count
count += 1;
}
if section.empty() {
to_remove.push(i);
}
}
}
for i in to_remove {
self.set_section_at(i, None);
}
self.modified = modified;
count
}
/// Returns the biomes of this chunk.
pub fn biomes(&self) -> &[Biome] {
&self.biomes
}
/// Returns a mutable reference to the biomes of this chunk.
pub fn biomes_mut(&mut self) -> &mut [Biome] {
self.modified = true;
&mut self.biomes
}
/// Gets the biome for the specified column.
///
/// # Panics
/// Panics if `x < 16` or `z < 16`.
pub fn biome_at(&self, x: usize, z: usize) -> Biome {
let index = Self::biome_index(x, z);
self.biomes[index]
}
/// Sets the biome for the specified column.
///
/// # Panics
/// Panics if `x < 16` or `z < 16`.
pub fn set_biome_at(&mut self, x: usize, z: usize, biome: Biome) {
let index = Self::biome_index(x, z);
self.modified = true;
self.biomes[index] = biome;
}
/// Checks whether this chunk has been modified since the last
/// call to this function.
pub fn check_modified(&mut self) -> bool {
let res = self.modified;
self.modified = false;
res
}
fn biome_index(x: usize, z: usize) -> usize {
assert!(x < 16);
assert!(z < 16);
(z << 4) | x
}
}
/// A chunk section consisting of a 16x16x16
/// cube of blocks.
#[derive(Clone, Debug)]
pub struct ChunkSection {
/// The block state data for this chunk section.
data: BitArray,
/// This section's palette. `None` if using the global palette.
/// The palette should always remain sorted so that a binary
/// search can be performed on it.
palette: Option<Vec<u16>>,
/// The number of solid blocks in this chunk, i.e. those
/// that are not air. This value is used to figure out when
/// the section becomes empty.
solid_block_count: u16,
block_light: BitArray,
sky_light: BitArray,
/// A section is considered dirty when it has been
/// modified since the last time it was optimized.
dirty: bool,
}
impl ChunkSection {
/// Creates a new, empty `ChunkSection`.
pub fn new(
mut data: BitArray,
mut palette: Option<Vec<u16>>,
block_light: BitArray,
sky_light: BitArray,
) -> Self {
// Correct palette if not using the global palette
if let Some(palette) = palette.as_mut() {
Self::correct_data_and_palette(&mut data, palette);
}
// Count solid blocks
let mut solid_block_count = 0;
for x in 0..16 {
for y in 0..16 {
for z in 0..16 {
if data.get(block_index(x, y, z)) != 0 {
solid_block_count += 1;
}
}
}
}
Self {
data,
palette,
solid_block_count,
dirty: false,
block_light,
sky_light,
}
}
/// Corrects a given raw palette and data array.
///
/// Since chunk data stored by external sources
/// (e.g. Vanilla) might not require a sorted palette
/// like Feather does, we need to sort the palette and
/// correct data in the array when reading from external
/// sources.
///
/// The correction is done in-place.
fn correct_data_and_palette(data: &mut BitArray, palette: &mut Vec<u16>) {
let original_palette = palette.clone(); // Palette without sorting guarantees
palette.sort_unstable();
for x in 0..16 {
for y in 0..16 {
for z in 0..16 {
// Replace index into palette of each block with
// new index into the sorted palette.
let block_index = block_index(x, y, z);
let old_index = data.get(block_index);
let new_index = palette
.binary_search(&original_palette[old_index as usize])
.unwrap();
data.set(block_index, new_index as u64);
}
}
}
}
/// Returns whether this chunk section is empty.
pub fn empty(&self) -> bool {
self.solid_block_count == 0
}
/// Retrieves the block at the given position in this chunk section.
/// The position is local to this section.
pub fn block_at(&self, x: usize, y: usize, z: usize) -> Block {
let index = block_index(x, y, z);
let block_id = self.data.get(index);
let global_id = match &self.palette {
Some(palette) => palette[block_id as usize] as u16,
None => block_id as u16,
};
Block::from_native_state_id(global_id).unwrap()
}
/// Sets the block at the given position in this chunk section.
/// The position is local to this section.
pub fn set_block_at(&mut self, x: usize, y: usize, z: usize, block: Block) {
self.dirty = true;
let index = block_index(x, y, z);
let block_id = block.native_state_id();
// The value that will be put into the
let mut paletted_index;
if let Some(palette) = self.palette.as_mut() {
// Retrieve the block index from the palette.
// If necessary, add the block to the palette.
match palette.binary_search(&block_id) {
Ok(index) => paletted_index = index,
Err(insertion_index) => {
palette.insert(insertion_index, block_id);
paletted_index = insertion_index;
// Resize if necessary
if needed_bits((palette.len() - 1) as u64) > self.data.bits_per_value {
let new_bits_per_value = self.data.bits_per_value + 1;
if new_bits_per_value <= MAX_BITS_PER_BLOCK {
self.data = self.data.resize_to(self.data.bits_per_value + 1).unwrap();
paletted_index = insertion_index;
} else {
// Switch to the global palette
let mut new_data = BitArray::new(GLOBAL_BITS_PER_BLOCK, SECTION_VOLUME);
for _x in 0..16 {
for _y in 0..16 {
for _z in 0..16 {
let block = self.block_at(_x, _y, _z);
new_data.set(
block_index(_x, _y, _z),
block.native_state_id() as u64,
);
}
}
}
self.palette = None;
paletted_index = block_id as usize;
self.data = new_data;
}
}
// Correct data, since palette entries after
// the one which was inserted will be offsetted
// by one.
for x in 0..16 {
for y in 0..16 {
for z in 0..16 {
let index = block_index(x, y, z);
let entry = self.data.get(index);
if entry >= insertion_index as u64 {
self.data.set(index, entry + 1);
}
}
}
}
}
}
} else {
// Use the global palette.
paletted_index = block_id as usize;
}
let old_block = self.block_at(x, y, z);
if block == Block::Air && old_block != Block::Air {
self.solid_block_count -= 1;
} else if block != Block::Air && old_block == Block::Air {
self.solid_block_count += 1;
}
self.data.set(index, paletted_index as u64);
debug_assert_eq!(self.block_at(x, y, z), block);
}
/// Optimizes this chunk section, reducing the bits
/// per block value as much as possible and removing unused
/// entries from the palette.
///
/// This function only optimizes the chunk if it is dirt,
/// i.e. if it has been modified since the last time
/// it was optimized. The returned value is `true` when
/// the chunk was optimized and `false` when it wasn't.
pub fn optimize(&mut self) -> bool {
// Only optimize the chunk if it has been modified.
if !self.dirty {
return false;
}
self.dirty = false;
// Replace palette with new one.
let mut new_palette = vec![];
for x in 0..16 {
for y in 0..16 {
for z in 0..16 {
let block = self.block_at(x, y, z).native_state_id();
match new_palette.binary_search(&block) {
Ok(_) => (),
Err(insert_index) => {
new_palette.insert(insert_index, block);
}
}
}
}
}
// Recalculate all block IDs to match with the new palette.
for x in 0..16 {
for y in 0..16 {
for z in 0..16 {
let block = self.block_at(x, y, z).native_state_id();
self.data.set(
block_index(x, y, z),
new_palette.binary_search(&block).unwrap() as u64,
);
}
}
}
self.palette = Some(new_palette);
// Recalculate bits per block value.
let mut new_bits_per_block = needed_bits(self.palette.as_ref().unwrap().len() as u64);
if new_bits_per_block > MAX_BITS_PER_BLOCK {
self.palette = None;
} else {
if new_bits_per_block < MIN_BITS_PER_BLOCK {
new_bits_per_block = MIN_BITS_PER_BLOCK;
}
self.data = self.data.resize_to(new_bits_per_block).unwrap();
}
true // Chunk was optimized
}
/// If the global palette is in use, convert it to a section palette.
/// This is used for chunk saving.
pub fn convert_palette_to_section(&mut self) {
if self.palette.is_some() {
// Nothing to do: section palette already in use.
return;
}
let mut blocks = MultiMap::with_capacity(1024);
for x in 0..16 {
for y in 0..16 {
for z in 0..16 {
blocks.insert(self.block_at(x, y, z), (x, y, z));
}
}
}
// Create a palette based on the blocks in the chunk.
// We also have to modify the data array based on the new palette.
let mut palette = Vec::with_capacity(1024);
for (block, positions) in blocks.into_iter() {
palette.push(block.native_state_id());
for (x, y, z) in positions {
let index = block_index(x, y, z);
self.data.set(index, (palette.len() - 1) as u64);
}
}
self.palette = Some(palette);
}
/// Returns the internal data array for this section.
pub fn data(&self) -> &BitArray {
&self.data
}
/// Returns the palette for this section.
pub fn palette(&self) -> Option<&Vec<u16>> {
self.palette.as_ref()
}
/// Returns the number of bits used to store each block.
pub fn bits_per_block(&self) -> u8 {
self.data.bits_per_value
}
pub fn sky_light(&self) -> &BitArray {
&self.sky_light
}
pub fn block_light(&self) -> &BitArray {
&self.block_light
}
pub fn sky_light_mut(&mut self) -> &mut BitArray {
&mut self.sky_light
}
pub fn block_light_mut(&mut self) -> &mut BitArray {
&mut self.block_light
}
pub fn sky_light_at(&self, x: usize, y: usize, z: usize) -> u8 {
let index = block_index(x, y, z);
self.sky_light.get(index) as u8
}
pub fn block_light_at(&self, x: usize, y: usize, z: usize) -> u8 {
let index = block_index(x, y, z);
self.block_light.get(index) as u8
}
pub fn set_sky_light_at(&mut self, x: usize, y: usize, z: usize, value: u8) {
assert!(value < 16, "light level cannot exceed 15");
let index = block_index(x, y, z);
self.sky_light.set(index, u64::from(value));
}
pub fn set_block_light_at(&mut self, x: usize, y: usize, z: usize, value: u8) {
assert!(value < 16, "light level cannot exceed 15");
let index = block_index(x, y, z);
self.block_light.set(index, u64::from(value));
}
}
impl Default for ChunkSection {
fn default() -> Self {
let air_id = Block::Air.native_state_id();
Self {
data: BitArray::new(4, SECTION_VOLUME),
palette: Some(vec![air_id]),
solid_block_count: 0,
dirty: false,
block_light: BitArray::new(4, SECTION_VOLUME),
sky_light: BitArray::new(4, SECTION_VOLUME),
}
}
}
/// Returns the index into a block state array
/// for the given block position.
fn block_index(x: usize, y: usize, z: usize) -> usize {
assert!(x < 16);
assert!(y < 16);
assert!(z < 16);
(y << 8) | (z << 4) | x
}
/// A "bit array." This struct manages
/// an internal array of `u64` to which
/// values of arbitrary bit length can be written.
#[derive(Clone, Debug)]
pub struct BitArray {
/// The internal data array containing all values
data: Vec<u64>,
/// The capacity, in values, of this array
capacity: usize,
/// The number of bits used to represent each value
bits_per_value: u8,
/// The maximum value represented by an entry in this array
value_mask: u64,
}
impl BitArray {
/// Creates a new `BitArray` with the given
/// bits per value and capacity. The array
/// will be initialized with zeroes.
pub fn new(bits_per_value: u8, capacity: usize) -> Self {
assert!(
bits_per_value <= 64,
"Bits per value cannot be more than 64"
);
assert!(bits_per_value > 0, "Bits per value must be positive");
let data = {
let len = (((capacity * (bits_per_value as usize)) as f64) / 64.0).ceil() as usize;
vec![0u64; len]
};
let value_mask = (1 << (bits_per_value as u64)) - 1;
Self {
data,
capacity,
bits_per_value,
value_mask,
}
}
/// Creates a new `BitArray` based on the given raw parts.
pub fn from_raw(data: Vec<u64>, bits_per_value: u8, capacity: usize) -> Self {
assert!(
bits_per_value <= 64,
"Bits per value cannot be more than 64"
);
assert!(bits_per_value > 0, "Bits per value must be positive");
let value_mask = (1 << (bits_per_value as u64)) - 1;
Self {
data,
capacity,
bits_per_value,
value_mask,
}
}
/// Returns the highest possible value represented
/// by and entry in this `BitArray`.
pub fn highest_possible_value(&self) -> u64 {
self.value_mask
}
/// Returns the value at the given location in this `BitArray`.
pub fn get(&self, index: usize) -> u64 {
assert!(index < self.capacity, "Index out of bounds");
let bit_index = index * (self.bits_per_value as usize);
let start_long_index = bit_index / 64;
let start_long = self.data[start_long_index];
let index_in_start_long = (bit_index % 64) as u64;
let mut result = start_long >> index_in_start_long;
let end_bit_offset = index_in_start_long + self.bits_per_value as u64;
if end_bit_offset > 64 {
// Value stretches across multiple longs
let end_long = self.data[start_long_index + 1];
result |= end_long << (64 - index_in_start_long);
}
result & self.value_mask
}
/// Sets the value at the given index into this `BitArray`
pub fn set(&mut self, index: usize, val: u64) {
assert!(index < self.capacity, "Index out of bounds");
assert!(
val <= self.value_mask,
"Value does not fit into bits_per_value"
);
let bit_index = index * (self.bits_per_value as usize);
let start_long_index = bit_index / 64;
let index_in_start_long = (bit_index % 64) as u64;
// Clear bits of this value first
self.data[start_long_index] = (self.data[start_long_index]
& !(self.value_mask << index_in_start_long))
| ((val & self.value_mask) << index_in_start_long);
let end_bit_offset = index_in_start_long + self.bits_per_value as u64;
if end_bit_offset > 64 {
// Value stretches across multiple longs
self.data[start_long_index + 1] = (self.data[start_long_index + 1]
& !((1 << (end_bit_offset - 64)) - 1))
| val >> (64 - index_in_start_long);
}
debug_assert_eq!(self.get(index), val);
}
/// Produces a `BitArray` with the same values
/// as this `BitArray` but with a new bits per value.
/// If a value in this `BitArray` cannot be represented
/// by the new bits per value, `Err` is returned.
pub fn resize_to(&self, new_bits_per_value: u8) -> Result<BitArray, ()> {
assert!(
new_bits_per_value <= 64,
"Bits per value cannot be more than 64"
);
let mut new_arr = BitArray::new(new_bits_per_value, self.capacity);
for i in 0..self.capacity {
let val = self.get(i);
if needed_bits(val) > new_bits_per_value {
return Err(());
}
new_arr.set(i, val);
debug_assert_eq!(new_arr.get(i), val);
}
Ok(new_arr)
}
/// Returns the internal array.
pub fn inner(&self) -> &Vec<u64> {
&self.data
}
}
/// Returns the number of bits
/// needed to represent the given value.
fn needed_bits(mut val: u64) -> u8 {
let mut result = 0;
loop {
val >>= 1;
result += 1;
if val == 0 {
break;
}
}
result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn chunk_new() {
let pos = ChunkPosition::new(0, 0);
let chunk = Chunk::new(pos);
// Confirm that chunk is empty
for x in 0..16 {