vpin 0.23.5

Rust library for working with Visual Pinball VPX 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
use super::biff::{self, BiffRead, BiffReader, BiffWrite, BiffWriter};
use crate::vpx::lzw::from_lzw_blocks;
use image::DynamicImage;
use log::warn;
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::fmt;

#[derive(PartialEq, Clone)]
pub struct ImageDataJpeg {
    pub path: String,
    pub name: String,
    // /**
    //  * Lowercased name?
    //  * No longer in use
    //  */
    pub internal_name: Option<String>,
    // alpha_test_value: f32,
    pub data: Vec<u8>,
}

impl fmt::Debug for ImageDataJpeg {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // avoid writing the data to the debug output
        f.debug_struct("ImageDataJpeg")
            .field("path", &self.path)
            .field("name", &self.name)
            // .field("alpha_test_value", &self.alpha_test_value)
            .field("data", &self.data.len())
            .finish()
    }
}

/**
 * A bitmap blob, typically used by textures.
 */
#[derive(PartialEq, Clone)]
pub struct ImageDataBits {
    /// Lzw compressed raw BMP 32-bit sBGRA bitmap data
    /// However we expect the alpha channel to always be 255
    pub lzw_compressed_data: Vec<u8>,
}

impl fmt::Debug for ImageDataBits {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // avoid writing the data to the debug output
        f.debug_struct("ImageDataBits")
            .field("data", &self.lzw_compressed_data.len())
            .finish()
    }
}

#[derive(PartialEq, Debug, Clone)]
pub struct ImageData {
    pub name: String, // NAME
    // /**
    //  * Lowercased name?
    //  * INME
    //  * No longer in use
    //  */
    pub internal_name: Option<String>,
    pub path: String, // PATH
    pub width: u32,   // WDTH
    pub height: u32,  // HGHT
    // TODO seems to be 1 for some kind of link type img, related to screenshots.
    // we only see this where a screenshot is set on the table info.
    // https://github.com/vpinball/vpinball/blob/1a70aa35eb57ec7b5fbbb9727f6735e8ef3183e0/Texture.cpp#L588
    pub link: Option<u32>, // LINK
    /// Alpha test value for transparency cutoff.
    ///
    /// ## File Storage
    /// Stored in the VPX file as BIFF tag `ALTV` in the range **0-255**.
    /// VPinball multiplies by `1/255` when reading and by `255` when writing,
    /// so the runtime value is in the range **0.0-1.0** (or negative for disabled).
    ///
    /// ## Values
    /// - **Negative** (e.g., `-1.0`): Alpha testing disabled, use alpha blending instead
    /// - **0.0-255.0**: Alpha test threshold; pixels with `alpha <= threshold/255` are discarded
    ///   - `1.0` = very low cutoff (~0.004), essentially shows all non-fully-transparent pixels
    ///   - `128.0` = mid cutoff (~0.5), typical for binary transparency masks
    ///   - `220.0` = high cutoff (~0.86), only very opaque pixels pass
    ///
    /// ## Defaults
    /// - **Before 10.8**: Default was `1.0` (enabled with minimal cutoff)
    /// - **Since 10.8**: Default is `-1.0` (disabled)
    ///
    /// ## Shader Usage
    /// In VPinball's shader (`fs_basic.sc`), this controls pixel discard:
    /// ```glsl
    /// if (pixel.a <= alphaTestValue)
    ///     discard;
    /// ```
    /// After the alpha test, VPinball also applies alpha blending:
    /// ```glsl
    /// pixel.a *= cBase_Alpha.a;  // Material opacity multiplied in
    /// ```
    ///
    /// BIFF tag: `ALTV`
    pub alpha_test_value: f32,
    /// Whether the image is fully opaque (no transparent pixels).
    ///
    /// ## Purpose
    /// This is a cached/precomputed flag that indicates whether the image
    /// contains any transparent pixels. When `true`, VPinball can skip
    /// alpha blending operations for better rendering performance.
    ///
    /// ## How It's Determined
    /// VPinball scans the actual pixel data to detect transparency:
    /// - For RGBA images: checks if any pixel has `alpha < 255`
    /// - For indexed images: checks if any palette entry has transparency
    ///
    /// See `Texture::UpdateOpaque()` in VPinball's `Texture.cpp`.
    ///
    /// ## Effect on Rendering
    /// - `true`: Image is fully opaque, no alpha blending needed
    /// - `false`: Image has transparency, requires alpha blending
    /// - `None`: Not set (older files), transparency is determined at runtime
    ///
    /// ## Version
    /// Added in VPinball 10.8
    ///
    /// BIFF tag: `OPAQ`
    pub is_opaque: Option<bool>,
    /// Whether the image uses signed pixel values.
    ///
    /// ## Purpose
    /// Indicates if the image data should be interpreted as signed values
    /// rather than unsigned. This is relevant for normal maps and other
    /// special texture types where values need to represent negative numbers
    /// (e.g., normals pointing in negative directions).
    ///
    /// ## Values
    /// - `true`: Image uses signed values (range -1.0 to 1.0 or -128 to 127)
    /// - `false`: Image uses unsigned values (range 0.0 to 1.0 or 0 to 255)
    /// - `None`: Not set (older files), defaults to unsigned
    ///
    /// ## Usage
    /// Primarily used for normal maps where the RGB channels encode
    /// surface normal directions that can be negative.
    ///
    /// ## Version
    /// Added in VPinball 10.8
    ///
    /// BIFF tag: `SIGN`
    pub is_signed: Option<bool>,
    // TODO we can probably only have one of jpeg or bits so we can make an enum
    /// This field is named jpeg, but it's actually used for any image that is not a bitmap
    pub jpeg: Option<ImageDataJpeg>,
    pub bits: Option<ImageDataBits>,
    pub md5_hash: Option<[u8; 16]>,
}

