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
use crate::map::*;
use crate::convert::TryTo;

use image::{ImageError, io::Reader as ImageReader, ImageFormat};
use serde::{Serialize, Deserialize};
use thiserror::Error;

use std::cell::RefCell;
use std::collections::HashMap;
use std::convert::TryFrom;
use std::io;
use std::io::Write;
use std::ffi::OsString;
use std::fmt;
use std::fs;
use std::path::{Path, PathBuf};

thread_local! {
    pub static IMAGE_NAMES: RefCell<Option<Vec<String>>> = RefCell::new(None);
    pub static SOUND_NAMES: RefCell<Option<Vec<String>>> = RefCell::new(None);
    pub static ENVELOPE_NAMES: RefCell<Option<Vec<String>>> = RefCell::new(None);

    pub static IMAGE_NAMES_MAPPING: RefCell<Option<HashMap<String, u16>>> = RefCell::new(None);
    pub static SOUND_NAMES_MAPPING: RefCell<Option<HashMap<String, u16>>> = RefCell::new(None);
    pub static ENVELOPE_NAMES_MAPPING: RefCell<Option<HashMap<String, u16>>> = RefCell::new(None);
}

fn save_json_file<T: Serialize>(json: &T, path: &Path) -> io::Result<()> {
    let mut bytes = serde_json::to_vec_pretty(json).unwrap();
    bytes.push('\n' as u8);
    save_bin_file(&bytes, path, "json")
}

fn save_bin_file(buf: &[u8], path: &Path, extension: &str) -> io::Result<()> {
    let mut file = fs::File::create(with_extension(path, extension))?;
    file.write_all(buf)?;
    Ok(())
}

#[derive(Error, Debug)]
pub struct MapDirError {
    pub path: PathBuf,
    pub kind: MapDirErrorKind,
}

#[derive(Debug)]
pub enum MapDirErrorKind {
    InvalidUtf8,
    PhysicsLayerName(LayerKind),
    ColorDepth16,
    DuplicateImageName,
    Io(io::Error),
    Json(serde_json::Error),
    Image(ImageError),
}

impl fmt::Display for MapDirError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use MapDirErrorKind::*;
        write!(f, "{:?}: ", self.path)?;
        match &self.kind {
            InvalidUtf8 => write!(f, "Invalid utf-8 in file name"),
            PhysicsLayerName(variant) => write!(f, "Physics layer '{:?}' has an incorrect name", variant),
            ColorDepth16 => write!(f, "Images with 16 bits per channel are not supported"),
            DuplicateImageName => write!(f, "Two images have the same file name with different extensions (.png, .json)"),
            Io(err) => write!(f, "{}", err),
            Json(err) => write!(f, "{}", err),
            Image(err) => write!(f, "{}", err),
        }
    }
}

trait WithPath {
    type OkType;

    fn err_with_path<U: Into<PathBuf>>(self, path: U) -> Result<Self::OkType, MapDirError>;
}

impl<T> WithPath for Result<T, MapDirErrorKind> {
    type OkType = T;
    fn err_with_path<U: Into<PathBuf>>(self, path: U) -> Result<T, MapDirError> {
        match self {
            Ok(ok) => Ok(ok),
            Err(kind) => Err(MapDirError {
                kind,
                path: path.into(),
            })
        }
    }
}

impl<T> WithPath for io::Result<T> {
    type OkType = T;
    fn err_with_path<U: Into<PathBuf>>(self, path: U) -> Result<T, MapDirError> {
        match self {
            Ok(ok) => Ok(ok),
            Err(err) => Err(MapDirError {
                kind: MapDirErrorKind::Io(err),
                path: path.into(),
            })
        }
    }
}

impl<T> WithPath for Result<T, serde_json::Error> {
    type OkType = T;
    fn err_with_path<U: Into<PathBuf>>(self, path: U) -> Result<T, MapDirError> {
        match self {
            Ok(ok) => Ok(ok),
            Err(err) => Err(MapDirError {
                kind: MapDirErrorKind::Json(err),
                path: path.into(),
            })
        }
    }
}

