Compare commits

...
8 changed files with 660 additions and 36 deletions

No files matched your search

+18 -16
View File
@@ -7,7 +7,7 @@
"name": "graphite-web-frontend",
"license": "Apache-2.0",
"dependencies": {
"@tauri-apps/api": "^2.2.0",
"@rollup/rollup-win32-x64-msvc": "^4.40.1",
"class-transformer": "^0.5.1",
"idb-keyval": "^6.2.1",
"reflect-metadata": "^0.2.2"
@@ -989,15 +989,13 @@
]
},
"node_modules/@rollup/rollup-win32-x64-msvc": {
"version": "4.34.9",
"resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.34.9.tgz",
"integrity": "sha512-AyleYRPU7+rgkMWbEh71fQlrzRfeP6SyMnRf9XX4fCdDPAJumdSBqYEcWPMzVQ4ScAl7E4oFfK0GUVn77xSwbw==",
"version": "4.40.1",
"resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.40.1.tgz",
"integrity": "sha512-ECyOuDeH3C1I8jH2MK1RtBJW+YPMvSfT0a5NN0nHfQYnDSJ6tUiZH3gzwVP5/Kfh/+Tt7tpWVF9LXNTnhTJ3kA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
]
@@ -1050,16 +1048,6 @@
"vite": "^5.0.0"
}
},
"node_modules/@tauri-apps/api": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/@tauri-apps/api/-/api-2.2.0.tgz",
"integrity": "sha512-R8epOeZl1eJEl603aUMIGb4RXlhPjpgxbGVEaqY+0G5JG9vzV/clNlzTeqc+NLYXVqXcn8mb4c5b9pJIUDEyAg==",
"license": "Apache-2.0 OR MIT",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/tauri"
}
},
"node_modules/@tsconfig/node10": {
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.11.tgz",
@@ -4668,6 +4656,20 @@
"url": "https://github.com/sponsors/jonschlinkert"
}
},
"node_modules/rollup/node_modules/@rollup/rollup-win32-x64-msvc": {
"version": "4.34.9",
"resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.34.9.tgz",
"integrity": "sha512-AyleYRPU7+rgkMWbEh71fQlrzRfeP6SyMnRf9XX4fCdDPAJumdSBqYEcWPMzVQ4ScAl7E4oFfK0GUVn77xSwbw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
]
},
"node_modules/run-parallel": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz",
+5 -4
View File
@@ -34,6 +34,7 @@
"reflect-metadata": "^0.2.2"
},
"devDependencies": {
"@rollup/rollup-win32-x64-msvc": "^4.40.1",
"@sveltejs/vite-plugin-svelte": "^3.1.2",
"@types/node": "^22.6.1",
"@typescript-eslint/eslint-plugin": "^8.7.0",
@@ -46,17 +47,17 @@
"eslint-plugin-prettier": "^5.2.1",
"eslint-plugin-svelte": "^2.44.0",
"postcss": "^8.4.47",
"prettier": "^3.3.3",
"prettier-plugin-svelte": "^3.2.6",
"prettier": "^3.3.3",
"process": "^0.11.10",
"rollup-plugin-license": "^3.5.3",
"sass": "1.78.0",
"svelte": "^4.2.19",
"svelte-preprocess": "^6.0.2",
"svelte": "^4.2.19",
"ts-node": "^10.9.2",
"typescript": "^5.6.2",
"vite": "^5.4.14",
"vite-multiple-assets": "1.3.1"
"vite-multiple-assets": "1.3.1",
"vite": "^5.4.14"
},
"//": "The dev dependency for `sass` can be removed once <https://github.com/sveltejs/svelte-preprocess/issues/656> is fixed, but meanwhile we have to",
"///": "list it here and pin it to 1.78.0 so `vite` and `svelte-preprocess` use it instead of 1.79+ which spams the console with deprecation warnings.",
+2 -2
View File
@@ -271,9 +271,9 @@ impl Bezier {
_ => *self,
};
let should_flip_direction = (self.start - intersection).normalize().abs_diff_eq(normal_start, MAX_ABSOLUTE_DIFFERENCE);
let should_flip_direction = (self.start - intersection).normalize_or_zero().abs_diff_eq(normal_start, MAX_ABSOLUTE_DIFFERENCE);
intermediate.apply_transformation(|point| {
let mut direction_unit_vector = (intersection - point).normalize();
let mut direction_unit_vector = (intersection - point).normalize_or_zero();
if should_flip_direction {
direction_unit_vector *= -1.;
}
+31 -13
View File
@@ -351,25 +351,38 @@ impl<PointId: crate::Identifier> Subpath<PointId> {
rotated_subpath
}
/// Reduces the segments of the subpath into simple subcurves, then scales each subcurve a set `distance` away.
/// The intersections of segments of the subpath are joined using the method specified by the `join` argument.
/// <iframe frameBorder="0" width="100%" height="400px" src="https://graphite.rs/libraries/bezier-rs#subpath/offset/solo" title="Offset Demo"></iframe>
pub fn offset(&self, distance: f64, join: Join) -> Subpath<PointId> {
// An offset at a distance 0 from the curve is simply the same curve
// An offset of a single point is not defined
// Early returns - same as before
if distance == 0. || self.len() <= 1 || self.len_segments() < 1 {
return self.clone();
}
let mut subpaths = self
.iter()
.filter(|bezier| !bezier.is_point())
.map(|bezier| bezier.offset(distance))
.filter(|subpath| subpath.len() >= 2) // In some cases the reduced and scaled bézier is marked by is_point (so the subpath is empty).
.collect::<Vec<Subpath<PointId>>>();
// Collect valid offset subpaths
let mut subpaths = Vec::new();
for bezier in self.iter() {
if bezier.is_point() {
continue;
}
// Try to offset the bezier and handle potential failures
let offset_result = std::panic::catch_unwind(|| bezier.offset(distance));
// Only include valid results
if let Ok(subpath) = offset_result {
if subpath.len() >= 2 {
subpaths.push(subpath);
}
}
}
// If we couldn't offset any segments, just return the original
if subpaths.is_empty() {
return self.clone();
}
let mut drop_common_point = vec![true; self.len()];
// Rest of the function remains the same
// Clip or join consecutive Subpaths
for i in 0..subpaths.len() - 1 {
let j = i + 1;
@@ -424,7 +437,7 @@ impl<PointId: crate::Identifier> Subpath<PointId> {
}
// Clip any overlap in the last segment
if self.closed {
if self.closed && !subpaths.is_empty() {
let out_tangent = self.get_segment(self.len_segments() - 1).unwrap().tangent(TValue::Parametric(1.));
let in_tangent = self.get_segment(0).unwrap().tangent(TValue::Parametric(0.));
let angle = out_tangent.angle_to(in_tangent);
@@ -462,6 +475,11 @@ impl<PointId: crate::Identifier> Subpath<PointId> {
}
}
// Ensure we have subpaths before merging
if subpaths.is_empty() {
return self.clone();
}
// Merge the subpaths. Drop points which overlap with one another.
let mut manipulator_groups = subpaths[0].manipulator_groups.clone();
for i in 1..subpaths.len() {
@@ -475,7 +493,7 @@ impl<PointId: crate::Identifier> Subpath<PointId> {
manipulator_groups.append(&mut subpaths[i].manipulator_groups.clone());
}
}
if self.closed && drop_common_point[0] {
if self.closed && !subpaths.is_empty() && drop_common_point[0] {
let last_group = manipulator_groups.pop().unwrap();
manipulator_groups[0].in_handle = last_group.in_handle;
}
+16
View File
@@ -33,6 +33,22 @@ fn string_slice(_: impl Ctx, #[implementations(String)] string: String, start: f
string.char_indices().skip(start).take(n).map(|(_, c)| c).collect()
}
#[node_macro::node(category("Text"))]
fn split_string_by_index(
_: impl Ctx,
#[implementations(String)]
/// The comma-separated string to split.
input: String,
/// The zero-based index of the item to retrieve.
#[default(0.0)]
#[min(0.0)]
index: f64,
) -> String {
let parts: Vec<&str> = input.split(',').map(|s| s.trim()).collect();
let floored_index = index.floor() as usize;
if floored_index < parts.len() { parts[floored_index].to_string() } else { String::new() }
}
#[node_macro::node(category("Text"))]
fn string_length(_: impl Ctx, #[implementations(String)] string: String) -> usize {
string.len()
@@ -1,6 +1,6 @@
use crate::instances::Instance;
use crate::vector::{VectorData, VectorDataTable};
use crate::{CloneVarArgs, Context, Ctx, ExtractAll, ExtractIndex, ExtractVarArgs, OwnedContextImpl};
use crate::{CloneVarArgs, Context, Ctx, ExtractAll, ExtractIndex, ExtractVarArgs, GraphicGroupTable, OwnedContextImpl};
use glam::{DAffine2, DVec2};
#[node_macro::node(name("Instance on Points"), category("Vector: Shape"), path(graphene_core::vector))]
@@ -33,6 +33,36 @@ async fn instance_on_points(
result
}
#[node_macro::node(name("Group Instance on Points"), category("Vector: Shape"), path(graphene_core::vector))]
async fn group_instance_on_points(
ctx: impl ExtractAll + CloneVarArgs + Ctx,
points: VectorDataTable,
#[implementations(Context -> GraphicGroupTable)] instance_node: impl Node<'n, Context<'static>, Output = GraphicGroupTable>,
) -> GraphicGroupTable {
let mut result = GraphicGroupTable::empty();
for Instance { instance: points, transform, .. } in points.instances() {
for (index, &point) in points.point_domain.positions().iter().enumerate() {
let transformed_point = transform.transform_point2(point);
let new_ctx = OwnedContextImpl::from(ctx.clone()).with_index(index).with_vararg(Box::new(transformed_point));
let instanced = instance_node.eval(new_ctx.into_context()).await;
for instanced_element in instanced.instances() {
let new_instance = result.push_instance(instanced_element);
*new_instance.transform *= DAffine2::from_translation(transformed_point);
}
}
}
// TODO: Remove once we support empty tables, currently this is here to avoid crashing
if result.is_empty() {
return GraphicGroupTable::empty();
}
result
}
#[node_macro::node(category("Attributes"), path(graphene_core::vector))]
async fn instance_position(ctx: impl Ctx + ExtractVarArgs) -> DVec2 {
match ctx.vararg(0).map(|dynamic| dynamic.downcast_ref::<DVec2>()) {
@@ -41,6 +41,10 @@ macro_rules! create_ids {
self.0 += 1;
*self
}
pub fn from_u64(id: u64) -> Self {
Self(id)
}
}
)*
};
+553
View File
@@ -13,6 +13,7 @@ use bezier_rs::{Cap, Join, ManipulatorGroup, Subpath, SubpathTValue, TValue};
use core::f64::consts::PI;
use glam::{DAffine2, DVec2};
use rand::{Rng, SeedableRng};
use std::collections::{HashMap, HashSet};
/// Implemented for types that can be converted to an iterator of vector data.
/// Used for the fill and stroke node so they can be used on VectorData or GraphicGroup
@@ -508,6 +509,470 @@ async fn round_corners(
result_table
}
#[node_macro::node(category("Vector"), path(graphene_core::vector))]
async fn project(
_: impl Ctx,
vector_data: VectorDataTable,
#[default(0.)]
#[range((-180., 180.))]
angle: Angle,
) -> VectorDataTable {
let vector_data_transform = vector_data.transform();
let vector_data = vector_data.one_instance().instance.clone();
// Convert angle to radians and get the projection direction vector
let angle_rad = angle.to_radians();
let direction = DVec2::new(angle_rad.cos(), angle_rad.sin());
// Create a perpendicular vector to the direction
let perpendicular = DVec2::new(-direction.y, direction.x);
let mut result = VectorData::empty();
result.style = vector_data.style.clone();
let mut initial_point_id: PointId = PointId::from_u64(0);
for mut subpath in vector_data.stroke_bezier_paths() {
subpath.apply_transform(vector_data_transform);
// Skip subpaths without enough points
if subpath.manipulator_groups().len() < 2 {
continue;
}
// Find the projection bounds along the perpendicular axis
let mut min_proj = f64::MAX;
let mut max_proj = f64::MIN;
let mut centroid = DVec2::ZERO;
let mut total_length = 0.0;
// Calculate centroid for positioning the projected line
for bezier in subpath.iter() {
let length = bezier.length(None);
if length > 0.0 {
let segment_centroid = bezier.length_centroid(None);
centroid += segment_centroid * length;
total_length += length;
}
// Sample multiple points along the curve to find projection bounds
for t in 0..=10 {
let t = t as f64 / 10.0;
let point = bezier.evaluate(TValue::Parametric(t));
let projection = point.dot(perpendicular);
min_proj = min_proj.min(projection);
max_proj = max_proj.max(projection);
}
}
if total_length > 0.0 {
centroid /= total_length;
} else {
// Use average position for point-like subpaths
centroid = subpath.manipulator_groups().iter().map(|group| group.anchor).sum::<DVec2>() / subpath.manipulator_groups().len() as f64;
}
// Calculate the average depth position along the projection direction
let depth_position = centroid.dot(direction);
// Create a line from min to max along the perpendicular axis
let start_point = direction * depth_position + perpendicular * min_proj;
let end_point = direction * depth_position + perpendicular * max_proj;
// Create a simple linear segment for the projection
// Have sane, increase IDs for the points, use id_count
let point_id_start = initial_point_id.next_id();
let point_id_end = initial_point_id.next_id();
result.point_domain.push(point_id_start, vector_data_transform.inverse().transform_point2(start_point));
result.point_domain.push(point_id_end, vector_data_transform.inverse().transform_point2(end_point));
let segment_id = SegmentId::generate();
let stroke_id = StrokeId::ZERO;
let start_index = result.point_domain.ids().len() - 2;
let end_index = result.point_domain.ids().len() - 1;
result.segment_domain.push(segment_id, start_index, end_index, bezier_rs::BezierHandles::Linear, stroke_id);
}
let mut result_table = VectorDataTable::new(result);
*result_table.transform_mut() = vector_data_transform;
result_table
}
#[node_macro::node(category("Vector"), path(graphene_core::vector))]
async fn delete_points_by_id(_: impl Ctx, vector_data: VectorDataTable, #[default("0")] id_ranges: String, #[default(false)] preserve_connectivity: bool) -> VectorDataTable {
let vector_data_transform = vector_data.transform();
let vector_data = vector_data.one_instance().instance.clone();
// Parse the ID ranges from the input string
let id_ranges = parse_id_ranges(&id_ranges);
// Create a set of point IDs to delete
let point_ids: Vec<PointId> = vector_data.point_domain.ids().to_vec();
let mut points_to_delete = HashSet::new();
for &(start, end) in &id_ranges {
// Adjust for 0-based indexing and limit to actual data size
let start_idx = start.saturating_sub(1);
let end_idx = end.saturating_sub(1).min(point_ids.len() - 1);
for idx in start_idx..=end_idx {
if idx < point_ids.len() {
points_to_delete.insert(point_ids[idx]);
}
}
}
if points_to_delete.is_empty() {
// No points to delete, return the original data
let mut result_table = VectorDataTable::new(vector_data);
*result_table.transform_mut() = vector_data_transform;
return result_table;
}
// Create a new vector data for the result
let mut result = VectorData::empty();
result.style = vector_data.style.clone();
if preserve_connectivity {
// Create a mapping of deleted points to their connected points
let mut connections = HashMap::new();
// Gather all connections from the original data
for segment in vector_data.segment_bezier_iter() {
let (_, _, start_id, end_id) = segment;
if points_to_delete.contains(&start_id) {
connections.entry(start_id).or_insert_with(HashSet::new).insert(end_id);
}
if points_to_delete.contains(&end_id) {
connections.entry(end_id).or_insert_with(HashSet::new).insert(start_id);
}
}
// Create new point domain with preserved points
for (i, &id) in point_ids.iter().enumerate() {
if !points_to_delete.contains(&id) {
let pos = vector_data.point_domain.positions()[i];
result.point_domain.push(id, pos);
}
}
// Process segments, creating new ones to maintain connectivity
for (segment_id, bezier, start_id, end_id) in vector_data.segment_bezier_iter() {
let start_deleted = points_to_delete.contains(&start_id);
let end_deleted = points_to_delete.contains(&end_id);
if !start_deleted && !end_deleted {
// Keep segments between non-deleted points
let start_idx = result.point_domain.resolve_id(start_id).unwrap();
let end_idx = result.point_domain.resolve_id(end_id).unwrap();
result.segment_domain.push(segment_id, start_idx, end_idx, bezier.handles, StrokeId::ZERO);
} else if preserve_connectivity && (start_deleted != end_deleted) {
// Find replacement connections for deleted points
let mut new_connections = Vec::new();
if start_deleted {
if let Some(connected) = connections.get(&start_id) {
for &connected_id in connected {
if !points_to_delete.contains(&connected_id) && connected_id != end_id {
new_connections.push((connected_id, end_id));
}
}
}
} else {
// end_deleted
if let Some(connected) = connections.get(&end_id) {
for &connected_id in connected {
if !points_to_delete.contains(&connected_id) && connected_id != start_id {
new_connections.push((start_id, connected_id));
}
}
}
}
// Create new segments to maintain connectivity
for (new_start, new_end) in new_connections {
let start_idx = result.point_domain.resolve_id(new_start).unwrap();
let end_idx = result.point_domain.resolve_id(new_end).unwrap();
result.segment_domain.push(SegmentId::generate(), start_idx, end_idx, bezier_rs::BezierHandles::Linear, StrokeId::ZERO);
}
}
}
} else {
// Simply remove the points and connected segments
// Create new point domain without deleted points
for (i, &id) in point_ids.iter().enumerate() {
if !points_to_delete.contains(&id) {
let pos = vector_data.point_domain.positions()[i];
result.point_domain.push(id, pos);
}
}
// Keep only segments that don't connect to deleted points
for (segment_id, bezier, start_id, end_id) in vector_data.segment_bezier_iter() {
if !points_to_delete.contains(&start_id) && !points_to_delete.contains(&end_id) {
// Map to new indices in the result's point domain
let start_idx = result.point_domain.resolve_id(start_id).unwrap();
let end_idx = result.point_domain.resolve_id(end_id).unwrap();
result.segment_domain.push(segment_id, start_idx, end_idx, bezier.handles, StrokeId::ZERO);
}
}
}
let mut result_table = VectorDataTable::new(result);
*result_table.transform_mut() = vector_data_transform;
result_table
}
// Parse the ID ranges from a string like "1-3, 5-7"
fn parse_id_ranges(input: &str) -> Vec<(usize, usize)> {
let mut ranges = Vec::new();
for range_str in input.split(',') {
let range_str = range_str.trim();
if range_str.is_empty() {
continue;
}
if let Some(dash_pos) = range_str.find('-') {
// Handle range like "1-3"
let start_str = &range_str[..dash_pos].trim();
let end_str = &range_str[dash_pos + 1..].trim();
if let (Ok(start), Ok(end)) = (start_str.parse::<usize>(), end_str.parse::<usize>()) {
if start <= end {
ranges.push((start, end));
}
}
} else {
// Handle single number like "5"
if let Ok(num) = range_str.parse::<usize>() {
ranges.push((num, num));
}
}
}
ranges
}
#[node_macro::node(category("Vector"), path(graphene_core::vector))]
async fn local_transform<I: 'n + Send>(
_: impl Ctx,
#[implementations(VectorDataTable, GraphicGroupTable)] instance: Instances<I>,
#[default(1., 1.)] scale: DVec2,
#[range((-360., 360.))]
#[default(0.)]
rotation: Angle,
#[default(false)] keep_original: bool,
) -> GraphicGroupTable
where
Instances<I>: GraphicElementRendered,
{
let mut result_table = GraphicGroupTable::default();
// Get the bounding box of the input
let Some(bounding_box) = instance.bounding_box(DAffine2::IDENTITY) else {
return result_table;
};
// Calculate the pivot point (center of the bounding box)
let pivot = (bounding_box[0] + bounding_box[1]) / 2.;
// 1. Translate to origin
// 2. Apply scale and rotation
// 3. Translate back
let local_transform = DAffine2::from_translation(pivot) * DAffine2::from_scale_angle_translation(scale, rotation.to_radians(), DVec2::ZERO) * DAffine2::from_translation(-pivot);
// Add original instance if requested
if keep_original {
result_table.push(instance.to_graphic_element());
}
// Create and add transformed instance
let mut transformed_element = instance.to_graphic_element();
transformed_element.new_ids_from_hash(None);
// Apply the transformation to the transformed instance
let transformed_instance = result_table.push(transformed_element);
*transformed_instance.transform = local_transform;
result_table
}
#[node_macro::node(category("Vector"), path(graphene_core::vector))]
async fn box_pack(
_: impl Ctx,
#[implementations(GraphicGroupTable)] instances: GraphicGroupTable,
#[expose]
#[implementations(VectorDataTable)]
container_shape: VectorDataTable,
#[default(10.)] padding: f64,
#[default(false)] sort_by_area: bool,
) -> GraphicGroupTable {
let mut result = GraphicGroupTable::empty();
// Get the container's bounding box
let container_transform = container_shape.transform();
let container_bbox = container_shape
.one_instance()
.instance
.bounding_box_with_transform(container_transform)
.unwrap_or_else(|| [DVec2::ZERO, DVec2::ZERO]);
let container_size = container_bbox[1] - container_bbox[0];
let container_origin = container_bbox[0];
// Extract bounding boxes and original instances
let mut items = Vec::new();
for instance in instances.instances() {
// Get the bounding box directly from the instance transform
if let Some(bbox) = instance.instance.bounding_box(*instance.transform) {
let size = bbox[1] - bbox[0];
items.push((size, *instance.transform, instance.instance.clone()));
}
}
// Sort instances by area if requested (larger first for better packing)
if sort_by_area {
items.sort_by(|a, b| {
let area_a = a.0.x * a.0.y;
let area_b = b.0.x * b.0.y;
area_b.partial_cmp(&area_a).unwrap_or(std::cmp::Ordering::Equal)
});
}
// Simple bin packing algorithm
let mut current_x = container_origin.x;
let mut current_y = container_origin.y;
let mut row_height = 0.0;
for (size, _, instance) in items {
// Add padding to the item size
let item_width = size.x + padding;
let item_height = size.y + padding;
let instance_size = DVec2::new(item_width, item_height);
// Check if we need to move to the next row
if current_x + item_width > container_origin.x + container_size.x {
current_x = container_origin.x;
current_y += row_height;
row_height = 0.0;
}
// Check if we've exceeded the container height
if current_y + item_height > container_origin.y + container_size.y {
// We could implement multi-page packing here
break;
}
// Calculate the position for this item
let position = DVec2::new(current_x, current_y);
// Extract the current center of the instance
let instance_center = {
if let Some(bbox) = instance.bounding_box(DAffine2::IDENTITY) {
(bbox[0] + bbox[1]) * 0.5
} else {
DVec2::ZERO
}
};
// Create a new transform that positions the instance correctly
let new_transform = DAffine2::from_translation(position - instance_center + instance_size * 0.5);
// Add to the result
let pushed = result.push(instance);
*pushed.transform = new_transform;
// Update position tracking
current_x += item_width;
row_height = row_height.max(item_height);
}
result
}
#[node_macro::node(category("Vector"), path(graphene_core::vector))]
async fn center_instances(
_: impl Ctx,
graphic_group: GraphicGroupTable,
#[default(true)] center_x: bool,
#[default(true)] center_y: bool,
#[default(false)] align_to_first_instance: bool,
) -> GraphicGroupTable {
// Create a new result table
let mut result_table = GraphicGroupTable::empty();
// Early return if no instances or no centering requested
if graphic_group.is_empty() || (!center_x && !center_y) {
return graphic_group;
}
// Calculate reference position - either the global center or first instance's center
let mut ref_center_x = 0.0;
let mut ref_center_y = 0.0;
if align_to_first_instance {
if let Some(first_instance) = graphic_group.instances().next() {
if let Some(bounds) = first_instance.instance.bounding_box(*first_instance.transform) {
ref_center_x = (bounds[0].x + bounds[1].x) / 2.0;
ref_center_y = (bounds[0].y + bounds[1].y) / 2.0;
}
}
} else {
// Calculate global center of all instances combined
if let Some(bounds) = graphic_group.bounding_box(DAffine2::IDENTITY) {
ref_center_x = (bounds[0].x + bounds[1].x) / 2.0;
ref_center_y = (bounds[0].y + bounds[1].y) / 2.0;
}
}
// Process each instance
for instance in graphic_group.instances() {
// Get the instance's bounding box
let Some(bounds) = instance.instance.bounding_box(*instance.transform) else {
// If no bounds, just copy the instance as is
result_table.push_instance(instance);
continue;
};
// Calculate the instance's current center
let instance_center_x = (bounds[0].x + bounds[1].x) / 2.0;
let instance_center_y = (bounds[0].y + bounds[1].y) / 2.0;
// Calculate the translation needed
let dx = if center_x { ref_center_x - instance_center_x } else { 0.0 };
let dy = if center_y { ref_center_y - instance_center_y } else { 0.0 };
// Skip if no translation needed
if dx.abs() < f64::EPSILON && dy.abs() < f64::EPSILON {
result_table.push_instance(instance);
continue;
}
// Create and apply the translation
let translation = DAffine2::from_translation(DVec2::new(dx, dy));
// Clone the instance and update its transform
let mut new_element = instance.instance.clone();
new_element.new_ids_from_hash(None);
let new_instance = result_table.push(new_element);
*new_instance.transform = translation * *instance.transform;
*new_instance.alpha_blending = *instance.alpha_blending;
*new_instance.source_node_id = *instance.source_node_id;
}
result_table
}
#[node_macro::node(name("Spatial Merge by Distance"), category("Debug"), path(graphene_core::vector))]
async fn spatial_merge_by_distance(
_: impl Ctx,
@@ -1015,6 +1480,94 @@ async fn offset_path(_: impl Ctx, vector_data: VectorDataTable, distance: f64, l
result
}
#[node_macro::node(category("Vector"), path(graphene_core::vector))]
async fn outer_path(_: impl Ctx, vector_data: VectorDataTable) -> VectorDataTable {
let vector_data_transform = vector_data.transform();
let vector_data = vector_data.one_instance().instance;
// Create a new VectorData to store our result
let mut result = VectorData::empty();
result.style = vector_data.style.clone();
// Collect all closed subpaths with their indices
let subpaths: Vec<_> = vector_data
.stroke_bezier_paths()
.enumerate()
.filter(|(_, subpath)| subpath.closed())
.map(|(i, mut subpath)| {
// Apply transform to work in world space
subpath.apply_transform(vector_data_transform);
(i, subpath)
})
.collect();
if subpaths.is_empty() {
// No closed paths found, return empty result
let mut result_table = VectorDataTable::new(result);
*result_table.transform_mut() = vector_data_transform;
return result_table;
}
// Find the outermost path:
// 1. Start by assuming all subpaths could be the outermost
let mut potential_outer_paths: Vec<_> = subpaths.iter().map(|(i, _)| *i).collect();
// 2. For each subpath, test against all others
for (i, subpath_i) in &subpaths {
// Skip if already eliminated
if !potential_outer_paths.contains(i) {
continue;
}
for (j, subpath_j) in &subpaths {
// Skip comparing to self
if i == j {
continue;
}
// Sample points from subpath_i
let total_points = 20;
let mut contained_points = 0;
// Check several points along subpath_i to see if they're contained in subpath_j
for k in 0..total_points {
let t = k as f64 / total_points as f64;
let point = subpath_i.evaluate(bezier_rs::SubpathTValue::GlobalParametric(t));
if subpath_j.contains_point(point) {
contained_points += 1;
}
}
// If most points from subpath_i are inside subpath_j,
// then subpath_i is not an outer path
if contained_points > total_points / 2 {
potential_outer_paths.retain(|&x| x != *i);
break;
}
}
}
// 3. Among remaining potential outer paths, choose the one with the largest area
if let Some(&outer_index) = potential_outer_paths.iter().max_by(|&&a, &&b| {
let area_a = subpaths.iter().find(|(i, _)| *i == a).map(|(_, s)| s.area(None, None).abs()).unwrap_or(0.0);
let area_b = subpaths.iter().find(|(i, _)| *i == b).map(|(_, s)| s.area(None, None).abs()).unwrap_or(0.0);
area_a.partial_cmp(&area_b).unwrap_or(std::cmp::Ordering::Equal)
}) {
// Find the outer path and add it to the result
if let Some((_, outer_path)) = subpaths.iter().find(|(i, _)| *i == outer_index) {
let mut path_copy = outer_path.clone();
path_copy.apply_transform(vector_data_transform.inverse());
result.append_subpath(path_copy, true);
}
}
// Create the resulting VectorDataTable
let mut result_table = VectorDataTable::new(result);
*result_table.transform_mut() = vector_data_transform;
result_table
}
#[node_macro::node(category("Vector"), path(graphene_core::vector))]
async fn solidify_stroke(_: impl Ctx, vector_data: VectorDataTable) -> VectorDataTable {
let vector_data_transform = vector_data.transform();