impl ImageData {
    const ALPHA_TEST_VALUE_DEFAULT: f32 = -1.0;

    pub(crate) fn change_extension(&mut self, ext: &str) {
        let mut path = self.path.clone();
        let re = Regex::new(r"\.[a-zA-Z0-9]+$").unwrap();
        path = re.replace(&path, format!(".{ext}")).to_string();
        self.path = path;

        // to the same for the jpeg path
        if let Some(jpeg) = &mut self.jpeg {
            let mut path = jpeg.path.clone();
            path = re.replace(&path, format!(".{ext}")).to_string();
            jpeg.path = path;
        }
    }

    pub fn is_link(&self) -> bool {
        self.link == Some(1)
    }

    pub fn ext(&self) -> String {
        // TODO we might want to also check the jpeg fsPath
        match self.path.split('.').next_back() {
            Some(ext) => ext.to_string(),
            None => "bin".to_string(),
        }
    }
}

#[derive(PartialEq, Debug, Serialize, Deserialize)]
pub(crate) struct ImageDataJson {
    pub(crate) name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    internal_name: Option<String>,
    path: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) width: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) height: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    link: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    alpha_test_value: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    is_opaque: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    is_signed: Option<bool>,

    // these are just for full compatibility with the original file
    #[serde(skip_serializing_if = "Option::is_none")]
    jpeg_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    jpeg_internal_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    jpeg_path: Option<String>,

    /// In case we have a duplicate name or the file name is not simply derived from the name
    /// because of special characters etc.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) name_dedup: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    md5_hash: Option<String>,
}