impl<T> WithPath for Result<T, ImageError> {
    type OkType = T;
    fn err_with_path<U: Into<PathBuf>>(self, path: U) -> Result<T, MapDirError> {
        match self {
            Ok(ok) => Ok(ok),
            Err(err) => Err(MapDirError {
                kind: MapDirErrorKind::Image(err),
                path: path.into(),
            })
        }
    }
}

impl TwMap {
    /// Saves the map in the MapDir format to the passed path.
    /// Will not overwrite existing files/directories, this would result in an IO-error.
    pub fn save_dir<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error> {
        self.load()?;
        self.check()?;
        self.save_dir_unwrap(path)?;
        Ok(())
    }

    fn save_dir_unwrap<P: AsRef<Path>>(&mut self, path: P) -> io::Result<()> {
        let path = path.as_ref();
        IMAGE_NAMES.with(|f| *f.borrow_mut() = Some(self.images.iter()
            .enumerate()
            .map(|(index, image)| indexed_name(image.name(), index, self.images.len()))
            .collect()));

        ENVELOPE_NAMES.with(|f| *f.borrow_mut() = Some(self.envelopes.iter()
            .enumerate()
            .map(|(index, env)| indexed_name(env.name(), index, self.envelopes.len()))
            .collect()));

        SOUND_NAMES.with(|f| *f.borrow_mut() = Some(self.sounds.iter()
            .enumerate()
            .map(|(index, env)| indexed_name(&env.name, index, self.sounds.len()))
            .collect()));

        fs::create_dir(path)?;

        save_json_file(&self.info, &path.join("info"))?;

        let dir_version = DirVersion::from(self.version);
        save_json_file(&dir_version, &path.join("version"))?;

        if self.images.len() != 0 {
            let images_path = path.join("images");
            fs::create_dir(&images_path)?;

            for (i, image) in self.images.iter().enumerate() {
                let image_file_name = indexed_name(image.name(), i, self.images.len());
                let image_path = images_path.join(&image_file_name);
                image.save_as_file(&image_path)?;
            }
        }

        if self.envelopes.len() != 0 {
            let envelopes_path = path.join("envelopes");
            fs::create_dir(&envelopes_path)?;
            for (i, envelope) in self.envelopes.iter().enumerate() {
                let envelope_file_name = indexed_name(&envelope.name(), i, self.envelopes.len());
                let envelope_path = envelopes_path.join(&envelope_file_name);
                save_json_file(&envelope, &envelope_path)?;
            }
        }

        let groups_path = path.join("groups");
        fs::create_dir(&groups_path)?;
        for (i, group) in self.groups.iter().enumerate() {
            let group_directory_name = indexed_name(&group.name, i, self.groups.len());
            let group_path = groups_path.join(&group_directory_name);
            fs::create_dir(&group_path)?;
            save_json_file(&group, &group_path.join("group"))?;

            let group_layers_path = group_path.join("layers");
            if !group.layers.is_empty() {
                fs::create_dir(&group_layers_path)?;
            }
            for (i, layer) in group.layers.iter().enumerate() {
                let layer_file_name = indexed_name(&layer.name(), i, group.layers.len());
                let layer_path = group_layers_path.join(layer_file_name);
                save_json_file(&layer, &layer_path)?;
            }
        }

        if self.sounds.len() != 0 {
            let sounds_path = path.join("sounds");
            fs::create_dir(&sounds_path)?;
            for (i, sound) in self.sounds.iter().enumerate() {
                let sound_file_name = indexed_name(&sound.name, i, self.sounds.len());
                let sound_path = sounds_path.join(&sound_file_name);
                save_bin_file(sound.data.unwrap_ref(), &sound_path, "opus")?;
            }
        }

        Ok(())
    }

    /// For parsing a TwMap map directory.
    pub fn parse_dir<P: AsRef<Path>>(path: P) -> Result<TwMap, Error> {
        let mut map = TwMap::parse_dir_unchecked(path)?;
        map.check()?;
        map.process_tile_flag_opaque();
        Ok(map)
    }

