mirror of
https://github.com/storytold/effectcraft.git
synced 2026-11-19 16:45:28 +00:00
Merge pull request #3779 from FredApps/onee/i786-psd-descriptors-placed
psd: parse descriptors and placed layers with craft-psd
This commit is contained in:
7 files changed
+323
-264
No files matched your search
Generated
+1
-1
@@ -1449,7 +1449,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-psd"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ce2ec507c2e6a6a078a5f450f641487f8931816d#ce2ec507c2e6a6a078a5f450f641487f8931816d"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e1fc4b1376148197c2cfd2381eeb400e2731269a#e1fc4b1376148197c2cfd2381eeb400e2731269a"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"flate2",
|
||||
|
||||
+1
-1
@@ -21,7 +21,7 @@ craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs"
|
||||
craft-ps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", default-features = false, features = ["read"] }
|
||||
craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
|
||||
craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
|
||||
craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "ce2ec507c2e6a6a078a5f450f641487f8931816d" }
|
||||
craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e1fc4b1376148197c2cfd2381eeb400e2731269a" }
|
||||
craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "77686f24fe8665c21369f1b593f4d65a973e2a45" }
|
||||
craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
|
||||
craft-lottie = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
|
||||
|
||||
+108
-114
@@ -42,8 +42,14 @@ pub enum RefItem {
|
||||
Class(String),
|
||||
Enum(String, String, String),
|
||||
Offset(String, i32),
|
||||
/// Identifier with the legacy unnamed `null` class.
|
||||
Identifier(i32),
|
||||
/// Index with the legacy unnamed `null` class.
|
||||
Index(i32),
|
||||
/// Identifier retaining the original class and its encoding.
|
||||
IdentifierWithClass(craft_psd::descriptor::Class, i32),
|
||||
/// Index retaining the original class and its encoding.
|
||||
IndexWithClass(craft_psd::descriptor::Class, i32),
|
||||
Name(String, String),
|
||||
}
|
||||
|
||||
@@ -108,14 +114,6 @@ impl Descriptor {
|
||||
}
|
||||
}
|
||||
|
||||
/// A key or class id: length-prefixed string, or a 4-character code when the length is 0.
|
||||
pub(crate) fn read_id(r: &mut Reader) -> Result<String> {
|
||||
let n = r.u32()? as usize;
|
||||
let n = if n == 0 { 4 } else { n };
|
||||
let b = r.bytes(n)?;
|
||||
Ok(String::from_utf8_lossy(b).into_owned())
|
||||
}
|
||||
|
||||
pub(crate) fn read_unicode(r: &mut Reader) -> Result<String> {
|
||||
let n = r.u32()? as usize;
|
||||
let mut v = Vec::with_capacity(n.min(r.remaining() / 2));
|
||||
@@ -128,122 +126,90 @@ pub(crate) fn read_unicode(r: &mut Reader) -> Result<String> {
|
||||
Ok(String::from_utf16_lossy(&v))
|
||||
}
|
||||
|
||||
/// Read a descriptor (after its version field).
|
||||
/// Preserve the application parser's per-container limits in the shared parser.
|
||||
pub(crate) const PARSE_LIMITS: craft_psd::descriptor::ParseLimits =
|
||||
craft_psd::descriptor::ParseLimits { max_descriptor_items: 100_000, max_list_items: 1_000_000 };
|
||||
|
||||
/// Read a descriptor (after its version field) with [`craft_psd::descriptor::Descriptor::parse_prefix`].
|
||||
/// The public [`Descriptor`] / [`DValue`] types stay this crate's (engine interchange uses them).
|
||||
pub fn read_descriptor(r: &mut Reader) -> Result<Descriptor> {
|
||||
read_descriptor_at(r, 0)
|
||||
let rest = r.data.get(r.pos..).unwrap_or(&[]);
|
||||
let (d, used) = craft_psd::descriptor::Descriptor::parse_prefix_with_limits(rest, PARSE_LIMITS).map_err(desc_err)?;
|
||||
r.skip(used)?;
|
||||
Ok(from_craft_descriptor(d))
|
||||
}
|
||||
|
||||
/// [`read_descriptor`] nested `depth` values deep: the limit in [`read_value`] counts nested
|
||||
/// descriptors too, so a file can't recurse until the stack overflows.
|
||||
fn read_descriptor_at(r: &mut Reader, depth: usize) -> Result<Descriptor> {
|
||||
let class_name = read_unicode(r)?;
|
||||
let class_id = read_id(r)?;
|
||||
let n = r.u32()? as usize;
|
||||
if n > 100_000 {
|
||||
return Err(Error::Invalid("descriptor item count".into()));
|
||||
fn desc_err(e: craft_psd::PsdError) -> Error {
|
||||
match e {
|
||||
craft_psd::PsdError::UnexpectedEof { .. } => Error::Truncated,
|
||||
craft_psd::PsdError::Unsupported(s) => Error::Unsupported(s),
|
||||
other => Error::Invalid(other.to_string()),
|
||||
}
|
||||
let mut items = Vec::with_capacity(n.min(64));
|
||||
for _ in 0..n {
|
||||
let key = read_id(r)?;
|
||||
let ty = r.tag()?;
|
||||
let v = read_value(r, &ty, depth)?;
|
||||
items.push((key, v));
|
||||
}
|
||||
Ok(Descriptor { class_name, class_id, items })
|
||||
}
|
||||
|
||||
fn read_value(r: &mut Reader, ty: &[u8; 4], depth: usize) -> Result<DValue> {
|
||||
if depth > 64 {
|
||||
return Err(Error::Invalid("descriptor nesting".into()));
|
||||
fn id_str(id: &craft_psd::descriptor::Id) -> String {
|
||||
String::from_utf8_lossy(id.as_bytes()).into_owned()
|
||||
}
|
||||
|
||||
fn unit_str(u: &[u8; 4]) -> String {
|
||||
String::from_utf8_lossy(u).into_owned()
|
||||
}
|
||||
|
||||
fn from_craft_descriptor(d: craft_psd::descriptor::Descriptor) -> Descriptor {
|
||||
Descriptor {
|
||||
class_name: d.name.to_string_lossy(),
|
||||
class_id: id_str(&d.class_id),
|
||||
items: d.items.into_iter().map(|(k, v)| (id_str(&k), from_craft_value(v))).collect(),
|
||||
}
|
||||
Ok(match ty {
|
||||
b"Objc" | b"GlbO" => DValue::Descriptor(read_descriptor_at(r, depth + 1)?),
|
||||
b"VlLs" => {
|
||||
let n = r.u32()? as usize;
|
||||
if n > 1_000_000 {
|
||||
return Err(Error::Invalid("descriptor list length".into()));
|
||||
}
|
||||
|
||||
fn from_craft_value(v: craft_psd::descriptor::Value) -> DValue {
|
||||
use craft_psd::descriptor::Value;
|
||||
match v {
|
||||
Value::Descriptor(d) | Value::GlobalObject(d) => DValue::Descriptor(from_craft_descriptor(d)),
|
||||
Value::List(l) => DValue::List(l.into_iter().map(from_craft_value).collect()),
|
||||
Value::Double(x) => DValue::Double(if x.is_finite() { x } else { 0.0 }),
|
||||
Value::UnitFloat { unit, value } => DValue::UnitFloat(unit_str(&unit), if value.is_finite() { value } else { 0.0 }),
|
||||
Value::UnitFloats { unit, values } => DValue::UnitFloats(unit_str(&unit), values.into_iter().map(|x| if x.is_finite() { x } else { 0.0 }).collect()),
|
||||
Value::Text(s) => DValue::Text(s.to_string_lossy()),
|
||||
Value::Enumerated { type_id, value } => DValue::Enum(id_str(&type_id), id_str(&value)),
|
||||
Value::Integer(i) => DValue::Integer(i),
|
||||
Value::LargeInteger(i) => DValue::LargeInteger(i),
|
||||
Value::Boolean(b) => DValue::Bool(b),
|
||||
Value::Class(c) | Value::GlobalClass(c) => DValue::Class(c.name.to_string_lossy(), id_str(&c.class_id)),
|
||||
Value::Alias(b) | Value::Path(b) | Value::RawData(b) => DValue::Raw(b),
|
||||
Value::ObjectArray(o) => DValue::ObjectArray(o.prefix, from_craft_descriptor(o.body)),
|
||||
Value::Reference(items) => DValue::Reference(items.into_iter().map(from_craft_ref).collect()),
|
||||
}
|
||||
}
|
||||
|
||||
fn legacy_reference_class(class: &craft_psd::descriptor::Class) -> bool {
|
||||
class.name.0 == [0] && class.class_id == craft_psd::descriptor::Id::Code(*b"null")
|
||||
}
|
||||
|
||||
fn from_craft_ref(it: craft_psd::descriptor::ReferenceItem) -> RefItem {
|
||||
use craft_psd::descriptor::ReferenceItem;
|
||||
match it {
|
||||
ReferenceItem::Property { class, key } => RefItem::Property(id_str(&class.class_id), id_str(&key)),
|
||||
ReferenceItem::Class(c) => RefItem::Class(id_str(&c.class_id)),
|
||||
ReferenceItem::Enumerated { class, type_id, value } => RefItem::Enum(id_str(&class.class_id), id_str(&type_id), id_str(&value)),
|
||||
ReferenceItem::Offset { class, offset } => RefItem::Offset(id_str(&class.class_id), offset),
|
||||
ReferenceItem::Identifier { class, id } => {
|
||||
if legacy_reference_class(&class) {
|
||||
RefItem::Identifier(id as i32)
|
||||
} else {
|
||||
RefItem::IdentifierWithClass(class, id as i32)
|
||||
}
|
||||
let mut v = Vec::with_capacity(n.min(256));
|
||||
for _ in 0..n {
|
||||
let t = r.tag()?;
|
||||
v.push(read_value(r, &t, depth + 1)?);
|
||||
}
|
||||
ReferenceItem::Index { class, index } => {
|
||||
if legacy_reference_class(&class) {
|
||||
RefItem::Index(index as i32)
|
||||
} else {
|
||||
RefItem::IndexWithClass(class, index as i32)
|
||||
}
|
||||
DValue::List(v)
|
||||
}
|
||||
b"ObAr" => {
|
||||
let n = r.u32()?;
|
||||
DValue::ObjectArray(n, read_descriptor_at(r, depth + 1)?)
|
||||
}
|
||||
b"doub" => DValue::Double(r.f64_finite()?),
|
||||
b"UntF" => {
|
||||
let unit = String::from_utf8_lossy(&r.tag()?).into_owned();
|
||||
DValue::UnitFloat(unit, r.f64_finite()?)
|
||||
}
|
||||
b"UnFl" => {
|
||||
let unit = String::from_utf8_lossy(&r.tag()?).into_owned();
|
||||
let n = r.u32()? as usize;
|
||||
let mut v = Vec::with_capacity(n.min(1024));
|
||||
for _ in 0..n {
|
||||
v.push(r.f64_finite()?);
|
||||
}
|
||||
DValue::UnitFloats(unit, v)
|
||||
}
|
||||
b"TEXT" => DValue::Text(read_unicode(r)?),
|
||||
b"enum" => {
|
||||
let t = read_id(r)?;
|
||||
DValue::Enum(t, read_id(r)?)
|
||||
}
|
||||
b"long" => DValue::Integer(r.u32()? as i32),
|
||||
b"comp" => DValue::LargeInteger(r.u64()? as i64),
|
||||
b"bool" => DValue::Bool(r.u8()? != 0),
|
||||
b"type" | b"GlbC" => {
|
||||
let name = read_unicode(r)?;
|
||||
DValue::Class(name, read_id(r)?)
|
||||
}
|
||||
b"alis" | b"tdta" | b"Pth " => {
|
||||
let n = r.u32()? as usize;
|
||||
DValue::Raw(r.bytes(n)?.to_vec())
|
||||
}
|
||||
b"obj " => {
|
||||
let n = r.u32()? as usize;
|
||||
let mut items = Vec::with_capacity(n.min(16));
|
||||
for _ in 0..n {
|
||||
let t = r.tag()?;
|
||||
items.push(match &t {
|
||||
b"prop" => {
|
||||
let _name = read_unicode(r)?;
|
||||
let class = read_id(r)?;
|
||||
RefItem::Property(class, read_id(r)?)
|
||||
}
|
||||
b"Clss" => {
|
||||
let _name = read_unicode(r)?;
|
||||
RefItem::Class(read_id(r)?)
|
||||
}
|
||||
b"Enmr" => {
|
||||
let _name = read_unicode(r)?;
|
||||
let class = read_id(r)?;
|
||||
let ty = read_id(r)?;
|
||||
RefItem::Enum(class, ty, read_id(r)?)
|
||||
}
|
||||
b"rele" => {
|
||||
let _name = read_unicode(r)?;
|
||||
let class = read_id(r)?;
|
||||
RefItem::Offset(class, r.u32()? as i32)
|
||||
}
|
||||
b"Idnt" => RefItem::Identifier(r.u32()? as i32),
|
||||
b"indx" => RefItem::Index(r.u32()? as i32),
|
||||
b"name" => {
|
||||
let _name = read_unicode(r)?;
|
||||
let class = read_id(r)?;
|
||||
RefItem::Name(class, read_unicode(r)?)
|
||||
}
|
||||
other => return Err(Error::Invalid(format!("reference item `{}`", String::from_utf8_lossy(other)))),
|
||||
});
|
||||
}
|
||||
DValue::Reference(items)
|
||||
}
|
||||
other => return Err(Error::Invalid(format!("descriptor type `{}`", String::from_utf8_lossy(other)))),
|
||||
})
|
||||
ReferenceItem::Name { class, name } => RefItem::Name(id_str(&class.class_id), name.to_string_lossy()),
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- writing
|
||||
@@ -387,13 +353,28 @@ fn write_value(out: &mut Vec<u8>, v: &DValue) {
|
||||
out.extend_from_slice(&o.to_be_bytes());
|
||||
}
|
||||
RefItem::Identifier(i) => {
|
||||
// Photoshop stores a class before the id; craft-psd reads it that way.
|
||||
out.extend_from_slice(b"Idnt");
|
||||
put_unicode(out, "");
|
||||
put_id(out, "null");
|
||||
out.extend_from_slice(&i.to_be_bytes());
|
||||
}
|
||||
RefItem::Index(i) => {
|
||||
out.extend_from_slice(b"indx");
|
||||
put_unicode(out, "");
|
||||
put_id(out, "null");
|
||||
out.extend_from_slice(&i.to_be_bytes());
|
||||
}
|
||||
RefItem::IdentifierWithClass(class, id) => {
|
||||
out.extend_from_slice(b"Idnt");
|
||||
put_reference_class(out, class);
|
||||
out.extend_from_slice(&id.to_be_bytes());
|
||||
}
|
||||
RefItem::IndexWithClass(class, index) => {
|
||||
out.extend_from_slice(b"indx");
|
||||
put_reference_class(out, class);
|
||||
out.extend_from_slice(&index.to_be_bytes());
|
||||
}
|
||||
RefItem::Name(c, n) => {
|
||||
out.extend_from_slice(b"name");
|
||||
put_unicode(out, "");
|
||||
@@ -406,6 +387,19 @@ fn write_value(out: &mut Vec<u8>, v: &DValue) {
|
||||
}
|
||||
}
|
||||
|
||||
fn put_reference_class(out: &mut Vec<u8>, class: &craft_psd::descriptor::Class) {
|
||||
out.extend_from_slice(&(class.name.0.len() as u32).to_be_bytes());
|
||||
for unit in &class.name.0 {
|
||||
out.extend_from_slice(&unit.to_be_bytes());
|
||||
}
|
||||
let length = match &class.class_id {
|
||||
craft_psd::descriptor::Id::Code(_) => 0,
|
||||
craft_psd::descriptor::Id::Str(bytes) => bytes.len() as u32,
|
||||
};
|
||||
out.extend_from_slice(&length.to_be_bytes());
|
||||
out.extend_from_slice(class.class_id.as_bytes());
|
||||
}
|
||||
|
||||
fn tag4(s: &str) -> [u8; 4] {
|
||||
let mut t = *b" ";
|
||||
for (i, b) in s.bytes().take(4).enumerate() {
|
||||
|
||||
+15
-32
@@ -1,7 +1,5 @@
|
||||
use super::limits::{Error, Result};
|
||||
use super::model::{
|
||||
Adjustment, ChannelInfo, ColorMode, Layer, LayerMask, LinkedFile, MAX_GROUP_DEPTH, Node, Rect, Section, SmartObject, SubPath, TextInfo, VectorMask,
|
||||
};
|
||||
use super::model::{Adjustment, ChannelInfo, ColorMode, Layer, LayerMask, LinkedFile, MAX_GROUP_DEPTH, Node, Rect, Section, SubPath, TextInfo, VectorMask};
|
||||
use super::{Psd, Reader, descriptor, engine_data, placed};
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -70,7 +68,7 @@ impl Psd {
|
||||
}
|
||||
if let Some(info) = &file.layer_info {
|
||||
psd.merged_alpha = info.merged_alpha;
|
||||
psd.layers = info.layers.iter().enumerate().map(|(i, rec)| psd.layer(rec, i, splice)).collect();
|
||||
psd.layers = info.layers.iter().enumerate().map(|(i, rec)| psd.layer(rec, i, splice)).collect::<Result<Vec<_>>>()?;
|
||||
}
|
||||
for b in &file.global_blocks {
|
||||
if let Some(stored) = b.stored.as_ref().filter(|_| linked(&b.key, 0)) {
|
||||
@@ -83,7 +81,7 @@ impl Psd {
|
||||
|
||||
/// One layer record of the model, its additional information read into [`Layer`].
|
||||
/// `splice` maps craft-psd's offsets back into `self.data` (see [`read_file`]).
|
||||
fn layer(&self, rec: &craft_psd::LayerRecord, index: usize, splice: Splice) -> Layer {
|
||||
fn layer(&self, rec: &craft_psd::LayerRecord, index: usize, splice: Splice) -> Result<Layer> {
|
||||
let channels = rec
|
||||
.channels
|
||||
.iter()
|
||||
@@ -113,10 +111,15 @@ impl Psd {
|
||||
}
|
||||
for b in &rec.blocks {
|
||||
l.keys.push(b.key);
|
||||
// A malformed block only loses that block's information.
|
||||
let _ = self.layer_block(&mut l, &b.key, &b.data);
|
||||
// A malformed optional block only loses that block's information.
|
||||
// Unsupported modern placement geometry must not silently become an
|
||||
// unwarped layer or fall back to a less expressive PlLd in either order.
|
||||
match self.layer_block(&mut l, &b.key, &b.data) {
|
||||
Err(e @ Error::Unsupported(_)) if matches!(&b.key, b"SoLd" | b"SoLE") => return Err(e),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
l
|
||||
Ok(l)
|
||||
}
|
||||
|
||||
/// The embedded bytes of linked file `uuid`.
|
||||
@@ -236,32 +239,12 @@ impl Psd {
|
||||
l.adjustment = Some(Adjustment::Other(String::from_utf8_lossy(key).into_owned()));
|
||||
}
|
||||
b"SoLd" | b"SoLE" => {
|
||||
let _id = r.tag()?;
|
||||
let _ver = r.u32()?;
|
||||
let _dver = r.u32()?;
|
||||
let d = descriptor::read_descriptor(&mut r)?;
|
||||
let uuid = d.text("Idnt").unwrap_or_default().to_string();
|
||||
let t = placed::eight(&d, "Trnf").unwrap_or([0.0; 8]);
|
||||
// The non-affine transform when present (perspective), else the transform.
|
||||
let t = placed::eight(&d, "nonAffineTransform").unwrap_or(t);
|
||||
let size = d.obj("Sz ").and_then(|s| Some([s.num("Wdth")?, s.num("Hght")?]));
|
||||
let warp = d.obj("warp").and_then(placed::Warp::read);
|
||||
l.smart_object = Some(SmartObject { uuid, quad: placed::quad_from(t), size, warp });
|
||||
l.smart_object = Some(placed::from_craft_smart(
|
||||
craft_psd::smart::SmartObject::from_placed_layer_data_with_limits(b, crate::descriptor::PARSE_LIMITS).map_err(|e| error(&e))?,
|
||||
));
|
||||
}
|
||||
b"PlLd" if l.smart_object.is_none() => {
|
||||
let _id = r.tag()?;
|
||||
let _ver = r.u32()?;
|
||||
let n = r.u8()? as usize;
|
||||
let uuid = String::from_utf8_lossy(r.bytes(n)?).into_owned();
|
||||
let _page = r.u32()?;
|
||||
let _pages = r.u32()?;
|
||||
let _aa = r.u32()?;
|
||||
let _ty = r.u32()?;
|
||||
let mut t = [0.0; 8];
|
||||
for v in &mut t {
|
||||
*v = r.f64_finite()?;
|
||||
}
|
||||
l.smart_object = Some(SmartObject { uuid, quad: placed::quad_from(t), size: None, warp: None });
|
||||
l.smart_object = Some(placed::from_craft_smart(craft_psd::smart::SmartObject::from_placed_layer(b).map_err(|e| error(&e))?));
|
||||
}
|
||||
b"vmsk" | b"vsms" => {
|
||||
let _ver = r.u32()?;
|
||||
|
||||
+43
-113
@@ -14,14 +14,7 @@ use crate::{Pixels, SmartObject};
|
||||
|
||||
/// The most pixels a baked smart object may have: 2^24 (256 MiB as float RGBA). The size comes
|
||||
/// from the file's transform, which is untrusted.
|
||||
pub const MAX_BAKE_PIXELS: u64 = 1 << 24;
|
||||
|
||||
/// The bake's rasterising budget, in bounding-box pixels visited over all mesh triangles, as a
|
||||
/// multiple of the output pixel count. A sane warp visits about 2× the output; a hostile mesh
|
||||
/// that makes every triangle cover the whole output would visit thousands of times more.
|
||||
const BAKE_WORK_FACTOR: u64 = 8;
|
||||
/// The smallest budget, so tiny outputs are never refused for rounding at the triangle edges.
|
||||
const MIN_BAKE_WORK: u64 = 1 << 20;
|
||||
pub const MAX_BAKE_PIXELS: u64 = craft_psd::smart::MAX_BAKE_PIXELS;
|
||||
|
||||
/// A placed layer's warp.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
@@ -61,14 +54,40 @@ pub(crate) fn floats(v: Option<&DValue>) -> Vec<f64> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The eight numbers of a transform entry (`Trnf`, `nonAffineTransform`), when it has exactly eight.
|
||||
pub(crate) fn eight(d: &Descriptor, key: &str) -> Option<[f64; 8]> {
|
||||
floats(d.get(key)).try_into().ok()
|
||||
pub(crate) fn from_craft_smart(s: craft_psd::smart::SmartObject) -> SmartObject {
|
||||
SmartObject { uuid: s.uuid, quad: s.quad, size: s.size, warp: s.warp.map(from_craft_warp) }
|
||||
}
|
||||
|
||||
/// The corner quad (top-left, top-right, bottom-right, bottom-left) from x0 y0 … x3 y3.
|
||||
pub(crate) fn quad_from(t: [f64; 8]) -> [[f64; 2]; 4] {
|
||||
[[t[0], t[1]], [t[2], t[3]], [t[4], t[5]], [t[6], t[7]]]
|
||||
fn from_craft_warp(w: craft_psd::smart::Warp) -> Warp {
|
||||
Warp {
|
||||
style: w.style,
|
||||
bend: w.bend,
|
||||
horizontal: w.horizontal,
|
||||
vertical: w.vertical,
|
||||
rotate_vertical: w.rotate_vertical,
|
||||
bounds: w.bounds,
|
||||
cols: w.cols,
|
||||
rows: w.rows,
|
||||
mesh: w.mesh,
|
||||
}
|
||||
}
|
||||
|
||||
fn to_craft_smart(s: &SmartObject) -> craft_psd::smart::SmartObject {
|
||||
craft_psd::smart::SmartObject { uuid: s.uuid.clone(), quad: s.quad, size: s.size, warp: s.warp.as_ref().map(to_craft_warp) }
|
||||
}
|
||||
|
||||
fn to_craft_warp(w: &Warp) -> craft_psd::smart::Warp {
|
||||
craft_psd::smart::Warp {
|
||||
style: w.style.clone(),
|
||||
bend: w.bend,
|
||||
horizontal: w.horizontal,
|
||||
vertical: w.vertical,
|
||||
rotate_vertical: w.rotate_vertical,
|
||||
bounds: w.bounds,
|
||||
cols: w.cols,
|
||||
rows: w.rows,
|
||||
mesh: w.mesh.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
impl Warp {
|
||||
@@ -111,7 +130,13 @@ impl Warp {
|
||||
|
||||
/// The warp of a content point (content pixels → content pixels).
|
||||
pub fn apply(&self, p: [f64; 2], w: f64, h: f64) -> [f64; 2] {
|
||||
let [l, t, r, b] = if self.bounds[2] > self.bounds[0] && self.bounds[3] > self.bounds[1] { self.bounds } else { [0.0, 0.0, w, h] };
|
||||
// Keep the local mapping facade aligned with the shared bake evaluator.
|
||||
let valid_bounds = self.bounds.iter().all(|x| x.is_finite())
|
||||
&& (self.bounds[2] - self.bounds[0]).is_finite()
|
||||
&& self.bounds[2] > self.bounds[0]
|
||||
&& (self.bounds[3] - self.bounds[1]).is_finite()
|
||||
&& self.bounds[3] > self.bounds[1];
|
||||
let [l, t, r, b] = if valid_bounds { self.bounds } else { [0.0, 0.0, w, h] };
|
||||
let (bw, bh) = (r - l, b - t);
|
||||
let (u, v) = ((p[0] - l) / bw, (p[1] - t) / bh);
|
||||
if self.style == "warpCustom" {
|
||||
@@ -313,105 +338,10 @@ impl SmartObject {
|
||||
/// `k` pixels per document pixel (into `size` pixels when given; see [`Self::placed_size`]).
|
||||
/// Returns the pixels and their document-space origin. `None` when the content is empty or
|
||||
/// the baked image would exceed [`MAX_BAKE_PIXELS`] or the mesh needs more rasterising work than
|
||||
/// the budget allows (see [`BAKE_WORK_FACTOR`]).
|
||||
/// the budget allows.
|
||||
pub fn render_placed(&self, content: &Pixels, k: f64, size: Option<(u32, u32)>) -> Option<(Pixels, [f64; 2])> {
|
||||
let (cw, ch) = (content.width as f64, content.height as f64);
|
||||
if content.width == 0 || content.height == 0 {
|
||||
return None;
|
||||
}
|
||||
// The quad is solved once for the bounds, the size and the whole grid.
|
||||
let m = square_to_quad(self.quad);
|
||||
let bb = self.bounds_with(&m, cw, ch);
|
||||
let (ow, oh) = match size {
|
||||
Some((w, h)) => (w.max(1), h.max(1)),
|
||||
None => size_for(bb, k),
|
||||
};
|
||||
let (ow, oh) = (ow as usize, oh as usize);
|
||||
let count = ow.checked_mul(oh).filter(|&c| c as u64 <= MAX_BAKE_PIXELS)?;
|
||||
// A forward grid, filled triangle by triangle with inverse barycentric sampling.
|
||||
let n = 48usize;
|
||||
let mut dst = Vec::with_capacity((n + 1) * (n + 1));
|
||||
let mut src = Vec::with_capacity((n + 1) * (n + 1));
|
||||
for j in 0..=n {
|
||||
for i in 0..=n {
|
||||
let s = [i as f64 / n as f64 * cw, j as f64 / n as f64 * ch];
|
||||
let d = self.map_with(&m, s, cw, ch);
|
||||
dst.push([(d[0] - bb[0]) * k, (d[1] - bb[1]) * k]);
|
||||
src.push(s);
|
||||
}
|
||||
}
|
||||
let mut out: Vec<[f32; 4]> = Vec::new();
|
||||
out.try_reserve_exact(count).ok()?;
|
||||
out.resize(count, [0.0; 4]);
|
||||
let sample = |x: f64, y: f64| -> [f32; 4] {
|
||||
let (fx, fy) = ((x - 0.5).clamp(0.0, cw - 1.0), (y - 0.5).clamp(0.0, ch - 1.0));
|
||||
let (x0, y0) = (fx.floor() as usize, fy.floor() as usize);
|
||||
let (x1, y1) = ((x0 + 1).min(content.width as usize - 1), (y0 + 1).min(content.height as usize - 1));
|
||||
let (a, b) = ((fx - x0 as f64) as f32, (fy - y0 as f64) as f32);
|
||||
let at = |x: usize, y: usize| {
|
||||
let p = content.data[y * content.width as usize + x];
|
||||
[p[0] * p[3], p[1] * p[3], p[2] * p[3], p[3]]
|
||||
};
|
||||
let (p00, p10, p01, p11) = (at(x0, y0), at(x1, y0), at(x0, y1), at(x1, y1));
|
||||
let mut o = [0.0; 4];
|
||||
for c in 0..4 {
|
||||
o[c] = (p00[c] * (1.0 - a) + p10[c] * a) * (1.0 - b) + (p01[c] * (1.0 - a) + p11[c] * a) * b;
|
||||
}
|
||||
o
|
||||
};
|
||||
let idx = |i: usize, j: usize| j * (n + 1) + i;
|
||||
// A sane mesh's triangles each span about one grid cell (ow/n by oh/n), rounded out to
|
||||
// whole pixels. A thin output (16384×1) stacks every grid row onto the same pixel row, so
|
||||
// allow each of the 2n² triangles about two cells' extent along each axis, with margin.
|
||||
let rounding = (4 * n as u64).saturating_mul((ow as u64).saturating_add(oh as u64).saturating_add(n as u64));
|
||||
let budget = (count as u64).saturating_mul(BAKE_WORK_FACTOR).max(MIN_BAKE_WORK).saturating_add(rounding);
|
||||
let mut work = 0u64;
|
||||
for j in 0..n {
|
||||
for i in 0..n {
|
||||
for tri in [[idx(i, j), idx(i + 1, j), idx(i + 1, j + 1)], [idx(i, j), idx(i + 1, j + 1), idx(i, j + 1)]] {
|
||||
let [a, b, c] = tri.map(|t| dst[t]);
|
||||
let den = (b[1] - c[1]) * (a[0] - c[0]) + (c[0] - b[0]) * (a[1] - c[1]);
|
||||
if den.abs() < 1e-12 {
|
||||
continue;
|
||||
}
|
||||
// Loop-invariant per triangle: the source corners and the barycentric coefficients.
|
||||
let [sa, sb, sc] = tri.map(|t| src[t]);
|
||||
let (l1y, l1x) = (b[1] - c[1], c[0] - b[0]);
|
||||
let (l2y, l2x) = (c[1] - a[1], a[0] - c[0]);
|
||||
let x0 = a[0].min(b[0]).min(c[0]).floor().max(0.0) as usize;
|
||||
let x1 = (a[0].max(b[0]).max(c[0]).ceil() as usize).min(ow);
|
||||
let y0 = a[1].min(b[1]).min(c[1]).floor().max(0.0) as usize;
|
||||
let y1 = (a[1].max(b[1]).max(c[1]).ceil() as usize).min(oh);
|
||||
work = work.saturating_add((x1.saturating_sub(x0) as u64).saturating_mul(y1.saturating_sub(y0) as u64));
|
||||
if work > budget {
|
||||
return None;
|
||||
}
|
||||
for y in y0..y1 {
|
||||
for x in x0..x1 {
|
||||
let (px, py) = (x as f64 + 0.5, y as f64 + 0.5);
|
||||
let l1 = (l1y * (px - c[0]) + l1x * (py - c[1])) / den;
|
||||
let l2 = (l2y * (px - c[0]) + l2x * (py - c[1])) / den;
|
||||
let l3 = 1.0 - l1 - l2;
|
||||
if l1 < -1e-9 || l2 < -1e-9 || l3 < -1e-9 {
|
||||
continue;
|
||||
}
|
||||
let sx = sa[0] * l1 + sb[0] * l2 + sc[0] * l3;
|
||||
let sy = sa[1] * l1 + sb[1] * l2 + sc[1] * l3;
|
||||
out[y * ow + x] = sample(sx, sy);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Back to straight alpha.
|
||||
for p in &mut out {
|
||||
if p[3] > 0.0 {
|
||||
for c in 0..3 {
|
||||
p[c] /= p[3];
|
||||
}
|
||||
}
|
||||
}
|
||||
Some((Pixels { width: ow as u32, height: oh as u32, data: out }, [bb[0], bb[1]]))
|
||||
let (out, origin) = to_craft_smart(self).render_placed_pixels(content.width, content.height, &content.data, k, size)?;
|
||||
Some((Pixels { width: out.width, height: out.height, data: out.data }, origin))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -92,3 +92,51 @@ fn a_tiny_file_claiming_a_huge_image_is_refused_within_the_budget() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_modern_placement_does_not_fall_back_to_legacy_in_either_order() {
|
||||
use craft_psd::descriptor::{Descriptor, Id, ObjectArray, UnicodeString, Value, VersionedDescriptor};
|
||||
let quad = [[0.0, 0.0], [20.0, 0.0], [20.0, 10.0], [0.0, 10.0]];
|
||||
let legacy = craft_psd::smart::SmartObject { uuid: "legacy".into(), quad, size: Some([20.0, 10.0]), warp: None }.to_placed_layer();
|
||||
let modern = |middle| {
|
||||
let floats = |values| Value::UnitFloats { unit: *b"#Pxl", values };
|
||||
let points = Descriptor::new("rationalPoint")
|
||||
.with("Hrzn", floats((0..4).flat_map(|_| (0..7).map(|i| i as f64 * 20.0 / 6.0)).collect()))
|
||||
.with("Vrtc", floats((0..4).flat_map(|j| [j as f64 * 10.0 / 3.0; 7]).collect()));
|
||||
let envelope = Descriptor::new("customEnvelopeWarp")
|
||||
.with("quiltSliceX", floats(vec![0.0, middle, 20.0]))
|
||||
.with("quiltSliceY", floats(vec![0.0, 10.0]))
|
||||
.with("meshPoints", Value::ObjectArray(ObjectArray { prefix: 28, body: points }));
|
||||
let warp = Descriptor::new("quiltWarp")
|
||||
.with("warpStyle", Value::Enumerated { type_id: Id::new("warpStyle"), value: Id::new("warpCustom") })
|
||||
.with("customEnvelopeWarp", Value::Descriptor(envelope));
|
||||
let descriptor = Descriptor::new("null")
|
||||
.with("Idnt", Value::Text(UnicodeString::new("modern")))
|
||||
.with("Trnf", Value::List(quad.iter().flatten().map(|v| Value::Double(*v)).collect()))
|
||||
.with("quiltWarp", Value::Descriptor(warp));
|
||||
let mut bytes = b"soLD".to_vec();
|
||||
bytes.extend_from_slice(&4u32.to_be_bytes());
|
||||
bytes.extend_from_slice(&VersionedDescriptor::new(descriptor).to_bytes());
|
||||
bytes
|
||||
};
|
||||
for key in [*b"SoLd", *b"SoLE"] {
|
||||
for legacy_first in [false, true] {
|
||||
for (bytes, expected) in [(modern(5.0), None), (modern(10.0), Some("modern")), (b"soLD".to_vec(), Some("legacy"))] {
|
||||
let mut blocks = vec![(key, bytes), (*b"PlLd", legacy.clone()), (*b"luni", vec![0])];
|
||||
if legacy_first {
|
||||
blocks.swap(0, 1);
|
||||
}
|
||||
let mut doc = WDoc::new(2, 2);
|
||||
doc.layers = vec![WLayer::empty("placement", blocks)];
|
||||
let result = Psd::parse(write(&doc));
|
||||
if let Some(uuid) = expected {
|
||||
let parsed = result.unwrap();
|
||||
assert_eq!(parsed.layers[0].smart_object.as_ref().unwrap().uuid, uuid);
|
||||
assert_eq!(parsed.layers[0].name, "placement", "malformed optional metadata still recovers");
|
||||
} else {
|
||||
assert!(matches!(result, Err(Error::Unsupported(_))), "unsupported modern placement must be reported");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+107
-3
@@ -641,11 +641,11 @@ fn placed_bake_solves_the_quad_once() {
|
||||
assert_eq!(counters::take(&QUAD), 1, "33×33 mapped points, one solve (was 1089)");
|
||||
so.placed_size(20.0, 10.0, 1.0);
|
||||
assert_eq!(counters::take(&QUAD), 1);
|
||||
// The bounds, the size and the 49×49 grid of one bake share a single solve (was 1089 × 2 + 2401).
|
||||
// The bake itself runs in craft-psd, so it no longer bumps this crate's quad counter.
|
||||
so.render_placed(&content(20, 10), 1.0, None).unwrap();
|
||||
assert_eq!(counters::take(&QUAD), 1);
|
||||
assert_eq!(counters::take(&QUAD), 0);
|
||||
so.render_placed(&content(20, 10), 1.0, Some((40, 40))).unwrap();
|
||||
assert_eq!(counters::take(&QUAD), 1);
|
||||
assert_eq!(counters::take(&QUAD), 0);
|
||||
// A single `map` still solves for itself.
|
||||
so.map([1.0, 1.0], 20.0, 10.0);
|
||||
assert_eq!(counters::take(&QUAD), 1);
|
||||
@@ -668,3 +668,107 @@ fn shared_unpredict_keeps_tail_bytes_and_refuses_unbudgeted_scratch() {
|
||||
assert!(p.unpredict(&mut bytes, 3, 2, &mut Budget::new(11)).is_err());
|
||||
assert_eq!(bytes, vec![0x31; 24], "budget refusal precedes mutation");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_descriptor_parser_preserves_application_count_limits() {
|
||||
use craft_psd::descriptor::{Descriptor as Shared, Value};
|
||||
let mut bytes = Shared::new("test").to_bytes();
|
||||
let end = bytes.len();
|
||||
bytes[end - 4..].copy_from_slice(&100_001u32.to_be_bytes());
|
||||
let error = crate::descriptor::read_descriptor(&mut Reader::new(&bytes)).unwrap_err();
|
||||
assert!(matches!(error, Error::Invalid(ref message) if message.contains("too many descriptor items")));
|
||||
let mut bytes = Shared::new("test").with("list", Value::List(vec![])).to_bytes();
|
||||
let end = bytes.len();
|
||||
bytes[end - 4..].copy_from_slice(&1_000_001u32.to_be_bytes());
|
||||
let error = crate::descriptor::read_descriptor(&mut Reader::new(&bytes)).unwrap_err();
|
||||
assert!(matches!(error, Error::Invalid(ref message) if message.contains("too many descriptor list items")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placed_bake_keeps_the_borrowed_source_available_on_rejection() {
|
||||
let object = SmartObject { uuid: String::new(), quad: [[0.0, 0.0], [2.0, 0.0], [2.0, 2.0], [0.0, 2.0]], size: None, warp: None };
|
||||
let source = Pixels { width: 2, height: 2, data: vec![[1.0, 0.5, 0.25, 0.5]; 4] };
|
||||
let original = source.data.clone();
|
||||
let ptr = source.data.as_ptr();
|
||||
assert!(object.render_placed(&source, 1.0, Some((u32::MAX, u32::MAX))).is_none());
|
||||
assert_eq!(source.data, original);
|
||||
assert_eq!(source.data.as_ptr(), ptr);
|
||||
assert!(object.render_placed(&source, 1.0, Some((2, 2))).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identifier_and_index_references_preserve_non_null_classes_exactly() {
|
||||
use craft_psd::descriptor::{Class, Descriptor as Shared, Id, ReferenceItem, UnicodeString, Value};
|
||||
for class in [
|
||||
Class { name: UnicodeString(vec![0xD800, 0]), class_id: Id::Code(*b"Lyr ") },
|
||||
Class { name: UnicodeString::default(), class_id: Id::Code(*b"null") },
|
||||
Class { name: UnicodeString::default(), class_id: Id::Str(b"null".to_vec()) },
|
||||
Class { name: UnicodeString(vec![0]), class_id: Id::Code(*b"null") },
|
||||
] {
|
||||
let mut original = Shared::new("test")
|
||||
.with("refs", Value::Reference(vec![ReferenceItem::Identifier { class: class.clone(), id: u32::MAX }, ReferenceItem::Index { class, index: 7 }]));
|
||||
original.name = UnicodeString(vec![0]);
|
||||
let bytes = original.to_bytes();
|
||||
let local = crate::descriptor::read_descriptor(&mut Reader::new(&bytes)).unwrap();
|
||||
let mut out = Vec::new();
|
||||
crate::descriptor::write_descriptor(&mut out, &local);
|
||||
assert_eq!(Shared::from_bytes(&out).unwrap(), original);
|
||||
assert_eq!(out, bytes);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn shared_descriptor_nesting_preserves_the_application_boundary() {
|
||||
use craft_psd::descriptor::{Descriptor as Shared, Value};
|
||||
for count in [33, 64, 65] {
|
||||
let mut value = Value::Integer(1);
|
||||
for _ in 0..count {
|
||||
value = Value::Descriptor(Shared::new("null").with("next", value));
|
||||
}
|
||||
let bytes = Shared::new("null").with("root", value).to_bytes();
|
||||
let result = crate::descriptor::read_descriptor(&mut Reader::new(&bytes));
|
||||
assert_eq!(result.is_ok(), count <= 64, "nested descriptor count {count}: {result:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_placed_layer_adapter_normalizes_before_warp_classification() {
|
||||
use craft_psd::descriptor::{Descriptor as Shared, Id, Value};
|
||||
let warp = Shared::new("warp")
|
||||
.with("warpStyle", Value::Enumerated { type_id: Id::new("warpStyle"), value: Id::new("warpArc") })
|
||||
.with("warpValue", Value::Double(f64::NAN))
|
||||
.with("warpPerspective", Value::Double(f64::INFINITY))
|
||||
.with("warpPerspectiveOther", Value::Double(f64::NEG_INFINITY));
|
||||
let quad = [f64::NAN, 0.0, 20.0, 0.0, 20.0, 10.0, 0.0, 10.0];
|
||||
let descriptor = Shared::new("null").with("Trnf", Value::List(quad.into_iter().map(Value::Double).collect())).with("warp", Value::Descriptor(warp));
|
||||
let mut bytes = b"soLD".to_vec();
|
||||
bytes.extend_from_slice(&4u32.to_be_bytes());
|
||||
bytes.extend_from_slice(&16u32.to_be_bytes());
|
||||
bytes.extend_from_slice(&descriptor.to_bytes());
|
||||
let shared = craft_psd::smart::SmartObject::from_placed_layer_data_with_limits(&bytes, crate::descriptor::PARSE_LIMITS).unwrap();
|
||||
let object = crate::placed::from_craft_smart(shared);
|
||||
assert_eq!(object.quad, [[0.0, 0.0], [20.0, 0.0], [20.0, 10.0], [0.0, 10.0]]);
|
||||
assert!(object.warp.is_none(), "normalization must precede identity classification");
|
||||
assert!(!object.needs_bake());
|
||||
assert_eq!(object.map([10.0, 5.0], 20.0, 10.0), [10.0, 5.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_and_shared_warp_mapping_agree_on_overflowing_bounds() {
|
||||
let mesh: Vec<_> = (0..4).flat_map(|j| (0..4).map(move |i| [i as f64 * 20.0 / 3.0, j as f64 * 10.0 / 3.0])).collect();
|
||||
for bounds in [[-f64::MAX, 0.0, f64::MAX, 10.0], [0.0, -f64::MAX, 20.0, f64::MAX]] {
|
||||
let shared = craft_psd::smart::SmartObject {
|
||||
uuid: String::new(),
|
||||
quad: [[0.0, 0.0], [20.0, 0.0], [20.0, 10.0], [0.0, 10.0]],
|
||||
size: Some([20.0, 10.0]),
|
||||
warp: Some(craft_psd::smart::Warp { style: "warpCustom".into(), bounds, cols: 1, rows: 1, mesh: mesh.clone(), ..Default::default() }),
|
||||
};
|
||||
let local = crate::placed::from_craft_smart(shared.clone());
|
||||
for point in [[5.0, 2.5], [10.0, 5.0], [15.0, 7.5]] {
|
||||
let actual = local.map(point, 20.0, 10.0);
|
||||
assert_eq!(actual, shared.map(point, 20.0, 10.0));
|
||||
for axis in 0..2 {
|
||||
assert!((actual[axis] - point[axis]).abs() < 1e-9, "{bounds:?} {point:?}: {actual:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user