impl ImageDataJson {
    pub fn from_image_data(image_data: &ImageData) -> Self {
        let (jpeg_name, jpeg_path, jpeg_internal_name) = if let Some(jpeg) = &image_data.jpeg {
            let jpeg_name = if jpeg.name == image_data.name {
                None
            } else {
                Some(jpeg.name.clone())
            };
            let jpeg_path = if jpeg.path == image_data.path {
                None
            } else {
                Some(jpeg.path.clone())
            };
            let jpeg_internal_name = jpeg.internal_name.clone();
            (jpeg_name, jpeg_path, jpeg_internal_name)
        } else {
            (None, None, None)
        };

        // TODO we might want to generate a warning if the alpha_test_value is the old default of 1.0
        //   which caused overhead in the shader
        let alpha_test_value = if image_data.alpha_test_value == ImageData::ALPHA_TEST_VALUE_DEFAULT
        {
            None
        } else {
            Some(image_data.alpha_test_value)
        };

        ImageDataJson {
            name: image_data.name.clone(),
            internal_name: image_data.internal_name.clone(),
            path: image_data.path.clone(),
            width: None,  // will be set later if needed
            height: None, // will be set later if needed
            link: image_data.link,
            alpha_test_value,
            is_opaque: image_data.is_opaque,
            is_signed: image_data.is_signed,
            jpeg_name,
            jpeg_internal_name,
            jpeg_path,
            name_dedup: None,
            md5_hash: image_data.md5_hash.map(hex::encode),
        }
    }

    pub fn to_image_data(&self, width: u32, height: u32, bits: Option<ImageDataBits>) -> ImageData {
        let mut jpeg = None;
        if !self.is_bmp() && !self.is_link() {
            let name = match &self.jpeg_name {
                Some(name) => name.clone(),
                None => self.name.clone(),
            };
            let path = match &self.jpeg_path {
                Some(path) => path.clone(),
                None => self.path.clone(),
            };
            let internal_name = self.jpeg_internal_name.clone();

            jpeg = Some(ImageDataJpeg {
                path,
                name,
                internal_name,
                data: vec![], // populated later
            });
        }

        let alpha_test_value = self
            .alpha_test_value
            .unwrap_or(ImageData::ALPHA_TEST_VALUE_DEFAULT);
        let md5_hash = self.md5_hash.as_ref().and_then(|h| {
            let bytes = hex::decode(h).ok()?;
            if bytes.len() == 16 {
                let mut arr = [0u8; 16];
                arr.copy_from_slice(&bytes);
                Some(arr)
            } else {
                None
            }
        });
        ImageData {
            name: self.name.clone(),
            internal_name: self.internal_name.clone(),
            path: self.path.clone(),
            width,
            height,
            link: self.link,
            alpha_test_value,
            is_opaque: self.is_opaque,
            is_signed: self.is_signed,
            jpeg,
            bits,
            md5_hash,
        }
    }

    pub fn is_link(&self) -> bool {
        self.link == Some(1)
    }

    pub(crate) fn ext(&self) -> String {
        // TODO we might want to also check the jpeg fsPath
        match self.path.split('.').next_back() {
            Some(ext) => ext.to_string(),
            None => "bin".to_string(),
        }
    }

    pub(crate) fn is_bmp(&self) -> bool {
        self.ext().eq_ignore_ascii_case("bmp")
    }
}

impl BiffWrite for ImageData {
    fn biff_write(&self, writer: &mut BiffWriter) {
        write(self, writer);
    }
}

impl BiffRead for ImageData {
    fn biff_read(reader: &mut BiffReader<'_>) -> Self {
        read(reader)
    }
}

impl Default for ImageData {
    fn default() -> Self {
        ImageData {
            name: "".to_string(),
            internal_name: None,
            path: "".to_string(),
            width: 0,
            height: 0,
            link: None,
            alpha_test_value: 0.0,
            is_opaque: None,
            is_signed: None,
            jpeg: None,
            bits: None,
            md5_hash: None,
        }
    }
}