    pub fn parse_dir_unchecked<P: AsRef<Path>>(path: P) -> Result<TwMap, Error> {
        let path = path.as_ref();

        fs::read_dir(&path)?;

        let images_path = path.join("images");
        let envelopes_path = path.join("envelopes");
        let groups_path = path.join("groups");
        let sounds_path = path.join("sounds");

        let image_names_mapping = create_dir_mapping(&images_path, &["png", "json"])?;
        IMAGE_NAMES_MAPPING.with(|f|
            *f.borrow_mut() = Some(image_names_mapping));

        let envelope_names_mapping = create_dir_mapping(&envelopes_path, &["json"])?;
        ENVELOPE_NAMES_MAPPING.with(|f|
            *f.borrow_mut() = Some(envelope_names_mapping));

        let sound_names_mapping = create_dir_mapping(&sounds_path, &["opus"])?;
        SOUND_NAMES_MAPPING.with(|f|
            *f.borrow_mut() = Some(sound_names_mapping));

        let info_path = path.join("info.json");
        let info = Info::deserialize_json(&info_path)?;

        let version_path = path.join("version.json");
        let dir_version = DirVersion::deserialize_json(&version_path)?;
        let version = dir_version.version;

        let mut images = Vec::new();
        for image_name in list_dir(&images_path, &["png", "json"])? {
            let image_path = images_path.join(&image_name);
            let mut image = Image::from_file(&image_path)?;
            *image.name_mut() = strip_name(image_name);
            images.push(image);
        }

        let mut envelopes = Vec::new();
        for envelope_name in list_dir(&envelopes_path, &["json"])? {
            let envelope_path = envelopes_path.join(&envelope_name);
            let envelope = Envelope::deserialize_json(&envelope_path)?;
            envelopes.push(envelope);
        }

        let mut groups = Vec::new();
        for group_name in list_dir(&groups_path, &[])? {
            let group_path = groups_path.join(&group_name);
            let group_info_path = group_path.join("group.json");
            let mut group = Group::deserialize_json(&group_info_path)?;

            let mut layers = Vec::new();
            let group_layers_path = group_path.join("layers");
            for layer_name in list_dir(&group_layers_path, &["json"])? {
                let layer_path = group_layers_path.join(&layer_name);
                let layer = Layer::deserialize_json(&layer_path)?;
                layers.push(layer);
            }
            group.layers = layers;

            groups.push(group);
        }

        let mut sounds = Vec::new();
        for sound_name in list_dir(&sounds_path, &["opus"])? {
            let sound_path = sounds_path.join(&sound_name);
            let data = fs::read(&sound_path)
                .err_with_path(&sound_path)?;
            sounds.push(Sound {
                name: strip_name(sound_name),
                data: CompressedData::Loaded(data),
            })
        }

        Ok(TwMap {
            version,
            info,
            images,
            envelopes,
            groups,
            sounds,
        })
    }
}

trait DeserializeJson: for<'de> Deserialize<'de> {
    fn deserialize_json(path: &Path) -> Result<Self, MapDirError> {
        let file = fs::read(path)
            .err_with_path(&path)?;
        serde_json::from_slice(&file)
            .err_with_path(&path)
    }
}

impl<T: for<'de> Deserialize<'de>> DeserializeJson for T {}

fn create_dir_mapping(path: &Path, extensions: &[&str]) -> Result<HashMap<String, u16>, MapDirError> {
    let file_names = list_dir(path, extensions)?;
    let mut file_mapping = HashMap::new();
    for (i, file_name) in file_names.iter().enumerate() {
        let name = PathBuf::from(&file_name).file_stem().unwrap().to_str().unwrap().to_string();
        if file_mapping.contains_key(&name) {
            return Err(MapDirErrorKind::DuplicateImageName)
                .err_with_path(path.join(&name))?;
        }
        file_mapping.insert(name, i.try_to::<u16>());
    }
    Ok(file_mapping)
}

