mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-29 09:34:33 +01:00
Merge pull request #136 from SteamSmith/feat/embed-colour-space
Export: record the chosen colour space in the files
This commit is contained in:
8 files changed
+398
-13
No files matched your search
+1
-1
@@ -19,7 +19,7 @@ end to end today (engine + UI + automation + tests), not what is planned.
|
||||
| Baking | 10 | 100% | AO, curvature (also from the normal map), thickness, world normal, position, ID, normal, height, **bent normals, opacity, color map and world-space direction**; **high-poly meshes**, cage, frontal/rear distances, average normals, **match by mesh name**; per-texture-set selection, common and per-map parameters, progress and cancel; **Auto-rebake** (`bake.autoRebake`: one map bakes itself again in the background when its bake settings, the low poly or the high polys change); **mesh maps from images** (baked elsewhere or edited) dropped on a slot; high-poly base color textures embedded or in files beside a `.gltf`, FBX or USD layer | — |
|
||||
| Viewport and display | 12 | 95% | PBR with image-based lighting, 6 procedural environments or imported HDR/EXR panoramas with exposure, rotation, blur, opacity, ACES/linear tone mapping, HDR pipeline with bloom, vignette, sharpen and grain, key-light shadows, 4× MSAA plus idle temporal accumulation, the baked normal map under the painted normal, channel / mesh-map / mask / UV checker views, 3D and 2D wireframes of the mesh's own polygons, brush cursor, axis gizmos, subsurface scattering blur, **depth of field**, saved cameras and cameras from glTF, FBX, COLLADA and USD files, displacement (also in shadows and the path tracers), **path-traced Rendering mode** (F10, on the GPU or the CPU) with environment importance sampling and an edge-aware **denoiser**; picks a discrete GPU on multi-GPU machines (`--gpu`, `WGPU_ADAPTER_NAME`, `WGPU_POWER_PREF`), and display textures are made on demand so a mesh with many materials imports on a small GPU | Hardware ray tracing |
|
||||
| Shader | 6 | 100% | Metallic/roughness and specular/glossiness PBR, **clear coat, sheen, anisotropy and subsurface scattering** (viewport and path tracer), height-to-normal, painted normals, parallax occlusion, emissive, opacity (dithered), AO intensity | — |
|
||||
| Export | 8 | 92% | 10 presets (incl. Godot 4 and **OpenPBR** with every shading lobe) plus **user output templates** (per-channel packing, converted maps, JSON import/export), PNG/JPEG/TGA/TIFF/BMP/WEBP/EXR/HDR, 8/16/32-bit, padding modes, size override, OpenGL/DirectX normals, **colour space** of the colour maps (sRGB, Linear Rec.709, ACEScg, ACES2065-1; data maps never converted), `$udim` tiles, **MaterialX** (`file.exportTextures` with `materialX`: a `.mtlx` OpenPBR material per set, `<UDIM>` aware), OBJ, textured GLB (with clearcoat/sheen) and USD (with clear coat) mesh export, zip download in the browser | Sheen and anisotropy in USD (UsdPreviewSurface has no inputs for them; GLB and OpenPBR maps carry them) |
|
||||
| Export | 8 | 92% | 10 presets (incl. Godot 4 and **OpenPBR** with every shading lobe) plus **user output templates** (per-channel packing, converted maps, JSON import/export), PNG/JPEG/TGA/TIFF/BMP/WEBP/EXR/HDR, 8/16/32-bit, padding modes, size override, OpenGL/DirectX normals, **colour space** of the colour maps (sRGB, Linear Rec.709, ACEScg, ACES2065-1; data maps never converted; the chosen space is recorded in the file as an ICC profile in PNG, JPEG, TIFF and WebP and as chromaticities in EXR), `$udim` tiles, **MaterialX** (`file.exportTextures` with `materialX`: a `.mtlx` OpenPBR material per set, `<UDIM>` aware), OBJ, textured GLB (with clearcoat/sheen) and USD (with clear coat) mesh export, zip download in the browser | Sheen and anisotropy in USD (UsdPreviewSurface has no inputs for them; GLB and OpenPBR maps carry them) |
|
||||
| UI and UX | 8 | 97% | Painter-style layout with **dockable, tabbed, floating panels**, menus, tool shelf, tool bar, asset shelf, texture set list, layer stack with context menu, properties, display/shader/history/log panels, export dialog, new project dialog, bake mode, rendering mode, settings (interface scale, autosave, viewport texture resolution, system title bar), **own title bar** with the app icon and window buttons (Windows, GNOME; integrated with the macOS traffic lights), saved UI layouts, a **History** panel that jumps to any step (back or forward), a **start window** (new, open, recent projects), **shortcut editor** with conflict detection, tooltips with shortcuts, a compact color picker (saturation/value square, hue strip, copyable RGB); all menu items live ([docs/parity.md](docs/parity.md)); **10 UI languages** with CJK and Arabic fonts ([docs/localization-parity.md](docs/localization-parity.md)); closed panels reopen where they were; frame-budgeted compositing and uploads keep 8K sets responsive | Native-speaker review of the translations |
|
||||
| Platforms | 4 | 76% | Windows, macOS (universal, signed and notarized), Linux (AppImage, deb, rpm, tar.gz, Flatpak), FreeBSD and web release workflows | First real release run; web build polish |
|
||||
| **Total** | **100** | **≈ 94%** | | |
|
||||
|
||||
@@ -42,7 +42,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export textures",
|
||||
["File"],
|
||||
None,
|
||||
"{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|\"all\", format?: png|jpg|tga|tif|exr|..., bitDepth?, padding?: none|dilation|dilationDefault|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1), materialX?: bool (also write a .mtlx OpenPBR material per texture set; needs the \"OpenPBR (separate maps)\" preset)}",
|
||||
"{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|\"all\", format?: png|jpg|tga|tif|exr|..., bitDepth?, padding?: none|dilation|dilationDefault|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, TIFF and WebP, the chromaticities in EXR; TGA, BMP and HDR can't hold one and warn), materialX?: bool (also write a .mtlx OpenPBR material per texture set; needs the \"OpenPBR (separate maps)\" preset)}",
|
||||
always,
|
||||
export_textures
|
||||
),
|
||||
|
||||
@@ -60,3 +60,38 @@ fn the_plan_reports_the_space_and_clamping_and_bad_names_are_errors() {
|
||||
}
|
||||
assert!(execute(&mut s, "export.plan", &json!({ "preset": "glTF PBR Metal Roughness", "colorSpace": null })).is_ok());
|
||||
}
|
||||
|
||||
fn png_icc(path: &str) -> Option<Vec<u8>> {
|
||||
use image::ImageDecoder;
|
||||
let file = std::io::BufReader::new(std::fs::File::open(path).unwrap());
|
||||
image::codecs::png::PngDecoder::new(file).unwrap().icc_profile().unwrap()
|
||||
}
|
||||
|
||||
fn find<'a>(r: &'a Value, part: &str) -> &'a str {
|
||||
r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap()).find(|f| f.contains(part)).unwrap_or_else(|| panic!("no {part} in {r}"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_chosen_colour_space_is_recorded_in_colour_maps_only() {
|
||||
let mut s = session();
|
||||
let png = |extra: Value| {
|
||||
let mut p = json!({ "format": "png", "bitDepth": 8 });
|
||||
for (k, v) in extra.as_object().unwrap() {
|
||||
p[k] = v.clone();
|
||||
}
|
||||
p
|
||||
};
|
||||
let (default, d0) = export(&mut s, "icc_default", png(json!({})));
|
||||
assert_eq!(png_icc(find(&default, "BaseColor")), None, "nothing is written unless a space is chosen");
|
||||
let (aces, d1) = export(&mut s, "icc_aces", png(json!({ "colorSpace": "ACEScg" })));
|
||||
let icc = png_icc(find(&aces, "BaseColor")).expect("the base colour map carries a profile");
|
||||
assert!(icc.windows(6).any(|w| w == b"ACEScg"), "the profile names its space");
|
||||
assert_eq!(Some(icc), texturecraft_formats::icc::profile(ColorSpace::AcesCg));
|
||||
assert_eq!(png_icc(find(&aces, "Normal")), None, "a normal map is data and has no colour space");
|
||||
// Formats that can't hold one say so, once per colour map.
|
||||
let (tga, d2) = export(&mut s, "icc_tga", png(json!({ "colorSpace": "ACEScg", "format": "tga" })));
|
||||
assert!(tga["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("TGA") && w.as_str().unwrap().contains("colour space")), "{tga}");
|
||||
for d in [d0, d1, d2] {
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
}
|
||||
@@ -768,7 +768,9 @@ pub fn render_maps(input: &ExportInput, opts: &ExportOptions) -> Result<Vec<Expo
|
||||
warnings.push(format!("\"{}\" packs colour into one channel (L), so it is written in linear Rec.709, not {}", p.name, space.name()));
|
||||
}
|
||||
let srgb: Vec<bool> = lay.iter().map(|(d, _)| *d != Dest::A && is_color(map) && !p.format.is_float() && space == ColorSpace::Srgb).collect();
|
||||
let bytes = encode(p.format, p.bit_depth, size, n, &data, &srgb, &mut warnings)?;
|
||||
// A colour space the user chose is written into the colour maps (data maps have none).
|
||||
let embed = (opts.color_space.is_some() && is_color(map) && rgb).then_some(space);
|
||||
let bytes = encode(p.format, p.bit_depth, size, n, &data, &srgb, embed, &mut warnings)?;
|
||||
Ok(ExportedFile { name: p.name, bytes, width: size.0, height: size.1, warnings })
|
||||
})
|
||||
.collect()
|
||||
@@ -812,17 +814,34 @@ fn resize(data: Vec<f32>, from: (u32, u32), n: usize, to: (u32, u32)) -> Vec<f32
|
||||
|
||||
/// Encode a `size` (width, height) image of `n` components (1 L, 2 LA, 3 RGB, 4 RGBA; linear
|
||||
/// values).
|
||||
fn encode(format: FileFormat, depth: u8, size: (u32, u32), n: usize, data: &[f32], srgb: &[bool], warnings: &mut Vec<String>) -> Result<Vec<u8>> {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn encode(
|
||||
format: FileFormat,
|
||||
depth: u8,
|
||||
size: (u32, u32),
|
||||
n: usize,
|
||||
data: &[f32],
|
||||
srgb: &[bool],
|
||||
embed: Option<ColorSpace>,
|
||||
warnings: &mut Vec<String>,
|
||||
) -> Result<Vec<u8>> {
|
||||
let failed = |e: &dyn std::fmt::Display| FormatError::Invalid(format!("{} encoding failed: {e}", format.extension()));
|
||||
// Where the colour space goes: an ICC profile in PNG, JPEG, TIFF and WebP, the chromaticities
|
||||
// attribute in EXR. The other formats have no place for it.
|
||||
if let Some(space) = embed
|
||||
&& matches!(format, FileFormat::Tga | FileFormat::Bmp | FileFormat::Hdr)
|
||||
{
|
||||
warnings.push(format!("{} files can't record a colour space; the colours are in {}", format.extension().to_ascii_uppercase(), space.name()));
|
||||
}
|
||||
match format {
|
||||
FileFormat::Exr => return write_exr(size, n, data, depth == 16).map_err(|e| failed(&e)),
|
||||
FileFormat::Exr => return write_exr(size, n, data, depth == 16, embed).map_err(|e| failed(&e)),
|
||||
FileFormat::Hdr => {
|
||||
if n == 2 || n == 4 {
|
||||
warnings.push("HDR has no alpha channel; alpha was dropped".into());
|
||||
}
|
||||
let rgb = remap(data, n, if n <= 2 { &[0, 0, 0] } else { &[0, 1, 2] });
|
||||
let bytes: Vec<u8> = rgb.iter().flat_map(|v| v.to_ne_bytes()).collect();
|
||||
return write_image(format, &bytes, size, image::ExtendedColorType::Rgb32F).map_err(|e| failed(&e));
|
||||
return write_image(format, &bytes, size, image::ExtendedColorType::Rgb32F, None).map_err(|e| failed(&e));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -845,7 +864,8 @@ fn encode(format: FileFormat, depth: u8, size: (u32, u32), n: usize, data: &[f32
|
||||
let b: Vec<u8> = encoded.iter().map(|v| (v * 255.0 + 0.5) as u8).collect();
|
||||
(b, [C::L8, C::La8, C::Rgb8, C::Rgba8].get(n.wrapping_sub(1)).copied().unwrap_or(C::Rgba8))
|
||||
};
|
||||
write_image(format, &bytes, size, color).map_err(|e| failed(&e))
|
||||
let icc = embed.and_then(crate::icc::profile);
|
||||
write_image(format, &bytes, size, color, icc).map_err(|e| failed(&e))
|
||||
}
|
||||
|
||||
/// Pick components `pick` from every texel of an `n`-component image.
|
||||
@@ -853,12 +873,42 @@ fn remap(data: &[f32], n: usize, pick: &[usize]) -> Vec<f32> {
|
||||
data.chunks_exact(n.max(1)).flat_map(|px| pick.iter().map(|k| px.get(*k).copied().unwrap_or(0.0))).collect()
|
||||
}
|
||||
|
||||
fn write_image(format: FileFormat, bytes: &[u8], (w, h): (u32, u32), color: image::ExtendedColorType) -> image::ImageResult<Vec<u8>> {
|
||||
/// Encode `bytes` as `format`, with `icc` (an ICC profile) embedded where the format has a place for one.
|
||||
fn write_image(format: FileFormat, bytes: &[u8], (w, h): (u32, u32), color: image::ExtendedColorType, icc: Option<Vec<u8>>) -> image::ImageResult<Vec<u8>> {
|
||||
use image::ImageEncoder;
|
||||
let mut out = Cursor::new(Vec::new());
|
||||
// `set_icc_profile` says no (an error to ignore) for an encoder without a place for it.
|
||||
let fmt = match format {
|
||||
FileFormat::Jpeg => {
|
||||
use image::ImageEncoder;
|
||||
image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, JPEG_QUALITY).write_image(bytes, w, h, color)?;
|
||||
let mut enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, JPEG_QUALITY);
|
||||
if let Some(p) = icc {
|
||||
let _ = enc.set_icc_profile(p);
|
||||
}
|
||||
enc.write_image(bytes, w, h, color)?;
|
||||
return Ok(out.into_inner());
|
||||
}
|
||||
FileFormat::Png if icc.is_some() => {
|
||||
let mut enc = image::codecs::png::PngEncoder::new(&mut out);
|
||||
if let Some(p) = icc {
|
||||
let _ = enc.set_icc_profile(p);
|
||||
}
|
||||
enc.write_image(bytes, w, h, color)?;
|
||||
return Ok(out.into_inner());
|
||||
}
|
||||
FileFormat::Tiff if icc.is_some() => {
|
||||
let mut enc = image::codecs::tiff::TiffEncoder::new(&mut out);
|
||||
if let Some(p) = icc {
|
||||
let _ = enc.set_icc_profile(p);
|
||||
}
|
||||
enc.write_image(bytes, w, h, color)?;
|
||||
return Ok(out.into_inner());
|
||||
}
|
||||
FileFormat::Webp if icc.is_some() => {
|
||||
let mut enc = image::codecs::webp::WebPEncoder::new_lossless(&mut out);
|
||||
if let Some(p) = icc {
|
||||
let _ = enc.set_icc_profile(p);
|
||||
}
|
||||
enc.write_image(bytes, w, h, color)?;
|
||||
return Ok(out.into_inner());
|
||||
}
|
||||
FileFormat::Png => image::ImageFormat::Png,
|
||||
@@ -874,7 +924,7 @@ fn write_image(format: FileFormat, bytes: &[u8], (w, h): (u32, u32), color: imag
|
||||
}
|
||||
|
||||
/// OpenEXR with Y / YA / RGB / RGBA channels, half or full float, ZIP compression.
|
||||
fn write_exr((w, h): (u32, u32), n: usize, data: &[f32], half: bool) -> exr::error::Result<Vec<u8>> {
|
||||
fn write_exr((w, h): (u32, u32), n: usize, data: &[f32], half: bool, space: Option<ColorSpace>) -> exr::error::Result<Vec<u8>> {
|
||||
use exr::prelude::*;
|
||||
let names: &[&str] = match n {
|
||||
1 => &["Y"],
|
||||
@@ -893,7 +943,12 @@ fn write_exr((w, h): (u32, u32), n: usize, data: &[f32], half: bool) -> exr::err
|
||||
.collect();
|
||||
let layer = Layer::new((w as usize, h as usize), LayerAttributes::default(), Encoding::SMALL_LOSSLESS, AnyChannels::sort(channels));
|
||||
let mut out = Cursor::new(Vec::new());
|
||||
let image = Image::from_layer(layer);
|
||||
let mut image = Image::from_layer(layer);
|
||||
// The primaries and white point of the values, in the attribute OpenEXR readers look for.
|
||||
if let Some(space) = space {
|
||||
let [r, g, b, white] = space.chromaticities().map(|xy| Vec2(xy[0] as f32, xy[1] as f32));
|
||||
image.attributes.chromaticities = Some(exr::meta::attribute::Chromaticities { red: r, green: g, blue: b, white });
|
||||
}
|
||||
let writer = image.write();
|
||||
// No worker threads on the web.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
|
||||
@@ -563,7 +563,13 @@ fn colour_space_converts_colour_maps_only() {
|
||||
let default_png = fx.render(&ExportOptions::new(preset.clone()));
|
||||
let mut srgb = ExportOptions::new(preset.clone());
|
||||
srgb.color_space = Some(ColorSpace::Srgb);
|
||||
assert_eq!(find(&default_png, "_BaseColor.png").bytes, find(&fx.render(&srgb), "_BaseColor.png").bytes);
|
||||
let srgb_png = fx.render(&srgb);
|
||||
assert_eq!(decode(find(&default_png, "_BaseColor.png")).to_rgb8(), decode(find(&srgb_png, "_BaseColor.png")).to_rgb8());
|
||||
// The chosen one is written into the file as its profile; the default says nothing, as before.
|
||||
assert_eq!(embedded_icc(FileFormat::Png, &find(&srgb_png, "_BaseColor.png").bytes), crate::icc::profile(ColorSpace::Srgb));
|
||||
assert_eq!(embedded_icc(FileFormat::Png, &find(&default_png, "_BaseColor.png").bytes), None);
|
||||
// Data maps carry none, even when a space is chosen.
|
||||
assert_eq!(embedded_icc(FileFormat::Png, &find(&srgb_png, "_Normal.png").bytes), None);
|
||||
// An explicit sRGB in a float file is encoded once, not twice.
|
||||
let mut float_srgb = ExportOptions::new(preset);
|
||||
float_srgb.format_override = Some(FileFormat::Exr);
|
||||
@@ -615,3 +621,67 @@ fn colour_packed_into_one_channel_warns_instead_of_converting_silently() {
|
||||
assert!(fx.render(&opts(Some(ColorSpace::AcesCg)))[0].warnings.iter().any(|w| w.contains("ACEScg")));
|
||||
assert!(fx.render(&opts(None))[0].warnings.is_empty(), "linear Rec.709 needs no conversion");
|
||||
}
|
||||
|
||||
/// The ICC profile a PNG, TIFF, JPEG or WebP file carries.
|
||||
fn embedded_icc(format: FileFormat, bytes: &[u8]) -> Option<Vec<u8>> {
|
||||
use image::ImageDecoder;
|
||||
let c = || Cursor::new(bytes);
|
||||
match format {
|
||||
FileFormat::Png => image::codecs::png::PngDecoder::new(c()).ok()?.icc_profile().ok()?,
|
||||
FileFormat::Tiff => image::codecs::tiff::TiffDecoder::new(c()).ok()?.icc_profile().ok()?,
|
||||
FileFormat::Jpeg => image::codecs::jpeg::JpegDecoder::new(c()).ok()?.icc_profile().ok()?,
|
||||
FileFormat::Webp => image::codecs::webp::WebPDecoder::new(c()).ok()?.icc_profile().ok()?,
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_chosen_colour_space_is_embedded_as_an_icc_profile() {
|
||||
let data = vec![0.25f32; 8 * 8 * 3];
|
||||
for format in [FileFormat::Png, FileFormat::Tiff, FileFormat::Jpeg, FileFormat::Webp] {
|
||||
for depth in [8u8, 16] {
|
||||
if depth == 16 && matches!(format, FileFormat::Jpeg | FileFormat::Webp) {
|
||||
continue;
|
||||
}
|
||||
for space in ColorSpace::ALL {
|
||||
let mut warnings = Vec::new();
|
||||
let bytes = encode(format, depth, (8, 8), 3, &data, &[false; 3], Some(space), &mut warnings).unwrap();
|
||||
assert_eq!(embedded_icc(format, &bytes), crate::icc::profile(space), "{format:?} {depth}-bit {space:?}");
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
}
|
||||
// No colour space chosen (a data map, or the default): nothing is embedded.
|
||||
let bytes = encode(format, depth, (8, 8), 3, &data, &[false; 3], None, &mut Vec::new()).unwrap();
|
||||
assert_eq!(embedded_icc(format, &bytes), None, "{format:?} {depth}-bit");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exr_carries_the_chromaticities_of_the_space() {
|
||||
let data = vec![0.25f32; 4 * 4 * 3];
|
||||
let read = |bytes: &[u8]| {
|
||||
let meta = exr::meta::MetaData::read_from_buffered(Cursor::new(bytes), false).unwrap();
|
||||
meta.headers[0].shared_attributes.chromaticities
|
||||
};
|
||||
assert!(read(&encode(FileFormat::Exr, 16, (4, 4), 3, &data, &[false; 3], None, &mut Vec::new()).unwrap()).is_none());
|
||||
for space in ColorSpace::ALL {
|
||||
let c = read(&encode(FileFormat::Exr, 32, (4, 4), 3, &data, &[false; 3], Some(space), &mut Vec::new()).unwrap()).unwrap_or_else(|| panic!("{space:?}"));
|
||||
let [r, g, b, w] = space.chromaticities();
|
||||
for (got, want) in [(c.red, r), (c.green, g), (c.blue, b), (c.white, w)] {
|
||||
assert!((f64::from(got.0) - want[0]).abs() < 1e-5 && (f64::from(got.1) - want[1]).abs() < 1e-5, "{space:?}: {got:?} vs {want:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formats_without_a_place_for_a_colour_space_say_so() {
|
||||
let data = vec![0.25f32; 4 * 4 * 3];
|
||||
for format in [FileFormat::Tga, FileFormat::Bmp, FileFormat::Hdr] {
|
||||
let mut warnings = Vec::new();
|
||||
encode(format, 8, (4, 4), 3, &data, &[false; 3], Some(ColorSpace::AcesCg), &mut warnings).unwrap();
|
||||
assert!(warnings.iter().any(|w| w.contains("colour space") && w.contains("ACEScg")), "{format:?}: {warnings:?}");
|
||||
let mut quiet = Vec::new();
|
||||
encode(format, 8, (4, 4), 3, &data, &[false; 3], None, &mut quiet).unwrap();
|
||||
assert!(quiet.is_empty(), "{format:?}: nothing to say without a chosen space: {quiet:?}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
//! ICC profiles for the export colour spaces: a version 2.1 matrix/curve display profile, small
|
||||
//! (about 1.2 KiB) and readable by every colour-managed viewer and editor.
|
||||
//!
|
||||
//! The colorants come from the space's primaries adapted to the D50 profile connection space
|
||||
//! (see `ColorSpace::to_xyz_d50`). sRGB carries its transfer curve as a sampled table; the linear
|
||||
//! spaces carry a gamma of 1. Written from the ICC.1:2001-04 specification; nothing is copied
|
||||
//! from a colour-management library or from another profile.
|
||||
|
||||
use texturecraft_texel::{ColorSpace, srgb_to_linear};
|
||||
|
||||
/// Samples of the sRGB curve table.
|
||||
const CURVE_POINTS: usize = 1024;
|
||||
/// The D50 white of the profile connection space.
|
||||
const D50_XYZ: [f64; 3] = [0.9642, 1.0, 0.8249];
|
||||
|
||||
fn s15f16(v: f64) -> [u8; 4] {
|
||||
((v * 65536.0).round().clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32).to_be_bytes()
|
||||
}
|
||||
|
||||
fn xyz_tag(v: [f64; 3]) -> Vec<u8> {
|
||||
let mut b = b"XYZ \0\0\0\0".to_vec();
|
||||
for c in v {
|
||||
b.extend_from_slice(&s15f16(c));
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
fn text_tag(text: &str) -> Vec<u8> {
|
||||
let mut b = b"text\0\0\0\0".to_vec();
|
||||
b.extend_from_slice(text.as_bytes());
|
||||
b.push(0);
|
||||
b
|
||||
}
|
||||
|
||||
/// `textDescriptionType` with the ASCII description only.
|
||||
fn desc_tag(text: &str) -> Vec<u8> {
|
||||
let mut b = b"desc\0\0\0\0".to_vec();
|
||||
b.extend_from_slice(&(text.len() as u32 + 1).to_be_bytes());
|
||||
b.extend_from_slice(text.as_bytes());
|
||||
b.push(0);
|
||||
// No Unicode text and no Macintosh ScriptCode text: empty fields and the 67-byte filler.
|
||||
b.extend_from_slice(&[0; 4 + 4 + 2 + 1 + 67]);
|
||||
b
|
||||
}
|
||||
|
||||
fn curve_tag(space: ColorSpace) -> Vec<u8> {
|
||||
let mut b = b"curv\0\0\0\0".to_vec();
|
||||
if space == ColorSpace::Srgb {
|
||||
b.extend_from_slice(&(CURVE_POINTS as u32).to_be_bytes());
|
||||
for i in 0..CURVE_POINTS {
|
||||
let v = f64::from(srgb_to_linear(i as f32 / (CURVE_POINTS - 1) as f32));
|
||||
b.extend_from_slice(&((v * 65535.0).round().clamp(0.0, 65535.0) as u16).to_be_bytes());
|
||||
}
|
||||
} else {
|
||||
// One entry is a gamma, u8Fixed8: 1.0 is linear.
|
||||
b.extend_from_slice(&1u32.to_be_bytes());
|
||||
b.extend_from_slice(&0x0100u16.to_be_bytes());
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
fn description(space: ColorSpace) -> &'static str {
|
||||
match space {
|
||||
ColorSpace::Srgb => "sRGB (Rec.709 primaries, sRGB curve)",
|
||||
ColorSpace::LinearRec709 => "Linear Rec.709 (sRGB primaries, D65)",
|
||||
ColorSpace::AcesCg => "ACEScg (AP1 primaries, linear)",
|
||||
ColorSpace::Aces2065 => "ACES2065-1 (AP0 primaries, linear)",
|
||||
}
|
||||
}
|
||||
|
||||
/// The ICC profile of `space`, or None if its primaries are degenerate (never for the built-in ones).
|
||||
pub fn profile(space: ColorSpace) -> Option<Vec<u8>> {
|
||||
let m = space.to_xyz_d50()?;
|
||||
let column = |c: usize| [m[0][c], m[1][c], m[2][c]];
|
||||
let curve = curve_tag(space);
|
||||
// The green and blue curves are the red one's entry.
|
||||
let tags: [(&[u8; 4], Vec<u8>); 9] = [
|
||||
(b"desc", desc_tag(description(space))),
|
||||
(b"cprt", text_tag("No copyright, generated by TextureCraft")),
|
||||
(b"wtpt", xyz_tag(D50_XYZ)),
|
||||
(b"rXYZ", xyz_tag(column(0))),
|
||||
(b"gXYZ", xyz_tag(column(1))),
|
||||
(b"bXYZ", xyz_tag(column(2))),
|
||||
(b"rTRC", curve.clone()),
|
||||
(b"gTRC", curve.clone()),
|
||||
(b"bTRC", curve),
|
||||
];
|
||||
// Header (128) + tag count (4) + 12 per tag, then the tag data, each tag padded to 4 bytes.
|
||||
let table_end = 128 + 4 + 12 * tags.len();
|
||||
let mut offsets = Vec::new();
|
||||
let mut data: Vec<u8> = Vec::new();
|
||||
for (i, (_, bytes)) in tags.iter().enumerate() {
|
||||
let shared = i >= 7;
|
||||
let at = if shared { offsets.get(6).copied().unwrap_or(0) } else { table_end + data.len() };
|
||||
offsets.push(at);
|
||||
if !shared {
|
||||
data.extend_from_slice(bytes);
|
||||
while !data.len().is_multiple_of(4) {
|
||||
data.push(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
let total = table_end + data.len();
|
||||
let mut out = vec![0u8; 128];
|
||||
out.get_mut(0..4)?.copy_from_slice(&(total as u32).to_be_bytes());
|
||||
out.get_mut(8..12)?.copy_from_slice(&[2, 0x10, 0, 0]); // version 2.1.0
|
||||
out.get_mut(12..16)?.copy_from_slice(b"mntr");
|
||||
out.get_mut(16..20)?.copy_from_slice(b"RGB ");
|
||||
out.get_mut(20..24)?.copy_from_slice(b"XYZ ");
|
||||
// A fixed date (2026-01-01 00:00:00), so a space always gives the same bytes.
|
||||
out.get_mut(24..36)?.copy_from_slice(&[0x07, 0xEA, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0]);
|
||||
out.get_mut(36..40)?.copy_from_slice(b"acsp");
|
||||
for (k, v) in D50_XYZ.iter().enumerate() {
|
||||
out.get_mut(68 + 4 * k..72 + 4 * k)?.copy_from_slice(&s15f16(*v));
|
||||
}
|
||||
out.extend_from_slice(&(tags.len() as u32).to_be_bytes());
|
||||
for ((sig, bytes), at) in tags.iter().zip(&offsets) {
|
||||
out.extend_from_slice(*sig);
|
||||
out.extend_from_slice(&(*at as u32).to_be_bytes());
|
||||
out.extend_from_slice(&(bytes.len() as u32).to_be_bytes());
|
||||
}
|
||||
out.extend_from_slice(&data);
|
||||
Some(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn u32_at(b: &[u8], i: usize) -> u32 {
|
||||
u32::from_be_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]])
|
||||
}
|
||||
|
||||
/// The data of the tag `sig` in a profile.
|
||||
fn tag<'a>(p: &'a [u8], sig: &[u8; 4]) -> &'a [u8] {
|
||||
let n = u32_at(p, 128) as usize;
|
||||
for k in 0..n {
|
||||
let e = 132 + 12 * k;
|
||||
if &p[e..e + 4] == sig {
|
||||
let (at, len) = (u32_at(p, e + 4) as usize, u32_at(p, e + 8) as usize);
|
||||
return &p[at..at + len];
|
||||
}
|
||||
}
|
||||
panic!("no {sig:?} tag");
|
||||
}
|
||||
|
||||
fn xyz(t: &[u8]) -> [f64; 3] {
|
||||
[8, 12, 16].map(|i| f64::from(u32_at(t, i) as i32) / 65536.0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_profile_is_well_formed() {
|
||||
for s in ColorSpace::ALL {
|
||||
let p = profile(s).unwrap();
|
||||
assert_eq!(u32_at(&p, 0) as usize, p.len(), "{s:?}: the header names the real size");
|
||||
assert_eq!(&p[36..40], b"acsp");
|
||||
assert_eq!(&p[12..24], b"mntrRGB XYZ ");
|
||||
let n = u32_at(&p, 128) as usize;
|
||||
assert_eq!(n, 9);
|
||||
for k in 0..n {
|
||||
let e = 132 + 12 * k;
|
||||
let (at, len) = (u32_at(&p, e + 4) as usize, u32_at(&p, e + 8) as usize);
|
||||
assert!(at.is_multiple_of(4) && at >= 132 + 12 * n && at + len <= p.len(), "{s:?} tag {k}: {at}+{len} of {}", p.len());
|
||||
}
|
||||
assert_eq!(profile(s).unwrap(), p, "the same bytes every time");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colorants_add_up_to_d50_and_the_curves_are_right() {
|
||||
for s in ColorSpace::ALL {
|
||||
let p = profile(s).unwrap();
|
||||
let (r, g, b) = (xyz(tag(&p, b"rXYZ")), xyz(tag(&p, b"gXYZ")), xyz(tag(&p, b"bXYZ")));
|
||||
let sum = [0, 1, 2].map(|i| r[i] + g[i] + b[i]);
|
||||
assert!((sum[0] - 0.9642).abs() < 1e-3 && (sum[1] - 1.0).abs() < 1e-3 && (sum[2] - 0.8249).abs() < 1e-3, "{s:?} {sum:?}");
|
||||
let curve = tag(&p, b"rTRC");
|
||||
let count = u32_at(curve, 8) as usize;
|
||||
if s == ColorSpace::Srgb {
|
||||
assert_eq!(count, CURVE_POINTS);
|
||||
let at = |i: usize| f64::from(u16::from_be_bytes([curve[12 + 2 * i], curve[13 + 2 * i]])) / 65535.0;
|
||||
assert_eq!((at(0), at(CURVE_POINTS - 1)), (0.0, 1.0));
|
||||
// 0.5 encoded is 0.214 linear.
|
||||
assert!((at((CURVE_POINTS - 1) / 2) - 0.2140).abs() < 2e-3, "{}", at((CURVE_POINTS - 1) / 2));
|
||||
} else {
|
||||
assert_eq!((count, u16::from_be_bytes([curve[12], curve[13]])), (1, 0x0100), "{s:?}: a gamma of 1");
|
||||
}
|
||||
}
|
||||
let srgb = profile(ColorSpace::Srgb).unwrap();
|
||||
let red = xyz(tag(&srgb, b"rXYZ"));
|
||||
assert!((red[0] - 0.4361).abs() < 2e-3 && (red[1] - 0.2225).abs() < 2e-3 && (red[2] - 0.0139).abs() < 2e-3, "{red:?}");
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,7 @@
|
||||
pub mod export;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod fonts;
|
||||
pub mod icc;
|
||||
pub mod image_res;
|
||||
pub mod materialx;
|
||||
pub mod materialx_read;
|
||||
|
||||
@@ -55,6 +55,20 @@ impl ColorSpace {
|
||||
self != ColorSpace::Srgb
|
||||
}
|
||||
|
||||
/// The red, green and blue primaries and the white point as CIE xy chromaticities.
|
||||
pub fn chromaticities(self) -> [[f64; 2]; 4] {
|
||||
let p = self.primaries();
|
||||
[p.r, p.g, p.b, p.white]
|
||||
}
|
||||
|
||||
/// Linear RGB of this space to CIE XYZ adapted (Bradford) to the D50 white of the ICC profile
|
||||
/// connection space: the colorant matrix of a matrix/curve ICC profile. Columns are the
|
||||
/// red, green and blue colorants.
|
||||
pub fn to_xyz_d50(self) -> Option<[[f64; 3]; 3]> {
|
||||
let p = self.primaries();
|
||||
Some(mul(&adapt(p.white, D50)?, &rgb_to_xyz(&p)?))
|
||||
}
|
||||
|
||||
fn primaries(self) -> Primaries {
|
||||
match self {
|
||||
ColorSpace::Srgb | ColorSpace::LinearRec709 => REC709,
|
||||
@@ -88,6 +102,8 @@ struct Primaries {
|
||||
|
||||
const D65: [f64; 2] = [0.3127, 0.3290];
|
||||
const D60_ACES: [f64; 2] = [0.32168, 0.33767];
|
||||
/// The white of the ICC profile connection space.
|
||||
const D50: [f64; 2] = [0.3457, 0.3585];
|
||||
const REC709: Primaries = Primaries { r: [0.640, 0.330], g: [0.300, 0.600], b: [0.150, 0.060], white: D65 };
|
||||
const AP1: Primaries = Primaries { r: [0.713, 0.293], g: [0.165, 0.830], b: [0.128, 0.044], white: D60_ACES };
|
||||
const AP0: Primaries = Primaries { r: [0.7347, 0.2653], g: [0.0, 1.0], b: [0.0001, -0.0770], white: D60_ACES };
|
||||
@@ -196,6 +212,22 @@ mod tests {
|
||||
assert_eq!(ColorSpace::LinearRec709.from_linear_rec709([0.3, 2.0, -1.0]), [0.3, 2.0, -1.0], "linear Rec.709 is the identity, values above 1 kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colorants_adapted_to_d50_add_up_to_the_d50_white_and_match_srgb() {
|
||||
for s in ColorSpace::ALL {
|
||||
let m = s.to_xyz_d50().unwrap();
|
||||
let white = [0, 1, 2].map(|row| m[row][0] + m[row][1] + m[row][2]);
|
||||
assert!((white[0] - 0.9642).abs() < 1e-3 && (white[1] - 1.0).abs() < 1e-3 && (white[2] - 0.8249).abs() < 1e-3, "{s:?} {white:?}");
|
||||
}
|
||||
// The colorants of the published sRGB ICC profile (D50 adapted): 0.4361 0.2225 0.0139 for red.
|
||||
let m = ColorSpace::Srgb.to_xyz_d50().unwrap();
|
||||
let red = [m[0][0], m[1][0], m[2][0]];
|
||||
assert!((red[0] - 0.4361).abs() < 2e-3 && (red[1] - 0.2225).abs() < 2e-3 && (red[2] - 0.0139).abs() < 2e-3, "{red:?}");
|
||||
let c = ColorSpace::AcesCg.chromaticities();
|
||||
assert_eq!(c[0], [0.713, 0.293]);
|
||||
assert_eq!(c[3], [0.32168, 0.33767]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_values_stay_finite() {
|
||||
for s in ColorSpace::ALL {
|
||||
|
||||
Reference in new issue
Block a user