Compare commits

...
Author SHA1 Message Date
Timon 45757b45f4 Report attribute type conflicts from push/extend and when reading list attributes 2026-10-30 14:17:17 +00:00
Timon 207647e78f Report attribute type mismatches 2026-10-30 14:17:17 +00:00
Timon d90cc62bc1 Make nodes report errors instead of panicking or failing silently (#4837)
* Fix crashes and report errors in math nodes

* Fix crashes and report errors in text nodes and Boolean Operation

* Fix crashes and report errors in raster, brush and I/O nodes

* Fix crashes and report errors in vector and transform nodes

* Report errors from graphic and context nodes
2026-10-30 14:16:24 +00:00
55 changed files with 2765 additions and 1033 deletions

No files matched your search

Generated
+11 -2
View File
@@ -966,6 +966,7 @@ dependencies = [
"serde",
"serde_json",
"skrifa",
"thiserror 2.0.18",
"tinyvec",
"tsify",
"wasm-bindgen",
@@ -2177,6 +2178,7 @@ dependencies = [
"node-macro",
"raster-types",
"serde",
"thiserror 2.0.18",
"tsify",
"wasm-bindgen",
]
@@ -2264,6 +2266,7 @@ dependencies = [
"rand",
"raster-types",
"serde",
"thiserror 2.0.18",
"vector-types",
]
@@ -3614,10 +3617,10 @@ dependencies = [
"glam 0.33.10",
"graphene-core",
"graphic-types",
"log",
"math-parser",
"node-macro",
"rand",
"thiserror 2.0.18",
"vector-types",
]
@@ -4289,6 +4292,7 @@ dependencies = [
"node-macro",
"smallvec",
"text-nodes",
"thiserror 2.0.18",
"vector-types",
]
@@ -4837,6 +4841,7 @@ dependencies = [
"raster-types",
"serde",
"spirv-std",
"thiserror 2.0.18",
"tokio",
"tsify",
"vector-types",
@@ -4874,6 +4879,7 @@ dependencies = [
"node-macro",
"serde",
"serde_json",
"thiserror 2.0.18",
"tsify",
"wasm-bindgen",
"wgpu",
@@ -6120,13 +6126,13 @@ dependencies = [
"graphene-hash",
"graphene-resource",
"ipsum",
"log",
"node-macro",
"parley",
"rand",
"serde",
"serde_json",
"skrifa",
"thiserror 2.0.18",
"titlecase",
"tsify",
"unicode-segmentation",
@@ -6526,6 +6532,7 @@ dependencies = [
"node-macro",
"rand",
"serde",
"thiserror 2.0.18",
"vector-types",
]
@@ -6787,6 +6794,7 @@ dependencies = [
"repeat-nodes",
"rustc-hash 2.1.1",
"serde",
"thiserror 2.0.18",
"tokio",
"tsify",
"vector-types",
@@ -6816,6 +6824,7 @@ dependencies = [
"rustc-hash 2.1.1",
"serde",
"serde_json",
"thiserror 2.0.18",
"tinyvec",
"tsify",
"wasm-bindgen",
@@ -197,7 +197,7 @@ mod tests {
for file_type in [FileType::Png, FileType::Jpg, FileType::Webp, FileType::Tiff, FileType::Bmp, FileType::Tga, FileType::Ico] {
let encoded = file_type.encode(2, 1, pixels.clone()).unwrap_or_else(|error| panic!("{file_type:?}: {error}"));
let decoded = Image::from_encoded(&encoded).unwrap_or_else(|| panic!("{file_type:?} should read back"));
let decoded = Image::from_encoded(&encoded).unwrap_or_else(|error| panic!("{file_type:?} should read back: {error}"));
assert_eq!((decoded.width, decoded.height), (2, 1), "{file_type:?}");
// Only JPG lacks transparency, so it lands on white
@@ -623,13 +623,13 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
.collect(),
..Default::default()
}),
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::String("graphite:null".to_string()), false)],
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::String(String::new()), false)],
input_metadata: vec![
("Empty", "Has no effect, since the image is loaded from the URL.").into(),
("URL", "The web address or local asset path of the image to load.").into(),
],
output_names: vec!["Image".to_string()],
output_descriptions: vec!["The loaded image, which is empty if it fails to load or decode.".to_string()],
output_descriptions: vec!["The loaded image.".to_string()],
..Default::default()
},
description: Cow::Borrowed("Loads an image from a given URL."),
@@ -1179,7 +1179,7 @@ impl OverlayContextInternal {
// Lay out the text once, taking its dimensions and vector paths from the same thread-local context pass
let (text_size, text_list) = TextContext::with_thread_local(|text_context| {
let text_size = text_context.bounding_box(text, &FALLBACK_FONT_RESOURCE, typesetting, false);
let text_list = text_context.to_path(text, &FALLBACK_FONT_RESOURCE, typesetting, false);
let text_list = text_context.to_path(text, &FALLBACK_FONT_RESOURCE, typesetting, false).unwrap_or_default();
(text_size, text_list)
});
let text_width = text_size.x;
@@ -3447,6 +3447,18 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), old_inputs[2].clone(), network_path);
}
// Load Image's URL is empty until set, it used to be `graphite:null`
if reference == DefinitionIdentifier::Network("Load Image".into())
&& let Some(url) = node.inputs.get(1)
&& matches!(url.as_value(), Some(TaggedValue::String(url)) if url == "graphite:null")
{
document.network_interface.set_input(
&InputConnector::node_at_index(*node_id, 1),
NodeInput::value(TaggedValue::String(String::new()), url.is_exposed()),
network_path,
);
}
// `wgpu-executor` scope was removed, change to the auto injected scope node `graphene_std::platform_application_io::wgpu_executor`
for (i, input) in node.inputs.iter().enumerate() {
if let NodeInput::Scope(name) = input
@@ -480,7 +480,8 @@ pub fn star_outline(layer: Option<LayerNodeIdentifier>, document: &DocumentMessa
let viewport = document.metadata().transform_to_viewport(layer);
let points = sides as u64;
let targets: Vec<ClickTargetType> = vec![ClickTargetType::Path(star_polygon_bezpath(DVec2::ZERO, points, radius1, radius2))];
let Ok(star) = star_polygon_bezpath(DVec2::ZERO, points, radius1, radius2) else { return };
let targets: Vec<ClickTargetType> = vec![ClickTargetType::Path(star)];
overlay_context.outline(targets.iter(), viewport, None);
}
@@ -495,7 +496,8 @@ pub fn polygon_outline(layer: Option<LayerNodeIdentifier>, document: &DocumentMe
let viewport = document.metadata().transform_to_viewport(layer);
let points = sides as u64;
let targets: Vec<ClickTargetType> = vec![ClickTargetType::Path(regular_polygon_bezpath(DVec2::ZERO, points, radius))];
let Ok(polygon) = regular_polygon_bezpath(DVec2::ZERO, points, radius) else { return };
let targets: Vec<ClickTargetType> = vec![ClickTargetType::Path(polygon)];
overlay_context.outline(targets.iter(), viewport, None);
}
@@ -51,6 +51,7 @@ log = { workspace = true }
base64 = { workspace = true }
polycool = { workspace = true }
futures = { workspace = true }
thiserror = { workspace = true }
# Optional workspace dependencies
serde = { workspace = true, optional = true }
+182 -44
View File
@@ -1,3 +1,4 @@
use crate::TypeDescriptor;
use crate::bounds::{BoundingBox, RenderBoundingBox};
use crate::math::quad::Quad;
use crate::transform::ApplyTransform;
@@ -203,6 +204,12 @@ fn implicit_default_value(key: &str) -> Option<Box<dyn AnyAttributeValue>> {
}
}
/// What pushing and extending lists pad a missing `key` attribute with: `key`'s implicit default if it has type `T`, otherwise
/// `T::default()`.
pub fn implicit_default<T: Clone + Default + 'static>(key: &str) -> T {
implicit_default_value(key).and_then(|default| default.as_any().downcast_ref::<T>().cloned()).unwrap_or_default()
}
/// Appends `count` copies of `key`'s implicit default to `attribute` (see [`implicit_default_value`]).
fn pad_with_implicit_default(key: &str, attribute: &mut dyn AnyAttribute, count: usize) {
match implicit_default_value(key) {
@@ -398,8 +405,8 @@ pub trait AnyAttribute: std::any::Any + Send + Sync {
/// Converts the shared attribute into one that can be downcast to its concrete type.
fn into_any_arc(self: Arc<Self>) -> Arc<dyn std::any::Any + Send + Sync>;
/// Pushes a scalar attribute value onto the end of this attribute.
fn push(&mut self, value: Arc<dyn AnyAttributeValue>);
/// Pushes a scalar attribute value onto the end of this attribute, or a default if it has another type, which returns `false`.
fn push(&mut self, value: Arc<dyn AnyAttributeValue>) -> bool;
/// Pushes a default value onto the end of this attribute.
fn push_default(&mut self);
@@ -409,8 +416,8 @@ pub trait AnyAttribute: std::any::Any + Send + Sync {
fn push_repeated(&mut self, value: &dyn AnyAttributeValue, count: usize);
/// Sets the value at the given index, padding with defaults if the attribute is shorter than `index`.
/// Falls back to a default if the value's type doesn't match.
fn set_at(&mut self, index: usize, value: Box<dyn AnyAttributeValue>);
/// Hands the value back if it has another type.
fn set_at(&mut self, index: usize, value: Box<dyn AnyAttributeValue>) -> Result<(), Box<dyn AnyAttributeValue>>;
/// Creates a new attribute of the same type filled with `count` number of default values.
fn new_with_defaults(&self, count: usize) -> Arc<dyn AnyAttribute>;
@@ -423,8 +430,8 @@ pub trait AnyAttribute: std::any::Any + Send + Sync {
self.len() == 0
}
/// Appends all values from another attribute of the same type.
fn extend(&mut self, other: Arc<dyn AnyAttribute>);
/// Appends all values from another attribute of the same type, or defaults for them if it has another type, which returns `false` unless it is empty.
fn extend(&mut self, other: Arc<dyn AnyAttribute>) -> bool;
/// Returns a shared reference to the value at the requested index.
fn get_any(&self, index: usize) -> Option<&dyn std::any::Any>;
@@ -444,6 +451,9 @@ pub trait AnyAttribute: std::any::Any + Send + Sync {
/// Compares this attribute to another for value-by-value equality (object-safe wrapper around `PartialEq`).
/// Returns `false` if the underlying types differ.
fn eq_dyn(&self, other: &dyn AnyAttribute) -> bool;
/// The type of this attribute's values.
fn value_type(&self) -> TypeDescriptor;
}
/// Adapts a `&mut dyn Hasher` so generic `CacheHash::cache_hash<H>` calls (which require `H: Sized + Hasher`) can
@@ -542,9 +552,11 @@ impl<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>
/// Pushes an attribute value onto the end of this attribute's list, downcasting it to `T`.
/// Falls back to a default value if the type doesn't match, to maintain the attribute-length invariant.
fn push(&mut self, value: Arc<dyn AnyAttributeValue>) {
let value = value.into_any_arc().downcast::<T>().map(Arc::unwrap_or_clone).unwrap_or_default();
self.0.push(value);
fn push(&mut self, value: Arc<dyn AnyAttributeValue>) -> bool {
let value = value.into_any_arc().downcast::<T>().map(Arc::unwrap_or_clone);
let matches = value.is_ok();
self.0.push(value.unwrap_or_default());
matches
}
/// Pushes a default `T` value onto the end of this attribute list.
@@ -559,8 +571,11 @@ impl<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>
}
/// Sets the value at the given index, padding with defaults if the attribute is shorter than `index`.
/// Falls back to a default if the value's type doesn't match.
fn set_at(&mut self, index: usize, value: Box<dyn AnyAttributeValue>) {
/// Hands the value back if it isn't a `T`.
fn set_at(&mut self, index: usize, value: Box<dyn AnyAttributeValue>) -> Result<(), Box<dyn AnyAttributeValue>> {
if !value.as_any().is::<T>() {
return Err(value);
}
while self.0.len() < index {
self.0.push(T::default());
}
@@ -570,6 +585,7 @@ impl<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>
} else {
self.0[index] = value;
}
Ok(())
}
/// Creates a new attribute filled with `count` default `T` values.
@@ -585,14 +601,18 @@ impl<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>
/// Appends all values from another attribute, downcasting it to the same `Attribute<T>` type.
/// Falls back to padding with defaults if the type doesn't match, to maintain the attribute-length invariant.
fn extend(&mut self, other: Arc<dyn AnyAttribute>) {
fn extend(&mut self, other: Arc<dyn AnyAttribute>) -> bool {
let other_len = other.len();
match other.into_any_arc().downcast::<Self>().map(Arc::try_unwrap) {
Ok(Ok(other)) => self.0.extend(other.0),
Ok(Err(shared)) => self.0.extend_from_slice(&shared.0),
Err(_) => self.0.extend(std::iter::repeat_with(T::default).take(other_len)),
Err(_) => {
self.0.extend(std::iter::repeat_with(T::default).take(other_len));
return other_len == 0;
}
}
true
}
/// Returns a shared reference to the value at the given index as a type-erased `Any`.
@@ -629,6 +649,10 @@ impl<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>
fn eq_dyn(&self, other: &dyn AnyAttribute) -> bool {
other.as_any().downcast_ref::<Self>().is_some_and(|other| self.0 == other.0)
}
fn value_type(&self) -> TypeDescriptor {
crate::descriptor!(T)
}
}
// ==================
@@ -700,6 +724,11 @@ impl ListDyn {
pub fn attribute<U: 'static>(&self, key: &str, index: usize) -> Option<&U> {
self.attributes.get_value(key, index)
}
/// Returns the type of the values the attribute for the given key holds, or `None` if absent.
pub fn attribute_type(&self, key: &str) -> Option<TypeDescriptor> {
self.attributes.value_type(key)
}
}
impl<T> From<List<T>> for ListDyn {
@@ -1081,23 +1110,31 @@ impl Attributes {
/// Pushes an item's scalar attributes into this attribute store.
/// Existing attributes that the item lacks receive a default value.
/// New attribute keys create a new attribute padded with defaults for all prior items.
fn push_item(&mut self, item: ItemAttributeValues) {
/// Returns the first attribute that holds another type than the item's value for it, which gets the default instead.
fn push_item(&mut self, item: ItemAttributeValues) -> Option<AttributeTypeConflictError> {
let len = self.len;
self.len += 1;
if self.attributes.is_empty() && item.0.is_none() {
return;
return None;
}
let mut item_entries = item.into_entries();
let mut conflict = None;
// Push values into existing attributes, or the implicit default if the item lacks that attribute
for (attribute_key, attribute) in self.attributes.as_mut_slice() {
let attribute = unshared(attribute);
match item_entries.iter().position(|(key, _)| key == attribute_key) {
Some(position) => attribute.push(item_entries.swap_remove(position).1),
None => pad_with_implicit_default(attribute_key.as_str(), attribute, 1),
// An attribute without values holds no type to keep
Some(position) if len == 0 => *attribute = item_entries.swap_remove(position).1.into_attribute(attribute_key.as_str(), 0),
Some(position) => {
if !unshared(attribute).push(item_entries.swap_remove(position).1) {
conflict.get_or_insert_with(|| AttributeTypeConflictError {
name: attribute_key.as_str().to_string(),
});
}
}
None => pad_with_implicit_default(attribute_key.as_str(), unshared(attribute), 1),
}
}
@@ -1106,33 +1143,41 @@ impl Attributes {
let attribute = value.into_attribute(key.as_str(), len);
self.attributes.push((key, attribute));
}
conflict
}
/// Appends all attribute data from another attribute store into this one.
/// Attributes present in only one side are padded with defaults for the other side's items.
fn extend(&mut self, other: Attributes) {
/// Returns the first attribute both stores hold with values of different types, where the other store's items get the default.
fn extend(&mut self, other: Attributes) -> Option<AttributeTypeConflictError> {
let (len, other_len) = (self.len, other.len);
self.len += other_len;
// An empty store takes on the other's attributes whole, sharing them
if len == 0 && self.entries().is_empty() {
self.attributes = other.attributes;
return;
return None;
}
// Nothing to add or pad, so self's attributes can stay shared
if other.attributes.is_empty() && (other_len == 0 || self.attributes.is_empty()) {
return;
return None;
}
let mut other_entries = other.attributes.into_vec();
let mut conflict = None;
// Extend matching attributes, or pad self's attributes with implicit defaults for the other's item count
for (key, self_attribute) in self.attributes.as_mut_slice() {
let self_attribute = unshared(self_attribute);
match other_entries.iter().position(|(other_key, _)| other_key == key) {
Some(position) => self_attribute.extend(other_entries.swap_remove(position).1),
None => pad_with_implicit_default(key.as_str(), self_attribute, other_len),
// An attribute without values holds no type to keep
Some(position) if len == 0 => *self_attribute = other_entries.swap_remove(position).1,
Some(position) => {
if !unshared(self_attribute).extend(other_entries.swap_remove(position).1) {
conflict.get_or_insert_with(|| AttributeTypeConflictError { name: key.as_str().to_string() });
}
}
None => pad_with_implicit_default(key.as_str(), unshared(self_attribute), other_len),
}
}
@@ -1145,6 +1190,13 @@ impl Attributes {
self.attributes.push((key, combined));
}
conflict
}
/// The type of the values the attribute for the given key holds, if present.
fn value_type(&self, key: &str) -> Option<TypeDescriptor> {
self.entries().iter().find(|(k, _)| k.is(key)).map(|(_, attribute)| attribute.value_type())
}
/// Gets a reference to the value at the given index from the attribute for the given key.
@@ -1221,18 +1273,24 @@ impl Attributes {
}
/// Sets a single type-erased value at the given index of a list of `item_count` items, creating the attribute from the
/// value's type if the key holds none.
fn set_value_dyn(&mut self, key: &str, index: usize, value: Box<dyn AnyAttributeValue>, item_count: usize) {
let position = self.position(key);
if let Some((_, attribute)) = position.and_then(|position| self.attributes.as_mut_slice().get_mut(position)) {
unshared(attribute).set_at(index, value);
} else {
let mut new_attribute = Arc::<dyn AnyAttributeValue>::from(value).into_attribute(key, index);
let trailing_defaults = item_count.saturating_sub(new_attribute.len());
pad_with_implicit_default(key, unshared(&mut new_attribute), trailing_defaults);
self.attributes.push((AttributeKey::new(key), new_attribute));
/// value's type if the key holds none. An attribute of another type is replaced, padded with implicit defaults.
fn set_value_dyn(&mut self, key: &str, index: usize, mut value: Box<dyn AnyAttributeValue>, item_count: usize) {
if let Some(position) = self.position(key)
&& let Some((_, attribute)) = self.attributes.as_mut_slice().get_mut(position)
{
match unshared(attribute).set_at(index, value) {
Ok(()) => return,
Err(mistyped) => {
self.attributes.remove(position);
value = mistyped;
}
}
}
let mut new_attribute = Arc::<dyn AnyAttributeValue>::from(value).into_attribute(key, index);
let trailing_defaults = item_count.saturating_sub(new_attribute.len());
pad_with_implicit_default(key, unshared(&mut new_attribute), trailing_defaults);
self.attributes.push((AttributeKey::new(key), new_attribute));
}
/// Returns a debug-formatted string for the value at the given index in the attribute for the given key.
@@ -1327,6 +1385,12 @@ impl Attributes {
}
}
#[derive(Clone, Debug, PartialEq, thiserror::Error)]
#[error("The \"{name}\" attribute holds different types of values in the lists being combined")]
pub struct AttributeTypeConflictError {
pub name: String,
}
// =======
// List<T>
// =======
@@ -1488,7 +1552,7 @@ impl<T> List<T> {
}
/// Sets a single type-erased attribute value at the given index, creating the attribute from the value's underlying type if it doesn't exist (padded with defaults to match the list's length).
/// Falls back to default if the value's type doesn't match an existing attribute.
/// An existing attribute of another type is replaced the same way.
pub fn set_attribute_value_dyn(&mut self, key: impl AsRef<str>, index: usize, value: AttributeValueDyn) {
self.attributes.set_value_dyn(key.as_ref(), index, value.0, self.element.len());
}
@@ -1545,14 +1609,16 @@ impl<T: Clone> List<T> {
Arc::make_mut(&mut self.element)
}
/// Appends an item to the end of this list.
pub fn push(&mut self, item: Item<T>) {
/// Appends an item to the end of this list, returning the first attribute the list holds with another type than the item's value for it.
/// The list keeps its type for it, giving the item its default.
pub fn push(&mut self, item: Item<T>) -> Option<AttributeTypeConflictError> {
self.elements_mut().push(item.element);
self.attributes.push_item(item.attributes);
self.attributes.push_item(item.attributes)
}
/// Appends all items from another list into this one.
pub fn extend(&mut self, list: List<T>) {
/// Appends all items from another list into this one, returning the first attribute both lists have with values of different types.
/// This list keeps its type for it, giving the other list's items its default.
pub fn extend(&mut self, list: List<T>) -> Option<AttributeTypeConflictError> {
// An empty list adopts the other's elements without copying them
if self.element.is_empty() {
self.element = list.element;
@@ -1563,7 +1629,7 @@ impl<T: Clone> List<T> {
Err(shared) => elements.extend_from_slice(&shared),
}
}
self.attributes.extend(list.attributes);
self.attributes.extend(list.attributes)
}
/// Returns an iterator over mutable references to all element values.
@@ -2179,6 +2245,78 @@ mod tests {
assert_eq!(starts(&rebuilt), [11, 21, 10, 20, 0]);
}
// Combining lists keeps only the first type of an attribute both have, and reports the attribute whose values were lost
#[test]
fn combining_lists_reports_attribute_type_conflicts() {
let mut base = List::new_from_elements(vec![1_u32, 2]);
base.set_attribute_values(ATTR_START, vec![10_u64, 20]);
base.set_attribute_values(ATTR_NAME, vec![String::from("a"), String::from("b")]);
let mut matching = List::new_from_elements(vec![3_u32]);
matching.set_attribute_values(ATTR_START, vec![30_u64]);
matching.set_attribute_values(ATTR_END, vec![1.5_f64]);
assert_eq!(base.extend(matching), None);
let mut empty = List::new();
empty.set_attribute_values(ATTR_NAME, Vec::<i64>::new());
assert_eq!(base.extend(empty), None, "an empty list loses no values");
let mut mistyped = List::new_from_elements(vec![4_u32]);
mistyped.set_attribute_values(ATTR_NAME, vec![7_i64]);
let conflict = AttributeTypeConflictError { name: ATTR_NAME.to_string() };
assert_eq!(base.extend(mistyped), Some(conflict.clone()));
assert_eq!(conflict.to_string(), "The \"name\" attribute holds different types of values in the lists being combined");
assert_eq!(base.attribute::<String>(ATTR_NAME, 3), Some(&String::new()));
assert_eq!(base.push(Item::new_from_element(5).with_attribute(ATTR_START, 50_u64)), None);
let mistyped_item = Item::new_from_element(6).with_attribute(ATTR_START, 60_f64);
assert_eq!(base.push(mistyped_item), Some(AttributeTypeConflictError { name: ATTR_START.to_string() }));
assert_eq!(base.attribute::<u64>(ATTR_START, 5), Some(&0));
}
#[test]
fn an_attribute_without_values_takes_the_type_of_the_values_added_to_it() {
let mut mistyped = List::new_from_elements(vec![1_u32]);
mistyped.set_attribute_values(ATTR_NAME, vec![7_i64]);
let mut extended = List::<u32>::new();
extended.set_attribute_values(ATTR_NAME, Vec::<String>::new());
assert_eq!(extended.extend(mistyped), None);
assert_eq!(extended.attribute::<i64>(ATTR_NAME, 0), Some(&7));
let mut pushed = List::<u32>::new();
pushed.set_attribute_values(ATTR_NAME, Vec::<String>::new());
assert_eq!(pushed.push(Item::new_from_element(1).with_attribute(ATTR_NAME, 7_i64)), None);
assert_eq!(pushed.attribute::<i64>(ATTR_NAME, 0), Some(&7));
}
// An attribute's type reads back from a list's type-erased view, and a missing value reads as what padding fills in
#[test]
fn attribute_types_and_implicit_defaults_read_back() {
let mut list = List::new_from_elements(vec![1_u32]);
list.set_attribute(ATTR_OPACITY, 0, 0.5_f64);
let list = ListDyn::from(list);
assert_eq!(list.attribute_type(ATTR_OPACITY), Some(crate::descriptor!(f64)));
assert_eq!(list.attribute_type(ATTR_OPACITY).map(|value_type| value_type.to_string()), Some("Number".to_string()));
assert_eq!(list.attribute_type(ATTR_START), None);
assert_eq!(implicit_default::<f64>(ATTR_OPACITY), 1.);
assert_eq!(implicit_default::<f64>(ATTR_START), 0.);
assert_eq!(implicit_default::<i64>(ATTR_OPACITY), 0);
}
// A type-erased value of another type replaces the attribute, as a typed one does, instead of becoming the old type's default
#[test]
fn setting_a_value_of_another_type_replaces_the_attribute() {
let mut list = List::new_from_elements(vec![1_u32, 2]);
list.set_attribute_values(ATTR_OPACITY, vec![0.5_f64, 0.25]);
list.set_attribute_value_dyn(ATTR_OPACITY, 1, AttributeValueDyn(Box::new(3_i64)));
assert_eq!(list.iter_attribute_values::<i64>(ATTR_OPACITY).map(|values| values.copied().collect::<Vec<_>>()), Some(vec![0, 3]));
list.set_attribute_value_dyn(ATTR_OPACITY, 0, AttributeValueDyn(Box::new(0.75_f64)));
assert_eq!(list.iter_attribute_values::<f64>(ATTR_OPACITY).map(|values| values.copied().collect::<Vec<_>>()), Some(vec![0.75, 1.]));
}
// Keys are stored inline up to a length limit and shared beyond it, which reads the same either way
#[test]
fn attribute_keys_of_any_length_read_back() {
@@ -121,7 +121,7 @@ impl TransferCurveEvaluator {
}
// O(log n) search for the segment holding x
let upper = points.partition_point(|point| point.x <= x).min(points.len() - 1);
let upper = points.partition_point(|point| point.x <= x).clamp(1, points.len() - 1);
let lower = upper - 1;
let (a, b) = (points[lower], points[upper]);
let width = (b.x - a.x).max(f64::EPSILON);
@@ -206,6 +206,17 @@ mod tests {
}
}
#[test]
fn sampling_survives_a_value_or_point_that_is_not_a_number() {
assert!(TransferCurve::default().evaluate(f64::NAN).is_nan());
// A negative NaN sorts first, so every x between the points meets it
let curve = TransferCurve::new(vec![DVec2::new(-f64::NAN, 0.), DVec2::new(0.5, 0.7), DVec2::ONE]);
for x in (1..100).map(|i| i as f64 / 100.) {
curve.evaluate(x);
}
}
#[test]
fn a_moved_point_may_pass_another_while_keeping_its_index() {
let mut curve = TransferCurve::default();
@@ -189,6 +189,10 @@ impl Footprint {
};
pub fn viewport_bounds_in_local_space(&self) -> AxisAlignedBbox {
if self.transform.matrix2.determinant() == 0. {
return AxisAlignedBbox::ZERO;
}
let inverse = self.transform.inverse();
let res = self.resolution.as_dvec2();
let c0 = inverse.transform_point2(DVec2::ZERO);
@@ -232,7 +232,9 @@ impl Appearance {
let row = cover_row(coverage, paint);
match placement {
CoverPlacement::Above => self.0.push(row),
CoverPlacement::Above => {
self.0.push(row);
}
CoverPlacement::Below => {
let mut reordered = List::new_from_item(row);
reordered.extend(std::mem::take(&mut self.0));
@@ -2,7 +2,7 @@ use crate::appearance::{Appearance, Cover, Coverage};
use brush_types::Stroke;
use core_types::bounds::{BoundingBox, RenderBoundingBox};
use core_types::graphene_hash::CacheHash;
use core_types::list::{ATTR_APPEARANCE, ATTR_PAINT, Item, ItemAttributeValues, List, NodeIdPath};
use core_types::list::{ATTR_APPEARANCE, ATTR_PAINT, AttributeTypeConflictError, Item, ItemAttributeValues, List, NodeIdPath};
use core_types::math::quad::Quad;
use core_types::none;
use core_types::ops::FromAnchorPosition;
@@ -180,15 +180,16 @@ pub fn is_lone_anonymous_leaf(content: &List<Graphic>) -> bool {
/// Deeply flattens a `List<Graphic>`, collecting only elements matching a specific variant (extracted by `extract_variant`)
/// and discarding all other non-matching content. Recursion through `Graphic::GraphicList` sub-`List`s composes transforms and opacity.
fn flatten_graphic_list<T: Clone>(content: List<Graphic>, extract_variant: fn(Graphic) -> Option<List<T>>) -> List<T> {
/// Also gives the first attribute that the flattened lists have with values of different types.
fn flatten_graphic_list<T: Clone>(content: List<Graphic>, extract_variant: fn(Graphic) -> Option<List<T>>) -> (List<T>, Option<AttributeTypeConflictError>) {
// Its list is already the flat answer, so hand it back rather than rebuilding it item by item
if is_lone_anonymous_leaf(&content) {
let Some(item) = content.into_iter().next() else { return List::new() };
let Some(item) = content.into_iter().next() else { return (List::new(), None) };
return extract_variant(item.into_element()).unwrap_or_default();
return (extract_variant(item.into_element()).unwrap_or_default(), None);
}
fn flatten_recursive<T: Clone>(output: &mut List<T>, current_graphic_list: List<Graphic>, extract_variant: fn(Graphic) -> Option<List<T>>) {
fn flatten_recursive<T: Clone>(output: &mut List<T>, conflict: &mut Option<AttributeTypeConflictError>, current_graphic_list: List<Graphic>, extract_variant: fn(Graphic) -> Option<List<T>>) {
for current_graphic_item in current_graphic_list.into_iter() {
// Whether the parent carries each composed attribute: a structural fact (attribute presence), never a value comparison.
// Flattening composes a parent attribute onto its children only when the parent has it,
@@ -244,7 +245,7 @@ fn flatten_graphic_list<T: Clone>(content: List<Graphic>, extract_variant: fn(Gr
}
}
flatten_recursive(output, sub_list, extract_variant);
flatten_recursive(output, conflict, sub_list, extract_variant);
}
// Extract the target variant and push its items, composing the parent's attributes onto each
other => {
@@ -273,7 +274,9 @@ fn flatten_graphic_list<T: Clone>(content: List<Graphic>, extract_variant: fn(Gr
item.set_attribute(ATTR_APPEARANCE, appearance.clone());
}
output.push(item);
if let Some(item_conflict) = output.push(item) {
conflict.get_or_insert(item_conflict);
}
}
}
}
@@ -282,8 +285,9 @@ fn flatten_graphic_list<T: Clone>(content: List<Graphic>, extract_variant: fn(Gr
}
let mut output = List::new();
flatten_recursive(&mut output, content, extract_variant);
output
let mut conflict = None;
flatten_recursive(&mut output, &mut conflict, content, extract_variant);
(output, conflict)
}
/// Whether a normalized paint graphic list actually carries renderable paint.
@@ -405,7 +409,19 @@ pub trait IntoGraphicList: Clone + Send + Sync + Default + std::fmt::Debug + Par
where
Self: std::marker::Sized,
{
flatten_graphic_list(self.into_graphic_list(), T::try_from_graphic)
flatten_graphic_list(self.into_graphic_list(), T::try_from_graphic).0
}
/// Deeply flattens any content of type `T`, failing with the flattened list and the first attribute that holds values of different
/// types in the flattened lists (their later items hold the first type's default).
fn try_into_flattened_list<T: TryFromGraphic>(self) -> Result<List<T>, (List<T>, AttributeTypeConflictError)>
where
Self: std::marker::Sized,
{
match flatten_graphic_list(self.into_graphic_list(), T::try_from_graphic) {
(list, None) => Ok(list),
(list, Some(conflict)) => Err((list, conflict)),
}
}
}
@@ -1049,6 +1065,27 @@ mod tests {
assert_eq!(color_of(1), Some(Color::WHITE), "a padded item should inherit the parent appearance");
}
// Flattening lists that hold an attribute with different types keeps the first type, and says which attribute lost values
#[test]
fn flatten_reports_an_attribute_holding_different_types() {
let tagged = |value: Item<Vector>| Item::new_from_element(Graphic::VectorList(List::new_from_item(value)));
let mut graphics = List::new();
graphics.push(tagged(Item::new_from_element(Vector::default()).with_attribute("tag", 1_f64)));
graphics.push(tagged(Item::new_from_element(Vector::default()).with_attribute("tag", String::from("two"))));
let Err((flattened, conflict)) = graphics.clone().try_into_flattened_list::<Vector>() else {
panic!("expected the conflicting tag to be reported")
};
assert_eq!(conflict.name, "tag");
assert_eq!(flattened, graphics.clone().into_flattened_list::<Vector>());
assert_eq!(flattened.attribute::<f64>("tag", 1), Some(&0.));
let mut matching = List::new();
matching.push(tagged(Item::new_from_element(Vector::default()).with_attribute("tag", 1_f64)));
matching.push(tagged(Item::new_from_element(Vector::default()).with_attribute("tag", 2_f64)));
assert!(matching.try_into_flattened_list::<Vector>().is_ok());
}
#[test]
fn embedded_item_keeps_its_attributes_inside_the_variant() {
let color = Item::new_from_element(Color::RED).with_attribute(ATTR_POSITION, 0.25_f64);
@@ -33,6 +33,7 @@ base64 = { workspace = true }
bytemuck = { workspace = true }
image = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
# Optional workspace dependencies
serde = { workspace = true, optional = true }
+63 -10
View File
@@ -127,6 +127,14 @@ impl<P: core_types::CacheHash + Pixel> core_types::CacheHash for Image<P> {
}
}
#[derive(Debug, thiserror::Error)]
pub enum ImageError {
#[error("The {width}×{height} px image is too large")]
TooLarge { width: u32, height: u32 },
#[error("The file is not an image in a supported format, or it is damaged")]
Undecodable(#[source] ::image::ImageError),
}
impl<P: Pixel> Image<P> {
pub fn new(width: u32, height: u32, color: P) -> Self {
Self {
@@ -135,6 +143,18 @@ impl<P: Pixel> Image<P> {
data: vec![color; (width * height) as usize],
}
}
/// An image filled with `color`, failing where the pixel count overflows the `u32` pixel indices or can't be allocated.
pub fn try_new(width: u32, height: u32, color: P) -> Result<Self, ImageError> {
let too_large = || ImageError::TooLarge { width, height };
let count = width.checked_mul(height).ok_or_else(too_large)? as usize;
let mut data = Vec::new();
data.try_reserve_exact(count).map_err(|_| too_large())?;
data.resize(count, color);
Ok(Self { width, height, data })
}
}
impl Image<Color> {
@@ -144,8 +164,8 @@ impl Image<Color> {
Image { width, height, data }
}
/// Decodes an image file of any supported format.
pub fn from_encoded(data: &[u8]) -> Option<Self> {
/// Decodes an image file of any supported format, or gives the reason it can't be.
pub fn from_encoded(data: &[u8]) -> Result<Self, ImageError> {
let image = decode(data)?;
// Most files hold eight-bit samples, which decode through a table of all 256 values rather than a power function for each
@@ -159,7 +179,7 @@ impl Image<Color> {
.map(|&[red, green, blue, alpha]| SRGBA8::new(red, green, blue, alpha).into())
.collect();
return Some(Image {
return Ok(Image {
width: image.width(),
height: image.height(),
data,
@@ -187,7 +207,7 @@ impl Image<Color> {
})
.collect();
Some(Image {
Ok(Image {
width: image.width(),
height: image.height(),
data,
@@ -196,7 +216,7 @@ impl Image<Color> {
/// The pixel size of an image file, if it decodes in full as [`Image::from_encoded`] needs it to.
pub fn encoded_size(data: &[u8]) -> Option<(u32, u32)> {
decode(data).map(|image| (image.width(), image.height()))
decode(data).ok().map(|image| (image.width(), image.height()))
}
/// The image shrunk by half along each axis `times` times, averaging each block of pixels with their colors weighted by their alpha.
@@ -246,9 +266,17 @@ impl Image<Color> {
}
/// A TGA file has no signature to recognize it by, so a file of no recognized format is tried as one.
fn decode(data: &[u8]) -> Option<::image::DynamicImage> {
fn decode(data: &[u8]) -> Result<::image::DynamicImage, ImageError> {
let format = ::image::guess_format(data).unwrap_or(::image::ImageFormat::Tga);
::image::load_from_memory_with_format(data, format).ok()
::image::load_from_memory_with_format(data, format).map_err(|error| {
// The memory limit error carries no size, which the header gives
if let ::image::ImageError::Limits(_) = error
&& let Ok((width, height)) = ::image::ImageReader::with_format(std::io::Cursor::new(data), format).into_dimensions()
{
return ImageError::TooLarge { width, height };
}
ImageError::Undecodable(error)
})
}
use super::*;
@@ -389,12 +417,37 @@ mod test {
let mut encoded = Vec::new();
pixels.write_to(&mut std::io::Cursor::new(&mut encoded), format).unwrap();
let image = Image::from_encoded(&encoded).unwrap_or_else(|| panic!("{format:?} should decode"));
let image = Image::from_encoded(&encoded).unwrap_or_else(|error| panic!("{format:?} should decode: {error}"));
assert_eq!(Image::encoded_size(&encoded), Some((2, 1)), "{format:?}");
assert_eq!(image.to_flat_u8().0, pixels.as_raw().as_slice(), "{format:?}");
}
assert!(Image::from_encoded(b"not an image").is_none());
assert!(Image::from_encoded(b"not an image").is_err());
}
#[test]
fn a_file_that_does_not_decode_gives_its_reason() {
use super::*;
assert!(matches!(Image::from_encoded(b"not an image"), Err(ImageError::Undecodable(_))));
// A BMP header for a 32-bit image of 30000×30000 pixels, which is far beyond the decoder's memory limit
let mut file = b"BM".to_vec();
for field in [54_u32, 0, 54, 40, 30000, 30000] {
file.extend(field.to_le_bytes());
}
file.extend([1, 0, 32, 0]);
file.extend([0; 24]);
let error = Image::from_encoded(&file).unwrap_err();
assert!(matches!(error, ImageError::TooLarge { width: 30000, height: 30000 }), "{error:?}");
}
#[test]
fn an_image_too_large_for_its_pixel_indices_is_not_made() {
use super::*;
assert!(matches!(Image::try_new(65536, 65536, Color::BLACK), Err(ImageError::TooLarge { width: 65536, height: 65536 })));
assert_eq!(Image::try_new(3, 2, Color::BLACK).unwrap().data, vec![Color::BLACK; 6]);
}
#[test]
@@ -453,7 +506,7 @@ mod test {
file.extend([0, 255, 0, 0]);
assert!(::image::load_from_memory_with_format(&file, ::image::ImageFormat::Tga).is_ok());
assert!(Image::from_encoded(&file).is_none());
assert!(Image::from_encoded(&file).is_err());
}
#[test]
+1 -1
View File
@@ -2,7 +2,7 @@ pub mod image;
pub mod raster_types;
// Re-exports for convenience
pub use image::Image;
pub use image::{Image, ImageError};
pub use raster_types::*;
// Re-export color types from no-std-types
@@ -40,6 +40,7 @@ rustc-hash = { workspace = true }
polycool = { workspace = true }
robust = { workspace = true }
tinyvec = { workspace = true }
thiserror = { workspace = true }
# Optional workspace dependencies
serde = { workspace = true, optional = true }
@@ -81,9 +81,20 @@ pub fn tangent_on_bezpath(bezpath: &BezPath, t_value: TValue, segments_length: O
dvec2_to_point(pathseg_tangent(segment, t))
}
/// Computes sample locations along a bezpath, returning parametric `(segment_index, t)` pairs and whether the path was closed.
/// The failure of [`compute_sample_locations`]: the path would need more samples than the most it places on one subpath.
#[derive(Debug, thiserror::Error)]
pub enum SampleCountError {
#[error("The separation is too small for this path: it would need more than {limit} points")]
SeparationTooSmall { limit: usize },
#[error("The quantity is more than the maximum of {limit} points")]
QuantityTooLarge { limit: usize },
}
/// Computes sample locations along a bezpath, returning parametric `(segment_index, t)` pairs and whether the path was closed,
/// or `None` when there's nothing to sample.
/// The `bezpath` is used for euclidean-to-parametric conversion, and `segments_length` provides pre-calculated world-space segment lengths.
/// Callers can evaluate these locations on any bezpath with the same topology (e.g., an untransformed version).
#[allow(clippy::type_complexity)]
pub fn compute_sample_locations(
bezpath: &BezPath,
point_spacing_type: PointSpacingType,
@@ -92,7 +103,7 @@ pub fn compute_sample_locations(
stop_offset: f64,
adaptive_spacing: bool,
segments_length: &[f64],
) -> Option<(Vec<(usize, f64)>, bool)> {
) -> Result<Option<(Vec<(usize, f64)>, bool)>, SampleCountError> {
let was_closed = matches!(bezpath.elements().last(), Some(PathEl::ClosePath));
// Calculate the total length of the collected segments.
@@ -103,36 +114,44 @@ pub fn compute_sample_locations(
// Sanity check that the usable length is positive.
if used_length <= 0. {
return None;
return Ok(None);
}
const SAFETY_MAX_COUNT: f64 = 10_000. - 1.;
const MAX_POINTS: usize = 10_000;
// Determine the number of points to generate along the path.
let sample_count = match point_spacing_type {
PointSpacingType::Separation => {
let spacing = amount.min(used_length - f64::EPSILON);
if adaptive_spacing {
let count = if adaptive_spacing {
// Calculate point count to evenly distribute points while covering the entire path.
// With adaptive spacing, we widen or narrow the points as necessary to ensure the last point is always at the end of the path.
(used_length / spacing).round().min(SAFETY_MAX_COUNT)
(used_length / spacing).round()
} else {
// Calculate point count based on exact spacing, which may not cover the entire path.
// Without adaptive spacing, we just evenly space the points at the exact specified spacing, usually falling short before the end of the path.
let count = (used_length / spacing + f64::EPSILON).floor().min(SAFETY_MAX_COUNT);
if count != SAFETY_MAX_COUNT {
used_length -= used_length % spacing;
}
count
(used_length / spacing + f64::EPSILON).floor()
};
if count >= MAX_POINTS as f64 {
return Err(SampleCountError::SeparationTooSmall { limit: MAX_POINTS });
}
if !adaptive_spacing {
used_length -= used_length % spacing;
}
count
}
PointSpacingType::Quantity => {
let count = (amount - 1.).floor();
if count >= MAX_POINTS as f64 {
return Err(SampleCountError::QuantityTooLarge { limit: MAX_POINTS });
}
count.max(1.)
}
PointSpacingType::Quantity => (amount - 1.).floor().clamp(1., SAFETY_MAX_COUNT),
};
// Skip if there are no points to generate.
if sample_count < 1. {
return None;
return Ok(None);
}
// Decide how many loop-iterations: if closed, skip the last duplicate point
@@ -169,7 +188,7 @@ pub fn compute_sample_locations(
locations.push((next_segment_index, t));
}
Some((locations, was_closed))
Ok(Some((locations, was_closed)))
}
#[derive(Debug, Clone, Copy)]
@@ -277,7 +296,8 @@ pub(crate) fn pathseg_length_centroid_and_length(segment: PathSeg, accuracy: Opt
/// Finds the parametric `t` value on the given path segment corresponding to a fractional arc-length `distance` (0–1).
/// Delegates to kurbo's `inv_arclen` which uses the ITP method with incremental arc-length computation.
pub fn eval_pathseg_euclidean(segment: PathSeg, distance: f64, accuracy: f64) -> f64 {
segment.inv_arclen(distance.clamp(0., 1.) * segment.arclen(accuracy), accuracy)
let length = segment.arclen(accuracy);
segment.inv_arclen(distance.clamp(0., 1.) * length, accuracy.max(length * 1e-14))
}
/// Converts from a bezpath (composed of multiple segments) to a point along a certain segment represented.
@@ -385,6 +405,10 @@ pub fn poisson_disk_points(bezpath_index: usize, bezpaths: &[(BezPath, Rect)], s
let width = this_bbox.width();
let height = this_bbox.height();
if width.is_infinite() || height.is_infinite() {
return Vec::new();
}
poisson_disk_sample(offset, width, height, separation_disk_diameter, point_in_shape_checker, line_intersect_shape_checker, rng)
}
@@ -645,7 +669,7 @@ pub fn bezpath_area_centroid_and_area(bezpath: &BezPath, error: Option<f64>, min
/// The length centroid is the center of mass for the arc length of the solid shape's perimeter.
/// An infinitely thin wire forming the path's shape would balance at this point.
///
/// It will return `None` if no segment is present.
/// It will return `None` if no segment has any length.
/// - `accuracy` is used to approximate the curve.
/// - `always_closed` is to consider the path as closed always.
pub fn bezpath_length_centroid_and_length(bezpath: &BezPath, accuracy: Option<f64>, always_closed: bool) -> Option<(DVec2, f64)> {
@@ -654,6 +678,7 @@ pub fn bezpath_length_centroid_and_length(bezpath: &BezPath, accuracy: Option<f6
segments
.into_iter()
.map(|bezier| pathseg_length_centroid_and_length(bezier, accuracy))
.filter(|&(_, length)| length != 0.)
.map(|(centroid, length)| (centroid * length, length))
.reduce(|(centroid_part1, length1), (centroid_part2, length2)| (centroid_part1 + centroid_part2, length1 + length2))
.map(|(centroid_part, length)| (centroid_part / length, length))
@@ -698,4 +723,25 @@ mod tests {
assert_eq!(area, 200. * 100.);
assert_eq!(center, glam::DVec2::new(200., 150.));
}
#[test]
fn centroid_of_a_huge_curve() {
let mut bezpath = BezPath::new();
bezpath.move_to((0., 0.));
bezpath.curve_to((0.55e60, 0.), (1e60, 0.45e60), (1e60, 1e60));
bezpath.close_path();
assert!(super::bezpath_area_centroid_and_area(&bezpath, Some(1e-3), Some(1e-3)).is_some());
}
#[test]
fn length_centroid_skips_zero_length_segments() {
let mut bezpath = BezPath::new();
bezpath.move_to((0., 0.));
bezpath.line_to((10., 0.));
bezpath.curve_to((10., 0.), (10., 0.), (10., 0.));
let (centroid, length) = super::bezpath_length_centroid_and_length(&bezpath, None, false).unwrap();
assert_eq!((centroid, length), (glam::DVec2::new(5., 0.), 10.));
}
}
@@ -216,8 +216,11 @@ fn pathseg_self_intersection(segment: PathSeg, accuracy: Option<f64>) -> Vec<(f6
PathSeg::Cubic(cubic_bez) => cubic_bez,
};
let size = approx_bounding_box(segment).size();
let accuracy_for_size = DEFAULT_ACCURACY.max(size.width.max(size.height) * 1e-9);
// Get 2 copies of the reduced curves
let quads1 = cubic_bez.to_quads(DEFAULT_ACCURACY).map(|(t1, t2, quad_bez)| (t1, t2, PathSeg::Quad(quad_bez))).collect::<Vec<_>>();
let quads1 = cubic_bez.to_quads(accuracy_for_size).map(|(t1, t2, quad_bez)| (t1, t2, PathSeg::Quad(quad_bez))).collect::<Vec<_>>();
let quads2 = quads1.clone();
let num_curves = quads1.len();
@@ -1,21 +1,30 @@
use super::bezpath_algorithms::{clip_simple_bezpaths, miter_line_join, round_line_join};
use super::consts::MAX_COINCIDENT_POINT_DISTANCE;
use crate::vector::misc::point_to_dvec2;
use kurbo::{BezPath, Join, ParamCurve, PathEl, PathSeg};
use kurbo::{BezPath, Join, ParamCurve, PathEl, PathSeg, Rect, Shape};
/// Value to control smoothness and mathematical accuracy to offset a cubic Bezier.
const CUBIC_REGULARIZATION_ACCURACY: f64 = 0.5;
/// Squared version to avoid sqrt in distance checks.
const MAX_COINCIDENT_POINT_DISTANCE_SQUARED: f64 = MAX_COINCIDENT_POINT_DISTANCE * MAX_COINCIDENT_POINT_DISTANCE;
const MAX_FITTED_SEGMENTS: usize = 10000;
/// The coordinate magnitude from which lyon's curve intersection, used to clip the offset pieces, panics converting it to an `i64`.
const MAX_CLIPPED_COORDINATE: f64 = i64::MAX as f64;
/// The failure of [`offset_bezpath`].
#[derive(Debug, thiserror::Error)]
pub enum OffsetPathError {
#[error("The shape or offset distance is too large to offset")]
TooLarge,
}
/// Reduces the segments of the bezpath into simple subcurves, then offset each subcurve a set `distance` away.
/// The intersections of segments of the subpath are joined using the method specified by the `join` argument.
pub fn offset_bezpath(bezpath: &BezPath, distance: f64, join: Join, miter_limit: Option<f64>) -> BezPath {
pub fn offset_bezpath(bezpath: &BezPath, distance: f64, join: Join, miter_limit: Option<f64>) -> Result<BezPath, OffsetPathError> {
// An offset at a distance 0 from the curve is simply the same curve.
// An offset of a single point is not defined.
if distance == 0. || bezpath.get_seg(1).is_none() {
return bezpath.clone();
return Ok(bezpath.clone());
}
let mut bezpaths = bezpath
@@ -45,7 +54,12 @@ pub fn offset_bezpath(bezpath: &BezPath, distance: f64, join: Join, miter_limit:
.collect::<Vec<BezPath>>();
if bezpaths.is_empty() {
return BezPath::new();
return Ok(BezPath::new());
}
let too_large = |bounds: Rect| [bounds.x0, bounds.y0, bounds.x1, bounds.y1].iter().any(|coordinate| coordinate.abs() >= MAX_CLIPPED_COORDINATE);
if bezpaths.iter().any(|bezpath| too_large(bezpath.bounding_box())) {
return Err(OffsetPathError::TooLarge);
}
// Clip or join consecutive subpaths
@@ -152,5 +166,5 @@ pub fn offset_bezpath(bezpath: &BezPath, distance: f64, join: Join, miter_limit:
offset_bezpath.close_path();
}
offset_bezpath
Ok(offset_bezpath)
}
@@ -13,6 +13,19 @@ use std::f64::consts::TAU;
/// Constant from <https://pomax.github.io/bezierinfo/#circles_cubic>
const HANDLE_OFFSET_FACTOR: f64 = 0.551784777779014;
/// Relative growth per radian below which spiral arc lengths use a circle, since the closed forms divide by the growth.
const SPIRAL_CIRCLE_GROWTH: f64 = 1e-6;
/// The most anchors a polygon or star can have before allocating them overflows the address space.
const MAX_POLYGON_ANCHORS: u64 = (isize::MAX as usize / size_of::<Anchor>()) as u64;
/// The failure of [`regular_polygon_bezpath`] and [`star_polygon_bezpath`].
#[derive(Debug, thiserror::Error)]
pub enum PolygonError {
#[error("A shape with {0} sides is too large to fit in memory")]
TooManySides(u64),
}
/// An anchor point with its optional incoming and outgoing handle positions, in absolute coordinates.
#[derive(Clone)]
struct Anchor {
@@ -64,8 +77,8 @@ pub fn rounded_rectangle_bezpath(corner1: DVec2, corner2: DVec2, corner_radii: [
let handle_offset = radius * HANDLE_OFFSET_FACTOR;
vec![
Anchor::new(point1, None, Some(point1 + handle_offset * (corner - point1).normalize())),
Anchor::new(point2, Some(point2 + handle_offset * (corner - point2).normalize()), None),
Anchor::new(point1, None, Some(point1 + handle_offset * (corner - point1).normalize_or_zero())),
Anchor::new(point2, Some(point2 + handle_offset * (corner - point2).normalize_or_zero()), None),
]
};
@@ -162,7 +175,12 @@ pub fn arc_bezpath(radius: f64, start_angle: f64, sweep_angle: f64, arc_type: Ar
}
/// Constructs a regular polygon (ngon). Based on `sides` and `radius`, which is the distance from the center to any vertex.
pub fn regular_polygon_bezpath(center: DVec2, sides: u64, radius: f64) -> BezPath {
/// Fails when it has more sides than can be allocated.
pub fn regular_polygon_bezpath(center: DVec2, sides: u64, radius: f64) -> Result<BezPath, PolygonError> {
if sides > MAX_POLYGON_ANCHORS {
return Err(PolygonError::TooManySides(sides));
}
let sides = sides.max(3);
let angle_increment = TAU / (sides as f64);
let positions = (0..sides).map(|i| {
@@ -170,11 +188,16 @@ pub fn regular_polygon_bezpath(center: DVec2, sides: u64, radius: f64) -> BezPat
center + radius * DVec2::new(f64::cos(angle), f64::sin(angle))
});
polyline_bezpath(positions, true)
Ok(polyline_bezpath(positions, true))
}
/// Constructs a star polygon (n-star). See [`regular_polygon_bezpath`], but with interspersed vertices at an `inner_radius`.
pub fn star_polygon_bezpath(center: DVec2, sides: u64, radius: f64, inner_radius: f64) -> BezPath {
pub fn star_polygon_bezpath(center: DVec2, sides: u64, radius: f64, inner_radius: f64) -> Result<BezPath, PolygonError> {
// Each side has an outer and an inner anchor
if sides > MAX_POLYGON_ANCHORS / 2 {
return Err(PolygonError::TooManySides(sides));
}
let sides = sides.max(2);
let angle_increment = 0.5 * TAU / (sides as f64);
let positions = (0..sides * 2).map(|i| {
@@ -183,7 +206,7 @@ pub fn star_polygon_bezpath(center: DVec2, sides: u64, radius: f64, inner_radius
center + radius * DVec2::new(f64::cos(angle), f64::sin(angle))
});
polyline_bezpath(positions, true)
Ok(polyline_bezpath(positions, true))
}
/// Constructs a line from `point1` to `point2`.
@@ -224,8 +247,26 @@ pub fn arrow_bezpath(start: DVec2, end: DVec2, shaft_width: f64, head_width: f64
polyline_bezpath(positions, true)
}
/// The failure of [`spiral_bezpath`].
#[derive(Debug, thiserror::Error)]
pub enum SpiralError {
#[error("The angular resolution must be greater than 0")]
AngularResolutionNotPositive,
#[error("The number of turns must be finite")]
TurnsNotFinite,
#[error("The start angle is too large to step through at this angular resolution")]
AngleTooLarge,
}
/// Constructs a spiral winding from an inner radius `a` out to `outer_radius`, sampled every `delta_theta` radians.
pub fn spiral_bezpath(a: f64, outer_radius: f64, turns: f64, start_angle: f64, delta_theta: f64, spiral_type: SpiralType) -> BezPath {
pub fn spiral_bezpath(a: f64, outer_radius: f64, turns: f64, start_angle: f64, delta_theta: f64, spiral_type: SpiralType) -> Result<BezPath, SpiralError> {
if delta_theta.is_nan() || delta_theta <= 0. {
return Err(SpiralError::AngularResolutionNotPositive);
}
if turns == f64::INFINITY {
return Err(SpiralError::TurnsNotFinite);
}
let mut anchors = Vec::new();
let mut prev_in_handle = None;
let theta_end = turns * TAU + start_angle;
@@ -236,6 +277,10 @@ pub fn spiral_bezpath(a: f64, outer_radius: f64, turns: f64, start_angle: f64, d
let mut theta = start_angle;
while theta < theta_end {
let theta_next = f64::min(theta + delta_theta, theta_end);
// A step lost to the angle's float precision would never reach the end
if theta_next == theta {
return Err(SpiralError::AngleTooLarge);
}
let p0 = spiral_point(theta, a, b, spiral_type);
let p3 = spiral_point(theta_next, a, b, spiral_type);
@@ -260,7 +305,7 @@ pub fn spiral_bezpath(a: f64, outer_radius: f64, turns: f64, start_angle: f64, d
theta = theta_next;
}
bezpath_from_anchors(&anchors, false)
Ok(bezpath_from_anchors(&anchors, false))
}
pub fn calculate_growth_factor(a: f64, turns: f64, outer_radius: f64, spiral_type: SpiralType) -> f64 {
@@ -309,6 +354,9 @@ fn log_spiral_point(theta: f64, a: f64, b: f64) -> DVec2 {
/// Computes arc length along a logarithmic spiral between two angles.
fn log_spiral_arc_length(theta_start: f64, theta_end: f64, a: f64, b: f64) -> f64 {
let factor = (1. + b * b).sqrt();
if b.abs() < SPIRAL_CIRCLE_GROWTH {
return a * (b * (theta_start + theta_end) / 2.).exp() * factor * (theta_end - theta_start);
}
(a / b) * factor * ((b * theta_end).exp() - (b * theta_start).exp())
}
@@ -337,6 +385,10 @@ fn archimedean_spiral_tangent(theta: f64, a: f64, b: f64) -> DVec2 {
/// Computes arc length along an Archimedean spiral between two angles.
fn archimedean_spiral_arc_length(theta_start: f64, theta_end: f64, a: f64, b: f64) -> f64 {
let middle_radius = a + b * (theta_start + theta_end) / 2.;
if b.abs() <= middle_radius.abs() * SPIRAL_CIRCLE_GROWTH {
return middle_radius.abs() * (theta_end - theta_start);
}
archimedean_spiral_arc_length_origin(theta_end, a, b) - archimedean_spiral_arc_length_origin(theta_start, a, b)
}
@@ -59,56 +59,58 @@ impl WeldExt for Vector {
})
.collect::<Vec<_>>();
// Collect points and segments to delete at the end to avoid invalidating indices
// Each collapse set keeps its first point, which every other point in the set merges into
let mut collapse_group = FxHashMap::default();
let mut kept_points = Vec::with_capacity(collapse.len());
let mut points_to_delete = FxHashSet::default();
let mut segments_to_delete = FxHashSet::default();
for (mut collapse_set, average_pos) in collapse.into_iter().zip(average_position) {
// Remove any segments where both endpoints are in the collapse set
for segment_index in 0..working.segment_ids.len() {
let start = working.point_ids[working.segment_start[segment_index]];
let end = working.point_ids[working.segment_end[segment_index]];
if collapse_set.contains(&start) && collapse_set.contains(&end) {
segments_to_delete.insert(working.segment_ids[segment_index]);
}
}
// Delete all points but the first, set its position to the average, and update segments
for (group, collapse_set) in collapse.iter().enumerate() {
let first_id = collapse_set.iter().copied().next().unwrap();
collapse_set.remove(&first_id);
let first_offset = indices.point_to_offset[&first_id];
kept_points.push((first_id, indices.point_to_offset[&first_id]));
// Look for segments with endpoints in `collapse_set` and replace them with the point we are collapsing to
for segment_index in 0..working.segment_ids.len() {
let start_id = working.point_ids[working.segment_start[segment_index]];
let end_id = working.point_ids[working.segment_end[segment_index]];
// Update Bezier handles for moved points
if start_id == first_id {
let point_position = working.point_positions[working.segment_start[segment_index]];
working.segment_handles[segment_index].move_start(average_pos - point_position);
}
if end_id == first_id {
let point_position = working.point_positions[working.segment_end[segment_index]];
working.segment_handles[segment_index].move_end(average_pos - point_position);
}
// Replace removed points with the collapsed point
if collapse_set.contains(&start_id) {
let point_position = working.point_positions[working.segment_start[segment_index]];
working.segment_start[segment_index] = first_offset;
working.segment_handles[segment_index].move_start(average_pos - point_position);
}
if collapse_set.contains(&end_id) {
let point_position = working.point_positions[working.segment_end[segment_index]];
working.segment_end[segment_index] = first_offset;
working.segment_handles[segment_index].move_end(average_pos - point_position);
for &id in collapse_set {
collapse_group.insert(id, group);
if id != first_id {
points_to_delete.insert(id);
}
}
}
// Update the position of the collapsed point
// Collect segments to delete at the end to avoid invalidating indices
let mut segments_to_delete = FxHashSet::default();
for segment_index in 0..working.segment_ids.len() {
let start_id = working.point_ids[working.segment_start[segment_index]];
let end_id = working.point_ids[working.segment_end[segment_index]];
let (start_group, end_group) = (collapse_group.get(&start_id).copied(), collapse_group.get(&end_id).copied());
// Remove any segments where both endpoints are in the same collapse set
if start_group.is_some() && start_group == end_group {
segments_to_delete.insert(working.segment_ids[segment_index]);
}
// Move the segment's ends in a collapse set, along with their handles, onto the point the set collapses to
if let Some(group) = start_group {
let point_position = working.point_positions[working.segment_start[segment_index]];
working.segment_handles[segment_index].move_start(average_position[group] - point_position);
let (first_id, first_offset) = kept_points[group];
if start_id != first_id {
working.segment_start[segment_index] = first_offset;
}
}
if let Some(group) = end_group {
let point_position = working.point_positions[working.segment_end[segment_index]];
working.segment_handles[segment_index].move_end(average_position[group] - point_position);
let (first_id, first_offset) = kept_points[group];
if end_id != first_id {
working.segment_end[segment_index] = first_offset;
}
}
}
// Update the positions of the collapsed points
for (&(_, first_offset), average_pos) in kept_points.iter().zip(average_position) {
working.point_positions[first_offset] = average_pos;
points_to_delete.extend(collapse_set)
}
// Drop the collapsed segments, then the merged-away points, remapping segment endpoints
@@ -404,13 +406,13 @@ fn weld_nearby_points(vector: &mut Vector, paths: &mut List<Path>, transform: DA
// Create a spatial grid with cell size of 'distance'
use std::collections::HashMap;
let mut grid: HashMap<(i32, i32), Vec<usize>> = HashMap::new();
let mut grid: HashMap<(i64, i64), Vec<usize>> = HashMap::new();
// Add points to grid cells without collecting all positions first
for i in 0..point_count {
let pos = transform.transform_point2(working.point_positions[i]);
let grid_x = ((pos.x - min_x) / distance).floor() as i32;
let grid_y = ((pos.y - min_y) / distance).floor() as i32;
let grid_x = ((pos.x - min_x) / distance).floor() as i64;
let grid_y = ((pos.y - min_y) / distance).floor() as i64;
grid.entry((grid_x, grid_y)).or_default().push(i);
}
@@ -428,15 +430,16 @@ fn weld_nearby_points(vector: &mut Vector, paths: &mut List<Path>, transform: DA
}
let pos_i = transform.transform_point2(working.point_positions[i]);
let grid_x = ((pos_i.x - min_x) / distance).floor() as i32;
let grid_y = ((pos_i.y - min_y) / distance).floor() as i32;
let grid_x = ((pos_i.x - min_x) / distance).floor() as i64;
let grid_y = ((pos_i.y - min_y) / distance).floor() as i64;
let mut group = vec![i];
// Check only neighboring cells (3x3 grid around current cell)
for dx in -1..=1 {
for dy in -1..=1 {
let neighbor_cell = (grid_x + dx, grid_y + dy);
// The saturating cast puts infinite points in the grid's edge cells, which have no neighbors beyond
let Some(neighbor_cell) = grid_x.checked_add(dx).zip(grid_y.checked_add(dy)) else { continue };
if let Some(indices) = grid.get(&neighbor_cell) {
for &j in indices {
@@ -697,6 +700,19 @@ mod tests {
vector.0.iter_attribute_values::<PointId>(ATTR_ID).map(|ids| ids.map(|id| id.inner()).collect()).unwrap_or_default()
}
// A point too far off for the grid of cells to hold sits at its edge, which has no cells beyond it to check
#[test]
fn weld_all_beside_an_infinite_point() {
let mut vector = pool(&[(0., 0.), (0.05, 0.), (f64::INFINITY, 0.)]);
let mut paths = List::new();
push_path(&mut paths, CurveType::Linear, [0, 1, 2], []);
vector.weld_all(&mut paths, DAffine2::IDENTITY, 0.1);
assert_eq!(vector.0.len(), 2);
assert!(near(vector.0.element(0), (0.025, 0.)));
}
// Two lines meeting across a small gap join there, while two close points of another path stay apart since only one is an end
#[test]
fn flow_ends_join_without_touching_other_points() {
@@ -333,7 +333,7 @@ impl SegmentGraph {
let tangent = self.segment(side.segment_index, side.reversed).tangent_at_start();
tangent.y.atan2(tangent.x)
});
angle[0].partial_cmp(&angle[1]).unwrap_or(std::cmp::Ordering::Equal)
angle[0].total_cmp(&angle[1])
})
}
@@ -1519,4 +1519,20 @@ mod tests {
assert!(loop_area > 0., "the inner loop should wind positively after normalization");
assert_eq!(references(&paths), vec![vec![0, 1, 4, 3, 2, 1, 5]], "the path stays whole around its flipped loop");
}
// Sorting more than 20 segment ends around a junction by their angles mustn't panic where NaN geometry gives no angle
#[test]
fn faces_around_a_junction_with_nan_spokes() {
// The spokes are stored out of angle order, since the sort only notices the inconsistent comparisons when it has to reorder
let spokes = 24;
let ring = (0..spokes).map(|index| match index % 3 {
0 => DVec2::NAN,
_ => DVec2::from_angle((index * 7 % spokes) as f64 / spokes as f64 * std::f64::consts::TAU) * 10.,
});
let points: Vec<DVec2> = std::iter::once(DVec2::ZERO).chain(ring).collect();
let segments: Vec<(usize, usize)> = (1..=spokes).flat_map(|index| [(0, index), (index, index % spokes + 1)]).collect();
let (vector, paths) = build_vector(&points, &segments);
vector.construct_faces(&paths);
}
}
@@ -797,9 +797,11 @@ impl Vector {
pub fn concat(&mut self, paths: &mut List<Path>, additional: &Self, additional_paths: &List<Path>, transform_of_additional: DAffine2, collision_hash_seed: u64, taken_ids: &mut IdCollisionSet) {
let offset = self.0.len() as u32;
// If the pool lacks the ID column, appending IDs pads its points with a default one, which is then taken too
let first_untaken_point = if self.0.iter_attribute_values::<PointId>(ATTR_ID).is_some() { self.0.len() } else { 0 };
// Remap colliding stable IDs so both sides stay addressable after the merge.
// Appended IDs are only checked against the IDs taken before this call.
let mut appended_point_ids = Vec::new();
for index in 0..additional.0.len() {
let Some(&position) = additional.0.element(index) else { continue };
let mut item = Item::new_from_element(transform_of_additional.transform_point2(position));
@@ -811,7 +813,6 @@ impl Vector {
id
};
item.set_attribute(ATTR_ID, id);
appended_point_ids.push(id);
}
self.0.push(item);
@@ -837,7 +838,9 @@ impl Vector {
paths.push(item);
}
taken_ids.points.extend(appended_point_ids);
// Read back from the pool, since appending points without IDs to a pool with the column pads them with a default one
let appended_point_ids = self.0.iter_attribute_values::<PointId>(ATTR_ID).into_iter().flatten().skip(first_untaken_point);
taken_ids.points.extend(appended_point_ids.copied());
taken_ids.segments.extend(appended_segment_ids);
}
@@ -1038,6 +1041,36 @@ mod tests {
assert_eq!(vector.index_of_point_id(PointId::ZERO), Some(0));
}
#[test]
fn concat_with_tracked_ids_matches_collecting_them_anew() {
let triangle = BezPath::from_vec(vec![
PathEl::MoveTo((0., 0.).into()),
PathEl::LineTo((1., 0.).into()),
PathEl::LineTo((0., 1.).into()),
PathEl::ClosePath,
]);
let (triangle, triangle_paths) = Vector::from_bezpath(&triangle);
let (curve, curve_paths) = Vector::from_bezpath(&open_curve_bezpath());
let unnamed = Vector(List::new_from_element(DVec2::ONE));
let parts = [
(&unnamed, &List::new()),
(&triangle, &triangle_paths),
(&lone_anchor(DVec2::X), &List::new()),
(&curve, &curve_paths),
(&triangle, &triangle_paths),
];
let (mut each, mut each_paths) = (Vector::default(), List::new());
let (mut tracked, mut tracked_paths, mut ids) = (Vector::default(), List::new(), IdCollisionSet::default());
for (seed, (part, part_paths)) in parts.into_iter().enumerate() {
let mut collected = IdCollisionSet::of(&each, &each_paths);
each.concat(&mut each_paths, part, part_paths, DAffine2::IDENTITY, seed as u64, &mut collected);
tracked.concat(&mut tracked_paths, part, part_paths, DAffine2::IDENTITY, seed as u64, &mut ids);
}
assert_eq!((tracked, tracked_paths), (each, each_paths));
}
// Handles carry the unnamed filler, so a zero-named anchor behind them is still the one found by ID
#[test]
fn handles_do_not_shadow_a_zero_named_anchor() {
@@ -10,9 +10,27 @@ use wgpu::{Extent3d, TextureFormat};
/// Uploads CPU image data to a GPU texture
fn upload_to_texture(executor: &WgpuExecutor, queue: &wgpu::Queue, image: &Raster<CPU>) -> Texture {
let rgba8_data: Vec<SRGBA8> = image.data.iter().map(|x| (*x).into()).collect();
let texture = executor.request_texture_with_format(glam::UVec2::new(image.width, image.height), TextureFormat::Rgba8UnormSrgb);
if image.width == 0 || image.height == 0 {
queue.write_texture(
texture.as_image_copy(),
bytemuck::bytes_of(&SRGBA8::TRANSPARENT),
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(4),
rows_per_image: Some(1),
},
Extent3d {
width: 1,
height: 1,
depth_or_array_layers: 1,
},
);
return texture;
}
let rgba8_data: Vec<SRGBA8> = image.data.iter().map(|x| (*x).into()).collect();
queue.write_texture(
texture.as_image_copy(),
bytemuck::cast_slice(rgba8_data.as_slice()),
@@ -17,6 +17,9 @@ impl Region {
pub(crate) fn new(footprint: &Footprint) -> Option<Self> {
let margin = DVec2::splat(2. / footprint.scale().max_element());
let viewport = footprint.viewport_bounds_in_local_space();
if !viewport.size().cmpgt(DVec2::ZERO).all() {
return None;
}
let bounds = AxisAlignedBbox {
start: viewport.start - margin,
end: viewport.end + margin,
+1
View File
@@ -38,6 +38,7 @@ graphene-animation = { workspace = true }
dyn-any = { workspace = true }
glam = { workspace = true }
log = { workspace = true }
thiserror = { workspace = true }
# Optional workspace dependencies
serde = { workspace = true, optional = true }
+72 -39
View File
@@ -6,63 +6,59 @@ use graphic_types::vector_types::Gradient;
use graphic_types::{Graphic, Vector};
use raster_types::{CPU, Raster};
#[node_macro::node(category("Data: Context"), icon("NodeReadContext"), path(graphene_core::vector))]
fn read_graphic(ctx: impl Ctx + ExtractVarArgs) -> Item<Graphic> {
let Ok(var_arg) = ctx.vararg(0) else { return Default::default() };
let var_arg = var_arg as &dyn std::any::Any;
var_arg.downcast_ref().cloned().unwrap_or_default()
#[derive(Debug, thiserror::Error)]
pub enum ReadContextError {
#[error("No {0} to read: this node only works inside a loop over {0} items, like in a Map node")]
NoLoopItem(&'static str),
#[error("No loop index to read: this node only works inside a loop, like in a Repeat or Map node")]
NoLoopIndex,
#[error("No position to read: this node only works inside a loop over points, like in a Repeat on Points node")]
NoLoopPosition,
#[error("Loop Level {level} is too high: the outermost loop around this node is level {outermost}")]
LoopLevelTooHigh { level: i64, outermost: usize },
}
#[node_macro::node(category("Data: Context"), icon("NodeReadContext"), path(graphene_core::vector))]
fn read_vector(ctx: impl Ctx + ExtractVarArgs) -> Item<Vector> {
let Ok(var_arg) = ctx.vararg(0) else { return Default::default() };
let var_arg = var_arg as &dyn std::any::Any;
var_arg.downcast_ref().cloned().unwrap_or_default()
fn read_graphic(ctx: impl Ctx + ExtractVarArgs) -> Result<Item<Graphic>, ReadContextError> {
ctx.vararg(0).ok().and_then(|var_arg| var_arg.downcast_ref().cloned()).ok_or(ReadContextError::NoLoopItem("graphic"))
}
#[node_macro::node(category("Data: Context"), icon("NodeReadContext"), path(graphene_core::vector))]
fn read_raster(ctx: impl Ctx + ExtractVarArgs) -> Item<Raster<CPU>> {
let Ok(var_arg) = ctx.vararg(0) else { return Default::default() };
let var_arg = var_arg as &dyn std::any::Any;
var_arg.downcast_ref().cloned().unwrap_or_default()
fn read_vector(ctx: impl Ctx + ExtractVarArgs) -> Result<Item<Vector>, ReadContextError> {
ctx.vararg(0).ok().and_then(|var_arg| var_arg.downcast_ref().cloned()).ok_or(ReadContextError::NoLoopItem("vector"))
}
#[node_macro::node(category("Data: Context"), icon("NodeReadContext"), path(graphene_core::vector))]
fn read_color(ctx: impl Ctx + ExtractVarArgs) -> Item<Color> {
let Ok(var_arg) = ctx.vararg(0) else { return Default::default() };
let var_arg = var_arg as &dyn std::any::Any;
var_arg.downcast_ref().cloned().unwrap_or_default()
fn read_raster(ctx: impl Ctx + ExtractVarArgs) -> Result<Item<Raster<CPU>>, ReadContextError> {
ctx.vararg(0).ok().and_then(|var_arg| var_arg.downcast_ref().cloned()).ok_or(ReadContextError::NoLoopItem("raster"))
}
#[node_macro::node(category("Data: Context"), icon("NodeReadContext"), path(graphene_core::vector))]
fn read_gradient(ctx: impl Ctx + ExtractVarArgs) -> Item<Gradient> {
let Ok(var_arg) = ctx.vararg(0) else { return Default::default() };
let var_arg = var_arg as &dyn std::any::Any;
fn read_color(ctx: impl Ctx + ExtractVarArgs) -> Result<Item<Color>, ReadContextError> {
ctx.vararg(0).ok().and_then(|var_arg| var_arg.downcast_ref().cloned()).ok_or(ReadContextError::NoLoopItem("color"))
}
var_arg.downcast_ref().cloned().unwrap_or_default()
#[node_macro::node(category("Data: Context"), icon("NodeReadContext"), path(graphene_core::vector))]
fn read_gradient(ctx: impl Ctx + ExtractVarArgs) -> Result<Item<Gradient>, ReadContextError> {
ctx.vararg(0).ok().and_then(|var_arg| var_arg.downcast_ref().cloned()).ok_or(ReadContextError::NoLoopItem("gradient"))
}
/// Reads the current number from within a **Map** node's loop.
#[node_macro::node(category("Data: Context"), icon("NodeReadContext"))]
fn read_number(ctx: impl Ctx + ExtractVarArgs) -> Item<f64> {
let Ok(var_arg) = ctx.vararg(0) else { return Default::default() };
let var_arg = var_arg as &dyn std::any::Any;
fn read_number(ctx: impl Ctx + ExtractVarArgs) -> Result<Item<f64>, ReadContextError> {
let var_arg = ctx.vararg(0).ok();
if let Some(item) = var_arg.downcast_ref::<Item<f64>>() {
return item.clone();
if let Some(item) = var_arg.and_then(|var_arg| var_arg.downcast_ref::<Item<f64>>()) {
return Ok(item.clone());
}
// An integer list widens to f64, keeping the item's attributes
if let Some(item) = var_arg.downcast_ref::<Item<i64>>() {
if let Some(item) = var_arg.and_then(|var_arg| var_arg.downcast_ref::<Item<i64>>()) {
let (element, attributes) = item.clone().into_parts();
return Item::from_parts(element as f64, attributes);
return Ok(Item::from_parts(element as f64, attributes));
}
Default::default()
Err(ReadContextError::NoLoopItem("number"))
}
#[node_macro::node(category("Data: Context"), icon("NodeReadPosition"), path(core_types::vector))]
@@ -74,9 +70,9 @@ fn read_position(
/// In programming terms: inside the double loop `i { j { ... } }`, *Loop Level* 0 = `j` and 1 = `i`. After inserting a third loop `k { ... }`, inside it, levels would be 0 = `k`, 1 = `j`, and 2 = `i`.
#[hard(0..)]
loop_level: Item<i64>,
) -> Item<DVec2> {
let loop_level = *loop_level.element();
Item::new_from_element(ctx.try_position().and_then(|mut iter| iter.nth(loop_level as usize).or_else(|| iter.last())).unwrap_or(DVec2::ZERO))
) -> Result<Item<DVec2>, ReadContextError> {
let positions = ctx.try_position().ok_or(ReadContextError::NoLoopPosition)?;
Ok(Item::new_from_element(at_loop_level(positions, *loop_level.element())?))
}
// TODO: Return i64 instead of f64 once automatic type conversion is implemented for nodes with generic type inputs, so an integer output doesn't wall this index off from the generic math nodes.
@@ -93,7 +89,44 @@ fn read_index(
/// In programming terms: inside the double loop `i { j { ... } }`, *Loop Level* 0 = `j` and 1 = `i`. After inserting a third loop `k { ... }`, inside it, levels would be 0 = `k`, 1 = `j`, and 2 = `i`.
#[hard(0..)]
loop_level: Item<i64>,
) -> Item<f64> {
let loop_level = *loop_level.element();
Item::new_from_element(ctx.try_index().and_then(|mut iter| iter.nth(loop_level as usize).or_else(|| iter.last())).unwrap_or(0) as f64)
) -> Result<Item<f64>, ReadContextError> {
let indices = ctx.try_index().ok_or(ReadContextError::NoLoopIndex)?;
Ok(Item::new_from_element(at_loop_level(indices, *loop_level.element())? as f64))
}
/// The value of the loop `level` loops out from the innermost one, given the loops' values from the innermost outwards.
fn at_loop_level<T>(levels: impl Iterator<Item = T>, level: i64) -> Result<T, ReadContextError> {
let levels: Vec<T> = levels.collect();
let outermost = levels.len().saturating_sub(1);
usize::try_from(level)
.ok()
.and_then(|level| levels.into_iter().nth(level))
.ok_or(ReadContextError::LoopLevelTooHigh { level, outermost })
}
#[cfg(test)]
mod tests {
use super::*;
use core_types::OwnedContextImpl;
#[test]
fn read_index_reads_each_loop_level_and_fails_past_the_outermost() {
let nested = OwnedContextImpl::default().with_index(4).with_index(7).into_context();
let level = |level: i64| read_index(nested.clone(), (), Item::new_from_element(level)).map(|index| *index.element());
assert_eq!(level(0).unwrap(), 7.);
assert_eq!(level(1).unwrap(), 4.);
assert_eq!(level(2).unwrap_err().to_string(), "Loop Level 2 is too high: the outermost loop around this node is level 1");
assert!(matches!(level(i64::MAX), Err(ReadContextError::LoopLevelTooHigh { .. })));
let outside = read_index(OwnedContextImpl::default().into_context(), (), Item::new_from_element(0));
assert!(matches!(outside, Err(ReadContextError::NoLoopIndex)));
}
#[test]
fn read_number_outside_a_loop_fails() {
let error = read_number(OwnedContextImpl::default().into_context()).unwrap_err();
assert_eq!(error.to_string(), "No number to read: this node only works inside a loop over number items, like in a Map node");
}
}
+1
View File
@@ -27,3 +27,4 @@ glam = { workspace = true }
serde = { workspace = true }
node-macro = { workspace = true }
rand = { workspace = true }
thiserror = { workspace = true }
+323 -177
View File
@@ -1,7 +1,9 @@
use brush_types::Stroke;
use core_types::bounds::{BoundingBox, RenderBoundingBox};
use core_types::list::{AttributeValueDyn, Item, List, ListDyn, NodeIdPath};
use core_types::{ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_TRANSFORM, AnyHash, BlendMode, CacheHash, CloneVarArgs, Color, Context, Ctx, ExtractAll, Interrupt, OwnedContextImpl};
use core_types::list::{AttributeTypeConflictError, AttributeValueDyn, Item, List, ListDyn, NodeIdPath, implicit_default};
use core_types::{
ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_TRANSFORM, AnyHash, BlendMode, CacheHash, CloneVarArgs, Color, Context, Ctx, ExtractAll, Interrupt, OwnedContextImpl, descriptor,
};
use glam::{DAffine2, DVec2};
use graphic_types::graphic::{Graphic, IntoGraphicList, is_lone_anonymous_leaf};
use graphic_types::{Artboard, Vector};
@@ -298,31 +300,31 @@ fn slice<T: Send + Sync + Clone + 'static>(
list.into_iter().skip(start).take(end - start).collect()
}
/// Pairwise ordering used by the Sort node for element values. Types without a natural
/// order compare as equal, so the stable sort leaves their items in their original relative positions.
/// Pairwise ordering used by the Sort node for element values. Types without a natural order give `None`,
/// so their items can only be sorted by a *Sort Order* list.
pub trait ElementOrder {
fn element_order(&self, _other: &Self) -> Ordering {
Ordering::Equal
fn element_order(&self, _other: &Self) -> Option<Ordering> {
None
}
}
impl ElementOrder for String {
fn element_order(&self, other: &Self) -> Ordering {
self.cmp(other)
fn element_order(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl ElementOrder for bool {
fn element_order(&self, other: &Self) -> Ordering {
self.cmp(other)
fn element_order(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl ElementOrder for f64 {
fn element_order(&self, other: &Self) -> Ordering {
self.total_cmp(other)
fn element_order(&self, other: &Self) -> Option<Ordering> {
Some(self.total_cmp(other))
}
}
impl ElementOrder for i64 {
fn element_order(&self, other: &Self) -> Ordering {
self.cmp(other)
fn element_order(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl ElementOrder for DVec2 {}
@@ -335,6 +337,12 @@ impl ElementOrder for Color {}
impl ElementOrder for Gradient {}
impl ElementOrder for Artboard {}
#[derive(Debug, thiserror::Error)]
pub enum SortError {
#[error("These items have no natural order, so connect a Sort Order list to sort them")]
NoNaturalOrder,
}
/// Reorders a list's items from smallest to largest, either by each item's own value or by a parallel list of sortable values in the *Sort Order* input. The sort is stable, so items with the same sort order retain their relative positions.
#[node_macro::node(category("Data: List"), icon("NodeSort"))]
fn sort<T: ElementOrder + Clone + Send + Sync + 'static, U: ElementOrder + Send + Sync + 'static>(
@@ -356,21 +364,29 @@ fn sort<T: ElementOrder + Clone + Send + Sync + 'static, U: ElementOrder + Send
sort_order: List<U>,
/// Reverses the sorted list order, following descending order instead of ascending (numbers largest-to-smallest, strings Z-to-A, etc.).
reverse: Item<bool>,
) -> List<T> {
) -> Result<List<T>, SortError> {
let reverse = reverse.into_element();
// Order by the parallel keys when provided (repeating the last if there are fewer keys than items), otherwise by the element values themselves
let keys = sort_order.iter_element_values().as_slice();
let elements: Vec<&T> = list.iter_element_values().collect();
let mut unordered = false;
let mut order: Vec<usize> = (0..list.len()).collect();
order.sort_by(|&a, &b| {
let ordering = match keys {
[] => elements[a].element_order(elements[b]),
keys => keys[a.min(keys.len() - 1)].element_order(&keys[b.min(keys.len() - 1)]),
};
let ordering = ordering.unwrap_or_else(|| {
unordered = true;
Ordering::Equal
});
if reverse { ordering.reverse() } else { ordering }
});
if unordered {
return Err(SortError::NoNaturalOrder);
}
let mut result = List::new();
for index in order {
@@ -379,7 +395,7 @@ fn sort<T: ElementOrder + Clone + Send + Sync + 'static, U: ElementOrder + Send
}
}
result
Ok(result)
}
#[node_macro::node(category("Data: List"), icon("NodeMap"))]
@@ -431,8 +447,42 @@ fn map<Item: AnyHash + Send + Sync + CacheHash + Clone>(
Ok(rows)
}
#[derive(Debug, thiserror::Error)]
pub enum MirrorError {
#[error("Text and fills have no bounds to mirror relative to, so set Relative to Bounds to None")]
NoBounds,
}
/// Whether the content holds text, which has no bounds in the graph.
pub trait HasText {
fn has_text(&self) -> bool {
false
}
}
impl HasText for String {
fn has_text(&self) -> bool {
!self.is_empty()
}
}
impl HasText for Graphic {
fn has_text(&self) -> bool {
match self {
Graphic::Text(item) => item.element().has_text(),
Graphic::TextList(list) => list.iter_element_values().any(HasText::has_text),
Graphic::Graphic(item) => item.element().has_text(),
Graphic::GraphicList(list) => list.iter_element_values().any(HasText::has_text),
_ => false,
}
}
}
impl HasText for Vector {}
impl HasText for Raster<CPU> {}
impl HasText for Raster<GPU> {}
impl HasText for Color {}
impl HasText for Gradient {}
#[node_macro::node(category("Graphic"), icon("NodeMirror"))]
fn mirror<T: BoundingBox + Send + Clone>(
fn mirror<T: BoundingBox + HasText + Send + Clone>(
_: impl Ctx,
#[implementations(
Graphic,
@@ -451,7 +501,7 @@ fn mirror<T: BoundingBox + Send + Clone>(
#[soft(-90..90)]
angle: Item<f64>,
#[default(true)] keep_original: Item<bool>,
) -> List<T> {
) -> Result<List<T>, MirrorError> {
let (relative_to_bounds, offset, angle, keep_original) = (relative_to_bounds.into_element(), offset.into_element(), angle.into_element(), keep_original.into_element());
// Normalize the direction vector
@@ -459,13 +509,16 @@ fn mirror<T: BoundingBox + Send + Clone>(
// The mirror reference may be based on the bounding box if an explicit reference point is chosen
let item_transform: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM);
let RenderBoundingBox::Rectangle(bounding_box) = content.bounding_box(DAffine2::IDENTITY, false) else {
return List::new_from_item(content);
let mirror_reference_point = match relative_to_bounds {
ReferencePoint::None => None,
reference_point => match content.bounding_box(DAffine2::IDENTITY, false) {
RenderBoundingBox::Rectangle(bounding_box) => reference_point.point_in_bounding_box((bounding_box[0], bounding_box[1]).into()).map(|point| point + normal * offset),
// Empty content looks the same mirrored
RenderBoundingBox::None if !content.element().has_text() => return Ok(std::iter::repeat_n(content, if keep_original { 2 } else { 1 }).collect()),
_ => return Err(MirrorError::NoBounds),
},
};
let reference_point_location = relative_to_bounds.point_in_bounding_box((bounding_box[0], bounding_box[1]).into());
let mirror_reference_point = reference_point_location.map(|point| point + normal * offset);
// Create the reflection matrix
let reflection = DAffine2::from_mat2_translation(
glam::DMat2::from_cols(
@@ -493,7 +546,7 @@ fn mirror<T: BoundingBox + Send + Clone>(
mirrored.set_attribute(ATTR_TRANSFORM, reflected_transform * item_transform);
result_list.push(mirrored);
result_list
Ok(result_list)
}
/// Returns the path identifying the subgraph (network) that contains this proto node — i.e. the input `node_path`
@@ -509,6 +562,14 @@ fn path_of_subgraph(_: impl Ctx, node_path: Item<NodeIdPath>) -> Item<NodeIdPath
Item::new_from_element(NodeIdPath(node_path.into_iter().take(len.saturating_sub(1)).collect()))
}
#[derive(Debug, thiserror::Error)]
pub enum AttributeTypeError {
#[error("The \"{name}\" attribute holds {held} values, not {requested}")]
WrongType { name: String, held: String, requested: String },
#[error(transparent)]
Conflict(#[from] AttributeTypeConflictError),
}
/// Sets a named attribute on the input list, computing one value per item via the value-producing input. That input
/// is evaluated once per item, with the item's index and the item itself (as a list containing only that item,
/// passed as a vararg) provided via context, so the upstream pipeline can return a different value per item that may
@@ -564,14 +625,8 @@ fn read_attribute_vector(
/// The attribute name (key) to read.
#[constant]
name: Item<String>,
) -> List<Vector> {
let name = name.into_element();
let mut result = List::with_capacity(content.len());
for index in 0..content.len() {
let Some(value) = content.attribute::<Vector>(&name, index) else { continue };
result.push(Item::new_from_element(value.clone()));
}
result
) -> Result<List<Vector>, AttributeTypeError> {
read_list_attribute(&content, name.element())
}
/// Reads a named `Number` or `Integer` attribute from the input list, outputting each value as an element of a new `Number[]`.
@@ -582,15 +637,16 @@ fn read_attribute_number(
/// The attribute name (key) to read.
#[constant]
name: Item<String>,
) -> List<f64> {
) -> Result<List<f64>, AttributeTypeError> {
let name = name.into_element();
let mut result = List::with_capacity(content.len());
for index in 0..content.len() {
let value = content.attribute::<f64>(&name, index).copied().or_else(|| content.attribute::<i64>(&name, index).map(|v| *v as f64));
let Some(value) = value else { continue };
result.push(Item::new_from_element(value));
if content.attribute_type(&name) == Some(descriptor!(i64)) {
return Ok((0..content.len())
.filter_map(|index| content.attribute::<i64>(&name, index))
.map(|value| Item::new_from_element(*value as f64))
.collect());
}
result
read_attribute(&content, &name)
}
/// Reads a named `Bool` attribute from the input list, outputting each value as an element of a new `Bool[]`.
@@ -601,14 +657,8 @@ fn read_attribute_bool(
/// The attribute name (key) to read.
#[constant]
name: Item<String>,
) -> List<bool> {
let name = name.into_element();
let mut result = List::with_capacity(content.len());
for index in 0..content.len() {
let Some(value) = content.attribute::<bool>(&name, index) else { continue };
result.push(Item::new_from_element(*value));
}
result
) -> Result<List<bool>, AttributeTypeError> {
read_attribute(&content, name.element())
}
/// Reads a named `String` attribute from the input list, outputting each value as an element of a new `String[]`.
@@ -619,14 +669,8 @@ fn read_attribute_string(
/// The attribute name (key) to read.
#[constant]
name: Item<String>,
) -> List<String> {
let name = name.into_element();
let mut result = List::with_capacity(content.len());
for index in 0..content.len() {
let Some(value) = content.attribute::<String>(&name, index) else { continue };
result.push(Item::new_from_element(value.clone()));
}
result
) -> Result<List<String>, AttributeTypeError> {
read_attribute(&content, name.element())
}
/// Reads a named `Transform` attribute from the input list, outputting each value as an element of a new `Transform[]`.
@@ -637,14 +681,8 @@ fn read_attribute_transform(
/// The attribute name (key) to read.
#[constant]
name: Item<String>,
) -> List<DAffine2> {
let name = name.into_element();
let mut result = List::with_capacity(content.len());
for index in 0..content.len() {
let Some(value) = content.attribute::<DAffine2>(&name, index) else { continue };
result.push(Item::new_from_element(*value));
}
result
) -> Result<List<DAffine2>, AttributeTypeError> {
read_attribute(&content, name.element())
}
/// Reads a named `Color` attribute from the input list, outputting each value as an element of a new `Color[]`.
@@ -655,14 +693,8 @@ fn read_attribute_color(
/// The attribute name (key) to read.
#[constant]
name: Item<String>,
) -> List<Color> {
let name = name.into_element();
let mut result = List::with_capacity(content.len());
for index in 0..content.len() {
let Some(value) = content.attribute::<Color>(&name, index) else { continue };
result.push(Item::new_from_element(*value));
}
result
) -> Result<List<Color>, AttributeTypeError> {
read_attribute(&content, name.element())
}
/// Reads a named `BlendMode` attribute from the input list, outputting each value as an element of a new `BlendMode[]`.
@@ -673,14 +705,8 @@ fn read_attribute_blend_mode(
/// The attribute name (key) to read.
#[constant]
name: Item<String>,
) -> List<BlendMode> {
let name = name.into_element();
let mut result = List::with_capacity(content.len());
for index in 0..content.len() {
let Some(value) = content.attribute::<BlendMode>(&name, index) else { continue };
result.push(Item::new_from_element(*value));
}
result
) -> Result<List<BlendMode>, AttributeTypeError> {
read_attribute(&content, name.element())
}
/// Reads a named `GradientForm` attribute from the input list, outputting each value as an element of a new `GradientForm[]`.
@@ -691,14 +717,8 @@ fn read_attribute_gradient_form(
/// The attribute name (key) to read.
#[constant]
name: Item<String>,
) -> List<GradientForm> {
let name = name.into_element();
let mut result = List::with_capacity(content.len());
for index in 0..content.len() {
let Some(value) = content.attribute::<GradientForm>(&name, index) else { continue };
result.push(Item::new_from_element(*value));
}
result
) -> Result<List<GradientForm>, AttributeTypeError> {
read_attribute(&content, name.element())
}
/// Reads a named `GradientSpread` attribute from the input list, outputting each value as an element of a new `GradientSpread[]`.
@@ -709,14 +729,8 @@ fn read_attribute_gradient_spread(
/// The attribute name (key) to read.
#[constant]
name: Item<String>,
) -> List<GradientSpread> {
let name = name.into_element();
let mut result = List::with_capacity(content.len());
for index in 0..content.len() {
let Some(value) = content.attribute::<GradientSpread>(&name, index) else { continue };
result.push(Item::new_from_element(*value));
}
result
) -> Result<List<GradientSpread>, AttributeTypeError> {
read_attribute(&content, name.element())
}
/// Reads a named `GradientSpace` attribute from the input list, outputting each value as an element of a new `GradientSpace[]`.
@@ -727,14 +741,8 @@ fn read_attribute_gradient_space(
/// The attribute name (key) to read.
#[constant]
name: Item<String>,
) -> List<GradientSpace> {
let name = name.into_element();
let mut result = List::with_capacity(content.len());
for index in 0..content.len() {
let Some(value) = content.attribute::<GradientSpace>(&name, index) else { continue };
result.push(Item::new_from_element(*value));
}
result
) -> Result<List<GradientSpace>, AttributeTypeError> {
read_attribute(&content, name.element())
}
/// Reads a named `GradientInterpolation` attribute from the input list, outputting each value as an element of a new `GradientInterpolation[]`.
@@ -745,14 +753,8 @@ fn read_attribute_gradient_interpolation(
/// The attribute name (key) to read.
#[constant]
name: Item<String>,
) -> List<GradientInterpolation> {
let name = name.into_element();
let mut result = List::with_capacity(content.len());
for index in 0..content.len() {
let Some(value) = content.attribute::<GradientInterpolation>(&name, index) else { continue };
result.push(Item::new_from_element(*value));
}
result
) -> Result<List<GradientInterpolation>, AttributeTypeError> {
read_attribute(&content, name.element())
}
/// Reads a named `GradientHueDirection` attribute from the input list, outputting each value as an element of a new `GradientHueDirection[]`.
@@ -763,14 +765,8 @@ fn read_attribute_gradient_hue_direction(
/// The attribute name (key) to read.
#[constant]
name: Item<String>,
) -> List<GradientHueDirection> {
let name = name.into_element();
let mut result = List::with_capacity(content.len());
for index in 0..content.len() {
let Some(value) = content.attribute::<GradientHueDirection>(&name, index) else { continue };
result.push(Item::new_from_element(*value));
}
result
) -> Result<List<GradientHueDirection>, AttributeTypeError> {
read_attribute(&content, name.element())
}
/// Reads a named `Gradient` attribute from the input list, outputting each value as an element of a new `Gradient[]`.
@@ -781,14 +777,8 @@ fn read_attribute_gradient_stops(
/// The attribute name (key) to read.
#[constant]
name: Item<String>,
) -> List<Gradient> {
let name = name.into_element();
let mut result = List::with_capacity(content.len());
for index in 0..content.len() {
let Some(value) = content.attribute::<Gradient>(&name, index) else { continue };
result.push(Item::new_from_element(value.clone()));
}
result
) -> Result<List<Gradient>, AttributeTypeError> {
read_list_attribute(&content, name.element())
}
/// Reads a named `Artboard` attribute from the input list, outputting each value as an element of a new `Artboard[]`.
@@ -799,14 +789,8 @@ fn read_attribute_artboard(
/// The attribute name (key) to read.
#[constant]
name: Item<String>,
) -> List<Artboard> {
let name = name.into_element();
let mut result = List::with_capacity(content.len());
for index in 0..content.len() {
let Some(value) = content.attribute::<Artboard>(&name, index) else { continue };
result.push(Item::new_from_element(value.clone()));
}
result
) -> Result<List<Artboard>, AttributeTypeError> {
read_attribute(&content, name.element())
}
/// Reads a named `Raster` attribute from the input list, outputting each value as an element of a new `Raster[]`.
@@ -817,14 +801,41 @@ fn read_attribute_raster(
/// The attribute name (key) to read.
#[constant]
name: Item<String>,
) -> List<Raster<CPU>> {
let name = name.into_element();
let mut result = List::with_capacity(content.len());
for index in 0..content.len() {
let Some(value) = content.attribute::<Raster<CPU>>(&name, index) else { continue };
result.push(Item::new_from_element(value.clone()));
) -> Result<List<Raster<CPU>>, AttributeTypeError> {
read_list_attribute(&content, name.element())
}
/// Reads the named attribute's value for every item, reading an attribute no item has as each item's implicit default.
fn read_attribute<T: Clone + Default + 'static>(content: &ListDyn, name: &str) -> Result<List<T>, AttributeTypeError> {
let requested = descriptor!(T);
if let Some(held) = content.attribute_type(name)
&& held != requested
{
return Err(AttributeTypeError::WrongType {
name: name.to_string(),
held: held.to_string(),
requested: requested.to_string(),
});
}
result
Ok((0..content.len())
.map(|index| Item::new_from_element(content.attribute::<T>(name, index).cloned().unwrap_or_else(|| implicit_default(name))))
.collect())
}
/// Reads the named attribute like [`read_attribute`], joining the lists of an attribute holding one list per item, as Write Attribute stores a list.
fn read_list_attribute<T: Clone + Default + 'static>(content: &ListDyn, name: &str) -> Result<List<T>, AttributeTypeError> {
if content.attribute_type(name) != Some(descriptor!(List<T>)) {
return read_attribute(content, name);
}
let mut result = List::new();
for list in (0..content.len()).filter_map(|index| content.attribute::<List<T>>(name, index)) {
if let Some(conflict) = result.extend(list.clone()) {
return Err(conflict.into());
}
}
Ok(result)
}
/// Joins two lists of the same type, extending the base list with the items from the new list.
@@ -868,11 +879,12 @@ fn extend<T: Send + Clone>(
List<Stroke>,
)]
new: List<T>,
) -> List<T> {
) -> Result<List<T>, (List<T>, AttributeTypeConflictError)> {
let mut base = base;
base.extend(new);
base
match base.extend(new) {
Some(conflict) => Err((base, conflict)),
None => Ok(base),
}
}
// TODO: Eventually remove this document upgrade code
@@ -886,7 +898,7 @@ fn legacy_layer_extend<T: Send + Clone>(
#[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<String>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<Gradient>)]
new: List<T>,
nested_node_path: Item<NodeIdPath>,
) -> List<T> {
) -> Result<List<T>, (List<T>, AttributeTypeConflictError)> {
// Drop this internal node's own trailing entry so the stamped path ends at the user-facing parent layer-style node (which encapsulates it)
let nested_node_path = nested_node_path.into_element().0;
let layer_path = {
@@ -895,12 +907,18 @@ fn legacy_layer_extend<T: Send + Clone>(
};
let mut base = base;
let mut conflict = None;
for mut row in new.into_iter() {
row.set_attribute(ATTR_EDITOR_LAYER_PATH, layer_path.clone());
base.push(row);
if let Some(row_conflict) = base.push(row) {
conflict.get_or_insert(row_conflict);
}
}
base
match conflict {
Some(conflict) => Err((base, conflict)),
None => Ok(base),
}
}
/// Nests the input graphical content in a wrapper graphic, collecting it all into a single group.
@@ -934,11 +952,11 @@ fn as_graphic(_: impl Ctx, value: Item<Graphic>) -> Item<Graphic> {
/// Removes a level of nesting from a `Graphic[]`, or all nesting if "Fully Flatten" is enabled.
#[node_macro::node(category("Graphic"), icon("NodeFlattenGraphic"))]
fn flatten_graphic(_: impl Ctx, content: List<Graphic>, fully_flatten: Item<bool>) -> List<Graphic> {
fn flatten_graphic(_: impl Ctx, content: List<Graphic>, fully_flatten: Item<bool>) -> Result<List<Graphic>, (List<Graphic>, AttributeTypeConflictError)> {
let fully_flatten = fully_flatten.into_element();
// TODO: Avoid mutable reference, instead return a new List<Graphic>?
fn flatten_list(output_graphic_list: &mut List<Graphic>, current_graphic_list: List<Graphic>, fully_flatten: bool, recursion_depth: usize) {
fn flatten_list(output_graphic_list: &mut List<Graphic>, conflict: &mut Option<AttributeTypeConflictError>, current_graphic_list: List<Graphic>, fully_flatten: bool, recursion_depth: usize) {
for index in 0..current_graphic_list.len() {
let Some(current_element) = current_graphic_list.element(index) else { continue };
let current_element = current_element.clone();
@@ -960,27 +978,34 @@ fn flatten_graphic(_: impl Ctx, content: List<Graphic>, fully_flatten: Item<bool
*graphic_transform = current_transform * *graphic_transform;
}
flatten_list(output_graphic_list, current_element, fully_flatten, recursion_depth + 1);
flatten_list(output_graphic_list, conflict, current_element, fully_flatten, recursion_depth + 1);
}
// Push any leaf element: a group beyond the recursion depth, or any non-group variant
_ => {
let attributes = current_graphic_list.clone_item_attributes(index);
output_graphic_list.push(Item::from_parts(current_element, attributes));
if let Some(item_conflict) = output_graphic_list.push(Item::from_parts(current_element, attributes)) {
conflict.get_or_insert(item_conflict);
}
}
}
}
}
let mut output = List::new();
flatten_list(&mut output, content, fully_flatten, 0);
let mut conflict = None;
flatten_list(&mut output, &mut conflict, content, fully_flatten, 0);
output
match conflict {
Some(conflict) => Err((output, conflict)),
None => Ok(output),
}
}
/// Converts a `Graphic[]` into a `Vector[]` by deeply flattening any vector content it contains, and discarding any non-vector content.
#[node_macro::node(category("Graphic"), icon("NodeFlattenVector"))]
pub fn flatten_vector(_: impl Ctx, content: List<Graphic>) -> List<Vector> {
let mut output: List<Vector> = content.clone().into_flattened_list();
pub fn flatten_vector(_: impl Ctx, content: List<Graphic>) -> Result<List<Vector>, (List<Vector>, AttributeTypeConflictError)> {
let mut flattened = content.clone().try_into_flattened_list();
let (Ok(output) | Err((output, _))) = &mut flattened;
// TODO: Replace this snapshot hack with per-layer metadata driven by each layer's Monitor node.
// TODO: Flattening here erases the upstream `List<Graphic>` hierarchy that editor metadata collection walks
@@ -1006,31 +1031,60 @@ pub fn flatten_vector(_: impl Ctx, content: List<Graphic>) -> List<Vector> {
output.set_attribute(ATTR_EDITOR_MERGED_LAYERS, 0, merged_layers);
}
output
flattened
}
#[derive(Debug, thiserror::Error)]
pub enum FlattenRasterError {
#[error("GPU rasters such as brush strokes can't be flattened yet, so they were left out")]
GpuRasters,
#[error(transparent)]
AttributeTypeConflict(#[from] AttributeTypeConflictError),
}
/// Whether the content holds GPU rasters, which flattening to CPU rasters leaves out.
fn has_gpu_raster(graphic: &Graphic) -> bool {
match graphic {
Graphic::RasterGPU(_) => true,
Graphic::RasterGPUList(list) => !list.is_empty(),
Graphic::Graphic(item) => has_gpu_raster(item.element()),
Graphic::GraphicList(list) => list.iter_element_values().any(has_gpu_raster),
_ => false,
}
}
/// Converts a `Graphic[]` into a `Raster[]` by deeply flattening any raster content it contains, and discarding any non-raster content.
#[node_macro::node(category("Graphic"), icon("NodeFlattenRaster"))]
fn flatten_raster(_: impl Ctx, content: List<Graphic>) -> List<Raster<CPU>> {
content.into_flattened_list()
fn flatten_raster(_: impl Ctx, content: List<Graphic>) -> Result<List<Raster<CPU>>, (List<Raster<CPU>>, FlattenRasterError)> {
let has_gpu_rasters = content.iter_element_values().any(has_gpu_raster);
let flattened = content.try_into_flattened_list();
if has_gpu_rasters {
let rasters = flattened.unwrap_or_else(|(rasters, _)| rasters);
return Err((rasters, FlattenRasterError::GpuRasters));
}
flattened.map_err(|(rasters, conflict)| (rasters, conflict.into()))
}
/// Converts a `Graphic[]` into a `Color[]` by deeply flattening any color content it contains, and discarding any non-color content.
#[node_macro::node(category("Graphic"), icon("NodeFlattenColor"))]
fn flatten_color(_: impl Ctx, content: List<Graphic>) -> List<Color> {
content.into_flattened_list()
fn flatten_color(_: impl Ctx, content: List<Graphic>) -> Result<List<Color>, (List<Color>, AttributeTypeConflictError)> {
content.try_into_flattened_list()
}
/// Converts a `Graphic[]` into a `Gradient[]` by deeply flattening any gradient content it contains, and discarding any non-gradient content.
#[node_macro::node(category("Graphic"), icon("NodeFlattenGradient"))]
fn flatten_gradient(_: impl Ctx, content: List<Graphic>) -> List<Gradient> {
content.into_flattened_list()
fn flatten_gradient(_: impl Ctx, content: List<Graphic>) -> Result<List<Gradient>, (List<Gradient>, AttributeTypeConflictError)> {
content.try_into_flattened_list()
}
/// Constructs a gradient from a `Color[]`, where each color becomes a gradient stop. A `position` attribute on the colors places their stops along the ramp and a `midpoint` attribute skews each transition, while colors carrying neither are distributed evenly across the 0 to 1 range.
#[node_macro::node(category("Gradient"), icon("NodeColorsToGradient"), name("Colors to Gradient"))]
fn colors_to_gradient(_: impl Ctx, colors: List<Graphic>) -> Item<Gradient> {
Item::new_from_element(Gradient::from(colors.into_flattened_list::<Color>()))
fn colors_to_gradient(_: impl Ctx, colors: List<Graphic>) -> Result<Item<Gradient>, (Item<Gradient>, AttributeTypeConflictError)> {
colors
.try_into_flattened_list::<Color>()
.map(|colors| Item::new_from_element(Gradient::from(colors)))
.map_err(|(colors, conflict)| (Item::new_from_element(Gradient::from(colors)), conflict))
}
/// Unwraps a gradient into a `Color[]` of its stops, keeping any `position` and `midpoint` attributes that place them along the ramp. Attributes belonging to the gradient as a whole (like spread and interpolation), rather than its individual color stops, are not preserved.
@@ -1042,6 +1096,7 @@ fn gradient_to_colors(_: impl Ctx, gradient: Item<Gradient>) -> List<Color> {
#[cfg(test)]
mod test {
use super::*;
use core_types::ATTR_OPACITY;
fn list_of<T>(elements: impl IntoIterator<Item = T>) -> List<T> {
elements.into_iter().map(Item::new_from_element).collect()
@@ -1059,50 +1114,141 @@ mod test {
#[test]
fn sorts_elements_by_their_natural_order() {
let list = list_of(["banana".to_string(), "apple".to_string(), "cherry".to_string()]);
let sorted = sort((), list, List::<f64>::new(), Item::new_from_element(false));
let sorted = sort((), list, List::<f64>::new(), Item::new_from_element(false)).unwrap();
assert_eq!(elements(&sorted), ["apple", "banana", "cherry"]);
}
#[test]
fn sorts_elements_in_reverse() {
let list = list_of([3., 1., 2.]);
let sorted = sort((), list, List::<f64>::new(), Item::new_from_element(true));
let sorted = sort((), list, List::<f64>::new(), Item::new_from_element(true)).unwrap();
assert_eq!(elements(&sorted), [3., 2., 1.]);
}
#[test]
fn sort_order_keys_override_element_order() {
let list = list_of(["apple".to_string(), "banana".to_string(), "cherry".to_string()]);
let sorted = sort((), list, list_of([2., 0., 1.]), Item::new_from_element(false));
let sorted = sort((), list, list_of([2., 0., 1.]), Item::new_from_element(false)).unwrap();
assert_eq!(elements(&sorted), ["banana", "cherry", "apple"]);
}
#[test]
fn short_sort_order_repeats_its_last_key() {
let list = list_of(["a".to_string(), "b".to_string(), "c".to_string()]);
let sorted = sort((), list, list_of([2., 1.]), Item::new_from_element(false));
let sorted = sort((), list, list_of([2., 1.]), Item::new_from_element(false)).unwrap();
assert_eq!(elements(&sorted), ["b", "c", "a"]);
}
#[test]
fn long_sort_order_ignores_its_extra_keys() {
let list = list_of([1., 2.]);
let sorted = sort((), list, list_of([3., 1., 0., 5.]), Item::new_from_element(false));
let sorted = sort((), list, list_of([3., 1., 0., 5.]), Item::new_from_element(false)).unwrap();
assert_eq!(elements(&sorted), [2., 1.]);
}
#[test]
fn text_sort_order_keys_order_items_alphabetically() {
let list = list_of([1., 2., 3.]);
let sorted = sort((), list, list_of(["c".to_string(), "a".to_string(), "b".to_string()]), Item::new_from_element(false));
let sorted = sort((), list, list_of(["c".to_string(), "a".to_string(), "b".to_string()]), Item::new_from_element(false)).unwrap();
assert_eq!(elements(&sorted), [2., 3., 1.]);
}
#[test]
fn unsortable_elements_keep_their_original_order() {
fn unsortable_elements_need_sort_order_keys() {
let list = list_of([DVec2::new(3., 3.), DVec2::new(1., 1.), DVec2::new(2., 2.)]);
let sorted = sort((), list, List::<f64>::new(), Item::new_from_element(false));
assert_eq!(elements(&sorted), [DVec2::new(3., 3.), DVec2::new(1., 1.), DVec2::new(2., 2.)]);
assert!(matches!(sort((), list.clone(), List::<f64>::new(), Item::new_from_element(false)), Err(SortError::NoNaturalOrder)));
let sorted = sort((), list, list_of([2., 0., 1.]), Item::new_from_element(false)).unwrap();
assert_eq!(elements(&sorted), [DVec2::new(1., 1.), DVec2::new(2., 2.), DVec2::new(3., 3.)]);
let single = sort((), list_of([DVec2::ONE]), List::<f64>::new(), Item::new_from_element(false)).unwrap();
assert_eq!(elements(&single), [DVec2::ONE], "a single item is already in order");
}
fn mirrored<T: BoundingBox + HasText + Send + Clone>(content: T, relative_to_bounds: ReferencePoint) -> Result<List<T>, MirrorError> {
mirror((), content.into(), relative_to_bounds.into(), 0.0.into(), 0.0.into(), true.into())
}
#[test]
fn mirror_without_bounds_reflects_across_the_origin() {
let text = mirrored("text".to_string(), ReferencePoint::None).unwrap();
assert_eq!(text.len(), 2);
assert_eq!(text.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM, 1), DAffine2::from_scale(DVec2::new(-1., 1.)));
assert!(matches!(mirrored("text".to_string(), ReferencePoint::Center), Err(MirrorError::NoBounds)));
assert!(matches!(mirrored(Color::RED, ReferencePoint::Center), Err(MirrorError::NoBounds)));
}
#[test]
fn mirroring_empty_content_keeps_the_original_and_the_copy() {
assert_eq!(mirrored(Vector::default(), ReferencePoint::Center).unwrap().len(), 2);
assert_eq!(mirrored(String::new(), ReferencePoint::Center).unwrap().len(), 2);
}
fn with_values<U: Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash + 'static>(key: &str, values: Vec<U>) -> ListDyn {
let mut list = List::new_from_elements(vec![(); values.len()]);
list.set_attribute_values(key, values);
ListDyn::from(list)
}
#[test]
fn reading_a_missing_attribute_gives_each_item_its_implicit_default() {
let plain = ListDyn::from(List::new_from_elements(vec![(), ()]));
assert_eq!(elements(&read_attribute_number((), plain.clone(), Item::new_from_element(ATTR_OPACITY.to_string())).unwrap()), [1., 1.]);
assert_eq!(elements(&read_attribute_number((), plain.clone(), Item::new_from_element("misspelled".to_string())).unwrap()), [0., 0.]);
assert_eq!(
elements(&read_attribute_transform((), plain, Item::new_from_element(ATTR_TRANSFORM.to_string())).unwrap()),
[DAffine2::IDENTITY; 2]
);
}
#[test]
fn reading_an_attribute_as_another_type_fails() {
let numbers = with_values("tag", vec![1_f64, 2.]);
let error = read_attribute_bool((), numbers.clone(), Item::new_from_element("tag".to_string())).unwrap_err();
assert_eq!(error.to_string(), "The \"tag\" attribute holds Number values, not Bool");
assert_eq!(
elements(&read_attribute_number((), with_values("tag", vec![3_i64]), Item::new_from_element("tag".to_string())).unwrap()),
[3.]
);
}
#[test]
fn reading_a_list_attribute_joins_the_lists() {
let vectors = with_values("shapes", vec![list_of([Vector::default(), Vector::default()]), list_of([Vector::default()])]);
assert_eq!(read_attribute_vector((), vectors, Item::new_from_element("shapes".to_string())).unwrap().len(), 3);
let texts = with_values("words", vec![list_of(["a".to_string()])]);
let error = read_attribute_string((), texts, Item::new_from_element("words".to_string())).unwrap_err();
assert_eq!(error.to_string(), "The \"words\" attribute holds String[] values, not String");
}
#[test]
fn reading_list_attributes_with_differently_typed_attributes_fails() {
let mut first = list_of([Vector::default()]);
first.set_attribute("tag", 0, 5_f64);
let mut second = list_of([Vector::default()]);
second.set_attribute("tag", 0, "text".to_string());
let vectors = with_values("shapes", vec![first, second]);
let error = read_attribute_vector((), vectors, Item::new_from_element("shapes".to_string())).unwrap_err();
assert_eq!(error.to_string(), "The \"tag\" attribute holds different types of values in the lists being combined");
}
#[test]
fn extending_with_an_attribute_of_another_type_falls_back_with_its_name() {
let mut base = list_of([1., 2.]);
base.set_attribute("tag", 0, 5_f64);
let mut new = list_of([3.]);
new.set_attribute("tag", 0, "text".to_string());
let Err((extended, conflict)) = extend((), base, new) else {
panic!("expected the conflicting tag to be reported")
};
assert_eq!(elements(&extended), [1., 2., 3.]);
assert_eq!(extended.attribute::<f64>("tag", 2), Some(&0.));
assert_eq!(conflict.name, "tag");
}
#[test]
@@ -1186,7 +1332,7 @@ mod test {
let colors = gradient_to_colors((), Item::new_from_element(gradient.clone()));
assert_eq!(elements(&colors), [Color::RED, Color::GREEN, Color::BLUE], "every stop should come out as its color");
let restored = colors_to_gradient((), embed_colors(colors));
let restored = colors_to_gradient((), embed_colors(colors)).unwrap();
assert_eq!(
restored.element(),
&gradient,
@@ -1199,7 +1345,7 @@ mod test {
let gradient = Gradient::from(vec![Color::RED, Color::GREEN, Color::BLUE]);
assert!(!gradient.has_position_attribute(), "even spacing is stored as the attribute's absence");
let restored = colors_to_gradient((), embed_colors(gradient_to_colors((), Item::new_from_element(gradient.clone()))));
let restored = colors_to_gradient((), embed_colors(gradient_to_colors((), Item::new_from_element(gradient.clone())))).unwrap();
assert_eq!(restored.element(), &gradient, "a default ramp should round trip without gaining attributes it never had");
}
}
@@ -12,8 +12,8 @@ pub use graph_craft::document::value::RenderOutputType;
#[cfg(target_family = "wasm")]
pub use graphene_canvas_utils as canvas_utils;
use graphic_types::Graphic;
use graphic_types::raster_types::Image;
use graphic_types::raster_types::{CPU, GPU, Raster};
use graphic_types::raster_types::{Image, ImageError};
use rendering::{Render, RenderParams};
use std::sync::Arc;
@@ -208,11 +208,14 @@ fn pending_resource(_primary: &(), _url: &Item<String>) -> Item<Resource> {
///
/// Supports the formats: PNG, JPG, GIF, WEBP, TIFF, BMP, TGA, ICO, HDR, EXR.
#[node_macro::node(category("Data: I/O"), icon("NodeBytesToImage"), name("Bytes to Image"))]
fn bytes_to_image(_: impl Ctx, data: Item<Resource>) -> Item<Raster<CPU>> {
fn bytes_to_image(_: impl Ctx, data: Item<Resource>) -> Result<Item<Raster<CPU>>, ImageError> {
let data = data.into_element();
let Some(image) = Image::from_encoded(data.as_ref()) else { return Item::default() };
if data.is_empty() {
return Ok(Item::default());
}
let image = Image::from_encoded(data.as_ref())?;
Item::new_from_element(Raster::new_cpu(image))
Ok(Item::new_from_element(Raster::new_cpu(image)))
}
/// Renders a view of the input graphic within an area defined by the *Footprint*.
+3 -3
View File
@@ -104,8 +104,8 @@ fn text_to_vector(
_: impl Ctx,
/// A styled text string produced by the **Text** node (or any other string source).
string: Item<String>,
) -> Item<Vector> {
shape_text_item(&string, false).into_iter().next().unwrap_or_default()
) -> Result<Item<Vector>, TextToVectorError> {
Ok(shape_text_item(&string, false)?.into_iter().next().unwrap_or_default())
}
/// Splits a styled text string into a separate vector item for each of its glyphs (letterforms).
@@ -114,6 +114,6 @@ fn text_to_vector_glyphs(
_: impl Ctx,
/// A styled text string produced by the **Text** node (or any other string source).
string: Item<String>,
) -> List<Vector> {
) -> Result<List<Vector>, TextToVectorError> {
shape_text_item(&string, true)
}
+1 -1
View File
@@ -26,4 +26,4 @@ dyn-any = { workspace = true }
glam = { workspace = true }
rand = { workspace = true }
math-parser = { workspace = true }
log = { workspace = true }
thiserror = { workspace = true }
File diff suppressed because it is too large. Load diff
+1
View File
@@ -25,3 +25,4 @@ linesweeper = { workspace = true }
log = { workspace = true }
smallvec = { workspace = true }
vector-types = { workspace = true }
thiserror = { workspace = true }
+45 -32
View File
@@ -10,9 +10,20 @@ use graphic_types::{Graphic, Vector};
use linesweeper::topology::Topology;
use linesweeper::{BinaryOp, FillRule, binary_op};
use smallvec::SmallVec;
use vector_types::kurbo::{Affine, BezPath, CubicBez, Line, ParamCurve, PathEl, PathSeg, Point, QuadBez};
use vector_types::kurbo::{Affine, BezPath, CubicBez, Line, ParamCurve, PathEl, PathSeg, Point, QuadBez, Shape};
pub use vector_types::vector::misc::BooleanOperation;
/// Why a boolean operation gives no result.
#[derive(Debug, thiserror::Error)]
pub enum BooleanOperationError {
#[error("An operand has coordinates that aren't finite")]
NonFiniteCoordinates,
#[error(transparent)]
Text(#[from] text_nodes::TextToVectorError),
#[error("The operands can't be combined because {0}")]
Topology(#[from] linesweeper::Error),
}
// TODO: Fix boolean ops to work by removing .transform() and .one_instance_*() calls,
// TODO: since before we used a Vec of single-item `List`s and now we use a single `List`
// TODO: with multiple items while still assuming a single item for the boolean operations.
@@ -30,12 +41,12 @@ fn boolean_operation(
/// Intersection cuts away all but the overlapping areas shared by every path.
/// Difference cuts away the areas where an even number of paths overlap, keeping those where an odd number do.
operation: Item<BooleanOperation>,
) -> Item<Vector> {
) -> Result<Item<Vector>, BooleanOperationError> {
let operation = operation.into_element();
// The first index is the bottom of the stack
let flattened = flatten_vector(&content);
let mut result_vector_list = boolean_operation_on_vector_list(&flattened, operation);
let flattened = flatten_vector(&content)?;
let mut result_vector_list = boolean_operation_on_vector_list(&flattened, operation)?;
// Replace the transformation matrix with a mutation of the vector points themselves
if result_vector_list.element_mut(0).is_some() {
@@ -65,7 +76,7 @@ fn boolean_operation(
set_paths_at(&mut result_vector_list, 0, result_paths);
}
result_vector_list.into_iter().next().unwrap_or_default()
Ok(result_vector_list.into_iter().next().unwrap_or_default())
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
@@ -104,7 +115,7 @@ impl std::ops::AddAssign for WindingNumber {
self.elems = rhs.elems;
} else {
for (me, them) in self.elems.iter_mut().zip(&rhs.elems) {
*me += *them;
*me = me.wrapping_add(*them);
}
}
}
@@ -133,7 +144,7 @@ impl WindingNumber {
}
}
fn boolean_operation_on_vector_list(vector: &List<Vector>, boolean_operation: BooleanOperation) -> List<Vector> {
fn boolean_operation_on_vector_list(vector: &List<Vector>, boolean_operation: BooleanOperation) -> Result<List<Vector>, BooleanOperationError> {
const EPSILON: f64 = 1e-5;
let mut list = List::new();
let mut paths = Vec::new();
@@ -161,18 +172,15 @@ fn boolean_operation_on_vector_list(vector: &List<Vector>, boolean_operation: Bo
for index in 0..vector.len() {
let element = vector.element(index).unwrap();
let element_paths = paths_from_list_row_attributes(vector, index).unwrap_or_else(|| no_paths());
paths.push(to_bez_path(element, element_paths, vector.attribute_cloned_or_default(ATTR_TRANSFORM, index)));
paths.push(to_bez_path(element, element_paths, vector.attribute_cloned_or_default(ATTR_TRANSFORM, index))?);
}
let top = match Topology::<WindingNumber>::from_paths(paths.iter().enumerate().map(|(idx, path)| (path, (idx, paths.len()))), EPSILON) {
Ok(top) => top,
Err(e) => {
log::error!("Boolean operation failed while building topology: {e}");
row.set_paths(List::<Path>::new());
list.push(row);
return list;
}
};
// Far from the origin, the tolerance grows with the coordinates' magnitude like linesweeper's own `binary_op`, since the sweep can't resolve less
let bounds = paths.iter().map(Shape::bounding_box).reduce(|a, b| a.union(b)).unwrap_or_default();
let magnitude = bounds.min_x().min(bounds.min_y()).abs().max(bounds.max_x().max(bounds.max_y()).abs());
let epsilon = EPSILON.max(magnitude * f64::EPSILON * 64.);
let top = Topology::<WindingNumber>::from_paths(paths.iter().enumerate().map(|(idx, path)| (path, (idx, paths.len()))), epsilon).map_err(linesweeper::Error::from)?;
let contours = top.contours(|winding| winding.is_inside(boolean_operation));
let mut result_paths = List::new();
let closed_contours = contours.contours().map(|contour| closed(contour.path.clone()));
@@ -180,14 +188,14 @@ fn boolean_operation_on_vector_list(vector: &List<Vector>, boolean_operation: Bo
row.set_paths(result_paths);
list.push(row);
list
Ok(list)
}
/// Flattens graphic content into the operands of a boolean operation, matching `flatten_graphic_list`'s attribute composition.
/// Non-path content is dropped, since it contributes no region to operate on.
fn flatten_vector(graphic_list: &List<Graphic>) -> List<Vector> {
(0..graphic_list.len())
.flat_map(|index| {
fn flatten_vector(graphic_list: &List<Graphic>) -> Result<List<Vector>, BooleanOperationError> {
let operands = (0..graphic_list.len())
.map(|index| {
let graphic = graphic_list.element(index).unwrap();
// Whether the parent carries each attribute is a structural fact, so an absent one never invents a column on the children
@@ -234,11 +242,11 @@ fn flatten_vector(graphic_list: &List<Graphic>) -> List<Vector> {
other => other,
};
match graphic {
Ok(match graphic {
Graphic::Vector(item) => vec![compose_parent(*item)],
Graphic::VectorList(vector) => vector.into_iter().map(compose_parent).collect::<Vec<_>>(),
Graphic::Text(item) => text_nodes::shape_text_list(&List::new_from_item(item), false).into_iter().map(compose_parent).collect::<Vec<_>>(),
Graphic::TextList(text) => text_nodes::shape_text_list(&text, false).into_iter().map(compose_parent).collect::<Vec<_>>(),
Graphic::Text(item) => text_nodes::shape_text_list(&List::new_from_item(item), false)?.into_iter().map(compose_parent).collect::<Vec<_>>(),
Graphic::TextList(text) => text_nodes::shape_text_list(&text, false)?.into_iter().map(compose_parent).collect::<Vec<_>>(),
Graphic::GraphicList(mut graphic) => {
if parent_has_transform {
for transform in graphic.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM) {
@@ -265,12 +273,12 @@ fn flatten_vector(graphic_list: &List<Graphic>) -> List<Vector> {
// Unioning each group lets it enter the outer operation as one region, which is why this cannot defer
// to `flatten_graphic_list`. Splicing children in as sibling operands makes them subtract from each other.
let flattened = flatten_vector(&graphic);
let flattened = flatten_vector(&graphic)?;
if flattened.is_empty() {
// The union call emits one blank operand even from an empty list
Vec::new()
} else {
boolean_operation_on_vector_list(&flattened, BooleanOperation::Union).into_iter().collect::<Vec<_>>()
boolean_operation_on_vector_list(&flattened, BooleanOperation::Union)?.into_iter().collect::<Vec<_>>()
}
}
// Rasters, colors, and gradients bound no region, so they contribute no operand
@@ -280,9 +288,11 @@ fn flatten_vector(graphic_list: &List<Graphic>) -> List<Vector> {
Graphic::StrokeList(_) => Vec::new(),
// Normalized to GraphicList above
Graphic::Graphic(_) => Vec::new(),
}
})
})
.collect()
.collect::<Result<Vec<_>, BooleanOperationError>>()?;
Ok(operands.into_iter().flatten().collect())
}
// This quantization should potentially be removed since it's not conceptually necessary,
@@ -309,7 +319,7 @@ fn closed(mut path: BezPath) -> BezPath {
path
}
fn to_bez_path(vector: &Vector, element_paths: &List<Path>, transform: DAffine2) -> BezPath {
fn to_bez_path(vector: &Vector, element_paths: &List<Path>, transform: DAffine2) -> Result<BezPath, BooleanOperationError> {
let transform = Affine::new(transform.to_cols_array());
let mut path = BezPath::new();
@@ -330,7 +340,10 @@ fn to_bez_path(vector: &Vector, element_paths: &List<Path>, transform: DAffine2)
}
}
path
if !path.is_finite() {
return Err(BooleanOperationError::NonFiniteCoordinates);
}
Ok(path)
}
pub fn boolean_intersect(a: &BezPath, b: &BezPath) -> Vec<BezPath> {
@@ -355,7 +368,7 @@ mod tests {
#[test]
fn difference_leaves_the_overlap_of_two_shapes_empty() {
let content: List<Graphic> = [operand(&Circle::new((0., 0.), 100.)), operand(&Rect::new(50., 50., 200., 200.))].into_iter().collect();
let result = boolean_operation((), content, Item::new_from_element(BooleanOperation::Difference));
let result = boolean_operation((), content, Item::new_from_element(BooleanOperation::Difference)).unwrap();
let paths = result.attribute::<List<Path>>(ATTR_PATHS).cloned().unwrap_or_default();
let vector = result.element();
@@ -370,7 +383,7 @@ mod tests {
#[test]
fn difference_keeps_areas_covered_by_an_odd_number_of_shapes() {
let circles = [(0., 0.), (60., 0.), (30., 52.)].map(|center| operand(&Circle::new(center, 50.)));
let result = boolean_operation((), circles.into_iter().collect(), Item::new_from_element(BooleanOperation::Difference));
let result = boolean_operation((), circles.into_iter().collect(), Item::new_from_element(BooleanOperation::Difference)).unwrap();
let paths = result.attribute::<List<Path>>(ATTR_PATHS).cloned().unwrap_or_default();
let vector = result.element();
+2
View File
@@ -34,6 +34,7 @@ std = [
"dep:fastnoise-lite",
"dep:kurbo",
"dep:color",
"dep:thiserror",
]
wasm = [
"core-types/wasm",
@@ -75,6 +76,7 @@ fastnoise-lite = { workspace = true, optional = true }
serde = { workspace = true, optional = true }
kurbo = { workspace = true, optional = true }
color = { workspace = true, optional = true }
thiserror = { workspace = true, optional = true }
# Workspace Wasm dependencies
tsify = { workspace = true, optional = true }
+29 -9
View File
@@ -2,7 +2,7 @@
use crate::adjust::Adjust;
#[cfg(feature = "std")]
use crate::color_lookup_table::LutCache;
use crate::color_lookup_table::{LutCache, LutParseError};
use core::fmt::Debug;
#[cfg(feature = "std")]
use core_types::list::{Item, List};
@@ -705,6 +705,11 @@ fn curves<T: Adjust<Color> + Send>(
image
}
#[cfg(feature = "std")]
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("A control point has a coordinate that isn't finite")]
pub struct NonFinitePointError;
/// Builds a transfer curve from a `Vec2[]` of control points, each mapping the input value at its x to the output value at its y. A smooth spline runs through them, holding the outermost points' values beyond them.
#[cfg(feature = "std")]
#[node_macro::node(category("Raster: Adjustment"), icon("NodePointsToTransferCurve"), name("Points to Transfer Curve"))]
@@ -712,9 +717,12 @@ fn points_to_transfer_curve(
_: impl Ctx,
/// The control points, in any order, with both coordinates on the 0 to 1 range.
points: List<DVec2>,
) -> Item<TransferCurve> {
) -> Result<Item<TransferCurve>, NonFinitePointError> {
let points: Vec<DVec2> = points.iter_element_values().copied().collect();
Item::new_from_element(TransferCurve::new(points))
if !points.iter().all(|point| point.is_finite()) {
return Err(NonFinitePointError);
}
Ok(Item::new_from_element(TransferCurve::new(points)))
}
// Aims for interoperable compatibility with:
@@ -2177,9 +2185,9 @@ fn selective_color<T: Adjust<Color>>(
}
};
let offset_r = f32::clamp(ink(c) * slope_r, -r, -r + 1.) * color_parameter_group_scale_factor;
let offset_g = f32::clamp(ink(m) * slope_g, -g, -g + 1.) * color_parameter_group_scale_factor;
let offset_b = f32::clamp(ink(y) * slope_b, -b, -b + 1.) * color_parameter_group_scale_factor;
let offset_r = (ink(c) * slope_r).max(-r).min(-r + 1.) * color_parameter_group_scale_factor;
let offset_g = (ink(m) * slope_g).max(-g).min(-g + 1.) * color_parameter_group_scale_factor;
let offset_b = (ink(y) * slope_b).max(-b).min(-b + 1.) * color_parameter_group_scale_factor;
// An 8-bit PSD document sums the groups' 8-bit offsets, which this float node does not currently attempt to reproduce
sum += Vec3::new(offset_r, offset_g, offset_b);
@@ -2542,9 +2550,12 @@ fn color_lookup<T: Adjust<Color> + Send>(
#[widget(ParsedWidgetOverride::Custom = "lut_file")]
lut_file: Item<Resource>,
#[data] lut_cache: LutCache,
) -> Item<T> {
) -> Result<Item<T>, LutParseError> {
let mut image = image;
let Ok(lut) = lut_cache.parse(lut_file.element()) else { return image };
if lut_file.element().is_empty() {
return Ok(image);
}
let lut = lut_cache.parse(lut_file.element())?;
image.element_mut().adjust(|color| {
// Lookup tables address the gamma-encoded channels
@@ -2554,7 +2565,7 @@ fn color_lookup<T: Adjust<Color> + Send>(
Color::from_gamma_srgb_channels(r, g, b, a)
});
image
Ok(image)
}
#[cfg(feature = "std")]
@@ -3063,6 +3074,15 @@ mod tests {
assert_close(run_selective_color([100., 50., 130.], RelativeAbsolute::Relative, groups), [100., 191., 130.]);
}
#[test]
fn selective_color_survives_a_channel_that_is_not_a_number() {
let mut groups = [[0.; 4]; 9];
groups[7] = [10., 0., 0., 0.];
for mode in [RelativeAbsolute::Relative, RelativeAbsolute::Absolute] {
run_selective_color([f32::NAN, 100., 130.], mode, groups);
}
}
/// Runs Posterize on one gamma-space gray value (0..255) and returns the gamma-space result on the same scale.
fn run_posterize(value: f32, levels: i64) -> f32 {
let pixel = Color::from_gamma_srgb_channels(value / 255., value / 255., value / 255., 1.);
@@ -40,13 +40,16 @@ impl LutCache {
}
/// Why a file could not be read as a lookup table.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum LutParseError {
/// An ICC profile that describes a device's colors, not an "abstract" or "device link" profile that remaps them.
#[error("The ICC profile describes a device's colors, but only abstract and device link profiles work as LUTs")]
IccProfileClass,
/// An ICC "abstract" profile that does not map Lab to Lab, or a "device link" profile that does not map RGB to RGB.
#[error("The ICC profile's color spaces are unsupported, as a device link profile must map RGB to RGB and an abstract profile Lab to Lab")]
IccColorSpaces,
/// Not a lookup table in any of the formats, or one that is damaged.
#[error("The file is not a LUT in a supported format, or it is damaged")]
Unreadable,
}
@@ -93,7 +96,8 @@ impl Curve {
return outputs[count - 1];
}
let upper = inputs.partition_point(|&input| input <= value).min(count - 1);
// A NaN value leaves the search without a segment, so the clamp keeps it in bounds
let upper = inputs.partition_point(|&input| input <= value).clamp(1, count - 1);
let lower = upper - 1;
let t = (value - inputs[lower]) / (inputs[upper] - inputs[lower]).max(f32::EPSILON);
outputs[lower] + t * (outputs[upper] - outputs[lower])
@@ -81,6 +81,13 @@ mod tests {
assert_close(lut.apply([1., 0.5, 2.]), [0.5, 0.25, 1.]);
}
#[test]
fn pre_lut_passes_a_value_that_is_not_a_number_through() {
let text = "CSPLUTV100\n1D\n2\n0 2\n0 1\n2\n0 2\n0 1\n2\n0 2\n0 1\n2\n0 0 0\n1 1 1\n";
let lut = Lut::parse(text.as_bytes()).unwrap();
assert!(lut.apply([f32::NAN, 0.5, 2.])[0].is_nan());
}
#[test]
fn pre_lut_under_two_points_is_identity() {
let text = "CSPLUTV100\n1D\n0\n1\n0\n2\n0 0 0\n1 1 1\n";
+9 -6
View File
@@ -147,9 +147,10 @@ fn median_filter(
}
// 1D gaussian kernel
fn gaussian_kernel(radius: f64) -> Vec<f64> {
fn gaussian_kernel(radius: f64, image_extent: u32) -> Vec<f64> {
// Given radius, compute the size of the kernel that's approximately three times the radius
let kernel_radius = (3. * radius).ceil() as usize;
// Taps further out than the image extends never land on a pixel, so the kernel stops there while its weights keep the full radius
let kernel_radius = ((3. * radius).ceil() as usize).min(image_extent as usize);
let kernel_size = 2 * kernel_radius + 1;
let mut gaussian_kernel: Vec<f64> = vec![0.; kernel_size];
@@ -173,7 +174,7 @@ fn gaussian_kernel(radius: f64) -> Vec<f64> {
}
fn gaussian_blur_algorithm(buffer: Image<Color>, radius: f64, gamma: bool) -> Image<Color> {
let kernel = gaussian_kernel(radius);
let kernel = gaussian_kernel(radius, buffer.width.max(buffer.height));
if gamma {
let working = premultiply_gamma(buffer);
let blurred = gaussian_separable(working, &kernel, |r, g, b, a| PremultipliedGammaPixel { r, g, b, a });
@@ -260,6 +261,8 @@ where
let mut x_axis = Image::new(width, height, P::default());
let mut y_axis = Image::new(width, height, P::default());
let radius = radius.min(width.max(height) as f64) as i32;
for pass in [false, true] {
let (max, old_buffer, current_buffer) = match pass {
false => (width, &buffer, &mut x_axis),
@@ -272,7 +275,7 @@ where
let (mut r_sum, mut g_sum, mut b_sum, mut a_sum, mut weight_sum) = (0., 0., 0., 0., 0.);
let i = [x, y][pass];
for d in (i as i32 - radius as i32).max(0)..=(i as i32 + radius as i32).min(max as i32 - 1) {
for d in (i as i32 - radius).max(0)..=(i as i32 + radius).min(max as i32 - 1) {
if let Some(px) = old_buffer.get_pixel([d as u32, x][pass], [y, d as u32][pass]) {
let weight = 1.;
r_sum += px.r() as f64 * weight;
@@ -296,8 +299,8 @@ fn median_filter_algorithm(original_buffer: Image<Color>, radius: u32) -> Image<
let (width, height) = original_buffer.dimensions();
let mut output = Image::new(width, height, Color::TRANSPARENT);
// Pre-allocate and reuse buffers outside the loops to avoid repeated allocations.
let window_capacity = ((2 * radius + 1).pow(2)) as usize;
let window_span = |extent: u32| (radius as usize).saturating_mul(2).saturating_add(1).min(extent as usize);
let window_capacity = window_span(width) * window_span(height);
let mut r_vals: Vec<f32> = Vec::with_capacity(window_capacity);
let mut g_vals: Vec<f32> = Vec::with_capacity(window_capacity);
let mut b_vals: Vec<f32> = Vec::with_capacity(window_capacity);
+61 -36
View File
@@ -8,13 +8,13 @@ use core_types::math::bbox::Bbox;
use core_types::transform::Transform;
use dyn_any::DynAny;
use fastnoise_lite;
use glam::{DAffine2, DVec2, Vec2};
use glam::{DAffine2, DVec2, UVec2, Vec2};
use graphene_resource::Resource;
use rand::prelude::*;
use rand_chacha::ChaCha8Rng;
use raster_types::Image;
use raster_types::{Bitmap, BitmapMut};
use raster_types::{CPU, Raster};
use raster_types::{Image, ImageError};
use std::fmt::Debug;
use std::hash::Hash;
@@ -30,6 +30,16 @@ impl From<std::io::Error> for Error {
}
}
/// Two rasters that must line up pixel for pixel but differ in size.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("{first} and {second} must be the same size, but {first} is {}×{} pixels and {second} is {}×{}", .first_size.x, .first_size.y, .second_size.x, .second_size.y)]
pub struct SizeMismatchError {
pub first: &'static str,
pub first_size: UVec2,
pub second: &'static str,
pub second_size: UVec2,
}
#[node_macro::node(category("Raster"), icon("NodeChannelsToImage"), name("Channels to Image"))]
fn channels_to_image(
_: impl Ctx,
@@ -38,24 +48,31 @@ fn channels_to_image(
#[expose] green: Item<Raster<CPU>>,
#[expose] blue: Item<Raster<CPU>>,
#[expose] alpha: Item<Raster<CPU>>,
) -> Item<Raster<CPU>> {
) -> Result<Item<Raster<CPU>>, SizeMismatchError> {
// An unconnected channel arrives as the default zero-sized raster, which counts as absent
let present = |channel: Item<Raster<CPU>>| (channel.element().width > 0 && channel.element().height > 0).then_some(channel);
let (red, green, blue, alpha) = (present(red), present(green), present(blue), present(alpha));
// Take this item's transform and blending attributes from the first present channel
let Some(attributes) = [&red, &green, &blue, &alpha].iter().find_map(|channel| channel.as_ref()).map(|channel| channel.attributes().clone()) else {
return Item::default();
return Ok(Item::default());
};
// All present channels must share the same dimensions; a mismatch yields the default zero-sized raster
let channel_dimensions = [&red, &green, &blue, &alpha].map(|channel| channel.as_ref().map(|channel| (channel.element().width, channel.element().height)));
let Some(&(width, height)) = channel_dimensions.iter().flatten().next() else {
return Item::default();
// All present channels must share the same dimensions
let channel_dimensions = [("Red", &red), ("Green", &green), ("Blue", &blue), ("Alpha", &alpha)]
.map(|(name, channel)| channel.as_ref().map(|channel| (name, UVec2::new(channel.element().width, channel.element().height))));
let Some(&(first, first_size)) = channel_dimensions.iter().flatten().next() else {
return Ok(Item::default());
};
if channel_dimensions.iter().flatten().any(|&(other_width, other_height)| other_width != width || other_height != height) {
return Item::default();
if let Some(&(second, second_size)) = channel_dimensions.iter().flatten().find(|&&(_, size)| size != first_size) {
return Err(SizeMismatchError {
first,
first_size,
second,
second_size,
});
}
let (width, height) = (first_size.x, first_size.y);
// Set each output pixel's channels from the present inputs, defaulting absent color channels to 0 and absent alpha to 1
let mut image = Image::new(width, height, Color::TRANSPARENT);
@@ -82,7 +99,7 @@ fn channels_to_image(
}
}
Item::from_parts(Raster::new_cpu(image), attributes)
Ok(Item::from_parts(Raster::new_cpu(image), attributes))
}
#[node_macro::node(category("Raster"), icon("NodeMask"))]
@@ -103,9 +120,8 @@ fn mask(
let mut row = image;
let image_size = DVec2::new(row.element().width as f64, row.element().height as f64);
let stencil_transform: DAffine2 = stencil.attribute_cloned_or_default(ATTR_TRANSFORM);
let mask_size = stencil_transform.scale_magnitudes();
if mask_size == DVec2::ZERO {
if stencil_transform.matrix2.determinant() == 0. {
return row;
}
@@ -132,20 +148,22 @@ fn mask(
}
#[node_macro::node(category(""))]
fn extend_image_to_bounds(_: impl Ctx, image: Item<Raster<CPU>>, bounds: Item<DAffine2>) -> Item<Raster<CPU>> {
fn extend_image_to_bounds(_: impl Ctx, image: Item<Raster<CPU>>, bounds: Item<DAffine2>) -> Result<Item<Raster<CPU>>, (Item<Raster<CPU>>, ImageError)> {
let bounds = *bounds.element();
let image_transform: DAffine2 = image.attribute_cloned_or_default(ATTR_TRANSFORM);
let image_aabb = Bbox::unit().affine_transform(image_transform).to_axis_aligned_bbox();
let bounds_aabb = Bbox::unit().affine_transform(bounds.transform()).to_axis_aligned_bbox();
if image_aabb.contains(bounds_aabb.start) && image_aabb.contains(bounds_aabb.end) {
return image;
return Ok(image);
}
let (image, mut attributes) = image.into_parts();
let (image_width, image_height) = (image.width, image.height);
let (image_width, image_height) = (image.element().width, image.element().height);
if image_width == 0 || image_height == 0 {
return empty_image(bounds, Color::TRANSPARENT);
return empty_image(bounds, Color::TRANSPARENT).map_err(|error| (image, error));
}
if image_transform.matrix2.determinant() == 0. {
return Ok(image);
}
let orig_image_scale = DVec2::new(image_width as f64, image_height as f64);
@@ -157,7 +175,11 @@ fn extend_image_to_bounds(_: impl Ctx, image: Item<Raster<CPU>>, bounds: Item<DA
let new_scale = new_end - new_start;
// Copy over original image into enlarged image.
let mut new_image = Image::new(new_scale.x as u32, new_scale.y as u32, Color::TRANSPARENT);
let mut new_image = match Image::try_new(new_scale.x as u32, new_scale.y as u32, Color::TRANSPARENT) {
Ok(new_image) => new_image,
Err(error) => return Err((image, error)),
};
let (image, mut attributes) = image.into_parts();
let offset_in_new_image = (-new_start).as_uvec2();
for y in 0..image_height {
let old_start = y * image_width;
@@ -172,17 +194,17 @@ fn extend_image_to_bounds(_: impl Ctx, image: Item<Raster<CPU>>, bounds: Item<DA
let new_texture_to_layer_space = image_transform * DAffine2::from_scale(1. / orig_image_scale) * DAffine2::from_translation(new_start) * DAffine2::from_scale(new_scale);
attributes.insert(ATTR_TRANSFORM, new_texture_to_layer_space);
Item::from_parts(Raster::new_cpu(new_image), attributes)
Ok(Item::from_parts(Raster::new_cpu(new_image), attributes))
}
/// Creates an image filled with one color, sized in pixels by the transform's scale and placed by the transform.
fn empty_image(transform: DAffine2, color: Color) -> Item<Raster<CPU>> {
fn empty_image(transform: DAffine2, color: Color) -> Result<Item<Raster<CPU>>, ImageError> {
let width = transform.transform_vector2(DVec2::new(1., 0.)).length() as u32;
let height = transform.transform_vector2(DVec2::new(0., 1.)).length() as u32;
let image = Image::new(width, height, color);
let image = Image::try_new(width, height, color)?;
Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, transform)
Ok(Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, transform))
}
/// Displays an image from a file.
@@ -195,11 +217,14 @@ fn image(
/// The image file to display.
#[widget(ParsedWidgetOverride::Custom = "image_file")]
resource: Item<Resource>,
) -> Item<Raster<CPU>> {
) -> Result<Item<Raster<CPU>>, ImageError> {
let resource = resource.into_element();
let Some(image) = Image::from_encoded(resource.as_ref()) else { return Item::default() };
if resource.is_empty() {
return Ok(Item::default());
}
let image = Image::from_encoded(resource.as_ref())?;
Item::new_from_element(Raster::new_cpu(image))
Ok(Item::new_from_element(Raster::new_cpu(image)))
}
/// Generates customizable procedural noise patterns.
@@ -238,7 +263,7 @@ fn noise_pattern(
#[widget(ParsedWidgetOverride::Custom = "noise_inspector_cellular_jitter")]
#[default(1.)]
cellular_jitter: Item<f64>,
) -> Item<Raster<CPU>> {
) -> Result<Item<Raster<CPU>>, ImageError> {
let (clip, seed, scale, domain_warp_amplitude) = (*clip.element(), *seed.element(), *scale.element(), *domain_warp_amplitude.element());
let (fractal_octaves, fractal_lacunarity, fractal_gain) = (*fractal_octaves.element(), *fractal_lacunarity.element(), *fractal_gain.element());
let (fractal_weighted_strength, fractal_ping_pong_strength, cellular_jitter) = (*fractal_weighted_strength.element(), *fractal_ping_pong_strength.element(), *cellular_jitter.element());
@@ -262,7 +287,7 @@ fn noise_pattern(
// If the image would not be visible, return an empty image
if size.x <= 0. || size.y <= 0. {
return Item::default();
return Ok(Item::default());
}
let transform = DAffine2::from_translation(offset) * DAffine2::from_scale(size);
@@ -272,7 +297,7 @@ fn noise_pattern(
let height = (size.y * footprint_scale.y) as u32;
// All
let mut image = Image::new(width, height, Color::from_luminance(0.5));
let mut image = Image::try_new(width, height, Color::from_luminance(0.5))?;
let mut noise = fastnoise_lite::FastNoiseLite::with_seed(seed as i32);
noise.set_frequency(Some(1. / (scale as f32).max(f32::EPSILON)));
@@ -308,7 +333,7 @@ fn noise_pattern(
}
}
return Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, transform);
return Ok(Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, transform));
}
};
noise.set_noise_type(Some(noise_type));
@@ -366,11 +391,11 @@ fn noise_pattern(
}
}
Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, transform)
Ok(Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, transform))
}
#[node_macro::node(category("Raster"), icon("NodeMandelbrot"))]
fn mandelbrot(ctx: impl ExtractFootprint + Send) -> Item<Raster<CPU>> {
fn mandelbrot(ctx: impl ExtractFootprint + Send) -> Result<Item<Raster<CPU>>, ImageError> {
let footprint = ctx.footprint();
let viewport_bounds = footprint.viewport_bounds_in_local_space();
@@ -382,14 +407,14 @@ fn mandelbrot(ctx: impl ExtractFootprint + Send) -> Item<Raster<CPU>> {
// If the image would not be visible, return an empty image
if size.x <= 0. || size.y <= 0. {
return Item::default();
return Ok(Item::default());
}
let scale = footprint.scale();
let width = (size.x * scale.x) as u32;
let height = (size.y * scale.y) as u32;
let mut data = Vec::with_capacity(width as usize * height as usize);
let mut image = Image::try_new(width, height, Color::TRANSPARENT)?;
let max_iter = 255;
let scale = 3. * size.as_vec2() / Vec2::new(width as f32, height as f32);
@@ -400,11 +425,11 @@ fn mandelbrot(ctx: impl ExtractFootprint + Send) -> Item<Raster<CPU>> {
let c = pos * scale + coordinate_offset;
let iter = mandelbrot_impl(c, max_iter);
data.push(map_color(iter, max_iter));
*image.get_mut(x as usize, y as usize) = map_color(iter, max_iter);
}
}
Item::new_from_element(Raster::new_cpu(Image { width, height, data })).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(offset) * DAffine2::from_scale(size))
Ok(Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(offset) * DAffine2::from_scale(size)))
}
#[inline(always)]
+1 -1
View File
@@ -32,8 +32,8 @@ dyn-any = { workspace = true }
glam = { workspace = true }
parley = { workspace = true }
skrifa = { workspace = true }
log = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
convert_case = { workspace = true }
titlecase = { workspace = true }
fancy-regex = { workspace = true }
+61 -29
View File
@@ -4,11 +4,20 @@ use serde_json::Value;
use crate::unescape_string;
/// Why a JSON node's input gives no result.
#[derive(Debug, thiserror::Error)]
pub enum JsonError {
#[error("The JSON is invalid: {0}")]
InvalidJson(#[from] serde_json::Error),
#[error("The JSON path `{0}` is invalid")]
InvalidPath(String),
}
// ===========
// Format JSON
// ===========
/// Reformats a JSON string with control over indentation, line breaking, and spacing. Trailing commas are tolerated. Otherwise-invalid JSON input is returned unchanged.
/// Reformats a JSON string with control over indentation, line breaking, and spacing. Trailing commas are tolerated, while otherwise-invalid JSON gives an error.
#[node_macro::node(name("Format JSON"), category("String: JSON"), icon("NodeFormatJson"))]
fn format_json(
_: impl Ctx,
@@ -33,17 +42,20 @@ fn format_json(
/// Always break a container (array or object) across lines if it holds another container, even if it would fit within the break length. (Requires *Multi-Line* to take effect.)
#[default(true)]
break_nested: Item<bool>,
) -> Item<String> {
) -> Result<Item<String>, JsonError> {
let mut json = json;
let (compact, multi_line, break_length, break_nested) = (*compact.element(), *multi_line.element(), *break_length.element(), *break_nested.element());
let indent = indent.element().clone();
let cleaned = strip_trailing_commas(json.element());
let Ok(value) = serde_json::from_str::<serde_json::Value>(&cleaned) else { return json };
if cleaned.trim().is_empty() {
return Ok(json);
}
let value = serde_json::from_str::<serde_json::Value>(&cleaned)?;
let indent = unescape_string(indent);
let colon = if compact { ":" } else { ": " };
let comma_space = if compact { "," } else { ", " };
let line_width = break_length as usize;
let line_width = usize::try_from(break_length).unwrap_or(usize::MAX);
let result = if multi_line {
format_value(&value, 0, &indent, colon, comma_space, compact, break_nested, line_width)
@@ -52,14 +64,14 @@ fn format_json(
};
*json.element_mut() = result;
json
Ok(json)
}
/// Strips trailing commas before `]` and `}` to accept JSON-with-trailing-commas input.
/// Blanks out trailing commas before `]` and `}` to accept JSON-with-trailing-commas input.
/// Respects string literals so commas inside strings are left untouched.
fn strip_trailing_commas(json: &str) -> String {
let mut output = String::with_capacity(json.len());
let mut chars = json.chars().peekable();
let mut chars = json.chars();
let mut in_string = false;
while let Some(c) = chars.next() {
@@ -84,15 +96,9 @@ fn strip_trailing_commas(json: &str) -> String {
output.push(c);
}
',' => {
// Skip any whitespace after the comma
while chars.peek().is_some_and(|c| c.is_ascii_whitespace()) {
chars.next();
}
// Drop trailing commas (before `]` or `}`), but keep all others
if !chars.peek().is_some_and(|&c| c == ']' || c == '}') {
output.push(',');
}
// A trailing comma (before `]` or `}`) becomes a space, so error positions still point into the input
let trailing = chars.clone().find(|c| !c.is_ascii_whitespace()).is_some_and(|c| c == ']' || c == '}');
output.push(if trailing { ' ' } else { ',' });
}
_ => output.push(c),
}
@@ -210,25 +216,27 @@ fn query_json(
/// Strips the surrounding double quotes from string values, returning the raw text. Other types are never wrapped in quotes.
#[default(true)]
unquote_strings: Item<bool>,
) -> Item<String> {
) -> Result<Item<String>, JsonError> {
let mut json = json;
let path = path.element().clone();
let unquote_strings = *unquote_strings.element();
let cleaned = strip_trailing_commas(json.element());
let segments = parse_json_path(path.trim()).ok_or_else(|| JsonError::InvalidPath(path.trim().to_string()))?;
let result = match (serde_json::from_str::<Value>(&cleaned), parse_json_path(path.trim())) {
(Ok(value), Some(segments)) => {
let mut results = Vec::new();
resolve_all(&value, &segments, !unquote_strings, &mut results);
let result = if cleaned.trim().is_empty() {
String::new()
} else {
let value = serde_json::from_str::<Value>(&cleaned)?;
results.into_iter().next().map(|(text, _ty)| text).unwrap_or_default()
}
_ => String::new(),
let mut results = Vec::new();
resolve_all(&value, &segments, !unquote_strings, &mut results);
results.into_iter().next().map(|(text, _ty)| text).unwrap_or_default()
};
*json.element_mut() = result;
json
Ok(json)
}
/// Extracts every matched value from a JSON string using a path expression (see that parameter's description for its syntax). A list of zero or more resultant strings is produced. The `[]` path accessor is used to read more than one value.
@@ -258,15 +266,18 @@ fn query_json_all(
/// Strips the surrounding double quotes from string values, returning the raw text. Other types are never wrapped in quotes.
#[default(true)]
unquote_strings: Item<bool>,
) -> List<String> {
) -> Result<List<String>, JsonError> {
let cleaned = strip_trailing_commas(json.element());
let Ok(value): Result<Value, _> = serde_json::from_str(&cleaned) else { return List::new() };
let Some(segments) = parse_json_path(path.element().trim()) else { return List::new() };
let segments = parse_json_path(path.element().trim()).ok_or_else(|| JsonError::InvalidPath(path.element().trim().to_string()))?;
if cleaned.trim().is_empty() {
return Ok(List::new());
}
let value: Value = serde_json::from_str(&cleaned)?;
let mut results = Vec::new();
resolve_all(&value, &segments, !*unquote_strings.element(), &mut results);
results.into_iter().map(|(text, ty)| Item::new_from_element(text).with_attribute(ATTR_TYPE, ty.to_string())).collect()
Ok(results.into_iter().map(|(text, ty)| Item::new_from_element(text).with_attribute(ATTR_TYPE, ty.to_string())).collect())
}
/// A parsed segment of a JSON access path.
@@ -484,3 +495,24 @@ fn resolve_all(value: &serde_json::Value, segments: &[JsonPathSegment], quote_st
_ => {}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn an_error_after_a_trailing_comma_points_into_the_input() {
assert_eq!(strip_trailing_commas("[1, \"a,\",\n]"), "[1, \"a,\" \n]");
let error = serde_json::from_str::<Value>(&strip_trailing_commas("{\n\t\"a\": [1,],\n\t\"b\": x\n}")).unwrap_err();
assert_eq!((error.line(), error.column()), (3, 7));
}
#[test]
fn an_invalid_path_is_reported_without_json() {
let text = |text: &str| Item::new_from_element(text.to_string());
assert!(matches!(query_json((), text(""), text(".a["), Item::new_from_element(true)), Err(JsonError::InvalidPath(_))));
assert!(matches!(query_json_all((), text(""), text(".a["), Item::new_from_element(true)), Err(JsonError::InvalidPath(_))));
assert!(query_json_all((), text(""), text(""), Item::new_from_element(true)).unwrap().is_empty());
}
}
+82 -14
View File
@@ -22,7 +22,7 @@ use unicode_segmentation::UnicodeSegmentation;
pub use core_types as gcore;
pub use fallback::FALLBACK_FONT_RESOURCE;
pub use font::*;
pub use text_context::{TextContext, for_each_styled_glyph_run};
pub use text_context::{TextContext, TextToVectorError, for_each_styled_glyph_run};
pub use to_path::*;
pub use vector_types;
@@ -247,7 +247,7 @@ fn lorem_ipsum(
let rng = |n| rng.random_range(0..n);
let text = ipsum::generate(
*lorem_intro.element() as usize,
usize::try_from(*lorem_intro.element()).unwrap_or(usize::MAX),
(*lorem_intro_in.element()).into(),
*length.element() as usize,
(*length_in.element()).into(),
@@ -319,7 +319,7 @@ fn string_truncate(
suffix: Item<String>,
) -> Item<String> {
let mut string = string;
let max_length = *length.element() as usize;
let max_length = usize::try_from(*length.element()).unwrap_or(usize::MAX);
let grapheme_count = string.element().graphemes(true).count();
if grapheme_count <= max_length {
@@ -363,7 +363,7 @@ fn format_number(
) -> Item<String> {
let (number, attributes) = number.into_parts();
let number = round_away_float_noise(number);
if number.is_infinite() {
if !number.is_finite() {
return Item::from_parts(format_f64(number), attributes);
}
let (decimal_places, fixed_decimals, use_thousands_separator, start_at_10000) =
@@ -391,15 +391,15 @@ fn format_number(
let places = requested_places.min(max_places);
let formatted = format!("{number:.places$}");
// If the user requested more decimal places than the float can represent, pad with zeros
let extra_zeros = requested_places.saturating_sub(places);
// If the user requested more decimal places than the float can represent, pad with zeros, which only fixed decimals keep
let extra_zeros = if fixed_decimals { requested_places.saturating_sub(places) } else { 0 };
// Split into sign, whole, and decimal parts
let (sign, unsigned) = if let Some(rest) = formatted.strip_prefix('-') { ("-", rest) } else { ("", formatted.as_str()) };
let (whole_string, decimal_string) = match unsigned.split_once('.') {
Some((w, d)) => {
let padded = if extra_zeros > 0 { format!("{d}{:0>width$}", "", width = extra_zeros) } else { d.to_string() };
let padded = format!("{d}{}", "0".repeat(extra_zeros));
(w.to_string(), Some(padded))
}
None => (unsigned.to_string(), None),
@@ -548,6 +548,13 @@ fn string_reverse(
string
}
/// A text result longer than a string can hold.
#[derive(Debug, thiserror::Error)]
pub enum TextTooLongError {
#[error("Repeating the string {0} times would be too long")]
Repeat(i64),
}
/// Repeats the string a given number of times, optionally with a separator between each repetition.
#[node_macro::node(category("String"), icon("NodeStringRepeat"))]
fn string_repeat(
@@ -565,14 +572,21 @@ fn string_repeat(
/// `\n` (newline), `\r` (carriage return), `\t` (tab), `\0` (null), and `\\` (backslash).
#[default(true)]
separator_escaping: Item<bool>,
) -> Item<String> {
) -> Result<Item<String>, TextTooLongError> {
let mut string = string;
let separator = separator.element().clone();
let separator = if *separator_escaping.element() { unescape_string(separator) } else { separator };
let count = *count.element() as usize;
if string.element().is_empty() && separator.is_empty() {
return Ok(string);
}
let mut result = String::with_capacity((string.element().len() + separator.len()).saturating_mul(count));
let too_long = || TextTooLongError::Repeat(*count.element());
let count = usize::try_from(*count.element()).map_err(|_| too_long())?;
let capacity = (string.element().len() + separator.len()).checked_mul(count).ok_or_else(too_long)?;
let mut result = String::new();
result.try_reserve_exact(capacity).map_err(|_| too_long())?;
for i in 0..count {
if i > 0 {
result.push_str(&separator);
@@ -581,7 +595,7 @@ fn string_repeat(
}
*string.element_mut() = result;
string
Ok(string)
}
/// Pads the string to a target length by filling with the given repeated substring. If the string already meets or exceeds the target length, it is returned unchanged.
@@ -969,13 +983,20 @@ fn string_map(
Ok(result)
}
/// Read String evaluated where no loop over strings supplies one.
#[derive(Debug, thiserror::Error)]
pub enum ReadStringError {
#[error("No string to read: this node only works inside a loop over string items, like in a String Map node")]
NoLoopItem,
}
/// Reads the current string from within a **String Map** node's loop.
#[node_macro::node(category("Data: Context"), icon("NodeReadContext"))]
fn read_string(ctx: impl Ctx + ExtractVarArgs) -> Item<String> {
let Ok(var_arg) = ctx.vararg(0) else { return Item::new_from_element(String::new()) };
fn read_string(ctx: impl Ctx + ExtractVarArgs) -> Result<Item<String>, ReadStringError> {
let var_arg = ctx.vararg(0).map_err(|_| ReadStringError::NoLoopItem)?;
let var_arg = var_arg as &dyn std::any::Any;
var_arg.downcast_ref::<Item<String>>().cloned().unwrap_or_default()
var_arg.downcast_ref::<Item<String>>().cloned().ok_or(ReadStringError::NoLoopItem)
}
#[cfg(test)]
@@ -1033,4 +1054,51 @@ mod tests {
assert_eq!(run("__init__", CamelCase, Some("")), "init");
assert_eq!(run(" ", CapitalCase, Some("_")), "");
}
#[test]
fn format_number_pads_many_decimal_places_and_leaves_nan_alone() {
let format = |number: f64, decimal_places: i64, fixed_decimals: bool| {
format_number(
(),
Item::new_from_element(number),
Item::new_from_element(decimal_places),
Item::new_from_element(".".to_string()),
Item::new_from_element(fixed_decimals),
Item::new_from_element(false),
Item::new_from_element(",".to_string()),
Item::new_from_element(false),
)
.into_element()
};
assert_eq!(format(1.5, 70_000, true).len(), "1.".len() + 70_000);
assert_eq!(format(1.5, 70_000, false), "1.5");
assert_eq!(format(f64::NAN, 2, true), "NaN");
}
#[test]
fn string_repeat_refuses_results_too_long_to_hold() {
let repeat = |string: &str, count: i64, separator: &str| {
string_repeat(
(),
Item::new_from_element(string.to_string()),
Item::new_from_element(count),
Item::new_from_element(separator.to_string()),
Item::new_from_element(false),
)
.map(Item::into_element)
};
assert_eq!(repeat("ab", 3, ", ").unwrap(), "ab, ab, ab");
assert!(repeat("ab", i64::MAX, "").is_err());
assert!(repeat("", i64::MAX, ",,").is_err());
assert_eq!(repeat("", i64::MAX, "").unwrap(), "");
}
#[test]
fn read_string_only_reads_inside_a_loop_over_strings() {
assert!(read_string(OwnedContextImpl::default().into_context()).is_err());
let string_loop = OwnedContextImpl::default().with_vararg(Box::new(Item::new_from_element("a".to_string()))).into_context();
assert_eq!(read_string(string_loop).unwrap().into_element(), "a");
let number_loop = OwnedContextImpl::default().with_vararg(Box::new(Item::new_from_element(1_i64))).into_context();
assert!(read_string(number_loop).is_err());
}
}
+14 -12
View File
@@ -1,3 +1,4 @@
use super::text_context::TextToVectorError;
use core_types::list::{Item, List};
use core_types::{ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_TEXT_FRAME, ATTR_TRANSFORM};
use glam::{DAffine2, DVec2};
@@ -64,10 +65,10 @@ impl PathBuilder {
style_skew: Option<DAffine2>,
skew: DAffine2,
per_glyph_items: bool,
) -> bool {
) -> Result<bool, TextToVectorError> {
let location_ref = LocationRef::new(normalized_coords);
let settings = DrawSettings::unhinted(Size::new(size), location_ref);
glyph.draw(settings, self).unwrap();
glyph.draw(settings, self).map_err(TextToVectorError::UndrawableGlyph)?;
let has_geometry = !self.glyph_bezpath.is_empty();
// Apply transforms in correct order: style-based skew first, then user-requested skew
@@ -100,10 +101,10 @@ impl PathBuilder {
}
}
has_geometry
Ok(has_geometry)
}
pub fn render_glyph_run(&mut self, glyph_run: &GlyphRun<'_, ()>, letter_tilt: f64, per_glyph_items: bool, x_offset: f32, space_extra: f32) {
pub fn render_glyph_run(&mut self, glyph_run: &GlyphRun<'_, ()>, letter_tilt: f64, per_glyph_items: bool, x_offset: f32, space_extra: f32) -> Result<(), TextToVectorError> {
let mut run_x = glyph_run.offset() + x_offset;
let run_y = glyph_run.baseline();
@@ -148,17 +149,18 @@ impl PathBuilder {
run_x += glyph.advance;
let glyph_id = GlyphId::from(glyph.id);
if let Some(glyph_outline) = outlines.get(glyph_id) {
if !per_glyph_items {
self.origin = glyph_offset;
}
let drew_geometry = self.draw_glyph(&glyph_outline, font_size, &normalized_coords, glyph_offset, style_skew, skew, per_glyph_items);
let glyph_outline = outlines.get(glyph_id).ok_or(TextToVectorError::MissingOutline)?;
if !per_glyph_items {
self.origin = glyph_offset;
}
let drew_geometry = self.draw_glyph(&glyph_outline, font_size, &normalized_coords, glyph_offset, style_skew, skew, per_glyph_items)?;
if !drew_geometry && space_extra != 0. && glyph.advance > 0. {
run_x += space_extra;
}
if !drew_geometry && space_extra != 0. && glyph.advance > 0. {
run_x += space_extra;
}
}
Ok(())
}
pub fn finalize(mut self) -> List<Vector> {
+112 -88
View File
@@ -1,5 +1,82 @@
use core_types::list::{Item, List};
use core_types::{ATTR_END, ATTR_NAME, ATTR_START, Ctx};
use fancy_regex::{Expr, Regex};
/// Why a Regex node's pattern gives no result.
#[derive(Debug, thiserror::Error)]
pub enum RegexError {
#[error("The regex pattern is invalid: {0}")]
InvalidPattern(String),
#[error("The regex pattern can't use `\\K` inside a lookaround")]
KeepOutInLookaround,
#[error("The regex pattern takes too many steps on this string ({0})")]
TooComplex(fancy_regex::RuntimeError),
}
impl From<fancy_regex::Error> for RegexError {
fn from(error: fancy_regex::Error) -> Self {
// Leaves out the positions and quoted pattern the regex crates add, which count the flags prepended to the user's pattern
let reason = match error {
fancy_regex::Error::RuntimeError(error) => return Self::TooComplex(error),
fancy_regex::Error::ParseError(_, error) => error.to_string(),
fancy_regex::Error::CompileError(error) => match *error {
fancy_regex::CompileError::InnerError(error) => {
let reason = std::error::Error::source(&error).map_or_else(|| error.to_string(), ToString::to_string);
reason.lines().find_map(|line| line.strip_prefix("error: ")).map_or_else(|| reason.clone(), str::to_string)
}
error => error.to_string(),
},
error => error.to_string(),
};
Self::InvalidPattern(reason)
}
}
fn compile(pattern: &str, case_insensitive: bool, multiline: bool) -> Result<Regex, RegexError> {
let flags = match (case_insensitive, multiline) {
(false, false) => "",
(true, false) => "(?i)",
(false, true) => "(?m)",
(true, true) => "(?im)",
};
Ok(Regex::new(&format!("{flags}{pattern}"))?)
}
/// Refuses a `\K` inside a lookaround for the nodes that slice the string between matches, which panics in fancy-regex once a match starts before the previous one ended.
fn refuse_keep_out_in_lookaround(pattern: &str) -> Result<(), RegexError> {
let pattern = Expr::parse_tree(pattern)?.expr;
fn push_groups<'a>(expr: &'a Expr, groups: &mut Vec<&'a Expr>) {
if let Expr::Group(inner) = expr {
groups.push(inner.as_ref());
}
for child in expr.children_iter() {
push_groups(child, groups);
}
}
let mut groups = vec![&pattern];
push_groups(&pattern, &mut groups);
// A subroutine call runs its group's `\K` where the call is, so a call inside a lookaround counts as a `\K` there
let runs_keep_out = |groups_running: &[bool], expr: &Expr| {
let runs = |expr: &Expr| matches!(expr, Expr::KeepOut) || matches!(expr, Expr::SubroutineCall(group) if groups_running.get(*group) == Some(&true));
runs(expr) || expr.has_descendant(runs)
};
let mut groups_running = vec![false; groups.len()];
loop {
let next: Vec<bool> = groups.iter().map(|&group| runs_keep_out(&groups_running, group)).collect();
if next == groups_running {
break;
}
groups_running = next;
}
let keep_out_in_lookaround = |expr: &Expr| matches!(expr, Expr::LookAround(..)) && runs_keep_out(&groups_running, expr);
if keep_out_in_lookaround(&pattern) || pattern.has_descendant(keep_out_in_lookaround) {
return Err(RegexError::KeepOutInLookaround);
}
Ok(())
}
/// Checks whether the string contains a match for the given regular expression pattern. Optionally restricts the match to only the start and/or end of the string.
#[node_macro::node(category("String: Regex"), icon("NodeRegexContains"))]
@@ -17,30 +94,22 @@ fn regex_contains(
at_start: Item<bool>,
/// Only match if the pattern appears at the end of the string.
at_end: Item<bool>,
) -> Item<bool> {
) -> Result<Item<bool>, RegexError> {
let (string, attributes) = string.into_parts();
let pattern = pattern.element();
let (case_insensitive, multiline, at_start, at_end) = (*case_insensitive.element(), *multiline.element(), *at_start.element(), *at_end.element());
let flags = match (case_insensitive, multiline) {
(false, false) => "",
(true, false) => "(?i)",
(false, true) => "(?m)",
(true, true) => "(?im)",
};
let anchored_pattern = match (at_start, at_end) {
(true, true) => format!("{flags}\\A(?:{pattern})\\z"),
(true, false) => format!("{flags}\\A(?:{pattern})"),
(false, true) => format!("{flags}(?:{pattern})\\z"),
(false, false) => format!("{flags}{pattern}"),
let regex = if at_start || at_end {
// Parsing the pattern alone keeps a stray `)` in it from closing the anchoring group
Expr::parse_tree(pattern)?;
let (start, end) = (if at_start { "\\A" } else { "" }, if at_end { "\\z" } else { "" });
// The newline ends a trailing `(?x)` comment, which would swallow the group's `)`, and the `(?x)` makes the newline whitespace otherwise
compile(&format!("{start}(?:{pattern}(?x)\n){end}"), case_insensitive, multiline)?
} else {
compile(pattern, case_insensitive, multiline)?
};
let Ok(regex) = fancy_regex::Regex::new(&anchored_pattern) else {
log::error!("Invalid regex pattern: {pattern}");
return Item::from_parts(false, attributes);
};
Item::from_parts(regex.is_match(&string).unwrap_or(false), attributes)
Ok(Item::from_parts(regex.is_match(&string)?, attributes))
}
/// Replaces matches of a regular expression pattern in the string. The replacement string can reference captures: `$0` for the whole match and `$1`, `$2`, etc. for capture groups.
@@ -59,33 +128,20 @@ fn regex_replace(
case_insensitive: Item<bool>,
/// Make `^` and `$` match the start and end of each line, not just the whole string.
multiline: Item<bool>,
) -> Item<String> {
) -> Result<Item<String>, RegexError> {
let mut string = string;
let pattern = pattern.element().clone();
let replacement = replacement.element().clone();
let (replace_all, case_insensitive, multiline) = (*replace_all.element(), *case_insensitive.element(), *multiline.element());
let flags = match (case_insensitive, multiline) {
(false, false) => "",
(true, false) => "(?i)",
(false, true) => "(?m)",
(true, true) => "(?im)",
};
let full_pattern = format!("{flags}{pattern}");
refuse_keep_out_in_lookaround(&pattern)?;
let regex = compile(&pattern, case_insensitive, multiline)?;
let Ok(regex) = fancy_regex::Regex::new(&full_pattern) else {
log::warn!("Invalid regex pattern: {pattern}");
return string;
};
let result = if replace_all {
regex.replace_all(string.element(), replacement.as_str()).into_owned()
} else {
regex.replace(string.element(), replacement.as_str()).into_owned()
};
let limit = if replace_all { 0 } else { 1 };
let result = regex.try_replacen(string.element(), limit, replacement.as_str())?.into_owned();
*string.element_mut() = result;
string
Ok(string)
}
/// Finds a regex match in the string and returns its components. The result is a list where the first item is the whole match (`$0`) and subsequent items are the capture groups (`$1`, `$2`, etc., if any).
@@ -107,38 +163,27 @@ fn regex_find(
case_insensitive: Item<bool>,
/// Make `^` and `$` match the start and end of each line, not just the whole string.
multiline: Item<bool>,
) -> List<String> {
) -> Result<List<String>, RegexError> {
let string = string.element();
let pattern = pattern.element();
let (match_index, case_insensitive, multiline) = (*match_index.element(), *case_insensitive.element(), *multiline.element());
if pattern.is_empty() {
return List::new();
return Ok(List::new());
}
let flags = match (case_insensitive, multiline) {
(false, false) => "",
(true, false) => "(?i)",
(false, true) => "(?m)",
(true, true) => "(?im)",
};
let full_pattern = format!("{flags}{pattern}");
let Ok(regex) = fancy_regex::Regex::new(&full_pattern) else {
log::error!("Invalid regex pattern: {pattern}");
return List::new();
};
let regex = compile(pattern, case_insensitive, multiline)?;
// Capture group names indexed positionally; index 0 (the whole match) is always None.
let capture_names: Vec<Option<String>> = regex.capture_names().map(|name| name.map(str::to_string)).collect();
// Collect all matches since we need to support negative indexing
let matches: Vec<_> = regex.captures_iter(string).filter_map(|c| c.ok()).collect();
let matches = regex.captures_iter(string).collect::<Result<Vec<_>, _>>()?;
let resolved_index = if match_index < 0 {
let from_end = match_index.unsigned_abs();
if from_end > matches.len() as u64 {
return List::new();
return Ok(List::new());
}
matches.len() - from_end as usize
} else {
@@ -146,11 +191,11 @@ fn regex_find(
};
let Some(captures) = matches.get(resolved_index) else {
return List::new();
return Ok(List::new());
};
// Index 0 is the whole match, 1+ are capture groups
(0..captures.len())
Ok((0..captures.len())
.map(|i| {
let captured = captures.get(i);
let text = captured.map_or(String::new(), |m| m.as_str().to_string());
@@ -162,7 +207,7 @@ fn regex_find(
.with_attribute(ATTR_END, end)
.with_attribute(ATTR_NAME, name)
})
.collect()
.collect())
}
/// Finds all non-overlapping matches of a regular expression pattern in the string, returning a list of the matched substrings.
@@ -179,35 +224,24 @@ fn regex_find_all(
case_insensitive: Item<bool>,
/// Make `^` and `$` match the start and end of each line, not just the whole string.
multiline: Item<bool>,
) -> List<String> {
) -> Result<List<String>, RegexError> {
let string = string.element();
let pattern = pattern.element();
let (case_insensitive, multiline) = (*case_insensitive.element(), *multiline.element());
if pattern.is_empty() {
return List::new();
return Ok(List::new());
}
let flags = match (case_insensitive, multiline) {
(false, false) => "",
(true, false) => "(?i)",
(false, true) => "(?m)",
(true, true) => "(?im)",
};
let full_pattern = format!("{flags}{pattern}");
let Ok(regex) = fancy_regex::Regex::new(&full_pattern) else {
log::error!("Invalid regex pattern: {pattern}");
return List::new();
};
let regex = compile(pattern, case_insensitive, multiline)?;
regex
.find_iter(string)
.filter_map(|m| m.ok())
.map(|m| {
Item::new_from_element(m.as_str().to_string())
let m = m?;
Ok(Item::new_from_element(m.as_str().to_string())
.with_attribute(ATTR_START, m.start() as i64)
.with_attribute(ATTR_END, m.end() as i64)
.with_attribute(ATTR_END, m.end() as i64))
})
.collect()
}
@@ -226,26 +260,16 @@ fn regex_split(
case_insensitive: Item<bool>,
/// Make `^` and `$` match the start and end of each line, not just the whole string.
multiline: Item<bool>,
) -> List<String> {
) -> Result<List<String>, RegexError> {
let pattern = pattern.element().clone();
let (case_insensitive, multiline) = (*case_insensitive.element(), *multiline.element());
if pattern.is_empty() {
return List::new_from_item(string);
return Ok(List::new_from_item(string));
}
let flags = match (case_insensitive, multiline) {
(false, false) => "",
(true, false) => "(?i)",
(false, true) => "(?m)",
(true, true) => "(?im)",
};
let full_pattern = format!("{flags}{pattern}");
refuse_keep_out_in_lookaround(&pattern)?;
let regex = compile(&pattern, case_insensitive, multiline)?;
let Ok(regex) = fancy_regex::Regex::new(&full_pattern) else {
log::error!("Invalid regex pattern: {pattern}");
return List::new_from_item(string);
};
regex.split(string.element()).filter_map(|s| s.ok()).map(|s| s.to_string()).map(Item::new_from_element).collect()
regex.split(string.element()).map(|part| Ok(Item::new_from_element(part?.to_string()))).collect()
}
+21 -6
View File
@@ -13,6 +13,19 @@ thread_local! {
static THREAD_TEXT: RefCell<TextContext> = RefCell::new(TextContext::default());
}
/// Why a styled string can't be converted to vector paths.
#[derive(Debug, thiserror::Error)]
pub enum TextToVectorError {
#[error("The font is not a readable font file")]
UnreadableFont,
#[error("The font has a glyph that can't be drawn: {0}")]
UndrawableGlyph(#[source] skrifa::outline::DrawError),
#[error("The font has no vector outlines for some glyphs")]
MissingOutline,
#[error("The `{0}` attribute has the wrong type to use for text")]
MistypedAttribute(&'static str),
}
/// Iterates the glyph runs of a laid-out text in reading order, computing each line's last-line alignment correction
/// (`x_offset` and per-space `space_extra`) and skipping runs clipped by `max_height`. Shared by the vector shaper and the
/// SVG/Vello text renderers so the alignment logic lives in one place.
@@ -131,10 +144,8 @@ impl TextContext {
}
/// Convert text to vector paths using the specified font and typesetting configuration
pub fn to_path(&mut self, text: &str, font: &Resource, typesetting: TypesettingConfig, per_glyph_items: bool) -> List<Vector> {
let Some(layout) = self.layout_text(text, font, typesetting) else {
return List::new_from_element(Vector::default());
};
pub fn to_path(&mut self, text: &str, font: &Resource, typesetting: TypesettingConfig, per_glyph_items: bool) -> Result<List<Vector>, TextToVectorError> {
let layout = self.layout_text(text, font, typesetting).ok_or(TextToVectorError::UnreadableFont)?;
let text_frame_size = DVec2::new(
typesetting.max_width.unwrap_or_else(|| layout.full_width() as f64),
@@ -154,11 +165,15 @@ impl TextContext {
let mut path_builder = PathBuilder::new(per_glyph_items, layout.scale() as f64, text_frame_size, first_glyph_offset);
let mut drawn = Ok(());
for_each_styled_glyph_run(&layout, text, typesetting, |glyph_run, x_offset, space_extra| {
path_builder.render_glyph_run(glyph_run, typesetting.letter_tilt, per_glyph_items, x_offset, space_extra);
if drawn.is_ok() {
drawn = path_builder.render_glyph_run(glyph_run, typesetting.letter_tilt, per_glyph_items, x_offset, space_extra);
}
});
drawn?;
path_builder.finalize()
Ok(path_builder.finalize())
}
/// Calculate the bounding box of text using the specified font and typesetting configuration
+24 -20
View File
@@ -1,5 +1,5 @@
use super::TypesettingConfig;
use super::text_context::TextContext;
use super::text_context::{TextContext, TextToVectorError};
use core_types::blending::BlendMode;
use core_types::list::{Item, List, NodeIdPath};
use core_types::{
@@ -10,7 +10,7 @@ use glam::{DAffine2, DVec2};
use graphene_resource::Resource;
use vector_types::Vector;
pub fn to_path(text: &str, font: &Resource, typesetting: TypesettingConfig, per_glyph_items: bool) -> List<Vector> {
pub fn to_path(text: &str, font: &Resource, typesetting: TypesettingConfig, per_glyph_items: bool) -> Result<List<Vector>, TextToVectorError> {
TextContext::with_thread_local(|ctx| ctx.to_path(text, font, typesetting, per_glyph_items))
}
@@ -22,33 +22,37 @@ pub fn lines_clipping(text: &str, font: &Resource, typesetting: TypesettingConfi
TextContext::with_thread_local(|ctx| ctx.lines_clipping(text, font, typesetting))
}
/// The item's typography attribute, `None` when it is absent, or an error when it holds a type that text doesn't read.
fn typography_attribute<T: Clone + 'static>(item: &Item<String>, key: &'static str) -> Result<Option<T>, TextToVectorError> {
let Some(value) = item.attributes().get_any(key) else { return Ok(None) };
value.downcast_ref::<T>().cloned().map(Some).ok_or(TextToVectorError::MistypedAttribute(key))
}
/// Shapes a single styled string item into vector geometry, reading its font and typesetting from the item's
/// attributes (as set by the 'Text' node) and re-applying its transform and blending attributes onto the produced
/// paths. With `separate_glyphs`, each glyph becomes its own item; otherwise a single compound path is produced.
pub fn shape_text_item(item: &Item<String>, separate_glyphs: bool) -> List<Vector> {
pub fn shape_text_item(item: &Item<String>, separate_glyphs: bool) -> Result<List<Vector>, TextToVectorError> {
let text = item.element();
if text.is_empty() {
return List::new();
return Ok(List::new());
}
// Use fallback font when none is explicitly attached.
let font: Resource = {
let font: Resource = item.attribute_cloned_or_default(ATTR_FONT);
if font.is_empty() { super::FALLBACK_FONT_RESOURCE.clone() } else { font }
};
let font = typography_attribute::<Resource>(item, ATTR_FONT)?.filter(|font| !font.is_empty());
let font = font.unwrap_or_else(|| super::FALLBACK_FONT_RESOURCE.clone());
let defaults = TypesettingConfig::default();
let typesetting = TypesettingConfig {
font_size: item.attribute_cloned_or(ATTR_FONT_SIZE, defaults.font_size),
line_height_ratio: item.attribute_cloned_or(ATTR_LINE_HEIGHT, defaults.line_height_ratio),
letter_spacing: item.attribute_cloned_or(ATTR_LETTER_SPACING, defaults.letter_spacing),
letter_tilt: item.attribute_cloned_or(ATTR_LETTER_TILT, defaults.letter_tilt),
max_width: item.attribute::<f64>(ATTR_MAX_WIDTH).copied().filter(|width| *width > 0.),
max_height: item.attribute::<f64>(ATTR_MAX_HEIGHT).copied().filter(|height| *height > 0.),
align: item.attribute_cloned_or(ATTR_TEXT_ALIGN, defaults.align),
font_size: typography_attribute(item, ATTR_FONT_SIZE)?.unwrap_or(defaults.font_size),
line_height_ratio: typography_attribute(item, ATTR_LINE_HEIGHT)?.unwrap_or(defaults.line_height_ratio),
letter_spacing: typography_attribute(item, ATTR_LETTER_SPACING)?.unwrap_or(defaults.letter_spacing),
letter_tilt: typography_attribute(item, ATTR_LETTER_TILT)?.unwrap_or(defaults.letter_tilt),
max_width: typography_attribute::<f64>(item, ATTR_MAX_WIDTH)?.filter(|width| *width > 0.),
max_height: typography_attribute::<f64>(item, ATTR_MAX_HEIGHT)?.filter(|height| *height > 0.),
align: typography_attribute(item, ATTR_TEXT_ALIGN)?.unwrap_or(defaults.align),
};
let vectors = to_path(text, &font, typesetting, separate_glyphs);
let vectors = to_path(text, &font, typesetting, separate_glyphs)?;
let transform = item.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM);
let layer_path = item.attribute::<NodeIdPath>(ATTR_EDITOR_LAYER_PATH).cloned();
let blend_mode = item.attribute::<BlendMode>(ATTR_BLEND_MODE).copied();
@@ -76,19 +80,19 @@ pub fn shape_text_item(item: &Item<String>, separate_glyphs: bool) -> List<Vecto
result.push(produced);
}
result
Ok(result)
}
/// Shapes each string item of a styled `List<String>` into vector geometry, flattening the per-item results.
pub fn shape_text_list(strings: &List<String>, separate_glyphs: bool) -> List<Vector> {
pub fn shape_text_list(strings: &List<String>, separate_glyphs: bool) -> Result<List<Vector>, TextToVectorError> {
let mut result = List::new();
for index in 0..strings.len() {
let Some(item) = strings.clone_item(index) else { continue };
for produced in shape_text_item(&item, separate_glyphs).into_iter() {
for produced in shape_text_item(&item, separate_glyphs)?.into_iter() {
result.push(produced);
}
}
result
Ok(result)
}
+1
View File
@@ -27,6 +27,7 @@ node-macro = { workspace = true }
# Workspace dependencies
glam = { workspace = true }
rand = { workspace = true }
thiserror = { workspace = true }
# Optional workspace dependencies
serde = { workspace = true, optional = true }
@@ -160,14 +160,27 @@ fn extract_transform<T: Send>(_: impl Ctx, #[implementations(Graphic, Vector, Ra
Item::new_from_element(content.attribute_cloned_or_default(ATTR_TRANSFORM))
}
#[derive(Debug, thiserror::Error)]
pub enum InvertTransformError {
#[error("The transform can't be inverted because it collapses to a line or point")]
Singular,
#[error("The transform can't be inverted because it has values that aren't finite")]
NotFinite,
}
/// Produces the inverse of the input transform, which is the transform that undoes the effect of the original transform.
#[node_macro::node(category("Transform"), icon("NodeInvertTransform"))]
fn invert_transform(_: impl Ctx, transform: Item<DAffine2>) -> Item<DAffine2> {
let (transform, attributes) = transform.into_parts();
fn invert_transform(_: impl Ctx, transform: Item<DAffine2>) -> Result<Item<DAffine2>, (Item<DAffine2>, InvertTransformError)> {
let element = *transform.element();
if !element.is_finite() {
return Err((transform, InvertTransformError::NotFinite));
}
let Some(result) = element.matrix2.determinant().is_normal().then(|| element.inverse()).filter(DAffine2::is_finite) else {
return Err((transform, InvertTransformError::Singular));
};
let result = transform.inverse();
Item::from_parts(result, attributes)
let (_, attributes) = transform.into_parts();
Ok(Item::from_parts(result, attributes))
}
/// Extracts the translation component from the input transform.
+1
View File
@@ -38,6 +38,7 @@ rand = { workspace = true }
rustc-hash = { workspace = true }
log = { workspace = true }
qrcodegen = { workspace = true }
thiserror = { workspace = true }
# Optional workspace dependencies
serde = { workspace = true, optional = true }
+113 -36
View File
@@ -4,10 +4,10 @@ use core_types::{CacheHash, Ctx};
use dyn_any::DynAny;
use glam::DVec2;
use graphic_types::Vector;
use vector_types::vector::algorithms::shapes;
use vector_types::vector::SetVectorPaths;
use vector_types::vector::algorithms::shapes::{self, PolygonError, SpiralError};
use vector_types::vector::misc::SpiralType;
use vector_types::vector::misc::{ArcType, BoxCorners, GridTopology, GridType};
use vector_types::vector::{Path, SetVectorPaths};
/// Generates a circle shape with a chosen radius.
#[node_macro::node(category("Vector: Geometry"), icon("NodeCircle"))]
@@ -69,7 +69,7 @@ fn spiral(
#[unit("°")]
#[default(90.)]
angular_resolution: Item<f64>,
) -> Item<Vector> {
) -> Result<Item<Vector>, SpiralError> {
let (turns, start_angle, inner_radius, outer_radius, angular_resolution) = (
*turns.element(),
*start_angle.element(),
@@ -77,14 +77,15 @@ fn spiral(
*outer_radius.element(),
*angular_resolution.element(),
);
Vector::item_from_bezpath(&shapes::spiral_bezpath(
Ok(Vector::item_from_bezpath(&shapes::spiral_bezpath(
inner_radius,
outer_radius,
turns,
start_angle.to_radians(),
angular_resolution.to_radians(),
spiral_type.into_element(),
))
)?))
}
/// Generates an ellipse shape (an oval or stretched circle) with the chosen radii.
@@ -132,6 +133,9 @@ fn rectangle(
let size = DVec2::new(*width.element(), *height.element());
let radii = corner_radius.element().to_corner_values();
let mirror = DVec2::new(if size.x < 0. { -1. } else { 1. }, if size.y < 0. { -1. } else { 1. });
let size = size * mirror;
// Scale down overlapping adjacent radii to fit, following the CSS spec: <https://drafts.csswg.org/css-backgrounds/#corner-overlap>
let radii = if *clamped.element() {
let radii = radii.map(|radius| radius.max(0.));
@@ -150,7 +154,12 @@ fn rectangle(
radii
};
Vector::item_from_bezpath(&shapes::rounded_rectangle_bezpath(size / -2., size / 2., radii))
let mut bezpath = shapes::rounded_rectangle_bezpath(size / -2., size / 2., radii);
if mirror != DVec2::ONE {
bezpath.apply_affine(kurbo::Affine::scale_non_uniform(mirror.x, mirror.y));
}
Vector::item_from_bezpath(&bezpath)
}
/// Builds a set of four corner values, such as a rectangle's corner radii, from a list of one, two, three, or four values.
@@ -175,9 +184,9 @@ fn regular_polygon(
#[unit(" px")]
#[default(50)]
radius: Item<f64>,
) -> Item<Vector> {
) -> Result<Item<Vector>, PolygonError> {
let points = *sides.element() as u64;
Vector::item_from_bezpath(&shapes::regular_polygon_bezpath(DVec2::ZERO, points, *radius.element()))
Ok(Vector::item_from_bezpath(&shapes::regular_polygon_bezpath(DVec2::ZERO, points, *radius.element())?))
}
/// Generates an n-pointed star shape with inner and outer points at chosen radii from the center.
@@ -194,9 +203,9 @@ fn star(
#[unit(" px")]
#[default(25)]
radius_2: Item<f64>,
) -> Item<Vector> {
) -> Result<Item<Vector>, PolygonError> {
let points = *sides.element() as u64;
Vector::item_from_bezpath(&shapes::star_polygon_bezpath(DVec2::ZERO, points, *radius_1.element(), *radius_2.element()))
Ok(Vector::item_from_bezpath(&shapes::star_polygon_bezpath(DVec2::ZERO, points, *radius_1.element(), *radius_2.element())?))
}
/// Generates a heart shape with adjustable lobes, cleft, sides, and point.
@@ -272,6 +281,12 @@ pub enum QRCodeErrorCorrectionLevel {
High,
}
#[derive(Debug, thiserror::Error)]
pub enum QrCodeError {
#[error("The text is too long for a QR code at this error correction level ({0})")]
TextTooLong(#[from] qrcodegen::DataTooLong),
}
/// Generates a QR code from the input text.
#[node_macro::node(category("Vector: Geometry"), icon("NodeQrCode"), name("QR Code"))]
fn qr_code(
@@ -287,7 +302,7 @@ fn qr_code(
size: Item<f64>,
error_correction: Item<QRCodeErrorCorrectionLevel>,
individual_squares: Item<bool>,
) -> Item<Vector> {
) -> Result<Item<Vector>, QrCodeError> {
let (text, error_correction) = (text.into_element(), error_correction.into_element());
let (has_size, size, individual_squares) = (*has_size.element(), *size.element(), *individual_squares.element());
@@ -298,9 +313,7 @@ fn qr_code(
QRCodeErrorCorrectionLevel::High => qrcodegen::QrCodeEcc::High,
};
let Ok(qr_code) = qrcodegen::QrCode::encode_text(&text, ecc) else {
return Item::new_from_element(Vector::default()).with_paths(List::<Path>::new());
};
let qr_code = qrcodegen::QrCode::encode_text(&text, ecc)?;
let (mut vector, paths) = match individual_squares {
true => {
@@ -323,7 +336,7 @@ fn qr_code(
vector.transform(glam::DAffine2::from_scale(DVec2::splat(size / qr_code.size() as f64)));
}
Item::new_from_element(vector).with_paths(paths)
Ok(Item::new_from_element(vector).with_paths(paths))
}
/// Generates an arrow from the origin to the chosen coordinate.
@@ -376,6 +389,12 @@ impl GridSpacing for DVec2 {
}
}
#[derive(Debug, thiserror::Error)]
pub enum GridError {
#[error("The isometric angles cancel out, which makes the cells infinitely wide")]
AnglesCancelOut,
}
/// Generates a rectangular or isometric grid of points with the chosen number of columns and rows, joined into paths by the chosen topology.
#[node_macro::node(category("Vector: Geometry"), icon("NodeGrid"), inspector("grid_inspector"))]
fn grid<T: GridSpacing>(
@@ -400,7 +419,7 @@ fn grid<T: GridSpacing>(
#[unit("°")]
#[default(30., 30.)]
angles: Item<DVec2>,
) -> Item<Vector> {
) -> Result<Item<Vector>, GridError> {
let (grid_type, topology, staggered, columns, rows, angles) = (
lattice.into_element(),
topology.into_element(),
@@ -417,6 +436,9 @@ fn grid<T: GridSpacing>(
// Isometric grid spacing based on the two skew angles. Unused for rectangular grids.
let tan_a = angle_a.to_radians().tan();
let tan_b = angle_b.to_radians().tan();
if grid_type.is_isometric() && tan_a + tan_b == 0. {
return Err(GridError::AnglesCancelOut);
}
let isometric_spacing = DVec2::new(y_spacing / (tan_a + tan_b), y_spacing);
// The position of the grid point at column `x`, row `y`.
@@ -432,9 +454,9 @@ fn grid<T: GridSpacing>(
DVec2::new(isometric_spacing.x * x as f64, isometric_spacing.y * y as f64 + offset_y_fraction * isometric_spacing.x)
};
Lattice::new(grid_type, columns, rows, staggered && topology.supports_staggered(), position)
Ok(Lattice::new(grid_type, columns, rows, staggered && topology.supports_staggered(), position)
.layout(topology)
.into_item()
.into_item())
}
#[cfg(test)]
@@ -451,17 +473,20 @@ mod tests {
#[test]
fn isometric_grid_test() {
// Doesn't crash with weird angles
grid(
(),
(),
item(GridType::IsometricTiling),
item(GridTopology::Edges),
item(false),
item(5_i64),
item(5_i64),
item(0.),
item((0., 0.).into()),
// Doesn't crash with weird angles, and errors where they cancel out
assert!(
grid(
(),
(),
item(GridType::IsometricTiling),
item(GridTopology::Edges),
item(false),
item(5_i64),
item(5_i64),
item(0.),
item((0., 0.).into()),
)
.is_err()
);
grid(
(),
@@ -473,7 +498,8 @@ mod tests {
item(5_i64),
item(90.),
item((90., 90.).into()),
);
)
.unwrap();
// Works properly
let grid = grid(
@@ -486,7 +512,8 @@ mod tests {
item(5_i64),
item(10.),
item((30., 30.).into()),
);
)
.unwrap();
let paths = shared_paths_from_item_attributes(&grid);
assert_eq!(grid.element().anchor_points(&paths).count(), 5 * 5);
assert_eq!(grid.element().segment_iter(&paths).count(), 4 * 5 + 4 * 9);
@@ -509,7 +536,8 @@ mod tests {
item(5_i64),
item(10.),
item((40., 30.).into()),
);
)
.unwrap();
let paths = shared_paths_from_item_attributes(&grid);
assert_eq!(grid.element().anchor_points(&paths).count(), 5 * 5);
assert_eq!(grid.element().segment_iter(&paths).count(), 4 * 5 + 4 * 9);
@@ -533,7 +561,8 @@ mod tests {
item(3_i64),
item(10.),
item((30., 30.).into()),
);
)
.unwrap();
let paths = shared_paths_from_item_attributes(&grid);
let vector = grid.element();
@@ -554,7 +583,8 @@ mod tests {
item(4_i64),
item(10.),
item((30., 30.).into()),
);
)
.unwrap();
let paths = shared_paths_from_item_attributes(&grid);
let vector = grid.element();
@@ -576,7 +606,8 @@ mod tests {
item(3_i64),
item(10.),
item((30., 30.).into()),
);
)
.unwrap();
let paths = shared_paths_from_item_attributes(&grid);
let vector = grid.element();
assert_eq!(vector.stroke_manipulator_groups(&paths).filter(|(_, closed)| *closed).count(), 4);
@@ -624,9 +655,55 @@ mod tests {
item(1.),
item(QRCodeErrorCorrectionLevel::Low),
item(true),
);
)
.unwrap();
let paths = shared_paths_from_item_attributes(&qr);
assert!(qr.element().anchor_points(&paths).count() > 0);
assert!(!qr.element().segment_ids(&paths).is_empty());
}
#[test]
fn qr_code_reports_text_too_long() {
let qr = qr_code((), (), item("x".repeat(3000)), item(false), item(1.), item(QRCodeErrorCorrectionLevel::High), item(true));
assert!(matches!(qr, Err(QrCodeError::TextTooLong(_))));
}
// A radius small enough to underflow leaves no direction from its anchor to the corner to put the handle along
#[test]
fn rectangle_with_a_vanishing_corner_radius() {
let rectangle = rectangle((), (), item(100.), item(100.), item(BoxCorners::from(vec![1e-160, 10., 0., 0.])), item(false), item(true));
assert!(rectangle.element().positions().all(|position| position.is_finite()));
}
// A negative width mirrors the rectangle, rounding its corners inward as at the positive width
#[test]
fn rectangle_with_a_negative_width_keeps_its_rounded_corners() {
let anchors = |width: f64, clamped: bool| {
let rectangle = rectangle((), (), item(width), item(100.), item(BoxCorners::from(vec![30.])), item(clamped), item(false));
rectangle.element().anchor_positions(&shared_paths_from_item_attributes(&rectangle))
};
for clamped in [false, true] {
let mirrored: Vec<DVec2> = anchors(50., clamped).into_iter().map(|position| position * DVec2::new(-1., 1.)).collect();
assert_eq!(anchors(-50., clamped), mirrored);
}
}
#[test]
fn polygons_report_more_sides_than_can_be_allocated() {
assert!(matches!(regular_polygon((), (), item(i64::MAX), item(50.)), Err(PolygonError::TooManySides(sides)) if sides == i64::MAX as u64));
assert!(matches!(star((), (), item(i64::MAX), item(50.), item(25.)), Err(PolygonError::TooManySides(sides)) if sides == i64::MAX as u64));
assert!(regular_polygon((), (), item(6), item(50.)).is_ok());
}
// With the inner and outer radius the same, the spiral doesn't grow, so it winds around a circle
#[test]
fn spiral_between_equal_radii_is_a_circle() {
for spiral_type in [SpiralType::Archimedean, SpiralType::Logarithmic] {
let spiral = spiral((), (), item(spiral_type), item(2.), item(0.), item(25.), item(25.), item(90.)).unwrap();
assert!(spiral.element().positions().all(|position| position.is_finite()));
let anchors = spiral.element().anchor_positions(&shared_paths_from_item_attributes(&spiral));
assert!(anchors.iter().all(|anchor| (anchor.length() - 25.).abs() < 1e-9));
}
}
}
-3
View File
@@ -5,9 +5,6 @@ pub mod vector_modification_nodes;
mod vector_nodes;
mod voronoi;
#[macro_use]
extern crate log;
// Re-export for convenience
pub use core_types as gcore;
pub use generator_nodes::*;
File diff suppressed because it is too large. Load diff
+59 -44
View File
@@ -9,35 +9,50 @@
//! welded points and segments. Voronoi cells around the convex hull are unbounded, so they are clipped to the convex hull
//! of the input sites, which also bounds the whole diagram to a finite region.
use delaunator::{EMPTY, Point, triangulate};
use delaunator::{EMPTY, Point, Triangulation, triangulate};
use glam::DVec2;
#[derive(Debug, thiserror::Error)]
pub enum PointDiagramError {
#[error("Some points have positions that aren't finite")]
NonFinitePoints,
}
/// Triangulates `sites` with `delaunator`, which can't take non-finite positions among them.
fn triangulation(sites: &[DVec2]) -> Result<Triangulation, PointDiagramError> {
if !sites.iter().all(|site| site.is_finite()) {
return Err(PointDiagramError::NonFinitePoints);
}
let points: Vec<Point> = sites.iter().map(|p| Point { x: p.x, y: p.y }).collect();
Ok(triangulate(&points))
}
/// Computes the Delaunay triangulation of `sites`, returning each triangle as a triple of indices into `sites`.
///
/// Returns an empty vector when there are fewer than three points or they are all colinear (no triangle exists).
pub fn delaunay_triangles(sites: &[DVec2]) -> Vec<[usize; 3]> {
let points: Vec<Point> = sites.iter().map(|p| Point { x: p.x, y: p.y }).collect();
let triangulation = triangulate(&points);
triangulation.triangles.chunks_exact(3).map(|t| [t[0], t[1], t[2]]).collect()
/// Returns an empty vector when there are fewer than three points or they are all colinear (no triangle exists), and fails when a site isn't finite.
pub fn delaunay_triangles(sites: &[DVec2]) -> Result<Vec<[usize; 3]>, PointDiagramError> {
let triangulation = triangulation(sites)?;
Ok(triangulation.triangles.as_chunks::<3>().0.iter().map(|t| [t[0], t[1], t[2]]).collect())
}
/// Computes the Voronoi cell of every site, each clipped to the convex hull of `sites`.
///
/// Returns one closed polygon per site that produces a non-empty cell (degenerate or fully-clipped cells are omitted,
/// so the result may be shorter than `sites`). Returns an empty vector when no triangulation exists (fewer than three points or all colinear).
pub fn voronoi_cells(sites: &[DVec2]) -> Vec<Vec<DVec2>> {
voronoi_cells_per_site(sites).0.into_iter().flatten().collect()
/// so the result may be shorter than `sites`). Returns an empty vector when no triangulation exists (fewer than three points or all colinear), and fails when a site isn't finite.
pub fn voronoi_cells(sites: &[DVec2]) -> Result<Vec<Vec<DVec2>>, PointDiagramError> {
Ok(voronoi_cells_per_site(sites)?.0.into_iter().flatten().collect())
}
/// Applies Lloyd's relaxation: each step moves every interior site to the centroid of its Voronoi cell, yielding a more
/// even (centroidal) point distribution. A fractional `iterations` runs the whole-number steps and then blends each site
/// partway toward the result of one more step, so the relaxation can be animated smoothly. Returns the sites unchanged when
/// `iterations` is 0 or no diagram can be formed.
/// `iterations` is 0 or no diagram can be formed, and fails when `iterations` isn't 0 and a site isn't finite.
///
/// The convex-hull (perimeter) sites are pinned so the point cloud's outline is preserved. Otherwise, clipping the
/// unbounded perimeter cells would drag those sites around (inward for the convex hull, or outward into the corners of a
/// fixed bounding box), distorting the shape over successive iterations.
pub fn relax_sites(sites: &[DVec2], iterations: f64) -> Vec<DVec2> {
pub fn relax_sites(sites: &[DVec2], iterations: f64) -> Result<Vec<DVec2>, PointDiagramError> {
const MAX_STEPS_FOR_SAFETY: f64 = 1000.;
let iterations = iterations.clamp(0., MAX_STEPS_FOR_SAFETY);
let whole_steps = iterations.floor();
@@ -45,24 +60,24 @@ pub fn relax_sites(sites: &[DVec2], iterations: f64) -> Vec<DVec2> {
let mut current = sites.to_vec();
for _ in 0..whole_steps as u32 {
current = relax_once(&current);
current = relax_once(&current)?;
}
// Blend each site partway toward one further step for the fractional remainder.
if fraction > 0. {
let next = relax_once(&current);
let next = relax_once(&current)?;
for (point, target) in current.iter_mut().zip(next) {
*point = point.lerp(target, fraction);
}
}
current
Ok(current)
}
/// Performs a single Lloyd relaxation step: moves every interior site to its Voronoi cell centroid,
/// leaving the pinned convex-hull (perimeter) sites in place.
fn relax_once(sites: &[DVec2]) -> Vec<DVec2> {
let (cells, is_hull) = voronoi_cells_per_site(sites);
fn relax_once(sites: &[DVec2]) -> Result<Vec<DVec2>, PointDiagramError> {
let (cells, is_hull) = voronoi_cells_per_site(sites)?;
let mut relaxed = sites.to_vec();
for ((site, cell), on_hull) in relaxed.iter_mut().zip(cells).zip(is_hull) {
if on_hull {
@@ -72,7 +87,7 @@ fn relax_once(sites: &[DVec2]) -> Vec<DVec2> {
*site = centroid;
}
}
relaxed
Ok(relaxed)
}
/// The area-weighted centroid of a simple polygon, or `None` if it has fewer than three vertices or zero area.
@@ -95,11 +110,11 @@ fn polygon_centroid(polygon: &[DVec2]) -> Option<DVec2> {
/// Computes each site's clipped Voronoi cell, aligned with `sites` (index `i` is the cell of `sites[i]`), together with a
/// per-site flag marking the convex-hull (perimeter) sites. A cell is `None` when the site has no incident triangle
/// (e.g. a coincident duplicate) or its cell vanishes after clipping.
fn voronoi_cells_per_site(sites: &[DVec2]) -> (Vec<Option<Vec<DVec2>>>, Vec<bool>) {
let points: Vec<Point> = sites.iter().map(|p| Point { x: p.x, y: p.y }).collect();
let triangulation = triangulate(&points);
#[allow(clippy::type_complexity)]
fn voronoi_cells_per_site(sites: &[DVec2]) -> Result<(Vec<Option<Vec<DVec2>>>, Vec<bool>), PointDiagramError> {
let triangulation = triangulation(sites)?;
if triangulation.triangles.is_empty() {
return (vec![None; sites.len()], vec![false; sites.len()]);
return Ok((vec![None; sites.len()], vec![false; sites.len()]));
}
let triangles = &triangulation.triangles;
@@ -168,7 +183,7 @@ fn voronoi_cells_per_site(sites: &[DVec2]) -> (Vec<Option<Vec<DVec2>>>, Vec<bool
})
.collect();
(cells, is_hull)
Ok((cells, is_hull))
}
/// The circumcenter of a triangle, computed relative to `a` for numerical stability. Falls back to the centroid for a
@@ -306,18 +321,18 @@ mod tests {
// `delaunator` returns clockwise triangles, so `delaunay_triangles` keeps that order, but `voronoi_cells` are
// counter-clockwise. This documents the raw orientation; the Delaunay node reverses it to match the cells.
let sites = square_with_center();
for t in delaunay_triangles(&sites) {
for t in delaunay_triangles(&sites).unwrap() {
let poly = [sites[t[0]], sites[t[1]], sites[t[2]]];
assert!(signed_area(&poly) < 0., "delaunator triangles are expected to be clockwise");
}
for cell in voronoi_cells(&sites) {
for cell in voronoi_cells(&sites).unwrap() {
assert!(signed_area(&cell) > 0., "voronoi cells are expected to be counter-clockwise");
}
}
#[test]
fn delaunay_triangulates_square() {
let triangles = delaunay_triangles(&square_with_center());
let triangles = delaunay_triangles(&square_with_center()).unwrap();
// Four corner-to-center triangles tessellate the square.
assert_eq!(triangles.len(), 4);
for triangle in triangles {
@@ -329,12 +344,12 @@ mod tests {
#[test]
fn delaunay_degenerate_inputs_produce_no_triangles() {
assert!(delaunay_triangles(&[]).is_empty());
assert!(delaunay_triangles(&[DVec2::new(1., 1.)]).is_empty());
assert!(delaunay_triangles(&[DVec2::new(0., 0.), DVec2::new(1., 1.)]).is_empty());
assert!(delaunay_triangles(&[]).unwrap().is_empty());
assert!(delaunay_triangles(&[DVec2::new(1., 1.)]).unwrap().is_empty());
assert!(delaunay_triangles(&[DVec2::new(0., 0.), DVec2::new(1., 1.)]).unwrap().is_empty());
// Colinear points have no triangulation.
let colinear = vec![DVec2::new(0., 0.), DVec2::new(1., 1.), DVec2::new(2., 2.)];
assert!(delaunay_triangles(&colinear).is_empty());
assert!(delaunay_triangles(&colinear).unwrap().is_empty());
}
#[test]
@@ -343,14 +358,14 @@ mod tests {
// (100 for the 10x10 square). If the outward projection direction were inverted, the boundary cells would collapse
// inward and the total would fall well short of 100.
let sites = square_with_center();
let total: f64 = voronoi_cells(&sites).iter().map(|cell| signed_area(cell)).sum();
let total: f64 = voronoi_cells(&sites).unwrap().iter().map(|cell| signed_area(cell)).sum();
assert!((total - 100.).abs() < 1e-6, "cells should tile the hull (area 100), got {total}");
}
#[test]
fn voronoi_cells_stay_within_the_hull() {
let sites = square_with_center();
let cells = voronoi_cells(&sites);
let cells = voronoi_cells(&sites).unwrap();
assert!(!cells.is_empty());
// Clipping to the hull keeps every vertex inside the input bounds (with a small tolerance for float error).
for cell in &cells {
@@ -365,7 +380,7 @@ mod tests {
#[test]
fn relaxation_with_zero_iterations_is_identity() {
let sites = square_with_center();
assert_eq!(relax_sites(&sites, 0.), sites);
assert_eq!(relax_sites(&sites, 0.).unwrap(), sites);
}
#[test]
@@ -373,7 +388,7 @@ mod tests {
// Add a point clustered near the center; relaxation should redistribute the points without leaving the hull.
let mut sites = square_with_center();
sites.push(DVec2::new(5.5, 4.5));
let relaxed = relax_sites(&sites, 3.);
let relaxed = relax_sites(&sites, 3.).unwrap();
assert_eq!(relaxed.len(), sites.len());
assert_ne!(relaxed, sites, "relaxation should move the points");
@@ -394,7 +409,7 @@ mod tests {
DVec2::new(3., 3.),
DVec2::new(7., 4.),
];
let relaxed = relax_sites(&sites, 4.);
let relaxed = relax_sites(&sites, 4.).unwrap();
for i in 0..4 {
assert_eq!(relaxed[i], sites[i], "convex hull point {i} should be pinned");
@@ -416,9 +431,9 @@ mod tests {
// A fractional count lands exactly midway between the two bracketing whole-step results, exercising both the
// pure-fraction path (0.5) and the whole-steps-then-fraction path (2.5).
for whole in [0., 2.] {
let lower = relax_sites(&sites, whole);
let upper = relax_sites(&sites, whole + 1.);
let half = relax_sites(&sites, whole + 0.5);
let lower = relax_sites(&sites, whole).unwrap();
let upper = relax_sites(&sites, whole + 1.).unwrap();
let half = relax_sites(&sites, whole + 0.5).unwrap();
for i in 0..sites.len() {
let expected = (lower[i] + upper[i]) / 2.;
assert!((half[i] - expected).length() < 1e-9, "index {i} at {whole}.5: {half:?} vs {expected:?}", half = half[i]);
@@ -430,7 +445,7 @@ mod tests {
fn relaxation_leaves_degenerate_input_unchanged() {
// Fewer than three points cannot form a diagram, so relaxation is a no-op.
let sites = vec![DVec2::new(0., 0.), DVec2::new(1., 1.)];
assert_eq!(relax_sites(&sites, 5.), sites);
assert_eq!(relax_sites(&sites, 5.).unwrap(), sites);
}
#[test]
@@ -444,12 +459,12 @@ mod tests {
DVec2::new(7., 6.),
];
// A huge or infinite count must clamp to the converged result rather than hang on a billions-long loop.
let converged = relax_sites(&sites, 1000.);
assert_eq!(relax_sites(&sites, 1e9), converged);
assert_eq!(relax_sites(&sites, f64::INFINITY), converged);
let converged = relax_sites(&sites, 1000.).unwrap();
assert_eq!(relax_sites(&sites, 1e9).unwrap(), converged);
assert_eq!(relax_sites(&sites, f64::INFINITY).unwrap(), converged);
// NaN and negative counts resolve to zero steps, leaving the sites unchanged.
assert_eq!(relax_sites(&sites, f64::NAN), sites);
assert_eq!(relax_sites(&sites, -5.), sites);
assert_eq!(relax_sites(&sites, f64::NAN).unwrap(), sites);
assert_eq!(relax_sites(&sites, -5.).unwrap(), sites);
}
#[test]
@@ -460,7 +475,7 @@ mod tests {
let angle = i as f64 / 6. * std::f64::consts::TAU;
sites.push(DVec2::new(angle.cos() * 10., angle.sin() * 10.));
}
let cells = voronoi_cells(&sites);
let cells = voronoi_cells(&sites).unwrap();
assert!(!cells.is_empty());
// Every cell is a finite polygon with no runaway coordinates.
for cell in &cells {