fn read(reader: &mut BiffReader) -> ImageData {
    let mut image_data = ImageData::default();
    loop {
        reader.next(biff::WARN);
        if reader.is_eof() {
            break;
        }
        let tag = reader.tag();
        let tag_str = tag.as_str();
        match tag_str {
            "NAME" => {
                image_data.name = reader.get_string();
            }
            "PATH" => {
                image_data.path = reader.get_string();
            }
            "INME" => {
                image_data.internal_name = Some(reader.get_string());
            }
            "WDTH" => {
                image_data.width = reader.get_u32();
            }
            "HGHT" => {
                image_data.height = reader.get_u32();
            }
            "ALTV" => {
                image_data.alpha_test_value = reader.get_f32();
            }
            "OPAQ" => {
                image_data.is_opaque = Some(reader.get_bool());
            }
            "SIGN" => {
                image_data.is_signed = Some(reader.get_bool());
            }
            "BITS" => {
                // these have zero as length
                // read all the data until the next expected tag
                let data = reader.data_until("ALTV".as_bytes());
                //let reader = std::io::Cursor::new(data);

                // uncompressed = zlib.decompress(image_data.data[image_data.pos:]) #, wbits=9)
                // reader.skip_end_tag(len.try_into().unwrap());
                image_data.bits = Some(ImageDataBits {
                    lzw_compressed_data: data,
                });
            }
            "JPEG" => {
                // these have zero as length
                // Strangely, raw data are pushed outside the JPEG tag (breaking the BIFF structure of the file)
                let mut sub_reader = reader.child_reader();
                let jpeg_data = read_jpeg(&mut sub_reader);
                image_data.jpeg = Some(jpeg_data);
                let pos = sub_reader.pos();
                reader.skip_end_tag(pos);
            }
            "LINK" => {
                // TODO seems to be 1 for some kind of link type img, related to screenshots.
                // we only see this where a screenshot is set on the table info.
                // https://github.com/vpinball/vpinball/blob/1a70aa35eb57ec7b5fbbb9727f6735e8ef3183e0/Texture.cpp#L588
                image_data.link = Some(reader.get_u32());
            }
            "MD5H" => {
                let data = reader.get_data(16);
                let mut hash = [0u8; 16];
                hash.copy_from_slice(data);
                image_data.md5_hash = Some(hash);
            }
            _ => {
                warn!("Skipping image tag: {tag}");
                reader.skip_tag();
            }
        }
    }
    image_data
}

fn write(data: &ImageData, writer: &mut BiffWriter) {
    writer.write_tagged_string("NAME", &data.name);
    if let Some(inme) = &data.internal_name {
        writer.write_tagged_string("INME", inme);
    }
    writer.write_tagged_string("PATH", &data.path);
    writer.write_tagged_u32("WDTH", data.width);
    writer.write_tagged_u32("HGHT", data.height);
    if let Some(link) = data.link {
        writer.write_tagged_u32("LINK", link);
    }
    if let Some(bits) = &data.bits {
        writer.write_tagged_data_without_size("BITS", &bits.lzw_compressed_data);
    }
    if let Some(jpeg) = &data.jpeg {
        let bits = write_jpg(jpeg);
        writer.write_tagged_data_without_size("JPEG", &bits);
    }
    writer.write_tagged_f32("ALTV", data.alpha_test_value);
    if let Some(md5_hash) = &data.md5_hash {
        writer.write_tagged_data("MD5H", md5_hash);
    }
    if let Some(is_opaque) = data.is_opaque {
        writer.write_tagged_bool("OPAQ", is_opaque);
    }
    if let Some(is_signed) = data.is_signed {
        writer.write_tagged_bool("SIGN", is_signed);
    }
    writer.close(true);
}

fn read_jpeg(reader: &mut BiffReader) -> ImageDataJpeg {
    // I do wonder why all the tags are duplicated here
    let mut size_opt: Option<u32> = None;
    let mut path: String = "".to_string();
    let mut name: String = "".to_string();
    let mut data: Vec<u8> = vec![];
    // let mut alpha_test_value: f32 = 0.0;
    let mut internal_name: Option<String> = None;
    loop {
        reader.next(biff::WARN);
        if reader.is_eof() {
            break;
        }
        let tag = reader.tag();
        let tag_str = tag.as_str();
        match tag_str {
            "SIZE" => {
                size_opt = Some(reader.get_u32());
            }
            "DATA" => match size_opt {
                Some(size) => data = reader.get_data(size.try_into().unwrap()).to_vec(),
                None => {
                    panic!("DATA tag without SIZE tag");
                }
            },
            "NAME" => name = reader.get_string(),
            "PATH" => path = reader.get_string(),
            // "ALTV" => alpha_test_value = reader.get_f32(), // TODO why are these duplicated?
            "INME" => internal_name = Some(reader.get_string()),
            _ => {
                // skip this record
                warn!("skipping tag inside JPEG {tag}");
                reader.skip_tag();
            }
        }
    }
    let data = data.to_vec();
    ImageDataJpeg {
        path,
        name,
        internal_name,
        // alpha_test_value,
        data,
    }
}