fn list_dir(path: &Path, extensions: &[&str]) -> Result<Vec<String>, MapDirError> {
    let extensions: Vec<OsString> = extensions.iter()
        .map(|str| OsString::from(str))
        .collect();

    // filter out file names with incorrect extension
    let dir_entries = match fs::read_dir(path) {
        Ok(dir_entries) => dir_entries,
        Err(err) => {
            return if err.kind() == io::ErrorKind::NotFound {
                Ok(Vec::new())
            }
            else {
                Err(err).err_with_path(path)
            }
        }
    };

    // filter faulty entries / entries with incorrect file extensions
    let file_names = dir_entries
        .filter_map(|dir_entry| match dir_entry {
            Err(err) => Some(Err(err).err_with_path(path)),
            Ok(entry) => {
                let file_name = entry.file_name();
                if let Some(ext) = PathBuf::from(&file_name).extension() {
                    if extensions.contains(&ext.to_os_string()) {
                        Some(Ok(file_name))
                    }
                    else {
                        None
                    }
                }
                else {
                    // no extensions is used for listing directories
                    if extensions.is_empty() {
                        Some(Ok(file_name))
                    }
                    else {
                        None
                    }
                }
            }
        })
        .collect::<Result<Vec<_>, MapDirError>>()?;

    // ensure proper utf-8
    let mut file_names = file_names.into_iter()
        .map(|os_str| match os_str.to_str() {
            None => Err(MapDirErrorKind::InvalidUtf8).err_with_path(path.join(os_str)),
            Some(str) => Ok(str.to_string()),
        })
        .collect::<Result<Vec<String>, MapDirError>>()?;

    // sort alphabetically
    file_names.sort();
    Ok(file_names)
}

fn with_extension(path: &Path, extension: &str) -> PathBuf {
    let mut path = path.as_os_str().to_os_string();
    path.push(".");
    path.push(extension);
    PathBuf::from(path)
}


fn indexed_name(name: &str, i: usize, length: usize) -> String {
    let pad_length = (length - 1).to_string().chars().count();
    if name.is_empty() {
        format!("{:0width$}", i, width = pad_length)
    }
    else {
        format!("{:0width$}_{}", i, sanitize_name(name), width = pad_length)
    }
}

// removes index + file extension
fn strip_name(mut name: String) -> String {
    // remove file extension
    name = PathBuf::from(name).file_stem().unwrap().to_str().unwrap().to_string();

    // remove prefixed index, if it exists
    if let Some(mid) = name.find("_") {
        let (prefix, remaining) = name.split_at(mid + 1);
        match prefix[..prefix.len() - 1].parse::<usize>() {
            Ok(_) => remaining.to_string(),
            Err(_) => name,
        }
    }
    else {
        match name.parse::<usize>() {
            Ok(_) => String::new(),
            Err(_) => name,
        }
    }
}

fn sanitize_name(name: &str) -> String {
    sanitize_filename::sanitize_with_options(name, sanitize_filename::Options {
        windows: true,
        truncate: true,
        replacement: "_"
    })
}

#[derive(Serialize, Deserialize)]
struct DirVersion {
    #[serde(flatten)]
    version: Version,
    created_by: String,
}

impl From<Version> for DirVersion {
    fn from(version: Version) -> Self {
        let mut created_by = env!("CARGO_PKG_NAME").to_string();
        created_by.push(' ');
        created_by.extend(env!("CARGO_PKG_VERSION").chars());
        DirVersion {
            version,
            created_by,
        }
    }
}

impl Image {
    fn save_as_file(&self, path: &Path) -> io::Result<()> {
        match self {
            Image::External(img) => save_json_file(&img, path)?,
            Image::Embedded(img) => {
                let image = img.image.unwrap_ref();
                image.save(with_extension(path,"png"))
                    .map_err(|err| match err {
                        ImageError::IoError(err) => err,
                        _ => panic!("Image saving error that shouldn't happen."),
                    })?;
            }
        }
        Ok(())
    }
}

impl Image {
    fn from_file(path: &Path) -> Result<Self, MapDirError> {
        match path.extension().unwrap().to_str().unwrap() {
            "json" => Ok(ExternalImage::deserialize_json(path)?.into()),
            "png" => {
                let mut reader = ImageReader::open(path)
                    .err_with_path(path)?;
                reader.set_format(ImageFormat::Png);
                let image = reader.decode()
                    .err_with_path(path)?
                    .into_rgba8();

                Ok(EmbeddedImage {
                    name: String::new(),
                    image: image.into(),
                }.into())
            }
            _ => unreachable!(),
        }
    }
}

#[derive(Serialize, Deserialize)]
pub(crate) struct DirTileFlags {
    mirrored: bool,
    rotation: i32,
}

