mc_schem 1.1.2

A library to read, create, modify and write various Minecraft schematic files
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
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
/*
mc_schem is a rust library to generate, load, manipulate and save minecraft schematic files.
Copyright (C) 2024  joseph

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/

pub mod world_edit12;
pub mod world_edit13;
pub mod litematica;

pub mod vanilla_structure;
pub mod mc_version;
pub mod common;
pub mod schem_slice;


use std::cmp::max;
use std::collections::hash_map::DefaultHasher;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use crate::block::{Block, CommonBlock};
use fastnbt;
use flate2::Compression;
use crate::error::{Error};
//use schem::mc_version;
use crate::{PendingTick, schem};
use crate::region::{BlockEntity, Region, WorldSlice};

/// Minecraft data versions.
pub type DataVersion = mc_version::DataVersion;

/// Metadata of litematica
#[derive(Debug, Clone)]
pub struct LitematicaMetaData {
    pub data_version: i32,

    pub version: i32,
    pub sub_version: Option<i32>,
    pub time_created: i64,
    pub time_modified: i64,
    pub author: String,
    pub name: String,
    pub description: String,
    pub total_volume: i32,
    pub region_count: i32,
    pub total_blocks: i32,
    pub enclosing_size: [i32; 3],
}

#[allow(dead_code)]
impl LitematicaMetaData {
    // pub fn new() -> LitematicaMetaData {
    //     return Self::default();
    // }

    pub fn default() -> LitematicaMetaData {
        return Self::from_data_version(DataVersion::Java_1_20_4).unwrap();
    }

    /// Guess litematica version from data version
    pub fn data_version_to_lite_version(data_version: i32) -> Option<i32> {
        return if data_version < DataVersion::Java_1_12 as i32 {
            None
        } else if data_version < DataVersion::Java_1_13 as i32 {
            Some(4)
        } else if data_version < DataVersion::Java_1_18 as i32 {
            Some(5)
        } else {
            Some(6)
        };
    }

    /// Guess litematica sub version from data version
    pub fn data_version_to_lite_subversion(data_version: i32) -> Option<i32> {
        return if data_version < DataVersion::Java_1_18 as i32 {
            None
        } else {
            Some(1)
        };
    }

    /// Get default metadata from data version in `i32`
    pub fn from_data_version_i32(data_version: i32) -> Result<LitematicaMetaData, Error> {
        use std::time::{SystemTime, UNIX_EPOCH};
        if data_version < DataVersion::Java_1_12 as i32 {
            return Err(Error::UnsupportedVersion { data_version_i32: data_version });
        }
        let time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as i64;
        let result = LitematicaMetaData {
            data_version,
            version: Self::data_version_to_lite_version(data_version).unwrap_or(-1),
            sub_version: Self::data_version_to_lite_subversion(data_version),
            time_created: time,
            time_modified: time,
            author: String::from("mc_schem.rs"),
            name: String::from("Default litematica"),
            description: String::from("Default litematica generated by mc_schem.rs"),
            total_volume: 0,
            region_count: 0,
            total_blocks: 0,
            enclosing_size: [0; 3]
        };
        return Ok(result);
    }

    /// Get default metadata from data version
    pub fn from_data_version(data_version: DataVersion) -> Result<LitematicaMetaData, Error> {
        return Self::from_data_version_i32(data_version as i32);
    }
}

/// Metadata of World Edit 1.12-
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct WE12MetaData {
    pub materials: String,
    pub we_offset: [i32; 3],
    pub we_origin: [i32; 3],
    pub width: i16,
    pub height: i16,
    pub length: i16,
}

#[allow(dead_code)]
impl WE12MetaData {
    pub fn default() -> WE12MetaData {
        return WE12MetaData {
            materials: "Alpha".to_string(),
            we_offset: [0, 0, 0],
            we_origin: [0, 0, 0],
            width: 0,
            height: 0,
            length: 0
        };
    }
}

/// Metadata of World Edit 1.13+
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct WE13MetaData {
    pub data_version: i32,
    pub version: i32,
    pub we_offset: [i32; 3],
    pub offset: [i32; 3],
    //time stamp in milliseconds
    pub date: Option<i64>,
    pub v3_extra: Option<WE13MetaDataV3Extra>,
    pub width: i16,
    pub height: i16,
    pub length: i16,
}

/// Extra metadata of World Edit 1.13+, introduced in 1.20, version 3.
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct WE13MetaDataV3Extra {
    pub world_edit_version: String,
    pub editing_platform: String,
    pub origin: [i32; 3],
}

impl Default for WE13MetaData {
    fn default() -> WE13MetaData {
        use std::time::{SystemTime, UNIX_EPOCH};
        let time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as i64;
        return WE13MetaData {
            data_version: DataVersion::new() as i32,
            version: 5,
            we_offset: [0, 0, 0],
            offset: [0, 0, 0],
            date: Some(time),
            v3_extra: None,
            width: 0,
            height: 0,
            length: 0,
        };
    }
}

impl Default for WE13MetaDataV3Extra {
    fn default() -> Self {
        return WE13MetaDataV3Extra {
            world_edit_version: "(unknown)".to_string(),
            editing_platform: "".to_string(),
            origin: [0, 0, 0],
        }
    }
}

#[allow(dead_code)]
impl WE13MetaData {
    pub fn from_data_version(dv: DataVersion) -> Result<WE13MetaData, Error> {
        return Self::from_data_version_i32(dv as i32);
    }

    pub fn from_data_version_i32(dv: i32) -> Result<WE13MetaData, Error> {
        let mut result = Self::default();
        result.data_version = dv;
        if dv < DataVersion::Java_1_13 as i32 {
            return Err(Error::UnsupportedVersion { data_version_i32: dv });
        }
        // 1.13.2 => 2
        // 1.14.4 => 2
        // 1.18.2 => 2
        // 1.19.4 => 2
        // 1.20.2 => 3
        result.version = if dv < DataVersion::Java_1_20 as i32 {
            2
        } else {
            3
        };

        return Ok(result);
    }
}

/// Metadata of vanilla structure
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct VanillaStructureMetaData {
    pub data_version: i32,
}

#[allow(dead_code)]
impl VanillaStructureMetaData {
    pub fn default() -> VanillaStructureMetaData {
        return VanillaStructureMetaData {
            data_version: DataVersion::new() as i32,
        };
    }


    pub fn from_data_version(dv: DataVersion) -> Result<VanillaStructureMetaData, Error> {
        return Self::from_data_version_i32(dv as i32);
    }

    pub fn from_data_version_i32(dv: i32) -> Result<VanillaStructureMetaData, Error> {
        return Ok(VanillaStructureMetaData {
            data_version: dv
        });
    }
}

/// Raw metadata of different formats
#[derive(Debug)]
pub enum RawMetaData {
    Litematica(LitematicaMetaData),
    WE12(WE12MetaData),
    WE13(WE13MetaData),
    VanillaStructure(VanillaStructureMetaData),
}

/// Intermediate representation via different metadata formats
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct MetaDataIR {
    /// Data version of minecraft
    pub mc_data_version: i32,

    /// Unix time stamp in millisecond
    pub time_created: i64,
    /// Unix time stamp in millisecond
    pub time_modified: i64,
    pub author: String,
    pub name: String,
    pub description: String,

    pub litematica_version: i32,
    pub litematica_subversion: Option<i32>,

    pub schem_version: i32,
    pub schem_offset: [i32; 3],
    pub schem_we_offset: Option<[i32; 3]>,

    //pub date: Option<i64>,

    pub schem_world_edit_version: Option<String>,
    pub schem_editing_platform: Option<String>,
    pub schem_origin: Option<[i32; 3]>,
    /// `Alpha` or `Classic`
    pub schem_material: String,
    //pub raw_metadata: Option<MetaData>,
}

#[allow(dead_code)]
impl MetaDataIR {
    pub fn default() -> MetaDataIR {
        return Self::from_data_version(DataVersion::new()).unwrap();
    }

    pub fn from_data_version(version: DataVersion) -> Result<MetaDataIR, Error> {
        return Self::from_data_version_i32(version as i32);
    }

    pub fn from_data_version_i32(version: i32) -> Result<MetaDataIR, Error> {
        use std::time::{SystemTime, UNIX_EPOCH};
        let time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as i64;

        let result = MetaDataIR {
            mc_data_version: version,
            time_created: time,
            time_modified: time,
            author: String::from("mc_schem"),
            name: String::from("DefaultMetaDataIR"),
            description: String::from("Default metadata generated by mc_schem"),
            litematica_version: LitematicaMetaData::default().version,
            litematica_subversion: LitematicaMetaData::default().sub_version,
            schem_version: WE13MetaData::default().version,
            schem_offset: [0, 0, 0],
            schem_we_offset: Some([0, 0, 0]),
            //date: Some(time),
            schem_world_edit_version: None,
            schem_editing_platform: None,
            schem_origin: Some([0, 0, 0]),
            schem_material: "Alpha".to_string(),
        };
        return Ok(result);
    }
}

/// Schematic is part of a Minecraft world, like `.litematic` of litematica mod, `.schem` and
/// `.schematic` of world edit, `.nbt` of vanilla structure.
#[derive(Debug)]
pub struct Schematic {
    pub metadata: MetaDataIR,
    /// A list of regions. A schematic can have multiple regions.
    pub regions: Vec<Region>,
    //pub enclosing_size: [i64; 3],

}


// enum SchemFormat {
//     Litematica,
//     WorldEdit12,
//     WorldEdit13,
//     VanillaStructure,
// }
#[allow(dead_code)]
impl Schematic {
    pub fn new() -> Schematic {
        return Schematic {
            //data_version: mc_version::DataVersion::new() as i32,
            metadata: MetaDataIR::default(),
            regions: Vec::new(),
            //enclosing_size: [1, 1, 1],

        };
    }

    // pub fn metadata(&self) -> &MetaDataIR {
    //     return &self.metadata;
    // }
    //
    // pub fn set_metadata(&mut self, md: MetaDataIR) {
    //     self.metadata = md;
    // }
    //
    // pub fn regions(&self) -> &[Region] {
    //     return &self.regions;
    // }
    //
    // pub fn regions_mut(&mut self) -> &mut Vec<Region> {
    //     return &mut self.regions;
    // }

    /// Get a list of block index at `g_pos`. There may be multiple blocks in one position because
    /// there can be multiple regions.
    pub fn block_indices_at(&self, g_pos: [i32; 3]) -> Vec<u16> {
        let mut result = Vec::with_capacity(self.regions.len());
        for reg in &self.regions {
            let cur_pos = reg.global_pos_to_relative_pos(g_pos);
            if let Some(blk) = reg.block_index_at(cur_pos) {
                result.push(blk);
            }
        }
        return result;
    }

    /// Get a list of blocks at `g_pos`.
    pub fn blocks_at(&self, pos: [i32; 3]) -> Vec<&Block> {
        let mut result = Vec::new();
        self.get_blocks_at(pos, &mut result);
        return result;
    }

    /// Get a list of blocks at `g_pos`.
    pub fn get_blocks_at<'a>(&'a self, pos: [i32; 3], dest: &mut Vec<&'a Block>) {
        dest.clear();
        dest.reserve(self.regions.len());
        for reg in &self.regions {
            let cur_pos = reg.global_pos_to_relative_pos(pos);
            if let Some(blk) = reg.block_at(cur_pos) {
                dest.push(blk);
            }
        }
    }

    /// Get a list of blocks entities at `g_pos`.
    pub fn block_entities_at(&self, pos: [i32; 3]) -> Vec<&BlockEntity> {
        let mut result = Vec::with_capacity(self.regions.len());
        for reg in &self.regions {
            let cur_pos = reg.global_pos_to_relative_pos(pos);
            if let Some(blk) = reg.block_entities.get(&cur_pos) {
                result.push(blk);
            }
        }
        return result;
    }

    /// Get the index of first region that contain this `pos`
    pub fn first_region_index_at(&self, pos: [i32; 3]) -> Option<usize> {
        for (idx, reg) in self.regions.iter().enumerate() {
            let r_pos = reg.global_pos_to_relative_pos(pos);
            if reg.contains_coord(r_pos) {
                return Some(idx);
            }
        }
        return None;
    }

    /// Get first block index at `pos`
    pub fn first_block_index_at(&self, pos: [i32; 3]) -> Option<u16> {
        for reg in &self.regions {
            if let Some(bid) = reg.block_index_at(reg.global_pos_to_relative_pos(pos)) {
                return Some(bid);
            }
        }
        return None;
    }
    /// Get first block at `pos`
    pub fn first_block_at(&self, pos: [i32; 3]) -> Option<&Block> {
        for reg in &self.regions {
            if let Some(b) = reg.block_at(reg.global_pos_to_relative_pos(pos)) {
                return Some(b);
            }
        }
        return None;
    }
    /// Get first block entity at `pos`
    pub fn first_block_entity_at(&self, pos: [i32; 3]) -> Option<&BlockEntity> {
        for reg in &self.regions {
            if let Some(b) = reg.block_entities.get(&reg.global_pos_to_relative_pos(pos)) {
                return Some(b);
            }
        }
        return None;
    }

    pub fn first_pending_tick_at(&self, pos: [i32; 3]) -> &[PendingTick] {
        for reg in &self.regions {
            if let Some(b) = reg.pending_ticks.get(&reg.global_pos_to_relative_pos(pos)) {
                return b.as_slice();
            }
        }
        return &[];
    }

    /// Get detailed info of the first block at `pos`
    pub fn first_block_info_at(&self, pos: [i32; 3]) -> Option<(u16, &Block, Option<&BlockEntity>, &[PendingTick])> {
        for reg in &self.regions {
            let r_pos = reg.global_pos_to_relative_pos(pos);
            if !reg.contains_coord(r_pos) {
                continue;
            }
            if let Some(info) = reg.block_info_at(r_pos) {
                return Some(info);
            }
        }
        return None;
    }

    /// The enclosing shape(xyz) of schematic
    pub fn shape(&self) -> [i32; 3] {
        let mut result = [0, 0, 0];
        for reg in &self.regions {
            for dim in 0..3 {
                result[dim] = max(result[dim], reg.offset[dim] + reg.shape()[dim]);
            }
        }
        return result;
    }

    /// The volume of whole schematic
    pub fn volume(&self) -> u64 {
        let mut result: u64 = 1;
        for sz in self.shape() {
            result *= sz as u64;
        }
        return result;
    }

    /// Count of blocks
    pub fn total_blocks(&self, include_air: bool) -> u64 {
        let mut counter = 0;
        for reg in &self.regions {
            counter += reg.total_blocks(include_air);
        }
        return counter;
    }


    /// Returns `(Vec<(block, hash)>, Vec<LUT-cur-block-index-to-global-block-index>)`, this will
    /// be useful when merging multiple regions
    pub fn full_palette(&self) -> (Vec<(&Block, u64)>, Vec<Vec<usize>>) {
        let possible_max_palette_size;
        {
            let mut pmps: usize = 0;
            for reg in &self.regions {
                pmps = max(pmps, reg.palette.len());
            }
            possible_max_palette_size = pmps;
        }

        let mut palette: Vec<(&Block, u64)> = Vec::with_capacity(possible_max_palette_size);
        let mut lut_lut: Vec<Vec<usize>> = Vec::with_capacity(self.regions.len());
        for reg in &self.regions {
            let mut lut: Vec<usize> = Vec::with_capacity(reg.palette.len());

            for cur_blk in &reg.palette {
                let mut hasher = DefaultHasher::new();
                cur_blk.hash(&mut hasher);
                let cur_hash = hasher.finish();

                let mut cur_block_index_in_full_palette = palette.len();
                for (idx, (blk, hash)) in palette.iter().enumerate() {
                    if *hash != cur_hash {
                        continue;
                    }
                    if *blk != cur_blk {
                        continue;
                    }
                    cur_block_index_in_full_palette = idx;
                    break;
                }

                if cur_block_index_in_full_palette >= palette.len() {
                    palette.push((cur_blk, cur_hash));
                }
                lut.push(cur_block_index_in_full_palette);
            }
            lut_lut.push(lut);
        }
        return (palette, lut_lut);
    }

    /// Load schematic from file.
    pub fn from_file(filename: &str) -> Result<(Schematic, RawMetaData), Error> {
        if filename.ends_with(".litematic") {
            let (schem, raw) = Self::from_litematica_file(filename, &LitematicaLoadOption::default())?;
            return Ok((schem, RawMetaData::Litematica(raw)));
        }
        if filename.ends_with(".nbt") {
            let (schem, raw) = Self::from_vanilla_structure_file(filename, &VanillaStructureLoadOption::default())?;
            return Ok((schem, RawMetaData::VanillaStructure(raw)));
        }
        if filename.ends_with(".schem") {
            let (schem, raw) = Self::from_world_edit_13_file(filename, &WorldEdit13LoadOption::default())?;
            return Ok((schem, RawMetaData::WE13(raw)));
        }
        if filename.ends_with(".schematic") {
            let (schem, raw, ..) = Self::from_world_edit_12_file(filename, &WorldEdit12LoadOption::default())?;
            return Ok((schem, RawMetaData::WE12(raw)));
        }

        let split = filename.split(".");
        let extension = split.last().unwrap_or_else(|| "");


        return Err(Error::UnrecognisedExtension { extension: extension.to_string() });
    }

    /// Save schematic to file.
    pub fn save_to_file(&self, filename: &str) -> Result<(), Error> {
        if filename.ends_with(".litematic") {
            return self.save_litematica_file(filename, &LitematicaSaveOption::default());
        }
        if filename.ends_with(".nbt") {
            return self.save_vanilla_structure_file(filename, &VanillaStructureSaveOption::default());
        }
        if filename.ends_with(".schem") {
            return self.save_world_edit_13_file(filename, &WorldEdit13SaveOption::default());
        }

        let split = filename.split(".");
        let extension = split.last().unwrap_or_else(|| "");


        return Err(Error::UnrecognisedExtension { extension: extension.to_string() });
    }

    /// Count duplicated blocks.
    pub fn duplicated_blocks(&self) -> HashMap<[i32; 3], Vec<&Block>> {
        let mut result = HashMap::new();
        let mut temp = Vec::new();

        fn deduplicate<'a>(src: &[&'a Block], dest: &mut Vec<&'a Block>) {
            dest.reserve(src.len());
            dest.clear();
            for blk in src {
                if dest.contains(&*blk) {
                    continue;
                }
                dest.push(&*blk);
            }
        }

        let mut temp_deduplicated = Vec::with_capacity(self.regions.len());

        for y in 0..self.shape()[1] {
            for z in 0..self.shape()[2] {
                for x in 0..self.shape()[0] {
                    let pos = [x, y, z];
                    self.get_blocks_at(pos, &mut temp);
                    deduplicate(&temp, &mut temp_deduplicated);
                    if temp_deduplicated.len() >= 2 {
                        result.insert(pos, temp_deduplicated.clone());
                    }
                }
            }
        }
        return result;
    }

    /// Merge all regions without changing original schematic
    pub fn to_single_region(&self, background_block: &Block) -> Region {
        let mut region = Region::new();
        region.reshape(&self.shape());
        {
            let mut entity_num = 0;
            let mut be_num = 0;
            let mut pb_num = 0;
            for reg in &self.regions {
                entity_num += reg.entities.len();
                be_num += reg.block_entities.len();
                pb_num += reg.pending_ticks.len();
            }
            region.entities.reserve(entity_num);
            region.pending_ticks.reserve(pb_num);
            region.block_entities.reserve(be_num);
        }

        let (full_pal, lut_lut) = self.full_palette();
        let background_block_index;
        {
            region.palette.clear();
            region.palette.reserve(full_pal.len() + 1);
            for (blk, _hash) in &full_pal {
                region.palette.push((*blk).clone());
            }
            background_block_index = region.find_or_append_to_palette(background_block);
        }
        let shape = self.shape();
        for y in 0..shape[1] {
            for z in 0..shape[2] {
                for x in 0..shape[0] {
                    let g_pos = [x, y, z];
                    {
                        let res = region.set_block_id(g_pos, background_block_index);
                        debug_assert!(res.is_ok());
                    }
                    let reg_idx = self.first_region_index_at(g_pos);
                    let info = self.first_block_info_at(g_pos);
                    debug_assert!(reg_idx.is_some() == info.is_some());
                    let reg_idx = match reg_idx {
                        Some(ri) => ri,
                        None => continue,
                    };
                    let (local_block_idx, _blk, be_opt, pd_list) = info.unwrap();
                    let global_block_idx = lut_lut[reg_idx][local_block_idx as usize] as u16;
                    {
                        let res = region.set_block_id(g_pos, global_block_idx);
                        debug_assert!(res.is_ok());
                    }
                    if let Some(be) = be_opt {
                        region.block_entities.insert(g_pos, be.clone());
                    }
                    for pd in pd_list {
                        if let Some(dst) = region.pending_ticks.get_mut(&g_pos) {
                            dst.push(pd.clone());
                        } else {
                            region.pending_ticks.insert(g_pos, vec![pd.clone()]);
                        }
                    }
                }
            }
        }

        // entities
        {
            for reg in &self.regions {
                for entity in &reg.entities {
                    let mut e = entity.clone();
                    e.pos_shift(reg.offset);
                    region.entities.push(e);
                }
            }
        }

        return region;
    }

    /// Merge all regions in place
    pub fn merge_regions(&mut self, background_block: &Block) {
        let new_reg = self.to_single_region(background_block);
        self.regions = vec![new_reg];
    }
}

/// Convert nbt tag type to number id
pub fn id_of_nbt_tag(tag: &fastnbt::Value) -> u8 {
    return match tag {
        fastnbt::Value::Byte(_) => 1,
        fastnbt::Value::Short(_) => 2,
        fastnbt::Value::Int(_) => 3,
        fastnbt::Value::Long(_) => 4,
        fastnbt::Value::Float(_) => 5,
        fastnbt::Value::Double(_) => 6,
        fastnbt::Value::ByteArray(_) => 7,
        fastnbt::Value::String(_) => 8,
        fastnbt::Value::List(_) => 9,
        fastnbt::Value::Compound(_) => 10,
        fastnbt::Value::IntArray(_) => 11,
        fastnbt::Value::LongArray(_) => 12,
    }
}

/// Options to load vanilla structure
#[derive(Debug)]
pub struct VanillaStructureLoadOption {
    /// Background block of the schematic. vanilla structure will not store structure void.
    pub background_block: CommonBlock,
}

impl VanillaStructureLoadOption {
    pub fn default() -> VanillaStructureLoadOption {
        return VanillaStructureLoadOption {
            background_block: CommonBlock::StructureVoid
        }
    }
}

/// Options to save vanilla structure
#[derive(Debug)]
pub struct VanillaStructureSaveOption {
    /// Level of gzip compression, 0<= level <=9.
    pub compress_level: Compression,
    /// Whether to store air. If false, air will be not be treated, just like structure void.
    pub keep_air: bool,
}

impl Default for VanillaStructureSaveOption {
    fn default() -> VanillaStructureSaveOption {
        return VanillaStructureSaveOption {
            keep_air: true,
            compress_level: Compression::best(),
        }
    }
}

//#[derive(Debug)]
/// Options to load litematica
pub struct LitematicaLoadOption {
}

impl LitematicaLoadOption {
    pub fn default() -> LitematicaLoadOption {
        return LitematicaLoadOption {
        };
    }
}

/// Options to save litematica
#[derive(Debug)]
pub struct LitematicaSaveOption {
    /// Level of gzip compression, 0<= level <=9.
    pub compress_level: Compression,
    /// Whether to rename a region if multiple regions have same name. If `false`, returns error when
    /// name conflicts happen.
    pub rename_duplicated_regions: bool,
}

impl Default for LitematicaSaveOption {
    fn default() -> LitematicaSaveOption {
        return LitematicaSaveOption {
            rename_duplicated_regions: true,
            compress_level: Compression::best(),
        };
    }
}


/// Options to load litematica
#[derive(Debug)]
pub struct WorldEdit13LoadOption {}

#[allow(dead_code)]
impl WorldEdit13LoadOption {
    pub fn default() -> WorldEdit13LoadOption {
        return WorldEdit13LoadOption {};
    }
}

/// Options to save world edit 1.13+
#[derive(Debug)]
pub struct WorldEdit13SaveOption {
    /// Level of gzip compression, 0<= level <=9.
    pub compress_level: Compression,
    /// If the schematic contains multiple regions, some positions may not be covered by any region,
    /// but `.schem` can have only one region, so we must define a block for these positions.
    /// Air by default.
    pub background_block: CommonBlock,
}

#[allow(dead_code)]
impl Default for WorldEdit13SaveOption {
    fn default() -> WorldEdit13SaveOption {
        return WorldEdit13SaveOption {
            background_block: CommonBlock::Air,
            compress_level: Compression::best(),
        };
    }
}

/// Options to load litematica
#[derive(Debug)]
pub struct WorldEdit12LoadOption {
    /// Data version of this schematic. Data version is not stored in `.schematic`, so we should assign it.
    pub data_version: DataVersion,
}

impl Default for WorldEdit12LoadOption {
    fn default() -> Self {
        return WorldEdit12LoadOption {
            data_version: DataVersion::Java_1_12_2,
        }
    }
}