fn write_jpg(img: &ImageDataJpeg) -> Vec<u8> {
    let mut writer = BiffWriter::new();
    writer.write_tagged_string("NAME", &img.name);
    if let Some(inme) = &img.internal_name {
        writer.write_tagged_string("INME", inme);
    }
    writer.write_tagged_string("PATH", &img.path);
    writer.write_tagged_u32("SIZE", img.data.len().try_into().unwrap());
    writer.write_tagged_data("DATA", &img.data);
    // writer.write_tagged_f32("ALTV", img.alpha_test_value);
    writer.close(true);
    writer.get_data().to_vec()
}

pub(crate) fn vpx_image_to_dynamic_image(
    lzw_compressed_data: &[u8],
    width: u32,
    height: u32,
) -> DynamicImage {
    let decompressed_bgra = from_lzw_blocks(lzw_compressed_data);
    let decompressed_rgba: Vec<u8> = swap_red_and_blue(&decompressed_bgra);

    let rgba_image = image::RgbaImage::from_raw(width, height, decompressed_rgba)
        .expect("Decompressed image data does not match dimensions");
    let dynamic_image = DynamicImage::ImageRgba8(rgba_image);

    let uses_alpha = decompressed_bgra.chunks_exact(4).any(|bgra| bgra[3] != 255);
    if uses_alpha {
        dynamic_image
    } else {
        let rgb_image = dynamic_image.to_rgb8();
        DynamicImage::ImageRgb8(rgb_image)
    }
}

/// Can convert between RGBA and BGRA by swapping the red and blue channels
pub(crate) fn swap_red_and_blue(data: &[u8]) -> Vec<u8> {
    let mut swapped = Vec::with_capacity(data.len());
    for chunk in data.chunks_exact(4) {
        swapped.extend_from_slice(&[chunk[2], chunk[1], chunk[0], chunk[3]])
    }
    swapped
}

/// Check if an image has any transparent pixels
///
/// VPinball dynamically scans the actual pixel data to determine transparency
/// (see Texture.cpp UpdateOpaque). We do the same here.
///
/// Note: In VPX files:
/// - `bits` = BMP (bitmap) data, always BGRA format
/// - `jpeg` = can be JPEG, PNG, or other formats (the field name is misleading)
pub fn image_has_transparency(image: &ImageData) -> bool {
    // If is_opaque is explicitly set, use it
    if let Some(is_opaque) = image.is_opaque {
        return !is_opaque;
    }

    // Check jpeg field - this can contain JPEG, PNG, or other formats
    if let Some(ref jpeg) = image.jpeg {
        // Try to decode the image to check for alpha
        if let Ok(img) = image::load_from_memory(&jpeg.data) {
            return has_transparent_pixels(&img);
        }
        return false;
    }

    // Check bitmap data - scan for any non-opaque pixels
    if let Some(ref bits) = image.bits {
        // Decompress and check raw BGRA data directly (alpha is at index 3)
        let decompressed_bgra = from_lzw_blocks(&bits.lzw_compressed_data);
        return decompressed_bgra.chunks_exact(4).any(|bgra| bgra[3] != 255);
    }

    // Default to opaque if we can't determine
    false
}

/// Check if a DynamicImage has any transparent pixels
fn has_transparent_pixels(img: &DynamicImage) -> bool {
    match img {
        DynamicImage::ImageRgba8(rgba) => rgba.pixels().any(|p| p[3] != 255),
        DynamicImage::ImageRgba16(rgba) => rgba.pixels().any(|p| p[3] != 65535),
        DynamicImage::ImageRgba32F(rgba) => rgba.pixels().any(|p| p[3] < 1.0),
        DynamicImage::ImageLumaA8(la) => la.pixels().any(|p| p[1] != 255),
        DynamicImage::ImageLumaA16(la) => la.pixels().any(|p| p[1] != 65535),
        _ => false, // RGB, Luma, etc. have no alpha
    }
}

