Skip to content

Craft Anything: understand how any software works, and craft your own.

Rust

Export Unity floating-point textures as PNG (R3.9) (#1088)

Afloat2a5845c64b4a
diff --git a/crates/engine/src/tools/game_archive_tools.rs b/crates/engine/src/tools/game_archive_tools.rs
index 120145bf..52833676 100644
--- a/crates/engine/src/tools/game_archive_tools.rs
+++ b/crates/engine/src/tools/game_archive_tools.rs
@@ -87,7 +87,7 @@ pub fn specs() -> Vec<ToolSpec> {
spec(
"game_unity_asset_export",
"Take an asset out of a Unity game",
- "Save one object of a Unity serialized file (absolute path of a .assets or level file, or of a bundle: then `file` picks the serialized file inside, the first by default) as a file anyone can open: a texture (Texture2D, by its path_id from game_unity_list) becomes a PNG at `output` (an absolute path that doesn't exist yet). Pixels are read inside the object or from the .resS file it streams from. Formats: Alpha8, R8, RGB24, RGBA32, ARGB32, BGRA32, RGB565, RGBA4444, ARGB4444, DXT1, DXT5, BC4, BC5, BC6H (tone-mapped to 8 bits; brighter than white clips) and BC7; others (crunched, ASTC, ETC…) are refused with their name. Unity 2017.3 and later.",
+ "Save one object of a Unity serialized file (absolute path of a .assets or level file, or of a bundle: then `file` picks the serialized file inside, the first by default) as a file anyone can open: a texture (Texture2D, by its path_id from game_unity_list) becomes a PNG at `output` (an absolute path that doesn't exist yet). Pixels are read inside the object or from the .resS file it streams from. Formats: Alpha8, R8, RGB24, RGBA32, ARGB32, BGRA32, RGB565, RGBA4444, ARGB4444, RHalf, RGHalf, RGBAHalf, RFloat, RGFloat, RGBAFloat, DXT1, DXT5, BC4, BC5, BC6H and BC7. Floating-point colours are shown in 8-bit sRGB and clip at white. Other formats (crunched, ASTC, ETC…) are refused with their name. Unity 2017.3 and later.",
"Save a picture from a Unity game as a PNG.",
Toolset::Formats,
Effects::EVIDENCE.union(Effects::WRITES_FILESYSTEM),
diff --git a/crates/formats/src/bptc.rs b/crates/formats/src/bptc.rs
index 7baf5501..54b0a6f7 100644
--- a/crates/formats/src/bptc.rs
+++ b/crates/formats/src/bptc.rs
@@ -259,18 +259,19 @@ fn bc6h_halves(block: &[u8; 16], signed: bool) -> [[u16; 3]; 16] {
}
/// A half float's value.
-fn half(h: u16) -> f32 {
+pub(crate) fn half(h: u16) -> f32 {
let sign = if h & 0x8000 == 0 { 1.0 } else { -1.0 };
let (exponent, mantissa) = (i32::from(h >> 10 & 31), f32::from(h & 1023));
sign * match exponent {
0 => mantissa * 2f32.powi(-24),
+ 31 if mantissa != 0.0 => f32::NAN,
31 => f32::INFINITY,
e => (1024.0 + mantissa) * 2f32.powi(e - 25),
}
}
/// A linear light value as an 8-bit sRGB value; 0..1 is kept, brighter and negative values clip.
-fn srgb8(v: f32) -> u8 {
+pub(crate) fn srgb8(v: f32) -> u8 {
let v = v.clamp(0.0, 1.0);
let s = if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 };
(s * 255.0 + 0.5) as u8
diff --git a/crates/formats/src/pixels.rs b/crates/formats/src/pixels.rs
index 8a204dc2..758788c2 100644
--- a/crates/formats/src/pixels.rs
+++ b/crates/formats/src/pixels.rs
@@ -15,6 +15,12 @@ pub enum Layout {
Alpha8,
/// One grey channel.
R8,
+ RHalf,
+ RgHalf,
+ RgbaHalf,
+ RFloat,
+ RgFloat,
+ RgbaFloat,
Rgb24,
Rgba32,
Argb32,
@@ -41,14 +47,33 @@ pub fn size(layout: Layout, width: u32, height: u32) -> Option<usize> {
let blocks = w.div_ceil(4).checked_mul(h.div_ceil(4))?;
match layout {
Layout::Alpha8 | Layout::R8 => w.checked_mul(h),
- Layout::Rgb565 | Layout::Rgba4444 | Layout::Argb4444 => w.checked_mul(h)?.checked_mul(2),
+ Layout::Rgb565 | Layout::Rgba4444 | Layout::Argb4444 | Layout::RHalf => w.checked_mul(h)?.checked_mul(2),
Layout::Rgb24 => w.checked_mul(h)?.checked_mul(3),
- Layout::Rgba32 | Layout::Argb32 | Layout::Bgra32 => w.checked_mul(h)?.checked_mul(4),
+ Layout::Rgba32 | Layout::Argb32 | Layout::Bgra32 | Layout::RgHalf | Layout::RFloat => w.checked_mul(h)?.checked_mul(4),
+ Layout::RgbaHalf | Layout::RgFloat => w.checked_mul(h)?.checked_mul(8),
+ Layout::RgbaFloat => w.checked_mul(h)?.checked_mul(16),
Layout::Dxt1 | Layout::Bc4 => blocks.checked_mul(8),
Layout::Dxt5 | Layout::Bc5 | Layout::Bc6h | Layout::Bc6hSigned | Layout::Bc7 => blocks.checked_mul(16),
}
}
+/// Treat RGB as linear light, alpha as coverage, and show a scalar texture in grey.
+fn float_pixels(mut samples: impl Iterator<Item = f32>, channels: usize) -> impl Iterator<Item = [u8; 4]> {
+ std::iter::from_fn(move || {
+ let r = bptc::srgb8(samples.next()?);
+ if channels == 1 {
+ return Some([r, r, r, 255]);
+ }
+ let g = bptc::srgb8(samples.next()?);
+ if channels == 2 {
+ return Some([r, g, 0, 255]);
+ }
+ let b = bptc::srgb8(samples.next()?);
+ let a = (samples.next()?.clamp(0.0, 1.0) * 255.0).round() as u8;
+ Some([r, g, b, a])
+ })
+}
+
fn expand5(v: u16) -> u8 {
let v = (v & 31) as u8;
(v << 3) | (v >> 2)
@@ -194,7 +219,14 @@ pub fn decode_with_limit(layout: Layout, width: u32, height: u32, data: &[u8], m
}
};
let u16s = data.as_chunks::<2>().0.iter().map(|b| u16::from_le_bytes(*b));
+ let floats = data.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b));
match layout {
+ Layout::RHalf => put(&mut float_pixels(u16s.map(bptc::half), 1)),
+ Layout::RgHalf => put(&mut float_pixels(u16s.map(bptc::half), 2)),
+ Layout::RgbaHalf => put(&mut float_pixels(u16s.map(bptc::half), 4)),
+ Layout::RFloat => put(&mut float_pixels(floats, 1)),
+ Layout::RgFloat => put(&mut float_pixels(floats, 2)),
+ Layout::RgbaFloat => put(&mut float_pixels(floats, 4)),
Layout::Alpha8 => put(&mut data.iter().map(|a| [255, 255, 255, *a])),
Layout::R8 => put(&mut data.iter().map(|r| [*r, *r, *r, 255])),
Layout::Rgb24 => put(&mut data.as_chunks::<3>().0.iter().map(|[r, g, b]| [*r, *g, *b, 255])),
diff --git a/crates/formats/src/unity_texture.rs b/crates/formats/src/unity_texture.rs
index 2b8359b9..246fd356 100644
--- a/crates/formats/src/unity_texture.rs
+++ b/crates/formats/src/unity_texture.rs
@@ -169,6 +169,12 @@ fn layout(format: i32) -> Option<Layout> {
12 => Layout::Dxt5,
13 => Layout::Rgba4444,
14 => Layout::Bgra32,
+ 15 => Layout::RHalf,
+ 16 => Layout::RgHalf,
+ 17 => Layout::RgbaHalf,
+ 18 => Layout::RFloat,
+ 19 => Layout::RgFloat,
+ 20 => Layout::RgbaFloat,
24 => Layout::Bc6h,
25 => Layout::Bc7,
26 => Layout::Bc4,
@@ -215,6 +221,29 @@ mod tests {
}
}
+ #[test]
+ fn floating_point_formats_keep_channel_order_and_linear_alpha() {
+ let half: Vec<_> = [0x3800u16, 0x3400, 0x3c00, 0x3800].into_iter().flat_map(u16::to_le_bytes).collect();
+ let full: Vec<_> = [0.5f32, 0.25, 1.0, 0.5].into_iter().flat_map(f32::to_le_bytes).collect();
+ for (first, bytes, component_size) in [(15, &half, 2), (18, &full, 4)] {
+ for (i, (channels, expected)) in [(1, [188, 188, 188, 255]), (2, [188, 137, 0, 255]), (4, [188, 137, 255, 128])].into_iter().enumerate() {
+ let format = first + i as i32;
+ let n = channels * component_size;
+ assert_eq!(mip0_size(format, 1, 1), Some(n));
+ assert_eq!(decode(format, 1, 1, bytes).unwrap(), expected);
+ assert!(matches!(decode(format, 1, 1, &bytes[..n - 1]), Err(FormatError::Truncated(_))));
+ }
+ }
+ }
+
+ #[test]
+ fn floating_point_rows_clip_and_keep_nan_dark() {
+ let samples: Vec<_> = [0x7c00u16, 0xfc00, 0x7e00, 0x0001].into_iter().flat_map(u16::to_le_bytes).collect();
+ assert_eq!(decode(16, 1, 2, &samples).unwrap(), [0, 0, 0, 255, 255, 0, 0, 255]);
+ let samples: Vec<_> = [-2.0f32, 2.0, f32::NAN, f32::INFINITY].into_iter().flat_map(f32::to_le_bytes).collect();
+ assert_eq!(decode(20, 1, 1, &samples).unwrap(), [0, 255, 0, 255]);
+ }
+
#[test]
fn decodes_pixels_top_row_first() {
// 1×2 RGBA32: the stored first row is the bottom one.
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index 4a15ac43..207d8583 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -1080,8 +1080,9 @@ Owner: open · Status: todo
### R3.9 Game assets out
Owner: open · Status: in progress
- [ ] Unity: sounds out (the stored stream, usually FSB5; PCM ones as WAV)
-- [ ] Unity: crunched textures (DXT1Crunched, DXT5Crunched; two of the games checked use them) and
- the float formats (RHalf, RGHalf, RGBAHalf, RFloat, RGFloat, RGBAFloat)
+- [ ] Unity: crunched textures (DXT1Crunched, DXT5Crunched; two of the games checked use them)
+- [x] Unity: the float formats (RHalf, RGHalf, RGBAHalf, RFloat, RGFloat, RGBAFloat)
+ — claimed: Afloat16, branch feature/r3.9-unity-float-textures
- [ ] Unreal 5 and Oodle: IoStore packages, unversioned properties and Oodle-compressed paks
- [ ] Game files: save pictures from IoStore containers (needs the Unreal 5 support above)
- [ ] Unreal: sounds and meshes out (so a Deep-mode rebuild needs no outside converter for them)
diff --git a/docs/STATUS.md b/docs/STATUS.md
index 76132697..f221504b 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -24,6 +24,7 @@ workspace clippy, layers, fmt and the secret scan of all history were clean. Chi
| Reject incomplete simple packet block payloads | Simple packet blocks validate captured lengths and exclude alignment padding. Rejected lengths count toward the packet scan limit and produce one summary warning when the walk ends. | Synthetic byte fixtures in `pcapng_simple_payload` integration regressions. Cover short payloads, excess payload bytes, unlimited snaplen, legitimate snaplen truncation, alignment padding, bounded warnings, and later valid frames. Unit regressions exercise rejected-only and mixed packet budgets, exact EOF, and repeated iterator exhaustion. |
| Keep ZIP directory entries within the declared directory | ZIP central-directory entries stay within the declared directory. | Synthetic byte fixtures in `zip_directory_bounds` integration regressions. Cover a short declared entry after a valid entry even without a signature, fields borrowing end-record bytes, an oversized directory, both self-extracting offset conventions, and a trailing directory signature. |
| Refuse split ZIP archives without their other volumes | ZIP archives requiring other volumes are reported as unsupported. Explicit classic directory sizes and offsets must agree with ZIP64 unless set to their own sentinel. | Synthetic byte fixtures in `zip_split_volumes` integration regressions. Cover classic disk markers and counts, ZIP64 locator and record fields, conflicting classic/ZIP64 entry counts, entry disk sentinels both alone and after the sizes and local offset, and valid single-volume controls with mixed count sentinels. Additional regressions cover explicit directory-bound conflicts and each independently saturated end field. |
+| Unity floating-point textures | The PNG exporter reads RHalf, RGHalf, RGBAHalf, RFloat, RGFloat and RGBAFloat. RGB is converted from linear light to 8-bit sRGB, alpha stays linear, and scalar textures are shown in grey. | Synthetic half- and full-precision textures cover every channel layout, short mips, row order, non-finite values and clipping. |
| Check Unity bundle blocks against their declared output lengths | Unity bundle pieces must match their declared decoded lengths; LZMA must finish within the supplied compressed piece. | Synthetic byte fixtures in `unity_bundle_decompressed_length` integration regressions. Cover stored pieces that are short or long, LZ4 and LZ4HC size mismatches, LZMA with or without end markers, empty and short zero streams, bounded dictionary/output growth, oversized dictionary properties, and truncated or trailing compressed bytes. |
| Locate Unity bundle metadata within the declared bundle size | Unity bundle metadata placement respects the declared bundle extent. | Synthetic byte fixtures in `unity_bundle_declared_size` integration regressions. Cover versions 6 through 8, front and trailing tables, padding, appended bytes, invalid extents, and header-only prefixes of larger bundles. |
| Keep Unity bundle blocks inside the data region | The shared table parser refuses compressed block totals crossing the trailing table or the declared bundle end before listing or extraction can read block contents. | Synthetic `unity_bundle_data_region` regressions cover versions 6–8, both table positions, data alignment, appended bytes, cumulative sizes above 32 bits, exact fits, spare bytes and empty blocks. No real game bundle was run for this correction. |