impl From<TileFlags> for DirTileFlags {
    fn from(flags: TileFlags) -> Self {
        let flip_v = flags.contains(TileFlags::FLIP_V);
        let flip_h = flags.contains(TileFlags::FLIP_H);
        let rotate = flags.contains(TileFlags::ROTATE);

        DirTileFlags {
            mirrored: flip_v ^ flip_h,
            rotation: match (flip_h, rotate) {
                (false, false) => 0,
                (false, true) => 90,
                (true, false) => 180,
                (true, true) => 270,
            },
        }
    }
}

pub struct DirTileFlagsError(i32);

impl fmt::Display for DirTileFlagsError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "rotation can only be one of the values 0, 90, 180 and 270")
    }
}

impl TryFrom<DirTileFlags> for TileFlags {
    type Error = DirTileFlagsError;

    fn try_from(v: DirTileFlags) -> Result<Self, Self::Error> {
        let mut flags = TileFlags::empty();
        match v.rotation {
            0 => {},
            90 => flags.insert(TileFlags::ROTATE),
            180 => flags.insert(TileFlags::FLIP_H),
            270 => flags.insert(TileFlags::FLIP_H | TileFlags::ROTATE),
            n => return Err(DirTileFlagsError(n)),
        }
        if v.mirrored ^ flags.contains(TileFlags::FLIP_H) {
            flags.insert(TileFlags::FLIP_V);
        }
        Ok(flags)
    }
}

pub(crate) mod tiles_serialization {
    use crate::map::*;
    use serde::{Serialize, Serializer, Deserialize, Deserializer};
    use ndarray::Array2;
    use std::fmt;
    use crate::convert::TryTo;

    #[derive(Serialize, Deserialize)]
    struct DirTile<T> {
        #[serde(flatten)]
        pos: Point,
        #[serde(flatten)]
        tile: T,
    }

    #[derive(Serialize, Deserialize)]
    struct DirTiles<T> {
        width: usize,
        height: usize,
        tiles: Vec<DirTile<T>>,
    }

    fn dir_tiles<T>(tiles: &Array2<T>) -> DirTiles<T> where
        T: Serialize + Default + PartialEq + Copy {
        let width = tiles.ncols();
        let height = tiles.nrows();

        let tiles = tiles.indexed_iter()
            .filter_map(|((y, x), tile)| {
                if *tile == T::default() {
                    None
                }
                else {
                    let pos = Point { x: (x.try_to()), y: y.try_to() };
                    let tile = *tile;
                    let dir_tile = DirTile { pos, tile };
                    Some(dir_tile)
                }
            })
            .collect::<Vec<_>>();

        DirTiles {
            width,
            height,
            tiles,
        }
    }

    pub(crate) fn serialize<T, S>(tiles: &CompressedData<Array2<T>, TilesLoadInfo>, serializer: S) -> Result<S::Ok, S::Error> where
        T: Serialize + Default + PartialEq + Copy,
        S: Serializer {
        let tiles = tiles.unwrap_ref();
        dir_tiles(tiles).serialize(serializer)
    }

    pub enum DirTileError {
        DuplicateTile((usize, usize)),
        OutOfBounds((usize, usize), (usize, usize)),
    }

    impl fmt::Display for DirTileError {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            use DirTileError::*;
            match self {
                DuplicateTile(pos) => write!(f, "duplicate tile at ({}, {})", pos.0, pos.1),
                OutOfBounds(pos, bound) => write!(f, "tile out of bounds at y:{}, x:{} ((0, 0) is the top left corner), layer height: {}, width: {}", pos.0, pos.1, bound.0, bound.1),
            }
        }
    }

    fn undir_tiles<'a, T>(dir_tiles: DirTiles<T>) -> Result<Array2<T>, DirTileError> where
        T: Deserialize<'a> + Default + PartialEq + Copy {
        use DirTileError::*;

        let shape = (dir_tiles.height, dir_tiles.width);
        let mut tiles: Array2<Option<T>> = Array2::default(shape);

        for dir_tile in dir_tiles.tiles {
            let pos = (dir_tile.pos.y.try_to::<usize>(), dir_tile.pos.x.try_to::<usize>());
            match tiles.get(pos) {
                None => return Err(OutOfBounds(pos, shape)),
                Some(Some(_)) => return Err(DuplicateTile(pos)),
                Some(None) => tiles[pos] = Some(dir_tile.tile),
            }
        }
        let tiles = tiles.map(|&t| {
            match t {
                None => T::default(),
                Some(t) => t,
            }
        });
        Ok(tiles)
    }

    pub(crate) fn deserialize<'de, T, D>(deserializer: D) -> Result<CompressedData<Array2<T>, TilesLoadInfo>, D::Error> where
        T: Deserialize<'de> + Default + PartialEq + Copy,
        D: Deserializer<'de> {
        let tiles = DirTiles::deserialize(deserializer)?;
        let tiles = undir_tiles(tiles)
            .map_err(|err| serde::de::Error::custom(err))?;
        Ok(CompressedData::Loaded(tiles))
    }
}

