From e773fff9e38bcb670639873da7d2104a671b81e4 Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Fri, 4 Dec 2026 23:20:20 -0800 Subject: [PATCH] Replace the 'Rasterize' node's footprint with an area transform and a resolution, and remove the 'Footprint Value' node --- .../migrations/nodes/src/graphene_core/mod.rs | 1 + .../passthrough_from_footprint_value.rs | 37 +++ .../migrations/nodes/src/graphene_std/mod.rs | 1 + .../nodes/src/graphene_std/rasterize_v1.rs | 276 ++++++++++++++++++ .../node_graph/document_node_definitions.rs | 15 +- .../document/node_graph/node_inspector.rs | 139 +-------- .../messages/portfolio/document_migration.rs | 210 ++++++++++++- frontend/src/icons.ts | 2 - node-graph/graph-craft/src/document/value.rs | 56 ++-- .../interpreted-executor/src/node_registry.rs | 4 +- node-graph/libraries/core-types/src/misc.rs | 7 + node-graph/nodes/gcore/src/animation.rs | 3 - .../nodes/gcore/src/context_modification.rs | 2 - .../nodes/gstd/src/platform_application_io.rs | 102 +++++-- node-graph/nodes/math/src/lib.rs | 19 -- 15 files changed, 625 insertions(+), 249 deletions(-) create mode 100644 document/migrations/nodes/src/graphene_core/passthrough_from_footprint_value.rs create mode 100644 document/migrations/nodes/src/graphene_std/rasterize_v1.rs diff --git a/document/migrations/nodes/src/graphene_core/mod.rs b/document/migrations/nodes/src/graphene_core/mod.rs index c5b761d4c9..79429f6fc2 100644 --- a/document/migrations/nodes/src/graphene_core/mod.rs +++ b/document/migrations/nodes/src/graphene_core/mod.rs @@ -2,6 +2,7 @@ mod fill_v1; mod passthrough_from_read_attribute_gradient_form_node; +mod passthrough_from_footprint_value; mod passthrough_from_upload_texture_node; mod renames; mod vary_colors_from_assign_colors; diff --git a/document/migrations/nodes/src/graphene_core/passthrough_from_footprint_value.rs b/document/migrations/nodes/src/graphene_core/passthrough_from_footprint_value.rs new file mode 100644 index 0000000000..e2417636cb --- /dev/null +++ b/document/migrations/nodes/src/graphene_core/passthrough_from_footprint_value.rs @@ -0,0 +1,37 @@ +use migration_core::{Inputs, migration}; + +/// 'Footprint Value' is gone with the footprint input of 'Rasterize', whose migration takes over the inputs of one feeding it. One read +/// elsewhere passes on its empty primary input instead, since nothing else takes a footprint. +#[migration("math_nodes::FootprintValueNode"@1 => "graphene_core::ops::PassthroughNode"@2)] +pub fn passthrough_from_footprint_value(inputs: &mut Inputs) { + inputs.truncate(1); +} + +#[cfg(test)] +mod tests { + use super::*; + use migration_core::{decl, literal}; + use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo}; + + fn contract() -> SourceContract { + SourceContract::new(3, |random, _slot| literal(random.below(10) as f64)) + } + + #[test] + fn rewrites_history() { + check_commutation(&PassthroughFromFootprintValue, &contract()); + check_undo(&PassthroughFromFootprintValue, &contract()); + } + + #[test] + fn keeps_the_primary_input_and_drops_the_transform_and_resolution() { + let (primary, transform, resolution) = (literal(()), literal(1.), literal(2.)); + + let mut fixture = Fixture::new(&PassthroughFromFootprintValue); + let footprint_value = fixture.add(decl!("math_nodes::FootprintValueNode"@1), vec![primary.clone(), transform, resolution]); + let migrated = fixture.migrate(&PassthroughFromFootprintValue).unwrap(); + + assert_eq!(fixture.declaration_of(&migrated, footprint_value), Some(decl!("graphene_core::ops::PassthroughNode"@2))); + assert_eq!(fixture.inputs(&migrated, footprint_value), [primary]); + } +} diff --git a/document/migrations/nodes/src/graphene_std/mod.rs b/document/migrations/nodes/src/graphene_std/mod.rs index 5ebf83542e..2661131be7 100644 --- a/document/migrations/nodes/src/graphene_std/mod.rs +++ b/document/migrations/nodes/src/graphene_std/mod.rs @@ -1,3 +1,4 @@ //! Migrations of the nodes in `graphene_std`. +mod rasterize_v1; mod renames; diff --git a/document/migrations/nodes/src/graphene_std/rasterize_v1.rs b/document/migrations/nodes/src/graphene_std/rasterize_v1.rs new file mode 100644 index 0000000000..c47010876d --- /dev/null +++ b/document/migrations/nodes/src/graphene_std/rasterize_v1.rs @@ -0,0 +1,276 @@ +use migration_core::{Declaration, Graph, InputConnector, Inputs, MigrationError, NewNode, Node, NodeInput, OutputConnector, Upstream, decl, encode, literal, literal_of, migration}; +use serde::{Deserialize, Serialize}; +use std::collections::HashSet; + +const FOOTPRINT: u32 = 1; +const RASTERIZE: Declaration = decl!("graphene_std::platform_application_io::RasterizeNode"@1); + +/// Matched at any version, since naming one would order this migration after the one turning 'Footprint Value' into it, which must come after. +const PASSTHROUGH: &str = "graphene_core::ops::PassthroughNode"; + +/// The default area, a square 1000 px across centered at (500, 500), and its resolution of one pixel per px. +const DEFAULT_TRANSFORM: [f64; 6] = [1000., 0., 0., 1000., 500., 500.]; +const DEFAULT_RESOLUTION: [f64; 2] = [1000., 1000.]; + +/// A translation by half a unit, which moves a unit square anchored at its corner to one centered on the origin. +const CORNER_TO_CENTER: [f64; 6] = [1., 0., 0., 1., 0.5, 0.5]; + +/// Frozen mirror of the `TaggedValue` variants this migration reads and writes. +#[derive(Serialize, Deserialize)] +enum Tagged { + DVec2([f64; 2]), + DAffine2([f64; 6]), + Footprint(Footprint), +} + +/// Frozen mirror of the removed `Footprint` value, leaving out the render quality 'Rasterize' ignored. +#[derive(Serialize, Deserialize)] +struct Footprint { + transform: [f64; 6], + resolution: [u32; 2], +} + +/// 'Rasterize' takes its footprint's area as a transform placing a unit square centered on its origin, rather than anchored at its corner, +/// then its resolution. A 'Footprint Value' node feeding it, directly or through reroutes, hands over its own inputs and goes once nothing +/// else reads it. Any other wire can't be read before it runs, so it leaves the defaults, shown in the graph. +#[migration("graphene_std::platform_application_io::RasterizeNode"@1 => @2)] +pub fn rasterize_v1(node: &Node, graph: &Graph, inputs: &mut Inputs, upstream: &mut Upstream) -> Result<(), MigrationError> { + let Some(footprint) = node.inputs().get(FOOTPRINT as usize) else { + return Err(MigrationError::invariant("Rasterize has a Footprint input")); + }; + let footprint = through_reroutes(*graph, &footprint.input); + + let (transform, resolution) = match footprint { + NodeInput::Value { exposed, .. } => match literal_of::(footprint) { + Some(Tagged::Footprint(footprint)) => ( + value(Tagged::DAffine2(centered(footprint.transform)), *exposed), + value(Tagged::DVec2(footprint.resolution.map(f64::from)), *exposed), + ), + _ => defaults(*exposed), + }, + NodeInput::Node { id, index: 0 } if graph.declaration(*id) == Some(decl!("math_nodes::FootprintValueNode"@1)) => { + let parameters = graph.node(*id).map(|footprint_value| footprint_value.inputs()).and_then(|slots| Some((slots.get(1)?, slots.get(2)?))); + let Some((transform, resolution)) = parameters else { + return Err(MigrationError::invariant("Footprint Value has Transform and Resolution inputs")); + }; + + // Each Rasterize node it feeds takes over its inputs, so it's only needed by whatever else reads it + let readers = graph.consumers(OutputConnector { node: *id, output: 0 }); + let only_feeds_rasterize = readers + .iter() + .all(|reader| matches!(reader, InputConnector::Node { node, input: FOOTPRINT } if graph.declaration(*node) == Some(RASTERIZE))); + if only_feeds_rasterize { + upstream.remove_node(*id); + } + + let multiply = decl!("math_nodes::MultiplyNode"@1); + (centered_transform_input(&transform.input, multiply, upstream), resolution.input.clone()) + } + _ => defaults(true), + }; + + inputs.set(FOOTPRINT, transform); + inputs.insert(FOOTPRINT + 1, resolution); + Ok(()) +} + +/// Where `input` reads from past any 'Passthrough' nodes rerouting it, which pass their content along unchanged. +fn through_reroutes<'a>(graph: Graph<'a>, mut input: &'a NodeInput) -> &'a NodeInput { + let mut visited = HashSet::new(); + + // A cycle of reroutes leads nowhere else, so revisiting one ends the walk + while let NodeInput::Node { id, index: 0 } = input + && visited.insert(*id) + && graph.declaration(*id).is_some_and(|declaration| declaration.identifier == PASSTHROUGH) + && let Some(content) = graph.node(*id).and_then(|node| node.inputs().first()) + { + input = &content.input; + } + + input +} + +/// The area transform from a 'Footprint Value' node's transform input, through a `multiply` node centering its unit square if it's wired. +fn centered_transform_input(transform: &NodeInput, multiply: Declaration, upstream: &mut Upstream) -> NodeInput { + match transform { + NodeInput::Value { exposed, .. } => match literal_of::(transform) { + Some(Tagged::DAffine2(transform)) => value(Tagged::DAffine2(centered(transform)), *exposed), + _ => value(Tagged::DAffine2(DEFAULT_TRANSFORM), *exposed), + }, + wire => { + let multiply = upstream.add_node(NewNode { + declaration: multiply, + inputs: vec![wire.clone(), literal(Tagged::DAffine2(CORNER_TO_CENTER))], + }); + NodeInput::Node { id: multiply, index: 0 } + } + } +} + +/// The transform placing a unit square centered on its origin over the one `transform` places anchored at its corner, which is `transform` +/// followed by a translation of half a unit, computed in the order a `DAffine2` product computes it. +fn centered([x_axis_x, x_axis_y, y_axis_x, y_axis_y, translation_x, translation_y]: [f64; 6]) -> [f64; 6] { + [ + x_axis_x, + x_axis_y, + y_axis_x, + y_axis_y, + x_axis_x * 0.5 + y_axis_x * 0.5 + translation_x, + x_axis_y * 0.5 + y_axis_y * 0.5 + translation_y, + ] +} + +fn defaults(exposed: bool) -> (NodeInput, NodeInput) { + (value(Tagged::DAffine2(DEFAULT_TRANSFORM), exposed), value(Tagged::DVec2(DEFAULT_RESOLUTION), exposed)) +} + +fn value(value: Tagged, exposed: bool) -> NodeInput { + NodeInput::Value { value: encode(&value), exposed } +} + +#[cfg(test)] +mod tests { + use super::*; + use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo}; + + const FOOTPRINT_VALUE: Declaration = decl!("math_nodes::FootprintValueNode"@1); + + fn contract() -> SourceContract { + SourceContract::new(3, |random, slot| match slot { + 1 => literal(Tagged::Footprint(Footprint { + transform: [random.below(10) as f64, 0., 0., random.below(10) as f64, random.below(10) as f64, random.below(10) as f64], + resolution: [random.below(10) as u32, random.below(10) as u32], + })), + _ => literal(random.below(10) as f64), + }) + } + + /// Rasterize's inputs with `footprint` between its artwork and its executor. + fn rasterize_inputs(footprint: NodeInput) -> Vec { + vec![literal(0.), footprint, NodeInput::Scope("wgpu-executor".into())] + } + + /// Rasterize's migrated inputs with `transform` and `resolution` between its artwork and its executor. + fn migrated_inputs(transform: NodeInput, resolution: NodeInput) -> Vec { + vec![literal(0.), transform, resolution, NodeInput::Scope("wgpu-executor".into())] + } + + fn footprint_value_inputs(transform: NodeInput, resolution: NodeInput) -> Vec { + vec![literal(()), transform, resolution] + } + + #[test] + fn rewrites_history() { + check_commutation(&RasterizeV1, &contract()); + check_undo(&RasterizeV1, &contract()); + } + + #[test] + fn a_footprint_becomes_the_transform_centered_on_its_area_and_its_resolution() { + // The 64 by 32 pixel footprint over the 500 by 250 px rectangle from (-20, 40) + let footprint = Footprint { + transform: [500., 0., 0., 250., -20., 40.], + resolution: [64, 32], + }; + + let mut fixture = Fixture::new(&RasterizeV1); + let rasterize = fixture.add(RASTERIZE, rasterize_inputs(literal(Tagged::Footprint(footprint)))); + let migrated = fixture.migrate(&RasterizeV1).unwrap(); + + let expected = migrated_inputs(literal(Tagged::DAffine2([500., 0., 0., 250., 230., 165.])), literal(Tagged::DVec2([64., 32.]))); + assert_eq!(fixture.declaration_of(&migrated, rasterize), Some(decl!("graphene_std::platform_application_io::RasterizeNode"@2))); + assert_eq!(fixture.inputs(&migrated, rasterize), expected); + } + + #[test] + fn the_default_footprint_becomes_the_default_area_and_resolution() { + let footprint = Footprint { + transform: [1000., 0., 0., 1000., 0., 0.], + resolution: [1000, 1000], + }; + + let mut fixture = Fixture::new(&RasterizeV1); + let rasterize = fixture.add(RASTERIZE, rasterize_inputs(literal(Tagged::Footprint(footprint)))); + let migrated = fixture.migrate(&RasterizeV1).unwrap(); + + let (transform, resolution) = defaults(false); + assert_eq!(fixture.inputs(&migrated, rasterize), migrated_inputs(transform, resolution)); + } + + #[test] + fn a_footprint_value_node_hands_over_its_inputs_and_goes() { + let transform = literal(Tagged::DAffine2([300., 0., 0., 200., 10., 20.])); + let mut fixture = Fixture::new(&RasterizeV1); + let resolution_source = fixture.add(decl!("migration_testing::consumer"@1), Vec::new()); + let resolution = NodeInput::Node { id: resolution_source, index: 0 }; + let footprint_value = fixture.add(FOOTPRINT_VALUE, footprint_value_inputs(transform, resolution.clone())); + let first = fixture.add(RASTERIZE, rasterize_inputs(NodeInput::Node { id: footprint_value, index: 0 })); + let second = fixture.add(RASTERIZE, rasterize_inputs(NodeInput::Node { id: footprint_value, index: 0 })); + let migrated = fixture.migrate(&RasterizeV1).unwrap(); + + let expected = migrated_inputs(literal(Tagged::DAffine2([300., 0., 0., 200., 160., 120.])), resolution); + assert_eq!(fixture.inputs(&migrated, first), expected); + assert_eq!(fixture.inputs(&migrated, second), expected); + assert_eq!(fixture.declaration_of(&migrated, footprint_value), None, "nothing else reads the Footprint Value node"); + } + + #[test] + fn a_footprint_value_node_hands_over_its_inputs_through_reroutes() { + let transform = literal(Tagged::DAffine2([300., 0., 0., 200., 10., 20.])); + let resolution = literal(Tagged::DVec2([30., 20.])); + let mut fixture = Fixture::new(&RasterizeV1); + let footprint_value = fixture.add(FOOTPRINT_VALUE, footprint_value_inputs(transform, resolution.clone())); + let first_reroute = fixture.add(decl!("graphene_core::ops::PassthroughNode"@1), vec![NodeInput::Node { id: footprint_value, index: 0 }]); + let second_reroute = fixture.add(decl!("graphene_core::ops::PassthroughNode"@2), vec![NodeInput::Node { id: first_reroute, index: 0 }]); + let rasterize = fixture.add(RASTERIZE, rasterize_inputs(NodeInput::Node { id: second_reroute, index: 0 })); + let migrated = fixture.migrate(&RasterizeV1).unwrap(); + + let expected = migrated_inputs(literal(Tagged::DAffine2([300., 0., 0., 200., 160., 120.])), resolution); + assert_eq!(fixture.inputs(&migrated, rasterize), expected); + assert_eq!( + fixture.declaration_of(&migrated, footprint_value), + Some(FOOTPRINT_VALUE), + "the reroute still reads the Footprint Value node" + ); + } + + #[test] + fn a_wired_footprint_value_transform_reaches_the_area_through_a_multiply_node() { + let mut fixture = Fixture::new(&RasterizeV1); + let transform_source = fixture.add(decl!("migration_testing::consumer"@1), Vec::new()); + let wire = NodeInput::Node { id: transform_source, index: 0 }; + let footprint_value = fixture.add(FOOTPRINT_VALUE, footprint_value_inputs(wire.clone(), literal(Tagged::DVec2([30., 20.])))); + let rasterize = fixture.add(RASTERIZE, rasterize_inputs(NodeInput::Node { id: footprint_value, index: 0 })); + let migrated = fixture.migrate(&RasterizeV1).unwrap(); + + let inputs = fixture.inputs(&migrated, rasterize); + let NodeInput::Node { id: multiply, index: 0 } = inputs[1] else { + panic!("the area should be wired from a Multiply node"); + }; + assert_eq!(inputs, migrated_inputs(NodeInput::Node { id: multiply, index: 0 }, literal(Tagged::DVec2([30., 20.])))); + assert_eq!(fixture.declaration_of(&migrated, multiply), Some(decl!("math_nodes::MultiplyNode"@1))); + assert_eq!(fixture.inputs(&migrated, multiply), [wire, literal(Tagged::DAffine2(CORNER_TO_CENTER))]); + } + + #[test] + fn a_footprint_value_node_read_elsewhere_stays() { + let mut fixture = Fixture::new(&RasterizeV1); + let footprint_value = fixture.add(FOOTPRINT_VALUE, footprint_value_inputs(literal(Tagged::DAffine2(CORNER_TO_CENTER)), literal(Tagged::DVec2([1., 1.])))); + fixture.add(RASTERIZE, rasterize_inputs(NodeInput::Node { id: footprint_value, index: 0 })); + fixture.export(NodeInput::Node { id: footprint_value, index: 0 }); + let migrated = fixture.migrate(&RasterizeV1).unwrap(); + + assert_eq!(fixture.declaration_of(&migrated, footprint_value), Some(FOOTPRINT_VALUE)); + } + + #[test] + fn any_other_wire_leaves_the_defaults_shown_in_the_graph() { + let mut fixture = Fixture::new(&RasterizeV1); + let source = fixture.add(decl!("migration_testing::consumer"@1), Vec::new()); + let rasterize = fixture.add(RASTERIZE, rasterize_inputs(NodeInput::Node { id: source, index: 0 })); + let migrated = fixture.migrate(&RasterizeV1).unwrap(); + + let (transform, resolution) = defaults(true); + assert_eq!(fixture.inputs(&migrated, rasterize), migrated_inputs(transform, resolution)); + } +} diff --git a/editor/src/messages/portfolio/document/node_graph/document_node_definitions.rs b/editor/src/messages/portfolio/document/node_graph/document_node_definitions.rs index 92b137e011..08e3ec3428 100644 --- a/editor/src/messages/portfolio/document/node_graph/document_node_definitions.rs +++ b/editor/src/messages/portfolio/document/node_graph/document_node_definitions.rs @@ -1684,19 +1684,18 @@ mod test { #[test] fn rasterize_defaults_to_a_1000_px_square_at_full_resolution() { - use glam::{DAffine2, UVec2}; + use glam::DAffine2; use graph_craft::document::value::TaggedValue; use graphene_std::platform_application_io::rasterize; let definition = super::resolve_proto_node_definition(&rasterize::IDENTIFIER).expect("Rasterize should have a definition"); - let footprint = definition.node_template.input(rasterize::FootprintInput).and_then(|input| input.as_value()); + let transform = definition.node_template.input(rasterize::TransformInput).and_then(|input| input.as_value()); + let resolution = definition.node_template.input(rasterize::ResolutionInput).and_then(|input| input.as_value()); - let expected = Footprint { - transform: DAffine2::from_scale(DVec2::splat(1000.)), - resolution: UVec2::splat(1000), - ..Default::default() - }; - assert_eq!(footprint, Some(&TaggedValue::Footprint(expected))); + // The square from (0, 0) to (1000, 1000) + let expected_transform = DAffine2::from_scale_angle_translation(DVec2::splat(1000.), 0., DVec2::splat(500.)); + assert_eq!(transform, Some(&TaggedValue::DAffine2(expected_transform))); + assert_eq!(resolution, Some(&TaggedValue::DVec2(DVec2::splat(1000.)))); } // The executor input the compiler fills in has no type yet, which mustn't rule out every implementation diff --git a/editor/src/messages/portfolio/document/node_graph/node_inspector.rs b/editor/src/messages/portfolio/document/node_graph/node_inspector.rs index e7f25e8e56..7bcdc3e7af 100644 --- a/editor/src/messages/portfolio/document/node_graph/node_inspector.rs +++ b/editor/src/messages/portfolio/document/node_graph/node_inspector.rs @@ -31,7 +31,7 @@ use graphene_std::raster_types::{CPU, GPU, Image, Raster}; use graphene_std::text::{Font, TextAlign}; use graphene_std::text_nodes::{StringCapitalization, TextDenomination}; use graphene_std::transfer_curve::TransferCurve; -use graphene_std::transform::{Footprint, ReferencePoint, ScaleType, Transform}; +use graphene_std::transform::{ReferencePoint, ScaleType, Transform}; use graphene_std::vector::misc::BooleanOperation; use graphene_std::vector::misc::{ ArcType, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod, WeldMethod, @@ -421,7 +421,6 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type, // ============ Some(x) if id_is::(x) => font_widget(default_info), Some(x) if id_is::(x) => transfer_curve_widget(default_info), - Some(x) if id_is::(x) => footprint_widget(default_info, &mut extra_widgets), Some(x) if id_is::>(x) => vector_modification_widget(default_info).into(), Some(x) if id_is::>(x) => image_data_widget(default_info).into(), Some(x) if id_is::(x) => resource_widget(default_info, Vec::new()).into(), @@ -677,142 +676,6 @@ pub fn image_data_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Vec) -> LayoutGroup { - let ParameterWidgetsInfo { document_node, node_id, index, .. } = parameter_widgets_info; - - let mut location_widgets = start_widgets(¶meter_widgets_info); - location_widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance()); - - let mut scale_widgets = vec![TextLabel::new("").widget_instance()]; - add_blank_assist(&mut scale_widgets); - scale_widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance()); - - let mut resolution_widgets = vec![TextLabel::new("").widget_instance()]; - add_blank_assist(&mut resolution_widgets); - resolution_widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance()); - - let Some(document_node) = document_node else { return LayoutGroup::default() }; - let Some(input) = document_node.inputs.get(index) else { - log::warn!("A widget failed to be built because its node's input index is invalid."); - return Vec::new().into(); - }; - - if let Some(&TaggedValue::Footprint(footprint)) = input.as_non_exposed_value() { - let top_left = footprint.transform.transform_point2(DVec2::ZERO); - let bounds = footprint.scale(); - let oversample = footprint.resolution.as_dvec2() / bounds; - - location_widgets.extend_from_slice(&[ - NumberInput::new(Some(top_left.x)) - .label("X") - .unit(" px") - .on_update(parameter_widgets_info.update_value(move |x: &NumberInput| { - let (offset, scale) = { - let diff = DVec2::new(top_left.x - x.value.unwrap_or_default(), 0.); - (top_left - diff, bounds) - }; - - let footprint = Footprint { - transform: DAffine2::from_scale_angle_translation(scale, 0., offset), - resolution: (oversample * scale).as_uvec2(), - ..footprint - }; - - TaggedValue::Footprint(footprint) - })) - .on_commit(commit_value) - .widget_instance(), - Separator::new(SeparatorStyle::Related).widget_instance(), - NumberInput::new(Some(top_left.y)) - .label("Y") - .unit(" px") - .on_update(parameter_widgets_info.update_value(move |x: &NumberInput| { - let (offset, scale) = { - let diff = DVec2::new(0., top_left.y - x.value.unwrap_or_default()); - (top_left - diff, bounds) - }; - - let footprint = Footprint { - transform: DAffine2::from_scale_angle_translation(scale, 0., offset), - resolution: (oversample * scale).as_uvec2(), - ..footprint - }; - - TaggedValue::Footprint(footprint) - })) - .on_commit(commit_value) - .widget_instance(), - ]); - - scale_widgets.extend_from_slice(&[ - NumberInput::new(Some(bounds.x)) - .label("W") - .unit(" px") - .on_update(update_value_at_index( - move |x: &NumberInput| { - let (offset, scale) = (top_left, DVec2::new(x.value.unwrap_or_default(), bounds.y)); - - let footprint = Footprint { - transform: DAffine2::from_scale_angle_translation(scale, 0., offset), - resolution: (oversample * scale).as_uvec2(), - ..footprint - }; - - TaggedValue::Footprint(footprint) - }, - node_id, - index, - )) - .on_commit(commit_value) - .widget_instance(), - Separator::new(SeparatorStyle::Related).widget_instance(), - NumberInput::new(Some(bounds.y)) - .label("H") - .unit(" px") - .on_update(update_value_at_index( - move |x: &NumberInput| { - let (offset, scale) = (top_left, DVec2::new(bounds.x, x.value.unwrap_or_default())); - - let footprint = Footprint { - transform: DAffine2::from_scale_angle_translation(scale, 0., offset), - resolution: (oversample * scale).as_uvec2(), - ..footprint - }; - - TaggedValue::Footprint(footprint) - }, - node_id, - index, - )) - .on_commit(commit_value) - .widget_instance(), - ]); - - resolution_widgets.push( - NumberInput::new(Some((footprint.resolution.as_dvec2() / bounds).x * 100.)) - .label("Resolution") - .mode_range() - .min(0.) - .range_min(Some(1.)) - .range_max(Some(100.)) - .unit("%") - .on_update(parameter_widgets_info.update_value(move |x: &NumberInput| { - let resolution = (bounds * x.value.unwrap_or(100.) / 100.).as_uvec2().max((1, 1).into()).min((4000, 4000).into()); - - let footprint = Footprint { resolution, ..footprint }; - TaggedValue::Footprint(footprint) - })) - .on_commit(commit_value) - .widget_instance(), - ); - } - - let widgets = [LayoutGroup::row(location_widgets), LayoutGroup::row(scale_widgets), LayoutGroup::row(resolution_widgets)]; - let (last, rest) = widgets.split_last().expect("Footprint widget should return multiple rows"); - *extra_widgets = rest.to_vec(); - last.clone() -} - /// The X, Y, rotation, W, and H of a transform input. W and H show as a multiplier, or with the parameter's `size_unit` (like " px") where it declares one, for a transform scaling a shape of unit size. pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, size_unit: Option<&str>, extra_widgets: &mut Vec) -> LayoutGroup { let ParameterWidgetsInfo { document_node, node_id, index, .. } = parameter_widgets_info; diff --git a/editor/src/messages/portfolio/document_migration.rs b/editor/src/messages/portfolio/document_migration.rs index aea4c33bf9..4a7ff7ce85 100644 --- a/editor/src/messages/portfolio/document_migration.rs +++ b/editor/src/messages/portfolio/document_migration.rs @@ -6,7 +6,7 @@ use crate::messages::portfolio::document::node_graph::document_node_definitions: use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, NodeTemplate, NodeTemplateImplementation, OutputConnector}; use crate::messages::prelude::DocumentMessageHandler; -use glam::{DVec2, IVec2}; +use glam::{DAffine2, DVec2, IVec2}; use graph_craft::application_io::resource::{DataSource, Resource, ResourceHash, ResourceId}; use graph_craft::document::DocumentNode; use graph_craft::document::{DocumentNodeImplementation, NodeInput, value::TaggedValue}; @@ -297,10 +297,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[ node: graphene_std::math_nodes::floor::IDENTIFIER, aliases: &["graphene_math_nodes::FloorNode", "graphene_core::ops::FloorNode"], }, - NodeReplacement { - node: graphene_std::math_nodes::footprint_value::IDENTIFIER, - aliases: &["graphene_math_nodes::FootprintValueNode", "graphene_core::ops::FootprintValueNode"], - }, NodeReplacement { node: graphene_std::math_nodes::gradient_spread::IDENTIFIER, aliases: &["math_nodes::SpreadMethodNode"], @@ -1827,6 +1823,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_ for (node_id, node, network_path) in &nodes { migrate_node(node_id, node, network_path, document, reset_node_definitions_on_open); } + remove_footprint_value_nodes(document); create_layer_stacks(document); follow_segments_turned_on_load(document); @@ -2185,6 +2182,100 @@ fn read_noise_through_gamma_correction(document: &mut DocumentMessageHandler, no Some(()) } +/// Whether a node is a removed 'Footprint Value' node, under any identifier it had. +fn is_footprint_value(node: &DocumentNode) -> bool { + matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if identifier.as_str().ends_with("::FootprintValueNode")) +} + +/// Sets an upgraded Rasterize node's area transform and resolution from the footprint it took, stored or from a 'Footprint Value' node (even +/// through reroutes) whose inputs it takes over. Any other wire can't be read before it runs, so it leaves the defaults, shown in the graph. +fn set_rasterize_area_from_footprint(document: &mut DocumentMessageHandler, node_id: &NodeId, network_path: &[NodeId], footprint: &NodeInput) -> Option<()> { + use graphene_std::math_nodes::multiply; + + // A footprint's transform placed a unit square anchored at its corner, where the area's is centered on its origin + let corner_to_center = DAffine2::from_translation(DVec2::splat(0.5)); + let (transform_connector, resolution_connector) = (InputConnector::node_at_index(*node_id, 1), InputConnector::node_at_index(*node_id, 2)); + + // Reroutes pass the footprint along unchanged, and a cycle of them leads nowhere else + let mut footprint = footprint.clone(); + let mut visited = HashSet::new(); + while let NodeInput::Node { node_id: source, output_index: 0 } = footprint + && visited.insert(source) + && let Some(reroute) = document.network_interface.document_node(&source, network_path) + && matches!(&reroute.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::ops::passthrough::IDENTIFIER) + && let Some(content) = reroute.inputs.first() + { + footprint = content.clone(); + } + + match &footprint { + // A stored footprint loads as its transform's six numbers then its resolution's two + NodeInput::Value { tagged_value, exposed } => { + let TaggedValue::Numbers(numbers) = &**tagged_value else { return None }; + let &[x_axis_x, x_axis_y, y_axis_x, y_axis_y, translation_x, translation_y, width, height] = numbers.as_slice() else { + return None; + }; + + let transform = DAffine2::from_cols_array(&[x_axis_x, x_axis_y, y_axis_x, y_axis_y, translation_x, translation_y]) * corner_to_center; + let resolution = DVec2::new(width, height); + document + .network_interface + .set_input(&transform_connector, NodeInput::value(TaggedValue::DAffine2(transform), *exposed), network_path); + document + .network_interface + .set_input(&resolution_connector, NodeInput::value(TaggedValue::DVec2(resolution), *exposed), network_path); + } + NodeInput::Node { node_id: source, output_index: 0 } if document.network_interface.document_node(source, network_path).is_some_and(is_footprint_value) => { + let footprint_value = document.network_interface.document_node(source, network_path)?; + let (transform, resolution) = (footprint_value.inputs.get(1)?.clone(), footprint_value.inputs.get(2)?.clone()); + document.network_interface.set_input(&resolution_connector, resolution, network_path); + + match transform { + NodeInput::Value { tagged_value, exposed } => { + let &TaggedValue::DAffine2(transform) = &*tagged_value else { return None }; + let transform = NodeInput::value(TaggedValue::DAffine2(transform * corner_to_center), exposed); + document.network_interface.set_input(&transform_connector, transform, network_path); + } + // A wired transform goes through a Multiply node moving its unit square's anchor to the center + wire => { + document.network_interface.set_input(&transform_connector, wire, network_path); + + let multiply_id = NodeId::new(); + document + .network_interface + .insert_node(multiply_id, resolve_proto_node_type(multiply::IDENTIFIER)?.default_node_template(), network_path); + let multiplicand = NodeInput::value(TaggedValue::DAffine2(corner_to_center), false); + document.network_interface.set_input(&InputConnector::node_at_index(multiply_id, 1), multiplicand, network_path); + document.network_interface.insert_node_before_input(&multiply_id, &transform_connector, network_path); + } + } + } + _ => { + for connector in [transform_connector, resolution_connector] { + let default = document.network_interface.input_from_connector(&connector, network_path)?.as_value()?.clone(); + document.network_interface.set_input(&connector, NodeInput::value(default, true), network_path); + } + } + } + + Some(()) +} + +/// Deletes every 'Footprint Value' node once the Rasterize nodes it fed have taken over its inputs, disconnecting whatever else it fed. +fn remove_footprint_value_nodes(document: &mut DocumentMessageHandler) { + let footprint_value_nodes: Vec<(NodeId, Vec)> = document + .network_interface + .document_network() + .recursive_nodes() + .filter(|(_, node, _)| is_footprint_value(node)) + .map(|(node_id, _, path)| (*node_id, path)) + .collect(); + + for (node_id, network_path) in footprint_value_nodes { + document.network_interface.delete_nodes(vec![node_id], false, &network_path); + } +} + /// Converts a legacy stroke dash input (a `List`, single `f64`, or comma/space separated `String`) to the `DashPattern` value type. fn migrate_dash_input(input: &NodeInput) -> Option { let NodeInput::Value { tagged_value, exposed } = input else { return None }; @@ -3165,6 +3256,16 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId], inputs_count = 2; } + // Rasterize, like the wrapper network collapsed into it above, took a footprint where it now takes an area transform and a resolution + if reference == DefinitionIdentifier::ProtoNode(graphene_std::platform_application_io::rasterize::IDENTIFIER) && matches!(inputs_count, 2 | 3) { + let mut node_template = resolve_document_node_type(&reference)?.default_node_template(); + document.network_interface.replace_implementation(node_id, network_path, &mut node_template); + document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?; + document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), node.inputs[0].clone(), network_path); + set_rasterize_area_from_footprint(document, node_id, network_path, &node.inputs[1]); + inputs_count = 4; + } + // The removed "Brightness/Contrast Classic" node had no Use Classic input, so its three inputs become the unified node with the toggle on if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster::brightness_contrast::IDENTIFIER) && inputs_count == 3 { let mut node_template = resolve_document_node_type(&reference)?.default_node_template(); @@ -4732,11 +4833,8 @@ mod tests { let node_id = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(rasterize::IDENTIFIER), 0, 0).await; let document = editor.active_document_mut(); - let footprint = Footprint { - resolution: glam::UVec2::new(64, 32), - ..Default::default() - }; - let footprint_input = NodeInput::value(TaggedValue::Footprint(footprint), false); + // A footprint can't be written any more, so a placeholder value stands in for it until the document is serialized + let placeholder = NodeInput::value(TaggedValue::String("footprint placeholder".into()), false); // Save the node as the network that drew into a browser canvas, which took only the artwork and footprint let canvas_network = NodeNetworkTemplate { @@ -4754,27 +4852,111 @@ mod tests { ..Default::default() }; let mut legacy = NodeTemplate { - inputs: vec![NodeInput::type_default(list!(graphic_types::Graphic), true), footprint_input.clone()], + inputs: vec![NodeInput::type_default(list!(graphic_types::Graphic), true), placeholder], implementation: NodeTemplateImplementation::Network(canvas_network), ..Default::default() }; document.network_interface.replace_implementation(&node_id, &[], &mut legacy); document.network_interface.replace_inputs(&node_id, &[], &mut legacy); document.network_interface.set_reference(&node_id, &[], Some("Rasterize".into())); + + // A 64 by 32 pixel footprint over the 500 by 250 px rectangle from (-20, 40) + let placeholder = r#"{"String":"footprint placeholder"}"#; + let footprint = r#"{"Footprint":{"transform":[500.0,0.0,0.0,250.0,-20.0,40.0],"resolution":[64,32],"quality":"Full"}}"#; let serialized = document.serialize_document(); + assert!(serialized.contains(placeholder), "the placeholder should be serialized as expected"); + let serialized = serialized.replace(placeholder, footprint); let opened = load_legacy_document(serialized, &HashMapResourceStorage::new(), false).expect("the document should open"); let interface = &opened.network_interface; assert_eq!(interface.reference(&node_id, &[]), Some(DefinitionIdentifier::ProtoNode(rasterize::IDENTIFIER))); + + // The area's unit square is centered on its origin, so its translation is the rectangle's center + let area = DAffine2::from_scale_angle_translation(DVec2::new(500., 250.), 0., DVec2::new(230., 165.)); + let input = |index| interface.input_from_connector(&InputConnector::node_at_index(node_id, index), &[]).cloned(); + assert_eq!(input(1), Some(NodeInput::value(TaggedValue::DAffine2(area), false)), "the footprint should cover the same area"); assert_eq!( - interface.input_from_connector(&InputConnector::node_at_index(node_id, 1), &[]), - Some(&footprint_input), - "the footprint should carry over" + input(2), + Some(NodeInput::value(TaggedValue::DVec2(DVec2::new(64., 32.)), false)), + "the footprint should keep its resolution" ); + let definition_inputs = resolve_proto_node_type(rasterize::IDENTIFIER).expect("Rasterize should have a definition").node_template.inputs.len(); assert_eq!(interface.number_of_inputs(&node_id, &[]), definition_inputs, "the node should gain the inputs the compiler fills in"); } + #[tokio::test] + async fn opening_footprint_value_nodes_folds_them_into_the_rasterize_nodes_they_fed() { + use crate::messages::portfolio::document_storage_io::load_legacy_document; + use crate::test_utils::test_prelude::*; + use graph_craft::application_io::resource::HashMapResourceStorage; + use graphene_std::platform_application_io::rasterize; + + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let literal_rasterize = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(rasterize::IDENTIFIER), 0, 0).await; + let wired_rasterize = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(rasterize::IDENTIFIER), 0, 10).await; + let transform_source = editor + .create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER), -20, 10) + .await; + let reroute = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER), -5, 10).await; + let document = editor.active_document_mut(); + + let footprint_transform = DAffine2::from_scale_angle_translation(DVec2::new(300., 200.), 0., DVec2::new(10., 20.)); + let footprint_value = NodeTemplate { + implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new("math_nodes::FootprintValueNode")), + inputs: vec![ + NodeInput::value(TaggedValue::None, false), + NodeInput::value(TaggedValue::DAffine2(footprint_transform), false), + NodeInput::value(TaggedValue::DVec2(DVec2::new(30., 20.)), false), + ], + ..Default::default() + }; + let (literal_footprint, wired_footprint) = (NodeId(1), NodeId(2)); + document.network_interface.insert_node(literal_footprint, footprint_value.clone(), &[]); + document.network_interface.insert_node(wired_footprint, footprint_value, &[]); + document + .network_interface + .set_input(&InputConnector::node_at_index(wired_footprint, 1), NodeInput::node(transform_source, 0), &[]); + document + .network_interface + .set_input(&InputConnector::node_at_index(reroute, 0), NodeInput::node(wired_footprint, 0), &[]); + + // Each Rasterize node as saved before its area and resolution, taking the artwork, the footprint, and the executor + let definition = resolve_proto_node_type(rasterize::IDENTIFIER).expect("Rasterize should have a definition"); + let executor = definition.node_template.inputs.last().cloned().expect("Rasterize should take the executor"); + for (rasterize_node, footprint_node) in [(literal_rasterize, literal_footprint), (wired_rasterize, reroute)] { + let mut old_inputs = NodeTemplate { + inputs: vec![NodeInput::type_default(list!(graphic_types::Graphic), true), NodeInput::node(footprint_node, 0), executor.clone()], + ..Default::default() + }; + document.network_interface.replace_inputs(&rasterize_node, &[], &mut old_inputs); + } + + let opened = load_legacy_document(document.serialize_document(), &HashMapResourceStorage::new(), false).expect("the document should open"); + let interface = &opened.network_interface; + let input = |node, index| interface.input_from_connector(&InputConnector::node_at_index(node, index), &[]).cloned(); + + assert!(interface.document_node(&literal_footprint, &[]).is_none(), "the Footprint Value node should be removed"); + assert!(interface.document_node(&wired_footprint, &[]).is_none(), "the Footprint Value node should be removed"); + + let corner_to_center = DAffine2::from_translation(DVec2::splat(0.5)); + let resolution = Some(NodeInput::value(TaggedValue::DVec2(DVec2::new(30., 20.)), false)); + assert_eq!( + input(literal_rasterize, 1), + Some(NodeInput::value(TaggedValue::DAffine2(footprint_transform * corner_to_center), false)) + ); + assert_eq!(input(literal_rasterize, 2), resolution); + + // The wired transform reaches the area through a Multiply node centering its unit square + let Some(NodeInput::Node { node_id: multiply, output_index: 0 }) = input(wired_rasterize, 1) else { + panic!("the wired transform should reach the area through a node"); + }; + assert_eq!(input(multiply, 0), Some(NodeInput::node(transform_source, 0))); + assert_eq!(input(multiply, 1), Some(NodeInput::value(TaggedValue::DAffine2(corner_to_center), false))); + assert_eq!(input(wired_rasterize, 2), resolution); + } + #[tokio::test] async fn opening_a_document_with_the_removed_extract_node_turns_it_into_a_passthrough() { use crate::messages::portfolio::document_storage_io::load_legacy_document; diff --git a/frontend/src/icons.ts b/frontend/src/icons.ts index a5ba4599c6..23b61a72c5 100644 --- a/frontend/src/icons.ts +++ b/frontend/src/icons.ts @@ -191,7 +191,6 @@ import NodeFlattenGradient from "/../branding/assets/16x16-nodes/node-flatten-gr import NodeFlattenRaster from "/../branding/assets/16x16-nodes/node-flatten-raster.svg"; import NodeFlattenVector from "/../branding/assets/16x16-nodes/node-flatten-vector.svg"; import NodeFloor from "/../branding/assets/16x16-nodes/node-floor.svg"; -import NodeFootprintValue from "/../branding/assets/16x16-nodes/node-footprint-value.svg"; import NodeFormatJson from "/../branding/assets/16x16-nodes/node-format-json.svg"; import NodeFormatNumber from "/../branding/assets/16x16-nodes/node-format-number.svg"; import NodeGammaCorrection from "/../branding/assets/16x16-nodes/node-gamma-correction.svg"; @@ -485,7 +484,6 @@ export const ICON_16X16_NODES = { NodeFlattenRaster: { svg: NodeFlattenRaster, size: 16 }, NodeFlattenVector: { svg: NodeFlattenVector, size: 16 }, NodeFloor: { svg: NodeFloor, size: 16 }, - NodeFootprintValue: { svg: NodeFootprintValue, size: 16 }, NodeFormatJson: { svg: NodeFormatJson, size: 16 }, NodeFormatNumber: { svg: NodeFormatNumber, size: 16 }, NodeGammaCorrection: { svg: NodeGammaCorrection, size: 16 }, diff --git a/node-graph/graph-craft/src/document/value.rs b/node-graph/graph-craft/src/document/value.rs index 1e363a782c..f5ef484447 100644 --- a/node-graph/graph-craft/src/document/value.rs +++ b/node-graph/graph-craft/src/document/value.rs @@ -5,7 +5,6 @@ use brush_nodes::{BrushCache, Stroke}; use core_types::color::SRGBA8; use core_types::list::{Item, List, NodeIdPath}; use core_types::transfer_curve::TransferCurve; -use core_types::transform::Footprint; use core_types::{CacheHash, Color, ContextModification, MemoHash, Node, Poll, RuntimeHandle, SourceId, Type, TypeDescriptor}; pub use dyn_any::StaticType; pub use glam::{DAffine2, DVec2, IVec2, UVec2}; @@ -75,7 +74,7 @@ macro_rules! tagged_value { TypeDefault(Type), /// Stored compactly as a `Vec`, materializes as `List` at runtime via `to_dynany`/`to_any`. Aliases recover legacy on-disk shapes. #[serde(deserialize_with = "core_types::misc::migrate_to_numbers")] // TODO: Eventually remove this document upgrade code - #[serde(alias = "F64Array", alias = "F64Table", alias = "VecF64", alias = "VecF32", alias = "F64Array4")] + #[serde(alias = "F64Array", alias = "F64Table", alias = "VecF64", alias = "VecF32", alias = "F64Array4", alias = "Footprint")] Numbers(Vec), /// Stored compactly as a `Vec` of dash lengths, materializes as an `Item` at runtime via `to_dynany`/`to_any`. DashPattern(Vec), @@ -514,7 +513,6 @@ tagged_value! { #[serde(alias = "ColorTable", alias = "OptionalColor", alias = "ColorNotInTable")] Color(Color), Font(Font), - Footprint(Footprint), VectorModification(Box), ImageData(Image), Resource(ResourceId), @@ -706,17 +704,6 @@ impl TaggedValue { Some(DAffine2::from_scale_angle_translation(DVec2::new(width, height), 0., DVec2::new(x, y))) } - // The Inspector's X, Y, W, H, rendered at 100% resolution - fn to_footprint(input: &str) -> Option { - let transform = to_daffine2(input)?; - - Some(Footprint { - transform, - resolution: transform.matrix2.diagonal().as_uvec2(), - ..Default::default() - }) - } - fn to_stroke_align(input: &str) -> Option { let mut choices = input.split("::"); let (first, second) = (choices.next()?.trim(), choices.next()?.trim()); @@ -792,7 +779,6 @@ impl TaggedValue { () if ty == TypeId::of::() => to_color(string).map(TaggedValue::Color)?, () if ty == TypeId::of::() => to_gradient(string).map(|gradient| TaggedValue::GradientRamp(gradient.into()))?, () if ty == TypeId::of::() => to_reference_point(string).map(TaggedValue::ReferencePoint)?, - () if ty == TypeId::of::() => to_footprint(string).map(TaggedValue::Footprint)?, () if ty == TypeId::of::() => to_stroke_align(string).map(TaggedValue::StrokeAlign)?, () if ty == TypeId::of::() => to_blend_mode(string).map(TaggedValue::BlendMode)?, () if ty == TypeId::of::() => to_gradient_spread(string).map(TaggedValue::GradientSpread)?, @@ -1148,20 +1134,6 @@ mod number_default_parsing { assert_eq!(TaggedValue::from_primitive_string("- 1., 2.", &item!(DVec2)), Some(TaggedValue::DVec2(DVec2::new(-1., 2.)))); } - #[test] - fn footprint_defaults_parse_as_x_y_width_height() { - let expected = Footprint { - transform: DAffine2::from_scale_angle_translation(DVec2::new(10_000., 500.), 0., DVec2::new(-50., 20.)), - resolution: glam::UVec2::new(10_000, 500), - ..Default::default() - }; - assert_eq!( - TaggedValue::from_primitive_string("- 50., 20., 10_000., 500.", &item!(Footprint)), - Some(TaggedValue::Footprint(expected)) - ); - assert_eq!(TaggedValue::from_primitive_string("1., 2., 3.", &item!(Footprint)), None); - } - #[test] fn transform_defaults_parse_as_x_y_width_height() { let expected = DAffine2::from_scale_angle_translation(DVec2::new(500., 400.), 0., DVec2::new(250., -20.)); @@ -1303,3 +1275,29 @@ mod retired_numeric_variants { assert_ne!(load(serde_json::json!({ "F32": 2.2 })), TaggedValue::Number(2.2_f32 as f64)); } } + +// TODO: Eventually remove this document upgrade code +#[cfg(test)] +mod retired_footprint_variant { + use super::*; + + #[test] + fn a_footprint_reads_as_its_transform_then_its_resolution() { + let payload = serde_json::json!({ "Footprint": { "transform": [500., 0., 0., 250., -20., 40.], "resolution": [64, 32], "quality": "Full" } }); + let expected = TaggedValue::Numbers(vec![500., 0., 0., 250., -20., 40., 64., 32.]); + + let legacy = deserialize_tagged_value_with_legacy_migration(payload.clone()).expect("The footprint payload should deserialize"); + assert_eq!(*legacy.into_inner(), expected); + + let stored: TaggedValue = serde_json::from_value(payload).expect("The footprint payload should deserialize"); + assert_eq!(stored, expected); + } + + #[test] + fn a_null_in_a_footprint_transform_reads_as_zero() { + let payload = serde_json::json!({ "Footprint": { "transform": [1., 0., 0., 1., null, 0.], "resolution": [64, 32], "quality": "Full" } }); + let loaded: TaggedValue = serde_json::from_value(payload).expect("The footprint payload should deserialize"); + + assert_eq!(loaded, TaggedValue::Numbers(vec![1., 0., 0., 1., 0., 0., 64., 32.])); + } +} diff --git a/node-graph/interpreted-executor/src/node_registry.rs b/node-graph/interpreted-executor/src/node_registry.rs index 77856c61f5..bd8e8b6362 100644 --- a/node-graph/interpreted-executor/src/node_registry.rs +++ b/node-graph/interpreted-executor/src/node_registry.rs @@ -21,7 +21,7 @@ use graphene_std::render_node::RenderIntermediate; use graphene_std::text::{Font, TextAlign}; use graphene_std::text_nodes::{StringCapitalization, TextDenomination}; use graphene_std::transfer_curve::TransferCurve; -use graphene_std::transform::{Footprint, ReferencePoint, ScaleType}; +use graphene_std::transform::{ReferencePoint, ScaleType}; use graphene_std::vector::misc::{ ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod, WeldMethod, @@ -87,7 +87,6 @@ fn node_registry() -> HashMap, input: Context, fn_params: [Context => Item]), async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item]), async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item]), - async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item]), async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item]), async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item]), async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item]), @@ -347,7 +346,6 @@ fn node_registry() -> HashMap>(deserializer: D) -> enum NumbersFormat { Array(Vec), List(LegacyTable), + /// The removed `Footprint` value, stored only by 'Rasterize', for its upgrade to split back into its transform's six numbers then its resolution's two. + Footprint { + transform: [Option; 6], + resolution: [f64; 2], + }, } Ok(match NumbersFormat::deserialize(deserializer)? { NumbersFormat::Array(values) => values, NumbersFormat::List(list) => list.element, + // A `null` saved in place of a NaN or infinite number loads as 0, like elsewhere + NumbersFormat::Footprint { transform, resolution } => transform.into_iter().map(Option::unwrap_or_default).chain(resolution).collect(), }) } diff --git a/node-graph/nodes/gcore/src/animation.rs b/node-graph/nodes/gcore/src/animation.rs index 8ffbb496e5..edf8752b56 100644 --- a/node-graph/nodes/gcore/src/animation.rs +++ b/node-graph/nodes/gcore/src/animation.rs @@ -1,5 +1,4 @@ use core_types::list::{Item, List}; -use core_types::transform::Footprint; use core_types::{CacheHash, CloneVarArgs, Color, Context, Ctx, ExtractAll, ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime, Interrupt, OwnedContextImpl}; use glam::{DAffine2, DVec2}; use graphene_animation::AnimationCurve; @@ -82,7 +81,6 @@ fn step_real_time( Context -> Item, Context -> Item, Context -> Item, - Context -> Item, Context -> Item, Context -> Item, Context -> Item, @@ -130,7 +128,6 @@ fn step_animation_time( Context -> Item, Context -> Item, Context -> Item, - Context -> Item, Context -> Item, Context -> Item, Context -> Item, diff --git a/node-graph/nodes/gcore/src/context_modification.rs b/node-graph/nodes/gcore/src/context_modification.rs index 5667b8be6d..301ca99cd9 100644 --- a/node-graph/nodes/gcore/src/context_modification.rs +++ b/node-graph/nodes/gcore/src/context_modification.rs @@ -1,7 +1,6 @@ use core::f64; use core_types::context::{CloneVarArgs, Context, ContextModification, Ctx, ExtractAll}; use core_types::list::{AttributeValueDyn, Item, List, ListDyn, NodeIdPath}; -use core_types::transform::Footprint; use core_types::{Color, Interrupt, OwnedContextImpl}; use glam::{DAffine2, DVec2}; use graphene_animation::AnimationCurve; @@ -22,7 +21,6 @@ fn context_modification( Context -> Item, Context -> Item, Context -> Item, - Context -> Item, Context -> Item, Context -> Item, Context -> Item, diff --git a/node-graph/nodes/gstd/src/platform_application_io.rs b/node-graph/nodes/gstd/src/platform_application_io.rs index 2ff09c5bb8..345244ac35 100644 --- a/node-graph/nodes/gstd/src/platform_application_io.rs +++ b/node-graph/nodes/gstd/src/platform_application_io.rs @@ -5,7 +5,7 @@ use core_types::math::bbox::Bbox; use core_types::ops::ConvertAsync; use core_types::transform::Footprint; use core_types::{ATTR_EDITOR_MERGED_LAYERS, ATTR_TRANSFORM, NodeError}; -use glam::{DAffine2, UVec2}; +use glam::{DAffine2, DVec2, UVec2}; pub use graph_craft::application_io::resource::{Resource, ResourceHash, ResourceId}; pub use graph_craft::application_io::*; pub use graph_craft::document::value::RenderOutputType; @@ -229,31 +229,46 @@ fn svg_to_graphic(_: impl Ctx, #[name("SVG")] svg: Item) -> Result, - /// The area of the document to render, and the resolution to render it at. - #[default(0., 0., 1000., 1000.)] - footprint: Item, + /// Places the rectangle the image covers, measured from the origin of the content's local coordinate space. By default, it's a square 1000 px across centered at (500, 500). + #[unit(" px")] + #[default(500., 500., 1000., 1000.)] + transform: Item, + /// The number of pixels across and down the image, spread over the rectangle whatever its size. By default, it's 1000 by 1000, one pixel per px of the default rectangle. + #[unit(" px")] + #[hard(1..)] + #[default(1000., 1000.)] + resolution: Item, #[scope(wgpu_executor::IDENTIFIER)] executor: Item<::wgpu_executor::WgpuExecutor>, ) -> Result>, NodeError> { - rasterize_with_vello(data, footprint.into_element(), executor.into_element()).await + rasterize_with_vello(data, *transform.element(), resolution.element().as_uvec2(), executor.into_element()).await } -async fn rasterize_with_vello(data: List, footprint: Footprint, executor: ::wgpu_executor::WgpuExecutor) -> Result>, NodeError> { - let resolution = footprint.resolution; - if footprint.transform.matrix2.determinant() == 0. || resolution.cmpeq(UVec2::ZERO).any() { - log::trace!("Invalid footprint received for rasterization"); +/// Renders `data` within the rectangle `transform` places, a unit square centered on its origin, as an image of `resolution` pixels. +async fn rasterize_with_vello(data: List, transform: DAffine2, resolution: UVec2, executor: ::wgpu_executor::WgpuExecutor) -> Result>, NodeError> { + if transform.matrix2.determinant() == 0. || resolution.cmpeq(UVec2::ZERO).any() { + log::trace!("Invalid area or resolution received for rasterization"); return Ok(List::new()); } - let aabb = Bbox::from_transform(footprint.transform).to_axis_aligned_bbox(); + // An image fills the unit square from its corner rather than its center + let image_transform = transform * DAffine2::from_translation(DVec2::splat(-0.5)); + + let aabb = Bbox::from_transform(image_transform).to_axis_aligned_bbox(); let view = DAffine2::from_scale(resolution.as_dvec2() / aabb.size()) * DAffine2::from_translation(-aabb.start); let render_params = RenderParams { - footprint, + footprint: Footprint { + transform: image_transform, + resolution, + ..Default::default() + }, for_export: true, ..Default::default() }; @@ -265,12 +280,12 @@ async fn rasterize_with_vello(data: List, footprint: Footprint, executo // The input's layers stay reachable so the renderer can expose their click targets to the editor's tools Ok(List::new_from_item( Item::new_from_element(raster) - .with_attribute(ATTR_TRANSFORM, footprint.transform) + .with_attribute(ATTR_TRANSFORM, image_transform) .with_attribute(ATTR_EDITOR_MERGED_LAYERS, data), )) } -fn pending_raster(_data: &List, _footprint: &Item, _executor: &Item<::wgpu_executor::WgpuExecutor>) -> List> { +fn pending_raster(_data: &List, _transform: &Item, _resolution: &Item, _executor: &Item<::wgpu_executor::WgpuExecutor>) -> List> { List::new() } @@ -328,28 +343,53 @@ fn wgpu_executor(_: impl Ctx, #[scope(application_io::IDENTIFIER)] application_i mod tests { use super::*; use core_types::Color; - use glam::DVec2; + + /// A red rectangle covering x from 0 to 500 px and y from 0 to 1000 px. + fn left_half_red() -> List { + let red = Item::new_from_element(Raster::new_cpu(Image::new(1, 1, Color::RED))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::new(500., 1000.))); + List::new_from_item(Item::new_from_element(Graphic::RasterCPU(Box::new(red)))) + } + + /// Asserts each pixel of the image's first row is red for the first `red_columns` columns and transparent after. + fn assert_first_row_red_up_to(image: &Image, red_columns: u32) { + for x in 0..image.width { + let expected_red = x < red_columns; + assert_eq!( + image.data[x as usize].a() > 0.5, + expected_red, + "pixel {x} should be {}", + if expected_red { "red" } else { "transparent" } + ); + } + } #[tokio::test] - async fn rasterize_renders_the_footprint_area_at_its_resolution() { + async fn rasterize_renders_its_area_at_its_resolution() { let Some(executor) = ::wgpu_executor::WgpuExecutor::for_tests().await else { return }; - let red = Item::new_from_element(Raster::new_cpu(Image::new(1, 1, Color::RED))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::new(500., 1000.))); - let data = List::new_from_item(Item::new_from_element(Graphic::RasterCPU(Box::new(red)))); - let footprint = Footprint { - transform: DAffine2::from_scale(DVec2::splat(1000.)), - resolution: UVec2::splat(4), - ..Default::default() - }; - - let output = rasterize_with_vello(data, footprint, executor).await.expect("Rasterize should render"); + let area = DAffine2::from_scale_angle_translation(DVec2::splat(1000.), 0., DVec2::splat(500.)); + let output = rasterize_with_vello(left_half_red(), area, UVec2::splat(4), executor).await.expect("Rasterize should render"); let image = output.iter_element_values().next().expect("Rasterize should output one image").data(); assert_eq!((image.width, image.height), (4, 4)); - for x in 0..4 { - let pixel = image.data[(4 + x) as usize]; - let expected_red = x < 2; - assert_eq!(pixel.a() > 0.5, expected_red, "pixel {x} should be {}", if expected_red { "red" } else { "transparent" }); - } + assert_first_row_red_up_to(image, 2); + } + + // What 'Rasterize' version 1 output for a footprint, its migrated area transform and resolution reproduce + #[tokio::test] + async fn rasterize_renders_a_migrated_footprint_where_it_did() { + let Some(executor) = ::wgpu_executor::WgpuExecutor::for_tests().await else { return }; + + // Version 1 rendered the 4 by 2 pixel footprint over x from 250 to 750 px, its transform placing the image's corner-anchored unit square + let footprint_transform = DAffine2::from_scale_angle_translation(DVec2::new(500., 1000.), 0., DVec2::new(250., 0.)); + let migrated_area = footprint_transform * DAffine2::from_translation(DVec2::splat(0.5)); + + let output = rasterize_with_vello(left_half_red(), migrated_area, UVec2::new(4, 2), executor).await.expect("Rasterize should render"); + + assert_eq!(output.attribute_cloned_or_default::(ATTR_TRANSFORM, 0), footprint_transform); + + let image = output.element(0).expect("Rasterize should output one image").data(); + assert_eq!((image.width, image.height), (4, 2)); + assert_first_row_red_up_to(image, 2); } } diff --git a/node-graph/nodes/math/src/lib.rs b/node-graph/nodes/math/src/lib.rs index 6681d27c8e..bf2c0840b1 100644 --- a/node-graph/nodes/math/src/lib.rs +++ b/node-graph/nodes/math/src/lib.rs @@ -1,6 +1,5 @@ use core_types::context::{CloneVarArgs, ExtractAll}; use core_types::list::{Bundle, Item, List}; -use core_types::transform::Footprint; use core_types::{Color, Ctx, OwnedContextImpl, num_traits}; use core_types::{Context, Interrupt}; use glam::{DAffine2, DMat2, DVec2}; @@ -2082,24 +2081,6 @@ fn evaluate_gradient( Item::new_from_element(color) } -/// Constructs a footprint value which may be set to any transformation of a unit square describing a render area, and a render resolution at least 1x1 integer pixels. -#[node_macro::node(category("Value"), icon("NodeFootprintValue"))] -fn footprint_value( - _: impl Ctx, - _primary: (), - transform: Item, - #[unit(" px")] - #[hard(1..)] - #[default(100., 100.)] - resolution: Item, -) -> Item { - Item::new_from_element(Footprint { - transform: *transform.element(), - resolution: resolution.element().as_uvec2(), - ..Default::default() - }) -} - /// Composes a vec2 from its X and Y components. /// /// The inverse of this node is **Vec2 to Numbers**, which decomposes a vec2 back into its X and Y components.