#[cfg(test)]
mod test {

    use super::*;
    use pretty_assertions::assert_eq;

    #[test]
    fn test_write_read_jpeg() {
        let img = ImageDataJpeg {
            path: "path_value".to_string(),
            name: "name_value".to_string(),
            internal_name: Some("inme_value".to_string()),
            // alpha_test_value: 1.0,
            data: vec![1, 2, 3],
        };

        let bytes = write_jpg(&img);

        let read = read_jpeg(&mut BiffReader::new(&bytes));

        assert_eq!(read, img);
    }

    #[test]
    fn test_write_jpeg_should_have_tag_size_zero() {
        let image: ImageData = ImageData {
            name: "name_value".to_string(),
            internal_name: Some("inme_value".to_string()),
            path: "path_value".to_string(),
            width: 1,
            height: 2,
            link: None,
            alpha_test_value: 1.0,
            is_opaque: Some(true),
            is_signed: Some(false),
            jpeg: Some(ImageDataJpeg {
                path: "path_value".to_string(),
                name: "name_value".to_string(),
                internal_name: Some("inme_value".to_string()),
                // alpha_test_value: 1.0,
                data: vec![1, 2, 3],
            }),
            bits: None,
            md5_hash: None,
        };

        let mut writer = BiffWriter::new();
        ImageData::biff_write(&image, &mut writer);
        let data = writer.get_data();
        let mut reader = BiffReader::new(data);
        reader.next(false); // NAME
        reader.next(false); // INME
        reader.next(false); // PATH
        reader.next(false); // WDTH
        reader.next(false); // HGHT
        reader.next(false); // LINK
        assert_eq!(reader.tag().as_str(), "JPEG");
        assert_eq!(reader.remaining_in_record(), 0);
    }

    #[test]
    fn test_write_read() {
        let image: ImageData = ImageData {
            name: "name_value".to_string(),
            internal_name: Some("inme_value".to_string()),
            path: "path_value".to_string(),
            width: 1,
            height: 2,
            link: None,
            alpha_test_value: 1.0,
            is_opaque: Some(true),
            is_signed: Some(false),
            jpeg: Some(ImageDataJpeg {
                path: "path_value".to_string(),
                name: "name_value".to_string(),
                internal_name: Some("inme_value".to_string()),
                // alpha_test_value: 1.0,
                data: vec![1, 2, 3],
            }),
            bits: None,
            md5_hash: Some([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]),
        };
        let mut writer = BiffWriter::new();
        ImageData::biff_write(&image, &mut writer);
        let image_read = read(&mut BiffReader::new(writer.get_data()));
        assert_eq!(image, image_read);
    }

    #[test]
    fn test_write_read_json() {
        let image: ImageData = ImageData {
            name: "name_value".to_string(),
            internal_name: Some("inme_value".to_string()),
            path: "path_value".to_string(),
            width: 1,
            height: 2,
            link: None,
            alpha_test_value: 1.0,
            is_opaque: Some(true),
            is_signed: Some(false),
            jpeg: Some(ImageDataJpeg {
                path: "path_value".to_string(),
                name: "name_value".to_string(),
                internal_name: Some("inme_value".to_string()),
                // alpha_test_value: 1.0,
                data: vec![1, 2, 3],
            }),
            bits: None,
            md5_hash: Some([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]),
        };
        let image_json = ImageDataJson::from_image_data(&image);
        let mut image_read = image_json.to_image_data(1, 2, None);
        // these are populated later whe reading the actual images from the file
        if let Some(jpeg) = &mut image_read.jpeg {
            jpeg.data = vec![1, 2, 3];
        }
        image_read.width = 1;
        image_read.height = 2;
        assert_eq!(image, image_read);
    }
}