Skip to main content

source_vtf/
resource.rs

1use bitflags::bitflags;
2
3use crate::cursor::Cursor;
4use crate::subresource::image_data_len;
5use crate::{Error, Header, Result, Section};
6
7const RESOURCE_TABLE_OFFSET: usize = 80;
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
10#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
11#[cfg_attr(feature = "serde", serde(transparent))]
12pub struct ResourceTag(u32);
13
14impl ResourceTag {
15    pub const THUMBNAIL_DATA: Self = Self(0x000001);
16    pub const PALETTE_DATA: Self = Self(0x000002);
17    pub const FALLBACK_DATA: Self = Self(0x000003);
18    pub const PARTICLE_SHEET_DATA: Self = Self(0x000010);
19    pub const HOTSPOT_DATA: Self = Self(0x00002b);
20    pub const IMAGE_DATA: Self = Self(0x000030);
21    pub const EXTENDED_FLAGS: Self = Self::from_bytes(*b"TS0");
22    pub const CRC: Self = Self::from_bytes(*b"CRC");
23    pub const AUX_COMPRESSION: Self = Self::from_bytes(*b"AXC");
24    pub const LOD_CONTROL_INFO: Self = Self::from_bytes(*b"LOD");
25    pub const KEY_VALUES_DATA: Self = Self::from_bytes(*b"KVD");
26    pub const AUTHOR_INFO: Self = Self::from_bytes(*b"ATH");
27
28    pub const fn from_bytes(bytes: [u8; 3]) -> Self {
29        Self(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], 0]))
30    }
31
32    pub const fn value(self) -> u32 {
33        self.0
34    }
35
36    pub const fn to_bytes(self) -> [u8; 3] {
37        let bytes = self.0.to_le_bytes();
38        [bytes[0], bytes[1], bytes[2]]
39    }
40}
41
42bitflags! {
43    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
44    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
45    pub struct ResourceFlags: u8 {
46        /// The four bytes in the directory entry are the payload itself, not an offset.
47        const LOCAL_DATA = 1 << 1;
48    }
49}
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
53pub enum ResourceLocation {
54    Inline([u8; 4]),
55    Data { offset: usize, length: usize },
56}
57
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
60pub struct Resource {
61    tag: ResourceTag,
62    flags: ResourceFlags,
63    location: ResourceLocation,
64}
65
66impl Resource {
67    pub const fn tag(&self) -> ResourceTag {
68        self.tag
69    }
70
71    pub const fn flags(&self) -> ResourceFlags {
72        self.flags
73    }
74
75    pub const fn location(&self) -> &ResourceLocation {
76        &self.location
77    }
78}
79
80pub(crate) fn parse(bytes: &[u8], header: &Header) -> Result<Vec<Resource>> {
81    if !header.version().has_resource_table() {
82        return legacy_resources(bytes, header);
83    }
84
85    let header_size =
86        usize::try_from(header.header_size()).map_err(|_| Error::ArithmeticOverflow {
87            context: "VTF header size",
88        })?;
89    let table = bytes
90        .get(RESOURCE_TABLE_OFFSET..header_size)
91        .ok_or(Error::RangeOutOfBounds {
92            section: Section::ResourceTable,
93            offset: RESOURCE_TABLE_OFFSET,
94            end: header_size,
95            file_size: bytes.len(),
96        })?;
97    let mut cursor = Cursor::new(table, Section::ResourceTable);
98    let count =
99        usize::try_from(header.resource_count()).map_err(|_| Error::ArithmeticOverflow {
100            context: "VTF resource count",
101        })?;
102    let mut pending = Vec::new();
103    pending
104        .try_reserve_exact(count)
105        .map_err(|_| Error::ResourceAllocation {
106            count: header.resource_count(),
107        })?;
108
109    for _ in 0..count {
110        let type_and_flags = cursor.read_u32()?;
111        let tag = ResourceTag(type_and_flags & 0x00ff_ffff);
112        let flags = ResourceFlags::from_bits_retain((type_and_flags >> 24) as u8);
113        let value_bytes = cursor.read_u32()?.to_le_bytes();
114
115        if pending
116            .iter()
117            .any(|entry: &PendingResource| entry.tag == tag)
118        {
119            return Err(Error::DuplicateResource { tag: tag.value() });
120        }
121
122        let value = if flags.contains(ResourceFlags::LOCAL_DATA) {
123            PendingValue::Inline(value_bytes)
124        } else {
125            PendingValue::Offset(u32::from_le_bytes(value_bytes))
126        };
127        pending.push(PendingResource { tag, flags, value });
128    }
129
130    let mut offsets = pending
131        .iter()
132        .filter_map(|entry| match entry.value {
133            PendingValue::Inline(_) => None,
134            PendingValue::Offset(offset) => Some((usize::try_from(offset).ok(), entry.tag)),
135        })
136        .map(|(offset, tag)| {
137            offset
138                .ok_or(Error::ArithmeticOverflow {
139                    context: "VTF resource offset",
140                })
141                .map(|offset| (offset, tag))
142        })
143        .collect::<Result<Vec<_>>>()?;
144    offsets.sort_unstable_by_key(|&(offset, _)| offset);
145
146    for pair in offsets.windows(2) {
147        if pair[0].0 == pair[1].0 {
148            return Err(Error::DuplicateResourceOffset { offset: pair[0].0 });
149        }
150    }
151    for &(offset, tag) in &offsets {
152        if offset < header_size {
153            return Err(Error::ResourceInsideHeader {
154                tag: tag.value(),
155                offset,
156                header_size,
157            });
158        }
159        if offset > bytes.len() {
160            return Err(Error::RangeOutOfBounds {
161                section: Section::ResourceData,
162                offset,
163                end: offset,
164                file_size: bytes.len(),
165            });
166        }
167    }
168
169    let mut resources = Vec::new();
170    resources
171        .try_reserve_exact(count)
172        .map_err(|_| Error::ResourceAllocation {
173            count: header.resource_count(),
174        })?;
175    for entry in pending {
176        let location = match entry.value {
177            PendingValue::Inline(data) => ResourceLocation::Inline(data),
178            PendingValue::Offset(raw_offset) => {
179                let offset =
180                    usize::try_from(raw_offset).map_err(|_| Error::ArithmeticOverflow {
181                        context: "VTF resource offset",
182                    })?;
183                let position = offsets
184                    .binary_search_by_key(&offset, |&(candidate, _)| candidate)
185                    .map_err(|_| Error::MissingResource {
186                        tag: entry.tag.value(),
187                    })?;
188                let end = offsets
189                    .get(position + 1)
190                    .map_or(bytes.len(), |&(next_offset, _)| next_offset);
191                ResourceLocation::Data {
192                    offset,
193                    length: end - offset,
194                }
195            }
196        };
197        resources.push(Resource {
198            tag: entry.tag,
199            flags: entry.flags,
200            location,
201        });
202    }
203
204    validate_texture_resources(&resources, header)?;
205    Ok(resources)
206}
207
208fn legacy_resources(bytes: &[u8], header: &Header) -> Result<Vec<Resource>> {
209    let header_size =
210        usize::try_from(header.header_size()).map_err(|_| Error::ArithmeticOverflow {
211            context: "VTF header size",
212        })?;
213    let thumbnail_length = match header.thumbnail_format() {
214        Some(format) => format.byte_len(
215            u16::from(header.thumbnail_width()),
216            u16::from(header.thumbnail_height()),
217        )?,
218        None => 0,
219    };
220    let image_offset =
221        header_size
222            .checked_add(thumbnail_length)
223            .ok_or(Error::ArithmeticOverflow {
224                context: "legacy VTF image offset",
225            })?;
226    ensure_range(
227        Section::ThumbnailData,
228        header_size,
229        image_offset,
230        bytes.len(),
231    )?;
232
233    let image_length = image_data_len(header)?;
234    let image_end = image_offset
235        .checked_add(image_length)
236        .ok_or(Error::ArithmeticOverflow {
237            context: "legacy VTF image end",
238        })?;
239    ensure_range(Section::ImageData, image_offset, image_end, bytes.len())?;
240
241    let mut resources = Vec::with_capacity(2);
242    if thumbnail_length != 0 {
243        resources.push(Resource {
244            tag: ResourceTag::THUMBNAIL_DATA,
245            flags: ResourceFlags::empty(),
246            location: ResourceLocation::Data {
247                offset: header_size,
248                length: thumbnail_length,
249            },
250        });
251    }
252    resources.push(Resource {
253        tag: ResourceTag::IMAGE_DATA,
254        flags: ResourceFlags::empty(),
255        location: ResourceLocation::Data {
256            offset: image_offset,
257            length: image_length,
258        },
259    });
260    Ok(resources)
261}
262
263fn validate_texture_resources(resources: &[Resource], header: &Header) -> Result<()> {
264    let image = find(resources, ResourceTag::IMAGE_DATA).ok_or(Error::MissingResource {
265        tag: ResourceTag::IMAGE_DATA.value(),
266    })?;
267    let image_length = image_data_len(header)?;
268    validate_data_resource(image, image_length, Section::ImageData)?;
269
270    let thumbnail_length = match header.thumbnail_format() {
271        Some(format) => format.byte_len(
272            u16::from(header.thumbnail_width()),
273            u16::from(header.thumbnail_height()),
274        )?,
275        None => 0,
276    };
277    if thumbnail_length != 0 {
278        let thumbnail =
279            find(resources, ResourceTag::THUMBNAIL_DATA).ok_or(Error::MissingResource {
280                tag: ResourceTag::THUMBNAIL_DATA.value(),
281            })?;
282        validate_data_resource(thumbnail, thumbnail_length, Section::ThumbnailData)?;
283    }
284    Ok(())
285}
286
287fn validate_data_resource(resource: &Resource, expected: usize, section: Section) -> Result<()> {
288    match resource.location {
289        ResourceLocation::Inline(_) => Err(Error::InlineTextureData {
290            tag: resource.tag.value(),
291        }),
292        ResourceLocation::Data { length, .. } if length < expected => Err(Error::DataTooShort {
293            section,
294            expected,
295            actual: length,
296        }),
297        ResourceLocation::Data { .. } => Ok(()),
298    }
299}
300
301fn find(resources: &[Resource], tag: ResourceTag) -> Option<&Resource> {
302    resources.iter().find(|resource| resource.tag == tag)
303}
304
305fn ensure_range(section: Section, offset: usize, end: usize, file_size: usize) -> Result<()> {
306    if end > file_size {
307        return Err(Error::RangeOutOfBounds {
308            section,
309            offset,
310            end,
311            file_size,
312        });
313    }
314    Ok(())
315}
316
317#[derive(Debug, Clone, Copy)]
318struct PendingResource {
319    tag: ResourceTag,
320    flags: ResourceFlags,
321    value: PendingValue,
322}
323
324#[derive(Debug, Clone, Copy)]
325enum PendingValue {
326    Inline([u8; 4]),
327    Offset(u32),
328}