pub(crate) mod image_index_serialization {
    use serde::{Serialize, Serializer, Deserializer, Deserialize};
    use super::{IMAGE_NAMES, IMAGE_NAMES_MAPPING};
    use std::fmt;
    use crate::convert::To;

    pub(crate) fn serialize<S: Serializer>(opt_index: &Option<u16>, serializer: S) -> Result<S::Ok, S::Error> {
        IMAGE_NAMES.with(|f| opt_index.map(|index|
            f.borrow().as_ref().unwrap()[index.to::<usize>()].clone()).serialize(serializer))
    }

    struct ImageNameMissing(String);

    impl fmt::Display for ImageNameMissing {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "image with name {} isn't available", self.0)
        }
    }

    pub(crate) fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<u16>, D::Error> {
        let opt_name = <Option<String>>::deserialize(deserializer)?;
        let opt_index = match opt_name {
            None => None,
            Some(name) => IMAGE_NAMES_MAPPING.with(|f|
                match f.borrow().as_ref().unwrap().get(&name) {
                    None => Err(serde::de::Error::custom(ImageNameMissing(name))),
                    Some(&index) => Ok(Some(index))
                })?
        };
        Ok(opt_index)
    }
}

pub(crate) mod sound_index_serialization {
    use crate::convert::To;
    use serde::{Serialize, Serializer, Deserializer, Deserialize};
    use super::{SOUND_NAMES, SOUND_NAMES_MAPPING};
    use std::fmt;

    pub(crate) fn serialize<S: Serializer>(opt_index: &Option<u16>, serializer: S) -> Result<S::Ok, S::Error> {
        SOUND_NAMES.with(|f| opt_index.map(|index|
            f.borrow().as_ref().unwrap()[index.to::<usize>()].clone()).serialize(serializer))
    }

    struct SoundNameMissing(String);

    impl fmt::Display for SoundNameMissing {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "sound with name {} isn't available", self.0)
        }
    }

    pub(crate) fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<u16>, D::Error> {
        let opt_name = <Option<String>>::deserialize(deserializer)?;
        let opt_index = match opt_name {
            None => None,
            Some(name) => SOUND_NAMES_MAPPING.with(|f|
                match f.borrow().as_ref().unwrap().get(&name) {
                    None => Err(serde::de::Error::custom(SoundNameMissing(name))),
                    Some(&index) => Ok(Some(index))
                })?
        };
        Ok(opt_index)
    }
}

pub(crate) mod envelope_index_serialization {
    use crate::convert::To;
    use serde::{Serialize, Serializer, Deserializer, Deserialize};
    use super::{ENVELOPE_NAMES, ENVELOPE_NAMES_MAPPING};
    use std::fmt;

    pub(crate) fn serialize<S: Serializer>(opt_index: &Option<u16>, serializer: S) -> Result<S::Ok, S::Error> {
        ENVELOPE_NAMES.with(|f| opt_index.map(|index|
            f.borrow().as_ref().unwrap()[index.to::<usize>()].clone()).serialize(serializer))
    }

    struct EnvelopeNameMissing(String);

    impl fmt::Display for EnvelopeNameMissing {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "envelope with name {} isn't available", self.0)
        }
    }

    pub(crate) fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<u16>, D::Error> {
        let opt_name = <Option<String>>::deserialize(deserializer)?;
        let opt_index = match opt_name {
            None => None,
            Some(name) => ENVELOPE_NAMES_MAPPING.with(|f|
                match f.borrow().as_ref().unwrap().get(&name) {
                    None => Err(serde::de::Error::custom(EnvelopeNameMissing(name))),
                    Some(&index) => Ok(Some(index))
                })?
        };
        Ok(opt_index)
    }
}