Make the data model use Item and List types universally, with nodes authored as rank-polymorphic kernels (#4335)

* Add rank polymorphism node audit classifying all 271 nodes

* Implement StaticType for Item<T>

* Generate Item and mapped List wire variants for nodes declaring an Item<T> primary input

* Migrate nine nodes to Item element-wise kernels, dissolving the blending trait boilerplate

* Document the Item kernel implementation and staging plan

* Route Item<Vector> through TaggedValue::TypeDefault

* Add executor integration tests covering the Item and List wire variants

* Collapse element-wise Item/List wire pairs to the List form for conversion insertion

* Migrate sixteen vector modifier nodes to Item element-wise kernels

* Migrate Sample Image, Extend Image to Bounds, and Dehaze to Item element-wise kernels

* Fix bevel_with_transform test to actually exercise the transform attribute

* Implement From<T> for Item<T>

* Register PromoteNode rank adapters wrapping bare values into Item wires

* Insert PromoteNode adapters for Item/List wire pair fields in the preprocessor

* Define a real promote node backing the PromoteNode registry identifiers

* Zip ranked Item connectors by frame slot in the mapped element-wise variant

* Register ItemToListNode singleton raise adapters

* Resolve Item wires against List connectors by inserting promotion adapters at construction

* Rank the Offset Points distance connector and prove mixed-rank resolution end-to-end

* Implement Clampable for Item and List wires with per-variant clamp bounds

* Rank the Round Corners radius connector, exercising hard bounds on a ranked wire

* Implement ApplyTransform for Item

* Add Item wire implementations to the Transform node, keeping rank-0 chains rank 0

* Detect element-wise nodes by lazy primary connectors declaring Output = Item

* Convert Transform to an Item kernel with ranked parameters, delivering the broadcast milestone

* Rename Apply Transform to Bake Transform, baking item transforms on Vector, DAffine2, and DVec2

* Promote bare wires onto Item connectors at resolution via WrapItemNode adapters

* Rank the numeric, vector, and boolean parameters across the migrated element-wise nodes

* Rank the enum, integer, and seed parameters, registering their rank adapters via a consolidated macro

* Amend the audit with the DashPattern value type resolution

* Migrate the string family to Item element-wise kernels

* Unwrap Item wires into bare legacy connectors at resolution via UnwrapItemNode adapters

* Shadow owned node parameters in bodies instead of mut in signatures

* Migrate the math family and string measure nodes to Item element-wise kernels

* Convert the comparison and clamp nodes to Item kernels, dropping unreachable &str rows

* Flat-map expander kernels returning List under the mapped variant's frame

* Migrate the expander nodes to Item kernels flat-mapping under the frame

* Remove the unused peel_list helper

* Rank the raster adjustment and blending kernels, recontextualizing shader nodes onto an Item stand-in

Migrate the 16 adjustment nodes, Mix, Color Overlay, and Gradient Map from whole-List kernels to rank-0 Item kernels, letting the macro derive the List-mapped (zip) variants. Move the Adjust and Blend per-element seams off List onto the element types (add the Raster<CPU> impls, drop the now-dead List impls).

Shader nodes keep their bodies verbatim: PerPixelAdjust re-emits the identical kernel against a transparent no_std Item stand-in, so every Item<T> connector and .element() call resolves to a zero-cost identity on the GPU while the uniform buffer stays bare repr(C). The macro peels Item off ranked uniform params, wraps the fetched texel and uniforms at the entry point, and unwraps the result. This drops the shader_node/Item incompatibility guard. Register rank adapters for the adjustment enums.

* Update the rank polymorphism roadmap for the landed shader-node and adjustments chunk

* Rename the GPU Item stand-in to ShaderItem, aliased as Item at its shader-node import sites

* Flip the vector shape generators to emit rank-0 Item<Vector>

The shape generators (Rectangle, Circle, Ellipse, Arc, Spiral, Polygon, Star, Arrow, Line, Grid, QR Code) each produced exactly one shape wrapped in a singleton List<Vector>. Emit Item<Vector> directly so they connect to the rank-0 content connector of the migrated Transform node. Downstream List consumers receive the value through the existing Item to List promotion.

Relax the element-wise validation so a `()` (generator) primary may return Item<T> without being element-wise. Adapt the Repeat on Points test, which still takes a List content connector, by raising the generator's Item output through a singleton wrapper node.

* Parse ranked Item<T> parameter defaults against the bare element type

A ranked `Item<T>` parameter's default value is a bare, unranked `T` (promoted to the wire at resolution), but the preprocessor was handed the wrapped `Item<T>` type and could not parse the literal, flooding the console with warnings and dropping the defaults. Key the field's default_type metadata off the peeled element type for concrete ranked parameters, leaving generic `Item<T>` primaries and skip_impl nodes untouched.

* Parse an element-wise primary's scalar default against the bare element type

An element-wise node's primary reports its default_type as the List wire form so an unconnected primary defaults to an empty list. But when the primary carries a scalar `#[default]` (such as Root's radicand), that literal must parse as a bare element, not a List. Key the primary's default_type off the bare element type when it has a Default value source, keeping the List form otherwise.

* Add the DashPattern value type for stroke dash sequences

Introduce a rank-0 DashPattern value type (a Vec<f64> of alternating dash and gap lengths) so a stroke's dash pattern is a single frameable value rather than a rank-1 List<f64>. Register it as an auto-generated TaggedValue variant, parse its default from a comma or space separated string, and register its rank adapters. Not yet wired into the Stroke node.

* Rank the Fill and Stroke nodes element-wise and give Stroke a DashPattern connector

Migrate Fill and Stroke to element-wise Item<V> primaries (over Vector and Graphic element types) via a new element-level VectorItemMut trait, so styling one shape yields one shape and rank is preserved instead of promoting the input to a singleton List and emitting a List. The macro derives the List-mapped variant for genuine collections.

Wire the Stroke dash sequence to the new rank-0 DashPattern value type, collapsing the old content x paint x dash cartesian and dropping the IntoF64Vec trait. Update the stroke properties dash widget, the drawing tool, and graph-operation plumbing to read and write DashPattern, and migrate legacy F64Array, F64, and String dash inputs on document open.

Assign Colors stays a whole-collection node: each element's gradient position depends on its index among all siblings, which the element frame does not expose, so it keeps its List primary and the VectorListIterMut trait.

* Register rank adapters for the ranked Stroke enum parameters

The element-wise Stroke node ranks its align, cap, and paint order parameters as Item<StrokeAlign>, Item<StrokeCap>, and Item<PaintOrder>, but those enums lacked promotion adapters, so a bare default enum value could not be promoted to its Item wire and no Stroke variant resolved ("No construct found for node"). Register their rank adapters alongside StrokeJoin.

* Display Item wires in the Data panel without a List's ID column

Add a TableItemLayout impl for Item<T> and recognize Item wire types when introspecting graph data. An Item holds a single element, so it renders as a one-row table of the element plus its attributes with no leading index column, and it labels as its element type T rather than a List's T[]. Add ItemAttributeValues::get_any for the attribute widget dispatch.

* Register MonitorNode for Item wire types so the Data panel introspects them directly

Graph introspection wraps the inspected output in a generic MonitorNode typed to the wire. Without Item<T> monitor registrations, an Item<Vector> output could only be monitored after an Item to List promotion, so the Data panel captured and displayed a List<Vector> despite the connector being Item<Vector>. Register monitors for the Item types the element-wise nodes emit, and add the matching Data panel downcast entries.

* Color and double Item/List wires and cleave layer-stack connectors in the node graph

* Route wire color and rank through hidden nodes and refresh them on type changes

* Rework the DashPattern connector conversions with element-wise promotion and an explicit reducer node

* Rank the remaining value, context, aggregation, and transform nodes onto Item<T> wires

* Back DashPattern with a List<f64> so the Data panel can introspect its lengths

* Carry a single Item<T> through varargs so the Read context nodes emit Item<T> not List<T>

* Relax rank validation for aggregation shapes, add element adapters, and match variants by fewest promotions

* Rank the remaining bare and unnecessarily-List connectors across the node catalog

* Add Graphic::None and the FillChoice paint value, making colors and gradients plain values

* Rename GradientStops to Gradient and the legacy Gradient/Fill structs to LegacyGradient/LegacyFill

* Restore generator frame-from-params ranking to the roadmap as a planned stage

* Rename the ranked-field adapter identifier from PromoteNode to FieldAdapterNode to reflect its full contract

* Unload only the wires whose displayed style changed when types update

* Peel wire rank in the editor's semantic type checks so rank-0 layers are recognized

* Restore the whole-List Transform variant so rank-1 content wires resolve again

* Register the Item wire forms for the Memoize and Context Modification infrastructure nodes

* Give every ranked connector a field adapter and add numeric cast variants for legacy wires

* Key a ranked param's type default off its Item wire form when no literal default exists

* Inherit the layer's content value when splicing a node into an empty chain

* Migrate stale List-form TypeDefault inputs to the definition's current default

* Generate the mapped wire variant only when the element-wise node has a frame source

* Let a bare wire feed a List connector via a wrap-raise adapter, costed as two rank steps

* Add a zip companion to the whole-List Transform so ranked List parameters pair per slot

* Add the Sum, Average, Minimum, Maximum, Any, and All list reducers

* Convert the measure family to element-wise Item kernels per the audit classification

* Prefer the bare element value over the Item type default so ranked params keep their widgets

* Rename GradientStopsUI to GradientUI

* Split Fill's optional transform into a _has_transform bool and a ranked _transform matrix

* Rename the migration-only OptionalDAffine2 TaggedValue to LegacyOptionalDAffine2

* Flow byte buffers as Item<Resource> instead of List<u8> across the byte nodes

* Macro-generate the list-content wire variant, retiring the hand-written Transform-zip, Area, and Centroid companions

* Let ()-primary generators take ranked params and frame over them via the mapped variant, ranking Circle's radius

* Rank the vector shape generators' params to Item, adding a rank-aware input grab to the introspection harness

* Rank the value, color, and text generator params to Item

* Rank the raster, web-request, and context-reader generator params to Item

* Fix the repeat and brush test wirings left behind by the param-ranking sweeps

* Delete the vestigial Some, Unwrap Option, and Size Of debug nodes

* Delete the Attach Attribute node, folding its role into Write Attribute

* Add the Filter and Sort list companion nodes

* Guard the removed-definition migration swap target with a test

* Add the Box Corners value type in place of the rectangle corner radius list

* Split Text to Vector's per-glyph mode into a Text to Vector Glyphs node

* Rank the Combine Channels node's channel connectors to Item

* Make Map Points an element-wise node

* Delete the deprecated Upload Texture node

* Update the implementation roadmap to reflect the landed stages

* Let monitor introspection read rank-0 wires, locking in the layer coercion promotion path

* Prefer the rank-0 default when disconnecting a rank-capable input

* Make Path Modify an element-wise node

* Wrap node paths in a NodeIdPath newtype so they flow as a single Item

* Give Item<Raster<CPU>> a default so an unconnected Brush background resolves

* Stop the Brush node from setting layer attributes its paint operation doesn't produce

* Present-gate Flatten Path's adopted layer path like its fill and stroke

* Gate carried layer attributes on static column presence, not runtime values

* Give the remaining graphic Item<T> types a default so unconnected primaries resolve

* Dispatch a ranked param's Properties widget from its rank-0 element type

* Make Extract Transform an element-wise node, restoring the Origins to Polyline body

* Rename Flatten Path to Combine Paths

* Stamp Legacy Layer Extend's adopted layer path as a readable NodeIdPath

* Drop the dead List<u8> and List<NodeId> wire rows

* Rank Flatten Graphic's Fully Flatten toggle to Item

* Update the implementation roadmap with the endgame scope

* Make Combine Paths a reducer that collapses the whole frame into one path

* Stop type-converter nodes from carrying the source's unrelated attributes

* Format the Origins to Polyline regression test

* Wrap the Brush node's trace in a BrushTrace newtype so it flows as one value

* Make Switch a framed element-wise select, bundling whole collections

* Widen and align element-type coverage across the list and graphic nodes

* Register the compiler's cache chain pair for every ranked enum and newtype wire

* Fix wire colors for Passthrough outputs, bundled lists, and bools, and widen list wires

* Represent List wire types structurally with Type::List, replacing name-parsed rank promotion

* Treat scope and data fields as environment, rank scope wires as Item, and feed the render boundary through a context vararg

* Delete the vestigial Clone debug node

* Reinstate Upload Texture as an element-wise node and fix the GPU variants' scope executor and rank adapters

* Rename Combine Paths back to Flatten Path, deferring that rename to its own PR

* Deduplicate the promotion adapter registrations into the field adapter macro

* Rank Write Attribute's value connector to Item<AttributeValueDyn>, retiring the UnwrapItem bridge

* Vertical wire styling

* Store the editor layer path attribute as a bare NodeIdPath, not an Item<NodeIdPath>

* Rank Context Modification's features connector to Item<ContextFeatures>, dropping the dead memoize row

* Rank Path Modify's modification parameter to Item<Box<VectorModification>>

* Rename the field adapter node family to input adapter

* Drop the dead bare scalar rows from Context Modification's implementations list

* Move the dynamic executor's test module into its own file

* Drop the registry's unreachable bare rows for Memoize, the cache chain, and ConvertNode

* Materialize stored TaggedValues as ranked Item wires at the source

* Remove the bare-wire promotion and adapter machinery made dead by ranked value materialization

* Plant the input adapter for List-only inputs, composing position conversion from standard rows

* Consolidate Into/Convert conversions into the input adapter umbrella and rename the rank adapter identifiers

* Fix grouped layers gaining a phantom None stack element from the FillChoice default hijacking every List<Graphic> disconnect

* Enforce ranked node inputs in the macro, rejecting bare wire declarations

* Remove the unit Context => () machinery rows, leaving () purely as the no-primary sentinel

* Add a --signatures rank-audit mode to node-docs for the ranked-wire migration

* Remove the node-docs --signatures rank-audit mode now that ranked wires are enforced

* Migrate legacy no-color values on the Black & White, Color Overlay, and Empty Image color inputs

* Rewrite the element-wise accessor wire type at the primary input, not raw index 0

* Register the cache chain for Resource wires, replacing the lone hand-written Monitor row

* Gate the remaining Raster<GPU> registry rows behind the gpu feature

* Let List<DVec2> wires erase to ListDyn for the attribute reader and element counter

* Rename Extract Element to Item at Index, Count Elements to List Length, and Omit Element to Remove at Index

* Store paint picks as plain color/gradient values, removing the FillChoice value type

* Code review restructuring

* Sort by the consumed sort_key attribute or natural element order, adding the Sort Key node

* Remove the new list-combinator and reducer nodes to defer them to a follow-up PR

* Parse Fill and Stroke color defaults through the paint wire's Graphic element

* Emit ranked implementation-row default types structurally so their element TypeIds survive to default-literal parsing

* Exempt the deliberate no-paint choice from the stale List-form TypeDefault migration

* Migrate the legacy 4-input Fill directly to the split has-transform shape

* Upgrade the demo artwork

* Fix the valid AI review findings: Item eq/hash contract, table-era no-paint migration, quantize List rows, and other smaller issues

* Remove the rank polymorphism working documents

* Hash Item attribute values directly instead of debug-formatting them, speeding up cached evaluation

* Replace the data panel's dead bare-wire downcast arms with full coverage of the ranked monitor row types

* Derive PartialEq for Item now that attributes participate in equality

* Extend the data panel's attribute dispatchers with the newly supported scalar and choice enum types

* Add List monitor rows for the framed numeric conversion outputs so inspecting them resolves, with matching data panel arms
This commit is contained in:
Keavon Chambers
2026-07-15 19:03:01 -07:00
committed by GitHub
parent a040362d4a
commit 2090e9979a
119 changed files with 9013 additions and 5102 deletions

View File

@@ -1,204 +1,25 @@
use core_types::list::List;
use core_types::list::Item;
use core_types::registry::types::Percentage;
use core_types::{ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_OPACITY, ATTR_OPACITY_FILL, BlendMode, Color, Ctx};
use graphic_types::Graphic;
use graphic_types::Vector;
use graphic_types::raster_types::{CPU, Raster};
use vector_types::GradientStops;
pub(crate) trait MultiplyAlpha {
fn multiply_alpha(&mut self, factor: f64);
}
impl MultiplyAlpha for Color {
fn multiply_alpha(&mut self, factor: f64) {
*self = Color::from_rgbaf32_unchecked(self.r(), self.g(), self.b(), (self.a() * factor as f32).clamp(0., 1.))
}
}
fn multiply_list_attribute<T>(list: &mut List<T>, key: &str, factor: f64) {
if let Some(values) = list.iter_attribute_values_mut::<f64>(key) {
for v in values {
*v *= factor;
}
} else {
for v in list.iter_attribute_values_mut_or_default::<f64>(key) {
*v = factor;
}
}
}
impl MultiplyAlpha for List<Vector> {
fn multiply_alpha(&mut self, factor: f64) {
multiply_list_attribute(self, ATTR_OPACITY, factor);
}
}
impl MultiplyAlpha for List<Graphic> {
fn multiply_alpha(&mut self, factor: f64) {
multiply_list_attribute(self, ATTR_OPACITY, factor);
}
}
impl MultiplyAlpha for List<Raster<CPU>> {
fn multiply_alpha(&mut self, factor: f64) {
multiply_list_attribute(self, ATTR_OPACITY, factor);
}
}
impl MultiplyAlpha for List<Color> {
fn multiply_alpha(&mut self, factor: f64) {
multiply_list_attribute(self, ATTR_OPACITY, factor);
}
}
impl MultiplyAlpha for List<GradientStops> {
fn multiply_alpha(&mut self, factor: f64) {
multiply_list_attribute(self, ATTR_OPACITY, factor);
}
}
impl MultiplyAlpha for List<String> {
fn multiply_alpha(&mut self, factor: f64) {
multiply_list_attribute(self, ATTR_OPACITY, factor);
}
}
pub(crate) trait MultiplyFill {
fn multiply_fill(&mut self, factor: f64);
}
impl MultiplyFill for Color {
fn multiply_fill(&mut self, factor: f64) {
*self = Color::from_rgbaf32_unchecked(self.r(), self.g(), self.b(), (self.a() * factor as f32).clamp(0., 1.))
}
}
impl MultiplyFill for List<Vector> {
fn multiply_fill(&mut self, factor: f64) {
multiply_list_attribute(self, ATTR_OPACITY_FILL, factor);
}
}
impl MultiplyFill for List<Graphic> {
fn multiply_fill(&mut self, factor: f64) {
multiply_list_attribute(self, ATTR_OPACITY_FILL, factor);
}
}
impl MultiplyFill for List<Raster<CPU>> {
fn multiply_fill(&mut self, factor: f64) {
multiply_list_attribute(self, ATTR_OPACITY_FILL, factor);
}
}
impl MultiplyFill for List<Color> {
fn multiply_fill(&mut self, factor: f64) {
multiply_list_attribute(self, ATTR_OPACITY_FILL, factor);
}
}
impl MultiplyFill for List<GradientStops> {
fn multiply_fill(&mut self, factor: f64) {
multiply_list_attribute(self, ATTR_OPACITY_FILL, factor);
}
}
impl MultiplyFill for List<String> {
fn multiply_fill(&mut self, factor: f64) {
multiply_list_attribute(self, ATTR_OPACITY_FILL, factor);
}
}
trait SetBlendMode {
fn set_blend_mode(&mut self, blend_mode: BlendMode);
}
fn set_list_blend_mode<T>(list: &mut List<T>, blend_mode: BlendMode) {
for v in list.iter_attribute_values_mut_or_default::<BlendMode>(ATTR_BLEND_MODE) {
*v = blend_mode;
}
}
impl SetBlendMode for List<Vector> {
fn set_blend_mode(&mut self, blend_mode: BlendMode) {
set_list_blend_mode(self, blend_mode);
}
}
impl SetBlendMode for List<Graphic> {
fn set_blend_mode(&mut self, blend_mode: BlendMode) {
set_list_blend_mode(self, blend_mode);
}
}
impl SetBlendMode for List<Raster<CPU>> {
fn set_blend_mode(&mut self, blend_mode: BlendMode) {
set_list_blend_mode(self, blend_mode);
}
}
impl SetBlendMode for List<Color> {
fn set_blend_mode(&mut self, blend_mode: BlendMode) {
set_list_blend_mode(self, blend_mode);
}
}
impl SetBlendMode for List<GradientStops> {
fn set_blend_mode(&mut self, blend_mode: BlendMode) {
set_list_blend_mode(self, blend_mode);
}
}
impl SetBlendMode for List<String> {
fn set_blend_mode(&mut self, blend_mode: BlendMode) {
set_list_blend_mode(self, blend_mode);
}
}
trait SetClip {
fn set_clip(&mut self, clip: bool);
}
fn set_list_clip<T>(list: &mut List<T>, clip: bool) {
for v in list.iter_attribute_values_mut_or_default::<bool>(ATTR_CLIPPING_MASK) {
*v = clip;
}
}
impl SetClip for List<Vector> {
fn set_clip(&mut self, clip: bool) {
set_list_clip(self, clip);
}
}
impl SetClip for List<Graphic> {
fn set_clip(&mut self, clip: bool) {
set_list_clip(self, clip);
}
}
impl SetClip for List<Raster<CPU>> {
fn set_clip(&mut self, clip: bool) {
set_list_clip(self, clip);
}
}
impl SetClip for List<Color> {
fn set_clip(&mut self, clip: bool) {
set_list_clip(self, clip);
}
}
impl SetClip for List<GradientStops> {
fn set_clip(&mut self, clip: bool) {
set_list_clip(self, clip);
}
}
impl SetClip for List<String> {
fn set_clip(&mut self, clip: bool) {
set_list_clip(self, clip);
}
}
use graphic_types::raster_types::{CPU, GPU, Raster};
use vector_types::Gradient;
/// Applies the blend mode to the input graphics. Setting this allows for customizing how overlapping content is composited together.
#[node_macro::node(category("Blending"))]
fn blend_mode<T: SetBlendMode>(
fn blend_mode<T>(
_: impl Ctx,
/// The layer stack that will be composited when rendering.
#[implementations(
List<Graphic>,
List<Vector>,
List<Raster<CPU>>,
List<Color>,
List<GradientStops>,
List<String>,
)]
mut content: T,
/// The content that will be composited when rendering.
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String)]
content: Item<T>,
/// The choice of equation that controls how brightness and color blends between overlapping pixels.
blend_mode: BlendMode,
) -> T {
// TODO: Find a way to make this apply once to the list's parent (i.e. its item in its parent List<T> or Item<T>) rather than applying to each item in its own list, which produces the undesired result
content.set_blend_mode(blend_mode);
blend_mode: Item<BlendMode>,
) -> Item<T> {
let mut content = content;
let blend_mode = *blend_mode.element();
content.set_attribute(ATTR_BLEND_MODE, blend_mode);
content
}
@@ -206,64 +27,58 @@ fn blend_mode<T: SetBlendMode>(
/// Opacity affects the transparency of the content (together with anything above which is clipped to it).
/// Fill affects the transparency of the content itself, independent of any content clipped to it.
#[node_macro::node(category("Blending"))]
fn opacity<T: MultiplyAlpha + MultiplyFill>(
fn opacity<T>(
_: impl Ctx,
/// The layer stack that will be composited when rendering.
#[implementations(
List<Graphic>,
List<Vector>,
List<Raster<CPU>>,
List<Color>,
List<GradientStops>,
List<String>,
)]
mut content: T,
/// The content that will be composited when rendering.
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String)]
content: Item<T>,
/// Whether the *Opacity* property is enabled, multiplying the existing opacity by the chosen percentage.
#[widget(ParsedWidgetOverride::Hidden)]
#[default(true)]
has_opacity: bool,
has_opacity: Item<bool>,
/// How visible the content should be, including any content clipped to it.
/// Ranges from the default of 100% (fully opaque) to 0% (fully transparent).
#[widget(ParsedWidgetOverride::Custom = "optional_percentage")]
#[default(100.)]
opacity: Percentage,
opacity: Item<Percentage>,
/// Whether the *Fill* property is enabled, multiplying the existing fill by the chosen percentage.
#[widget(ParsedWidgetOverride::Hidden)]
has_fill: bool,
has_fill: Item<bool>,
/// How visible the content should be, independent of any content clipped to it.
/// Ranges from 0% (fully transparent) to the default of 100% (fully opaque).
#[widget(ParsedWidgetOverride::Custom = "optional_percentage")]
#[default(100.)]
fill: Percentage,
) -> T {
// TODO: Find a way to make this apply once to the list's parent (i.e. its item in its parent List<T> or Item<T>) rather than applying to each item in its own list, which produces the undesired result
fill: Item<Percentage>,
) -> Item<T> {
let mut content = content;
let (has_opacity, opacity, has_fill, fill) = (*has_opacity.element(), *opacity.element(), *has_fill.element(), *fill.element());
if has_opacity {
content.multiply_alpha(opacity / 100.);
let multiplied = content.attribute_cloned_or(ATTR_OPACITY, 1.) * (opacity / 100.);
content.set_attribute(ATTR_OPACITY, multiplied);
}
if has_fill {
content.multiply_fill(fill / 100.);
let multiplied = content.attribute_cloned_or(ATTR_OPACITY_FILL, 1.) * (fill / 100.);
content.set_attribute(ATTR_OPACITY_FILL, multiplied);
}
content
}
/// Sets whether the input graphics inherit the alpha of the content beneath them, "clipping" them to that content.
#[node_macro::node(category("Blending"))]
fn clipping_mask<T: SetClip>(
fn clipping_mask<T>(
_: impl Ctx,
/// The layer stack that will be composited when rendering.
#[implementations(
List<Graphic>,
List<Vector>,
List<Raster<CPU>>,
List<Color>,
List<GradientStops>,
List<String>,
)]
mut content: T,
/// The content that will be composited when rendering.
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String)]
content: Item<T>,
/// Whether the content inherits the alpha of the content beneath it.
clip: bool,
) -> T {
// TODO: Find a way to make this apply once to the list's parent (i.e. its item in its parent List<T> or Item<T>) rather than applying to each item in its own list, which produces the undesired result
content.set_clip(clip);
clip: Item<bool>,
) -> Item<T> {
let mut content = content;
let clip = *clip.element();
content.set_attribute(ATTR_CLIPPING_MASK, clip);
content
}

View File

@@ -1,5 +1,6 @@
use crate::brush_cache::BrushCache;
use crate::brush_stroke::{BrushStroke, BrushStyle};
use crate::brush_stroke::{BrushStyle, BrushTrace};
use core_types::ATTR_TRANSFORM;
use core_types::blending::BlendMode;
use core_types::bounds::{BoundingBox, RenderBoundingBox};
use core_types::color::{Alpha, Color, Pixel, Sample};
@@ -8,9 +9,7 @@ use core_types::list::{Item, List};
use core_types::math::bbox::{AxisAlignedBbox, Bbox};
use core_types::registry::FutureWrapperNode;
use core_types::transform::Transform;
use core_types::uuid::NodeId;
use core_types::value::ClonedNode;
use core_types::{ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM};
use core_types::{Ctx, Node};
use glam::{DAffine2, DVec2};
use raster_nodes::blending_nodes::blend_colors;
@@ -83,10 +82,11 @@ fn brush_stamp_generator(#[unit(" px")] diameter: f64, color: Color, hardness: f
/// Used to efficiently paint brush strokes. Applies the same texture repeatedly at different positions with proper blending and boundary handling.
#[node_macro::node(category(""), skip_impl)]
fn blit<BlendFn>(mut target: List<Raster<CPU>>, texture: Raster<CPU>, positions: Vec<DVec2>, blend_mode: BlendFn) -> List<Raster<CPU>>
fn blit<BlendFn>(target: List<Raster<CPU>>, texture: Raster<CPU>, positions: Vec<DVec2>, blend_mode: BlendFn) -> List<Raster<CPU>>
where
BlendFn: for<'any_input> Node<'any_input, (Color, Color), Output = Color>,
{
let mut target = target;
if positions.is_empty() {
return target;
}
@@ -137,7 +137,7 @@ where
pub async fn create_brush_texture(brush_style: &BrushStyle) -> Raster<CPU> {
let stamp = brush_stamp_generator(brush_style.diameter, brush_style.color, brush_style.hardness, brush_style.flow);
let transform = DAffine2::from_scale_angle_translation(DVec2::splat(brush_style.diameter), 0., -DVec2::splat(brush_style.diameter / 2.));
let blank_texture = empty_image((), transform, List::new_from_element(Color::TRANSPARENT)).into_iter().next().unwrap_or_default();
let blank_texture = empty_image((), Item::new_from_element(transform), Item::new_from_element(Color::TRANSPARENT));
let image = blend_stamp_closure(stamp, blank_texture, |a, b| blend_colors(a, b, BlendMode::Normal, 1.));
image.into_element()
@@ -191,18 +191,17 @@ pub fn blend_with_mode(background: Item<Raster<CPU>>, foreground: Item<Raster<CP
async fn brush(
_: impl Ctx,
/// Optional raster content that may be drawn onto.
mut background: List<Raster<CPU>>,
background: Item<Raster<CPU>>,
/// The list of brush stroke paths drawn by the Brush tool, with each including both its coordinates and styles.
trace: List<BrushStroke>,
trace: Item<BrushTrace>,
/// Internal cache data used to accelerate rendering of the brush content.
#[data]
cache: BrushCache,
) -> List<Raster<CPU>> {
if background.is_empty() {
background.push(Item::default());
}
// TODO: Find a way to handle more than one item
let list_item = background.clone_item(0).expect("Expected the one item we just pushed");
) -> Item<Raster<CPU>> {
let trace = trace.into_element().0;
let list_item = background;
let mut result_item = list_item.clone();
let bounds = List::new_from_item(list_item.clone()).bounding_box(DAffine2::IDENTITY, false);
let [start, end] = if let RenderBoundingBox::Rectangle(rect) = bounds { rect } else { [DVec2::ZERO, DVec2::ZERO] };
@@ -223,10 +222,7 @@ async fn brush(
let mut brush_plan = cache.compute_brush_plan(list_item, &draw_strokes);
// TODO: Find a way to handle more than one item
let Some(mut actual_image) = extend_image_to_bounds((), List::new_from_item(brush_plan.background), background_bounds).into_iter().next() else {
return List::new();
};
let mut actual_image = extend_image_to_bounds((), brush_plan.background, Item::new_from_element(background_bounds));
let final_stroke_idx = brush_plan.strokes.len().saturating_sub(1);
for (idx, stroke) in brush_plan.strokes.into_iter().enumerate() {
@@ -263,10 +259,9 @@ async fn brush(
);
let blit_target = if idx == 0 {
let target = core::mem::take(&mut brush_plan.first_stroke_texture);
extend_image_to_bounds((), List::new_from_item(target), stroke_to_layer)
List::new_from_item(extend_image_to_bounds((), target, Item::new_from_element(stroke_to_layer)))
} else {
empty_image((), stroke_to_layer, List::new_from_element(Color::TRANSPARENT))
// EmptyImageNode::new(CopiedNode::new(stroke_to_layer), CopiedNode::new(Color::TRANSPARENT)).eval(())
List::new_from_item(empty_image((), Item::new_from_element(stroke_to_layer), Item::new_from_element(Color::TRANSPARENT)))
};
let list = blit_node.eval(blit_target).await;
@@ -318,22 +313,14 @@ async fn brush(
actual_image = blend_image_closure(erase_restore_mask, actual_image, |a, b| blend_params.eval((a, b)));
}
// The paint operation changes only the raster and its bounds, so set just the resulting transform; blending, opacity,
// clipping, and layer-path attributes carry through from the input `background` rather than being invented here.
let transform: DAffine2 = actual_image.attribute_cloned_or_default(ATTR_TRANSFORM);
let blend_mode: BlendMode = actual_image.attribute_cloned_or_default(ATTR_BLEND_MODE);
let opacity: f64 = actual_image.attribute_cloned_or(ATTR_OPACITY, 1.);
let fill: f64 = actual_image.attribute_cloned_or(ATTR_OPACITY_FILL, 1.);
let clip: bool = actual_image.attribute_cloned_or_default(ATTR_CLIPPING_MASK);
let layer: List<NodeId> = actual_image.attribute_cloned_or_default(ATTR_EDITOR_LAYER_PATH);
*background.element_mut(0).unwrap() = actual_image.into_element();
background.set_attribute(ATTR_TRANSFORM, 0, transform);
background.set_attribute(ATTR_BLEND_MODE, 0, blend_mode);
background.set_attribute(ATTR_OPACITY, 0, opacity);
background.set_attribute(ATTR_OPACITY_FILL, 0, fill);
background.set_attribute(ATTR_CLIPPING_MASK, 0, clip);
background.set_attribute(ATTR_EDITOR_LAYER_PATH, 0, layer);
*result_item.element_mut() = actual_image.into_element();
result_item.set_attribute(ATTR_TRANSFORM, transform);
background
result_item
}
pub fn blend_image_closure(foreground: Item<Raster<CPU>>, mut background: Item<Raster<CPU>>, map_fn: impl Fn(Color, Color) -> Color) -> Item<Raster<CPU>> {
@@ -404,6 +391,7 @@ pub fn blend_stamp_closure(foreground: BrushStampGenerator<Color>, mut backgroun
#[cfg(test)]
mod test {
use super::*;
use crate::brush_stroke::BrushStroke;
use core_types::transform::Transform;
use glam::DAffine2;
@@ -421,8 +409,8 @@ mod test {
let image = brush(
(),
&BrushCache::default(),
List::new_from_element(Raster::new_cpu(Image::<Color>::default())),
List::new_from_element(BrushStroke {
Item::new_from_element(Raster::new_cpu(Image::<Color>::default())),
Item::new_from_element(BrushTrace::from(vec![BrushStroke {
trace: vec![crate::brush_stroke::BrushInputSample { position: DVec2::ZERO }],
style: BrushStyle {
color: Color::BLACK,
@@ -432,9 +420,9 @@ mod test {
spacing: 20.,
blend_mode: BlendMode::Normal,
},
}),
}])),
)
.await;
assert_eq!(image.element(0).unwrap().width, 20);
assert_eq!(image.element().width, 20);
}
}

View File

@@ -1,6 +1,7 @@
use core_types::CacheHash;
use core_types::blending::BlendMode;
use core_types::color::Color;
use core_types::list::{Item, List};
use core_types::math::bbox::AxisAlignedBbox;
use dyn_any::DynAny;
use glam::DVec2;
@@ -57,6 +58,22 @@ pub struct BrushStroke {
pub trace: Vec<BrushInputSample>,
}
/// One Brush layer's full sequence of strokes, treated as a single rank-0 value rather than a frame of independent strokes.
#[derive(Default, Debug, Clone, PartialEq, CacheHash, DynAny)]
pub struct BrushTrace(pub List<BrushStroke>);
impl From<List<BrushStroke>> for BrushTrace {
fn from(strokes: List<BrushStroke>) -> Self {
Self(strokes)
}
}
impl From<Vec<BrushStroke>> for BrushTrace {
fn from(strokes: Vec<BrushStroke>) -> Self {
Self(strokes.into_iter().map(Item::new_from_element).collect())
}
}
impl BrushStroke {
pub fn bounding_box(&self) -> AxisAlignedBbox {
let radius = self.style.diameter / 2.;

View File

@@ -1,8 +1,8 @@
use core_types::list::List;
use core_types::list::{Item, List};
use core_types::transform::Footprint;
use core_types::{CacheHash, CloneVarArgs, Color, Context, Ctx, ExtractAll, ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime, OwnedContextImpl};
use glam::{DAffine2, DVec2};
use graphic_types::vector_types::GradientStops;
use graphic_types::vector_types::Gradient;
use graphic_types::{Artboard, Graphic, Vector};
use raster_types::{CPU, GPU, Raster};
@@ -33,19 +33,22 @@ fn real_time(
ctx: impl Ctx + ExtractRealTime,
_primary: (),
/// The time and date component to be produced as a number.
component: RealTimeMode,
) -> f64 {
component: Item<RealTimeMode>,
) -> Item<f64> {
let component = component.into_element();
let real_time = ctx.try_real_time().unwrap_or_default();
// TODO: Implement proper conversion using and existing time implementation
match component {
let result = match component {
RealTimeMode::Utc => real_time,
RealTimeMode::Year => (real_time / DAY / 365.25).floor() + 1970., // TODO: Factor in a chosen timezone
RealTimeMode::Hour => (real_time / 1000. / 3600.).floor() % 24., // TODO: Factor in a chosen timezone
RealTimeMode::Minute => (real_time / 1000. / 60.).floor() % 60., // TODO: Factor in a chosen timezone
RealTimeMode::Second => (real_time / 1000.).floor() % 60.,
RealTimeMode::Millisecond => real_time % 1000.,
}
};
Item::new_from_element(result)
}
/// Produces the time, in seconds on the timeline, since the beginning of animation playback.
@@ -55,42 +58,50 @@ fn animation_time(
_primary: (),
#[default(1)]
#[unit("/sec")]
rate: f64,
) -> f64 {
ctx.try_animation_time().unwrap_or_default() * rate
rate: Item<f64>,
) -> Item<f64> {
Item::new_from_element(ctx.try_animation_time().unwrap_or_default() * *rate.element())
}
#[node_macro::node(category("Debug"))]
async fn quantize_real_time<T>(
ctx: impl Ctx + ExtractAll + CloneVarArgs,
#[implementations(
Context -> bool,
Context -> u32,
Context -> u64,
Context -> f32,
Context -> f64,
Context -> String,
Context -> DAffine2,
Context -> Footprint,
Context -> DVec2,
Context -> Item<bool>,
Context -> Item<u32>,
Context -> Item<u64>,
Context -> Item<f32>,
Context -> Item<f64>,
Context -> Item<String>,
Context -> Item<DAffine2>,
Context -> Item<Footprint>,
Context -> Item<DVec2>,
Context -> Item<Vector>,
Context -> Item<Graphic>,
Context -> Item<Raster<CPU>>,
Context -> Item<Raster<GPU>>,
Context -> Item<Color>,
Context -> Item<Gradient>,
Context -> Item<Artboard>,
Context -> List<String>,
Context -> List<f64>,
Context -> List<DVec2>,
Context -> List<Vector>,
Context -> List<Graphic>,
Context -> List<Raster<CPU>>,
Context -> List<Raster<GPU>>,
Context -> List<Color>,
Context -> List<Gradient>,
Context -> List<Artboard>,
Context -> List<GradientStops>,
Context -> List<String>,
Context -> List<f64>,
Context -> (),
)]
value: impl Node<'n, Context<'static>, Output = T>,
#[default(1)]
#[unit("sec")]
quantum: f64,
quantum: Item<f64>,
) -> T {
let time = ctx.try_real_time().unwrap_or_default();
let time = time / 1000.;
let quantum = quantum.into_element();
let mut quantized_time = (time * quantum.recip()).round() / quantum.recip();
if !quantized_time.is_finite() {
quantized_time = time;
@@ -104,32 +115,40 @@ async fn quantize_real_time<T>(
async fn quantize_animation_time<T>(
ctx: impl Ctx + ExtractAll + CloneVarArgs,
#[implementations(
Context -> bool,
Context -> u32,
Context -> u64,
Context -> f32,
Context -> f64,
Context -> String,
Context -> DAffine2,
Context -> Footprint,
Context -> DVec2,
Context -> Item<bool>,
Context -> Item<u32>,
Context -> Item<u64>,
Context -> Item<f32>,
Context -> Item<f64>,
Context -> Item<String>,
Context -> Item<DAffine2>,
Context -> Item<Footprint>,
Context -> Item<DVec2>,
Context -> Item<Vector>,
Context -> Item<Graphic>,
Context -> Item<Raster<CPU>>,
Context -> Item<Raster<GPU>>,
Context -> Item<Color>,
Context -> Item<Gradient>,
Context -> Item<Artboard>,
Context -> List<String>,
Context -> List<f64>,
Context -> List<DVec2>,
Context -> List<Vector>,
Context -> List<Graphic>,
Context -> List<Raster<CPU>>,
Context -> List<Raster<GPU>>,
Context -> List<Color>,
Context -> List<Gradient>,
Context -> List<Artboard>,
Context -> List<GradientStops>,
Context -> List<String>,
Context -> List<f64>,
Context -> (),
)]
value: impl Node<'n, Context<'static>, Output = T>,
#[default(1)]
#[unit("sec")]
quantum: f64,
quantum: Item<f64>,
) -> T {
let time = ctx.try_animation_time().unwrap_or_default();
let quantum = quantum.into_element();
let mut quantized_time = (time * quantum.recip()).round() / quantum.recip();
if !quantized_time.is_finite() {
quantized_time = time;
@@ -140,8 +159,8 @@ async fn quantize_animation_time<T>(
/// Produces the current position of the user's pointer within the document canvas.
#[node_macro::node(category("Animation"))]
fn pointer_position(ctx: impl Ctx + ExtractPointerPosition) -> DVec2 {
ctx.try_pointer_position().unwrap_or_default()
fn pointer_position(ctx: impl Ctx + ExtractPointerPosition) -> Item<DVec2> {
Item::new_from_element(ctx.try_pointer_position().unwrap_or_default())
}
// TODO: These nodes require more sophisticated algorithms for giving the correct result

View File

@@ -1,13 +1,13 @@
use core_types::list::List;
use core_types::list::Item;
use core_types::{Color, ExtractVarArgs};
use core_types::{Ctx, ExtractIndex, ExtractPosition};
use glam::DVec2;
use graphic_types::vector_types::GradientStops;
use graphic_types::vector_types::Gradient;
use graphic_types::{Graphic, Vector};
use raster_types::{CPU, Raster};
#[node_macro::node(category("Context"), path(graphene_core::vector))]
fn read_graphic(ctx: impl Ctx + ExtractVarArgs) -> List<Graphic> {
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;
@@ -15,7 +15,7 @@ fn read_graphic(ctx: impl Ctx + ExtractVarArgs) -> List<Graphic> {
}
#[node_macro::node(category("Context"), path(graphene_core::vector))]
fn read_vector(ctx: impl Ctx + ExtractVarArgs) -> List<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;
@@ -23,7 +23,7 @@ fn read_vector(ctx: impl Ctx + ExtractVarArgs) -> List<Vector> {
}
#[node_macro::node(category("Context"), path(graphene_core::vector))]
fn read_raster(ctx: impl Ctx + ExtractVarArgs) -> List<Raster<CPU>> {
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;
@@ -31,7 +31,7 @@ fn read_raster(ctx: impl Ctx + ExtractVarArgs) -> List<Raster<CPU>> {
}
#[node_macro::node(category("Context"), path(graphene_core::vector))]
fn read_color(ctx: impl Ctx + ExtractVarArgs) -> List<Color> {
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;
@@ -39,7 +39,7 @@ fn read_color(ctx: impl Ctx + ExtractVarArgs) -> List<Color> {
}
#[node_macro::node(category("Context"), path(graphene_core::vector))]
fn read_gradient(ctx: impl Ctx + ExtractVarArgs) -> List<GradientStops> {
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;
@@ -53,9 +53,10 @@ async fn read_position(
/// The number of nested loops to traverse outwards (from the innermost loop) to get the position from. The most upstream loop is level 0, and downstream loops add levels.
///
/// 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`.
loop_level: u32,
) -> DVec2 {
ctx.try_position().and_then(|mut iter| iter.nth(loop_level as usize).or_else(|| iter.last())).unwrap_or(DVec2::ZERO)
loop_level: Item<u32>,
) -> 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))
}
// TODO: Return u32, u64, or usize instead of f64 after #1621 is resolved and has allowed us to implement automatic type conversion in the node graph for nodes with generic type inputs.
@@ -70,7 +71,8 @@ async fn read_index(
/// The number of nested loops to traverse outwards (from the innermost loop) to get the index from. The most upstream loop is level 0, and downstream loops add levels.
///
/// 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`.
loop_level: u32,
) -> f64 {
ctx.try_index().and_then(|mut iter| iter.nth(loop_level as usize).or_else(|| iter.last())).unwrap_or(0) as f64
loop_level: Item<u32>,
) -> 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)
}

View File

@@ -1,11 +1,10 @@
use core::f64;
use core_types::context::{CloneVarArgs, Context, ContextFeatures, Ctx, ExtractAll};
use core_types::list::{AttributeDyn, AttributeValueDyn, List, ListDyn};
use core_types::list::{AttributeValueDyn, Item, List, ListDyn, NodeIdPath};
use core_types::transform::Footprint;
use core_types::uuid::NodeId;
use core_types::{Color, OwnedContextImpl};
use glam::{DAffine2, DVec2};
use graphic_types::vector_types::GradientStops;
use graphic_types::vector_types::Gradient;
use graphic_types::{Artboard, Graphic, Vector};
use raster_types::{CPU, GPU, Raster};
@@ -16,36 +15,41 @@ async fn context_modification<T>(
ctx: impl Ctx + CloneVarArgs + ExtractAll,
/// The data to pass through, evaluated with the stripped down context.
#[implementations(
Context -> (),
Context -> bool,
Context -> u32,
Context -> u64,
Context -> f32,
Context -> f64,
Context -> String,
Context -> DAffine2,
Context -> Footprint,
Context -> DVec2,
Context -> Item<bool>,
Context -> Item<u32>,
Context -> Item<u64>,
Context -> Item<f32>,
Context -> Item<f64>,
Context -> Item<String>,
Context -> Item<DAffine2>,
Context -> Item<Footprint>,
Context -> Item<DVec2>,
Context -> Item<Vector>,
Context -> Item<Graphic>,
Context -> Item<Raster<CPU>>,
Context -> Item<Raster<GPU>>,
Context -> Item<Color>,
Context -> Item<Artboard>,
Context -> Item<Gradient>,
Context -> Item<NodeIdPath>,
Context -> Item<AttributeValueDyn>,
Context -> List<String>,
Context -> List<NodeId>,
Context -> List<f64>,
Context -> List<u8>,
Context -> List<DVec2>,
Context -> List<Vector>,
Context -> List<Graphic>,
Context -> List<Raster<CPU>>,
Context -> List<Raster<GPU>>,
Context -> List<Color>,
Context -> List<Artboard>,
Context -> List<GradientStops>,
Context -> AttributeDyn,
Context -> AttributeValueDyn,
Context -> List<Gradient>,
Context -> ListDyn,
)]
value: impl Node<Context<'static>, Output = T>,
/// The parts of the context to keep when evaluating the input value. All other parts are nullified.
features_to_keep: ContextFeatures,
features_to_keep: Item<ContextFeatures>,
) -> T {
let new_context = OwnedContextImpl::from_flags(ctx, features_to_keep);
let new_context = OwnedContextImpl::from_flags(ctx, features_to_keep.into_element());
value.eval(Some(new_context.into())).await
}

View File

@@ -1,36 +1,11 @@
use core_types::Ctx;
use core_types::list::List;
use core_types::list::Item;
use glam::{DAffine2, DVec2};
use raster_types::{CPU, Raster};
/// Meant for debugging purposes, not general use. Logs the input value to the console and passes it through unchanged.
#[node_macro::node(category("Debug"), name("Log to Console"))]
fn log_to_console<T: std::fmt::Debug>(_: impl Ctx, #[implementations(bool, f64, u32, u64, DVec2, DAffine2, String)] value: T) -> T {
fn log_to_console<T: std::fmt::Debug>(_: impl Ctx, #[implementations(bool, f64, u32, u64, DVec2, DAffine2, String)] value: Item<T>) -> Item<T> {
// KEEP THIS `debug!()` - It acts as the output for the debug node itself
log::debug!("{value:#?}");
value
}
/// Meant for debugging purposes, not general use. Returns the size of the input type in bytes.
#[node_macro::node(category("Debug"))]
fn size_of(_: impl Ctx, ty: core_types::Type) -> Option<usize> {
ty.size()
}
/// Meant for debugging purposes, not general use. Wraps the input value in the Some variant of an Option.
#[node_macro::node(category("Debug"))]
fn some<T>(_: impl Ctx, #[implementations(f64, f32, u32, u64, String)] input: T) -> Option<T> {
Some(input)
}
/// Meant for debugging purposes, not general use. Unwraps the input value from an Option, returning the default value if the input is None.
#[node_macro::node(category("Debug"))]
fn unwrap_option<T: Default>(_: impl Ctx, #[implementations(Option<f64>, Option<u32>, Option<u64>, Option<String>)] input: Option<T>) -> T {
input.unwrap_or_default()
}
/// Meant for debugging purposes, not general use. Clones the input value.
#[node_macro::node(category("Debug"))]
fn clone<'i, T: Clone + 'i>(_: impl Ctx, #[implementations(&List<Raster<CPU>>)] value: &'i T) -> T {
value.clone()
}

View File

@@ -1,3 +1,4 @@
use core_types::list::Item;
use core_types::{CacheHash, Ctx};
use dyn_any::DynAny;
use glam::{DVec2, IVec2, UVec2};
@@ -6,11 +7,16 @@ use glam::{DVec2, IVec2, UVec2};
///
/// The inverse of this node is "Vec2 Value", which can have either or both its X and Y parameters exposed as graph inputs.
#[node_macro::node(name("Extract XY"), category("Math: Vector"))]
fn extract_xy<T: Into<DVec2>>(_: impl Ctx, #[implementations(DVec2, IVec2, UVec2)] vector: T, axis: XY) -> f64 {
match axis {
fn extract_xy<T: Into<DVec2>>(_: impl Ctx, #[implementations(DVec2, IVec2, UVec2)] vector: Item<T>, axis: Item<XY>) -> Item<f64> {
let vector = vector.into_element();
let axis = axis.into_element();
let result = match axis {
XY::X => vector.into().x,
XY::Y => vector.into().y,
}
};
Item::new_from_element(result)
}
/// The X or Y component of a vec2.

View File

@@ -1,3 +1,5 @@
use core_types::graphene_hash::CacheHash;
use core_types::list::{AttributeValueDyn, Bundle, Item, List};
use core_types::{Ctx, ExtractFootprint, ops::Convert, transform::Footprint};
use std::marker::PhantomData;
@@ -10,14 +12,92 @@ fn passthrough<'i, T: 'i + Send>(_: impl Ctx, content: T) -> T {
content
}
/// Shifts a whole wire value onto a connector's type through the std `Into` trait, serving the whole-`List` erasure onto `ListDyn` under the input adapter identifier.
#[node_macro::node(category(""), skip_impl)]
fn into<'i, T: 'i + Send + Into<O>, O: 'i + Send>(_: impl Ctx, value: T, _out_ty: PhantomData<O>) -> O {
value.into()
}
/// Raises an `Item` wire onto a `List` connector as its one-element list.
#[node_macro::node(category(""), skip_impl)]
async fn convert<'i, T: 'i + Send + Convert<O, C>, O: 'i + Send, C: 'i + Send>(ctx: impl Ctx + ExtractFootprint, value: T, converter: C, _out_ty: PhantomData<O>) -> O {
value.convert(*ctx.try_footprint().unwrap_or(&Footprint::DEFAULT), converter).await
fn item_to_list<'i, T: 'i + Send>(_: impl Ctx, value: Item<T>) -> List<T> {
value.into()
}
/// Boxes a ranked wire's element into a type-erased attribute value, carrying the cell's attributes through the wire.
#[node_macro::node(category(""), skip_impl)]
fn item_to_attribute_value<'i, T: 'i + Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash + 'static>(
_: impl Ctx,
value: Item<T>,
_element_ty: PhantomData<AttributeValueDyn>,
) -> Item<AttributeValueDyn> {
let (element, attributes) = value.into_parts();
Item::from_parts(AttributeValueDyn(Box::new(element)), attributes)
}
/// Boxes a whole `List` wire as one type-erased attribute value, for attributes whose per-item value is itself a collection.
#[node_macro::node(category(""), skip_impl)]
fn list_to_attribute_value<'i, T: 'i + Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash + 'static>(
_: impl Ctx,
value: T,
_element_ty: PhantomData<AttributeValueDyn>,
) -> Item<AttributeValueDyn> {
Item::new_from_element(AttributeValueDyn(Box::new(value)))
}
/// Wraps a whole `List` onto the wire as one rank-0 `Item<Bundle<T>>` so an entire collection can feed a connector that carries it as one opaque cell.
#[node_macro::node(category(""), skip_impl)]
fn bundle<'i, T: 'i + Send>(_: impl Ctx, value: List<T>) -> Item<Bundle<T>> {
Item::new_from_element(Bundle(value))
}
/// Unwraps a `Bundle` wire back into the whole `List` it carries, restoring the collection after it passed through a connector as one opaque cell.
#[node_macro::node(category(""), skip_impl)]
fn unbundle<'i, T: 'i + Send>(_: impl Ctx, value: Item<Bundle<T>>) -> List<T> {
value.into_element().0
}
/// Converts an `Item` wire's element to a different element type it can produce through the std `Into` trait,
/// letting a convertible wire feed an `Item` connector whose element type it does not match by identity.
#[node_macro::node(category(""), skip_impl)]
fn into_item<'i, T: 'i + Send + Into<E>, E: 'i + Send>(_: impl Ctx, value: Item<T>, _element_ty: PhantomData<E>) -> Item<E> {
let (value, attributes) = value.into_parts();
Item::from_parts(value.into(), attributes)
}
/// The `List` counterpart of `into_item`, converting every element to a different element type it can produce.
#[node_macro::node(category(""), skip_impl)]
fn into_list<'i, T: 'i + Send + Into<E>, E: 'i + Send>(_: impl Ctx, value: List<T>, _element_ty: PhantomData<E>) -> List<E> {
value
.into_iter()
.map(|item| {
let (value, attributes) = item.into_parts();
Item::from_parts(value.into(), attributes)
})
.collect()
}
/// The [`Convert`]-based counterpart of `into_item`, casting an `Item` wire's element to a connector's numeric element type.
#[node_macro::node(category(""), skip_impl)]
async fn convert_item<'i, T: 'i + Send + Convert<E, ()>, E: 'i + Send>(ctx: impl Ctx + ExtractFootprint, value: Item<T>, _element_ty: PhantomData<E>) -> Item<E> {
let footprint = *ctx.try_footprint().unwrap_or(&Footprint::DEFAULT);
let (value, attributes) = value.into_parts();
Item::from_parts(value.convert(footprint, ()).await, attributes)
}
/// The `List` counterpart of `convert_item`, casting every element to the connector's numeric element type.
#[node_macro::node(category(""), skip_impl)]
async fn convert_list<'i, T: 'i + Send + Convert<E, ()>, E: 'i + Send>(ctx: impl Ctx + ExtractFootprint, value: List<T>, _element_ty: PhantomData<E>) -> List<E> {
let footprint = *ctx.try_footprint().unwrap_or(&Footprint::DEFAULT);
let mut result = List::default();
for item in value.into_iter() {
let (value, attributes) = item.into_parts();
result.push(Item::from_parts(value.convert(footprint, ()).await, attributes));
}
result
}
#[cfg(test)]

View File

@@ -5,7 +5,7 @@ use glam::{DAffine2, DVec2};
use graphic_types::graphic::{Graphic, IntoGraphicList};
use graphic_types::{Artboard, Vector};
use raster_types::{CPU, GPU, Raster};
use vector_types::GradientStops;
use vector_types::Gradient;
/// Constructs a single-element `Artboard[]` with the given content and metadata stored as row attributes.
#[node_macro::node(category(""))]
@@ -19,20 +19,22 @@ pub async fn create_artboard<T: IntoGraphicList>(
Context -> List<Raster<CPU>>,
Context -> List<Raster<GPU>>,
Context -> List<Color>,
Context -> List<GradientStops>,
Context -> DAffine2,
Context -> List<Gradient>,
Context -> Item<DAffine2>,
)]
content: impl Node<Context<'static>, Output = T>,
/// Coordinate of the top-left corner of the artboard within the document.
location: DVec2,
location: Item<DVec2>,
/// Width and height of the artboard within the document.
dimensions: DVec2,
dimensions: Item<DVec2>,
/// Color of the artboard background.
background: List<Color>,
background: Item<Color>,
/// Whether to cut off the contained content that extends outside the artboard, or keep it visible.
#[default(true)]
clip: bool,
) -> List<Artboard> {
clip: Item<bool>,
) -> Item<Artboard> {
let (location, dimensions, clip) = (location.into_element(), dimensions.into_element(), clip.into_element());
let footprint = ctx.try_footprint().copied();
let mut new_ctx = OwnedContextImpl::from(ctx);
if let Some(mut footprint) = footprint {
@@ -47,14 +49,12 @@ pub async fn create_artboard<T: IntoGraphicList>(
let normalized_location = location.min(location + dimensions);
let normalized_dimensions = dimensions.abs().max(DVec2::ONE);
let background = background.element(0).copied().unwrap_or(Color::WHITE);
let background = background.into_element();
// Name is not stored here, it's resolved live from the parent layer's display name
List::new_from_item(
Item::new_from_element(Artboard::new(content))
.with_attribute(ATTR_LOCATION, normalized_location)
.with_attribute(ATTR_DIMENSIONS, normalized_dimensions)
.with_attribute(ATTR_BACKGROUND, background)
.with_attribute(ATTR_CLIP, clip),
)
Item::new_from_element(Artboard::new(content))
.with_attribute(ATTR_LOCATION, normalized_location)
.with_attribute(ATTR_DIMENSIONS, normalized_dimensions)
.with_attribute(ATTR_BACKGROUND, background)
.with_attribute(ATTR_CLIP, clip)
}

View File

@@ -1,67 +1,42 @@
use core_types::bounds::{BoundingBox, RenderBoundingBox};
use core_types::list::{AttributeDyn, AttributeValueDyn, Item, List, ListDyn};
use core_types::list::{AttributeValueDyn, Item, List, ListDyn, NodeIdPath};
use core_types::registry::types::{Angle, SignedInteger};
use core_types::uuid::NodeId;
use core_types::{ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_TRANSFORM, AnyHash, BlendMode, CacheHash, CloneVarArgs, Color, Context, Ctx, ExtractAll, OwnedContextImpl};
use glam::{DAffine2, DVec2};
use graphic_types::graphic::{Graphic, IntoGraphicList};
use graphic_types::{Artboard, Vector};
use raster_types::{CPU, GPU, Raster};
use vector_types::gradient::{GradientSpreadMethod, GradientType};
use vector_types::{GradientStop, GradientStops, ReferencePoint};
use vector_types::{Gradient, GradientStop, ReferencePoint};
/// Returns the value at the specified index in the list.
/// If no value exists at that index, the type's default value is returned.
#[node_macro::node(category("General"))]
pub fn index_elements<T: graphic_types::graphic::AtIndex + Clone + Default>(
_: impl Ctx,
/// The list of data.
#[implementations(
List<Artboard>,
List<Graphic>,
List<Vector>,
List<Raster<CPU>>,
List<Raster<GPU>>,
List<Color>,
List<GradientStops>,
List<String>,
List<f64>,
List<u8>,
List<NodeId>,
)]
list: T,
/// The index of the item to retrieve, starting from 0 for the first item. Negative indices count backwards from the end of the list, starting from -1 for the last item.
index: SignedInteger,
) -> T::Output
where
T::Output: Clone + Default,
{
let index = index as i32;
if index < 0 { list.at_index_from_end(-index as usize) } else { list.at_index(index as usize) }.unwrap_or_default()
}
/// Returns the list with the element at the specified index removed.
/// Returns the list with the item at the specified index removed.
/// If no value exists at that index, the list is returned unchanged.
#[node_macro::node(category("General"))]
pub fn omit_element<T: graphic_types::graphic::OmitIndex + Clone + Default>(
#[node_macro::node(category("General"), name("Remove at Index"))]
pub fn remove_at_index<T: graphic_types::graphic::OmitIndex + Clone + Default>(
_: impl Ctx,
/// The list of data.
#[implementations(
List<String>,
List<Artboard>,
List<Graphic>,
List<bool>,
List<f32>,
List<f64>,
List<u32>,
List<u64>,
List<DVec2>,
List<DAffine2>,
List<Vector>,
List<Graphic>,
List<Raster<CPU>>,
List<Raster<GPU>>,
List<Color>,
List<GradientStops>,
List<Gradient>,
List<Artboard>,
)]
list: T,
/// The index of the item to remove, starting from 0 for the first item. Negative indices count backwards from the end of the list, starting from -1 for the last item.
index: SignedInteger,
index: Item<SignedInteger>,
) -> T {
let index = index as i32;
let index = index.into_element() as i32;
if index < 0 {
list.omit_index_from_end(index.unsigned_abs() as usize)
@@ -70,62 +45,83 @@ pub fn omit_element<T: graphic_types::graphic::OmitIndex + Clone + Default>(
}
}
/// Returns the bare element (without the item's attributes) at the specified index in a `List`.
/// Use this when downstream nodes want just the inner value rather than a `List` containing a single item.
/// Returns the item at the specified index in a `List`, keeping its attributes.
/// If no value exists at that index, the element type's default is returned.
#[node_macro::node(category("General"))]
pub fn extract_element<T: Clone + Default + Send + Sync + 'static>(
#[node_macro::node(category("General"), name("Item at Index"))]
pub fn item_at_index<T: Clone + Default + Send + Sync + 'static>(
_: impl Ctx,
/// The `List` of data to extract from.
/// The `List` of data to take the item from.
#[implementations(
List<String>,
List<bool>,
List<f32>,
List<f64>,
List<u8>,
List<NodeId>,
List<Color>,
List<GradientStops>,
List<u32>,
List<u64>,
List<DVec2>,
List<DAffine2>,
List<Vector>,
List<Raster<CPU>>,
List<Graphic>,
List<Raster<CPU>>,
List<Color>,
List<Gradient>,
List<Artboard>,
)]
list: List<T>,
/// The index of the item to retrieve, starting from 0 for the first item. Negative indices count backwards from the end of the list, starting from -1 for the last item.
index: SignedInteger,
) -> T {
index: Item<SignedInteger>,
) -> Item<T> {
let len = list.len();
let index = index as i32;
let index = index.into_element() as i32;
let resolved = if index < 0 {
let from_end = index.unsigned_abs() as usize;
if from_end > len {
return T::default();
return Item::default();
}
len - from_end
} else {
index as usize
};
list.element(resolved).cloned().unwrap_or_default()
list.clone_item(resolved).unwrap_or_default()
}
#[node_macro::node(category("General"))]
async fn map<Item: AnyHash + Send + Sync + CacheHash>(
ctx: impl Ctx + CloneVarArgs + ExtractAll,
#[implementations(
List<Graphic>,
List<Vector>,
List<Raster<CPU>>,
List<Color>,
List<GradientStops>,
List<String>,
List<bool>,
List<f32>,
List<f64>,
List<u32>,
List<u64>,
List<DVec2>,
List<DAffine2>,
List<Vector>,
List<Graphic>,
List<Raster<CPU>>,
List<Raster<GPU>>,
List<Color>,
List<Gradient>,
List<Artboard>,
)]
content: List<Item>,
#[implementations(
Context -> List<Graphic>,
Context -> List<Vector>,
Context -> List<Raster<CPU>>,
Context -> List<Color>,
Context -> List<GradientStops>,
Context -> List<String>,
Context -> List<bool>,
Context -> List<f32>,
Context -> List<f64>,
Context -> List<u32>,
Context -> List<u64>,
Context -> List<DVec2>,
Context -> List<DAffine2>,
Context -> List<Vector>,
Context -> List<Graphic>,
Context -> List<Raster<CPU>>,
Context -> List<Raster<GPU>>,
Context -> List<Color>,
Context -> List<Gradient>,
Context -> List<Artboard>,
)]
mapped: impl Node<Context<'static>, Output = List<Item>>,
) -> List<Item> {
@@ -133,7 +129,7 @@ async fn map<Item: AnyHash + Send + Sync + CacheHash>(
for (i, row) in content.into_iter().enumerate() {
let owned_ctx = OwnedContextImpl::from(ctx.clone());
let owned_ctx = owned_ctx.with_vararg(Box::new(List::new_from_item(row))).with_index(i);
let owned_ctx = owned_ctx.with_vararg(Box::new(row)).with_index(i);
let list = mapped.eval(owned_ctx.into_context()).await;
rows.extend(list);
@@ -143,33 +139,34 @@ async fn map<Item: AnyHash + Send + Sync + CacheHash>(
}
#[node_macro::node(category("General"))]
async fn mirror<T: 'n + Send + Clone>(
async fn mirror<T: BoundingBox + 'n + Send + Clone>(
_: impl Ctx,
#[implementations(
List<Graphic>,
List<Vector>,
List<String>,
List<Raster<CPU>>,
List<Color>,
List<GradientStops>,
Graphic,
Vector,
Raster<CPU>,
Raster<GPU>,
Color,
Gradient,
String,
)]
content: List<T>,
#[default(ReferencePoint::Center)] relative_to_bounds: ReferencePoint,
#[unit(" px")] offset: f64,
content: Item<T>,
#[default(ReferencePoint::Center)] relative_to_bounds: Item<ReferencePoint>,
#[unit(" px")] offset: Item<f64>,
#[range]
#[soft(-90..90)]
angle: Angle,
#[default(true)] keep_original: bool,
) -> List<T>
where
List<T>: BoundingBox,
{
angle: Item<Angle>,
#[default(true)] keep_original: Item<bool>,
) -> List<T> {
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
let normal = DVec2::from_angle(angle.to_radians());
// The mirror reference may be based on the bounding box if an explicit reference point is chosen
let RenderBoundingBox::Rectangle(bounding_box) = content.bounding_box(DAffine2::IDENTITY, false) else {
return content;
let item_transform: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM);
let RenderBoundingBox::Rectangle(bounding_box) = content.element().bounding_box(item_transform, false) else {
return List::new_from_item(content);
};
let reference_point_location = relative_to_bounds.point_in_bounding_box((bounding_box[0], bounding_box[1]).into());
@@ -193,19 +190,14 @@ where
let mut result_list = List::new();
// Add original items depending on the keep_original flag
if keep_original {
for item in content.clone().into_iter() {
result_list.push(item);
}
result_list.push(content.clone());
}
// Create and add mirrored items
for mut row in content.into_iter() {
let current_transform: DAffine2 = row.attribute_cloned_or_default(ATTR_TRANSFORM);
row.set_attribute(ATTR_TRANSFORM, reflected_transform * current_transform);
result_list.push(row);
}
// Add the mirrored copy with the reflection composed onto its transform
let mut mirrored = content;
mirrored.set_attribute(ATTR_TRANSFORM, reflected_transform * item_transform);
result_list.push(mirrored);
result_list
}
@@ -217,95 +209,70 @@ where
/// editor tools (e.g. selection, click target routing) trace data back to its owning layer regardless of whether
/// the layer is at the root document network or nested inside a custom subgraph.
#[node_macro::node(name("Path of Subgraph"), category(""))]
pub fn path_of_subgraph(_: impl Ctx, node_path: List<NodeId>) -> List<NodeId> {
pub fn path_of_subgraph(_: impl Ctx, node_path: Item<NodeIdPath>) -> Item<NodeIdPath> {
let node_path = node_path.into_element().0;
let len = node_path.len();
node_path.into_iter().take(len.saturating_sub(1)).collect()
Item::new_from_element(NodeIdPath(node_path.into_iter().take(len.saturating_sub(1)).collect()))
}
/// 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
/// be derived from the item's own data. If the attribute already exists, its values are replaced; if not, it's added.
/// The value is type-erased into an `AttributeValueDyn` by an auto-inserted convert node, so this node only
/// The value is type-erased into an `Item<AttributeValueDyn>` by the auto-inserted input adapter, so this node only
/// monomorphizes over `T` instead of the cartesian product `(T, U)`.
#[node_macro::node(category("Attributes: Write"))]
async fn write_attribute<T: AnyHash + Clone + Send + Sync + CacheHash>(
ctx: impl ExtractAll + CloneVarArgs + Ctx,
/// The `List` to set the named attribute on (one value per item).
#[implementations(
List<Artboard>,
List<Graphic>,
List<Vector>,
List<Raster<CPU>>,
List<Color>,
List<GradientStops>,
List<f64>,
List<bool>,
List<String>,
List<bool>,
List<f32>,
List<f64>,
List<u32>,
List<u64>,
List<DVec2>,
List<DAffine2>,
List<Vector>,
List<Graphic>,
List<Raster<CPU>>,
List<Raster<GPU>>,
List<Color>,
List<Gradient>,
List<Artboard>,
List<BlendMode>,
List<GradientType>,
List<GradientSpreadMethod>,
)]
mut content: List<T>,
content: List<T>,
/// The attribute name (key) to write or replace.
name: String,
name: Item<String>,
/// The node that produces the attribute value for each item. Called once per item with the item's index in context.
#[implementations(Context -> AttributeValueDyn)]
value: impl Node<'n, Context<'static>, Output = AttributeValueDyn>,
#[implementations(Context -> Item<AttributeValueDyn>)]
value: impl Node<'n, Context<'static>, Output = Item<AttributeValueDyn>>,
) -> List<T> {
let name = name.into_element();
let mut content = content;
for index in 0..content.len() {
let row = content.clone_item(index).expect("index is within bounds");
let owned_ctx = OwnedContextImpl::from(ctx.clone()).with_vararg(Box::new(List::new_from_item(row))).with_index(index);
let v = value.eval(owned_ctx.into_context()).await;
let owned_ctx = OwnedContextImpl::from(ctx.clone()).with_vararg(Box::new(row)).with_index(index);
let v = value.eval(owned_ctx.into_context()).await.into_element();
content.set_attribute_value_dyn(&name, index, v);
}
content
}
/// Sets a named attribute on the primary list, with each value taken from the corresponding item's element in the source list (paired by index, wrapping if the source has fewer items).
/// The source is type-erased into an `AttributeDyn` by an auto-inserted convert node, so this node only monomorphizes over `T` instead of the cartesian product `(T, U)`.
#[node_macro::node(category("Attributes: Write"))]
fn attach_attribute<T: AnyHash + Clone + Send + Sync + CacheHash>(
_: impl Ctx,
/// The `List` to attach the new attribute to.
#[implementations(
List<Artboard>,
List<Graphic>,
List<Vector>,
List<Raster<CPU>>,
List<Color>,
List<GradientStops>,
List<f64>,
List<bool>,
List<String>,
List<DAffine2>,
List<BlendMode>,
List<GradientType>,
List<GradientSpreadMethod>,
)]
mut content: List<T>,
/// The source values to attach.
#[expose]
source: AttributeDyn,
/// The name to assign to the new destination attribute.
name: String,
) -> List<T> {
if source.is_empty() {
return content;
}
content.set_attribute_dyn(name, source);
content
}
/// Reads a named `Vector` attribute from the input list, outputting each value as an element of a new `Vector[]`.
#[node_macro::node(category("Attributes: Read"))]
fn read_attribute_vector(
_: impl Ctx,
content: ListDyn,
/// The attribute name (key) to read.
name: String,
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 };
@@ -320,8 +287,9 @@ fn read_attribute_number(
_: impl Ctx,
content: ListDyn,
/// The attribute name (key) to read.
name: String,
name: Item<String>,
) -> List<f64> {
let name = name.into_element();
let mut result = List::with_capacity(content.len());
for index in 0..content.len() {
let value = content
@@ -341,8 +309,9 @@ fn read_attribute_bool(
_: impl Ctx,
content: ListDyn,
/// The attribute name (key) to read.
name: String,
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 };
@@ -357,8 +326,9 @@ fn read_attribute_string(
_: impl Ctx,
content: ListDyn,
/// The attribute name (key) to read.
name: String,
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 };
@@ -373,8 +343,9 @@ fn read_attribute_transform(
_: impl Ctx,
content: ListDyn,
/// The attribute name (key) to read.
name: String,
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 };
@@ -389,8 +360,9 @@ fn read_attribute_color(
_: impl Ctx,
content: ListDyn,
/// The attribute name (key) to read.
name: String,
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 };
@@ -405,8 +377,9 @@ fn read_attribute_blend_mode(
_: impl Ctx,
content: ListDyn,
/// The attribute name (key) to read.
name: String,
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 };
@@ -421,8 +394,9 @@ fn read_attribute_gradient_type(
_: impl Ctx,
content: ListDyn,
/// The attribute name (key) to read.
name: String,
name: Item<String>,
) -> List<GradientType> {
let name = name.into_element();
let mut result = List::with_capacity(content.len());
for index in 0..content.len() {
let Some(value) = content.attribute::<GradientType>(&name, index) else { continue };
@@ -437,8 +411,9 @@ fn read_attribute_spread_method(
_: impl Ctx,
content: ListDyn,
/// The attribute name (key) to read.
name: String,
name: Item<String>,
) -> List<GradientSpreadMethod> {
let name = name.into_element();
let mut result = List::with_capacity(content.len());
for index in 0..content.len() {
let Some(value) = content.attribute::<GradientSpreadMethod>(&name, index) else { continue };
@@ -447,17 +422,18 @@ fn read_attribute_spread_method(
result
}
/// Reads a named `GradientStops` attribute from the input list, outputting each value as an element of a new `GradientStops[]`.
/// Reads a named `Gradient` attribute from the input list, outputting each value as an element of a new `Gradient[]`.
#[node_macro::node(category("Attributes: Read"))]
fn read_attribute_gradient_stops(
_: impl Ctx,
content: ListDyn,
/// The attribute name (key) to read.
name: String,
) -> List<GradientStops> {
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::<GradientStops>(&name, index) else { continue };
let Some(value) = content.attribute::<Gradient>(&name, index) else { continue };
result.push(Item::new_from_element(value.clone()));
}
result
@@ -469,8 +445,9 @@ fn read_attribute_artboard(
_: impl Ctx,
content: ListDyn,
/// The attribute name (key) to read.
name: String,
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 };
@@ -485,8 +462,9 @@ fn read_attribute_raster(
_: impl Ctx,
content: ListDyn,
/// The attribute name (key) to read.
name: String,
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 };
@@ -500,11 +478,43 @@ fn read_attribute_raster(
pub async fn extend<T: 'n + Send + Clone>(
_: impl Ctx,
/// The `List` whose items will appear at the start of the extended `List`.
#[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<String>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<GradientStops>)]
#[implementations(
List<String>,
List<bool>,
List<f32>,
List<f64>,
List<u32>,
List<u64>,
List<DVec2>,
List<DAffine2>,
List<Vector>,
List<Graphic>,
List<Raster<CPU>>,
List<Raster<GPU>>,
List<Color>,
List<Gradient>,
List<Artboard>,
)]
base: List<T>,
/// The `List` whose items will appear at the end of the extended `List`.
#[expose]
#[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<String>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<GradientStops>)]
#[implementations(
List<String>,
List<bool>,
List<f32>,
List<f64>,
List<u32>,
List<u64>,
List<DVec2>,
List<DAffine2>,
List<Vector>,
List<Graphic>,
List<Raster<CPU>>,
List<Raster<GPU>>,
List<Color>,
List<Gradient>,
List<Artboard>,
)]
new: List<T>,
) -> List<T> {
let mut base = base;
@@ -519,22 +529,22 @@ pub async fn extend<T: 'n + Send + Clone>(
#[node_macro::node(category(""))]
pub async fn legacy_layer_extend<T: 'n + Send + Clone>(
_: impl Ctx,
#[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<String>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<GradientStops>)] base: List<T>,
#[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<String>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<Gradient>)] base: List<T>,
#[expose]
#[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<String>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<GradientStops>)]
#[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: List<NodeId>,
nested_node_path: Item<NodeIdPath>,
) -> List<T> {
// Get the penultimate element of the node path, or None if the path is too short
// This is used to get the ID of the user-facing parent layer-style node (which encapsulates this internal node).
let layer = {
let index = nested_node_path.len().wrapping_sub(2);
nested_node_path.element(index).copied()
// 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 = {
let len = nested_node_path.len();
NodeIdPath(nested_node_path.into_iter().take(len.saturating_sub(1)).collect())
};
let mut base = base;
for mut row in new.into_iter() {
row.set_attribute(ATTR_EDITOR_LAYER_PATH, layer);
row.set_attribute(ATTR_EDITOR_LAYER_PATH, layer_path.clone());
base.push(row);
}
@@ -552,14 +562,14 @@ pub async fn wrap_graphic<T: Into<Graphic> + 'n>(
List<Raster<CPU>>,
List<Raster<GPU>>,
List<Color>,
List<GradientStops>,
List<Gradient>,
List<String>,
DAffine2,
DVec2,
Item<DAffine2>,
Item<DVec2>,
)]
content: T,
) -> List<Graphic> {
List::new_from_element(content.into())
) -> Item<Graphic> {
Item::new_from_element(content.into())
}
/// Converts a list of graphical content into a `Graphic[]` by placing it into an element of a new wrapper `Graphic[]`.
@@ -573,7 +583,7 @@ pub async fn to_graphic<T: IntoGraphicList>(
List<Raster<CPU>>,
List<Raster<GPU>>,
List<Color>,
List<GradientStops>,
List<Gradient>,
List<String>,
)]
content: T,
@@ -583,7 +593,9 @@ pub async fn to_graphic<T: IntoGraphicList>(
/// Removes a level of nesting from a `Graphic[]`, or all nesting if "Fully Flatten" is enabled.
#[node_macro::node(category("General"))]
pub async fn flatten_graphic(_: impl Ctx, content: List<Graphic>, fully_flatten: bool) -> List<Graphic> {
pub async fn flatten_graphic(_: impl Ctx, content: List<Graphic>, fully_flatten: Item<bool>) -> List<Graphic> {
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) {
for index in 0..current_graphic_list.len() {
@@ -663,20 +675,20 @@ pub async fn flatten_color<T: IntoGraphicList>(_: impl Ctx, #[implementations(Li
content.into_flattened_list()
}
/// Converts a `Graphic[]` into a `GradientStops[]` by deeply flattening any gradient content it contains, and discarding any non-gradient content.
/// Converts a `Graphic[]` into a `Gradient[]` by deeply flattening any gradient content it contains, and discarding any non-gradient content.
#[node_macro::node(category("General"))]
pub async fn flatten_gradient<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<GradientStops>)] content: T) -> List<GradientStops> {
pub async fn flatten_gradient<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Gradient>)] content: T) -> List<Gradient> {
content.into_flattened_list()
}
/// Constructs a gradient from a `Color[]`, where the colors are evenly distributed as gradient stops across the range from 0 to 1.
#[node_macro::node(category("Color"))]
fn colors_to_gradient<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Color>)] colors: T) -> List<GradientStops> {
#[node_macro::node(category("Color"), name("Colors to Gradient"))]
fn colors_to_gradient<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Color>)] colors: T) -> Item<Gradient> {
let colors = colors.into_flattened_list::<Color>();
let total_colors = colors.len();
if total_colors == 0 {
return List::new_from_element(GradientStops::new(vec![
return Item::new_from_element(Gradient::new(vec![
GradientStop {
position: 0.,
midpoint: 0.5,
@@ -691,7 +703,7 @@ fn colors_to_gradient<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Gr
}
if let (1, Some(&single_color)) = (total_colors, colors.element(0)) {
return List::new_from_element(GradientStops::new(vec![
return Item::new_from_element(Gradient::new(vec![
GradientStop {
position: 0.,
midpoint: 0.5,
@@ -710,5 +722,5 @@ fn colors_to_gradient<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Gr
midpoint: 0.5,
color: row.into_element(),
});
List::new_from_element(GradientStops::new(colors))
Item::new_from_element(Gradient::new(colors))
}

View File

@@ -58,7 +58,7 @@ pub mod subpath {
}
pub mod gradient {
pub use vector_types::{GradientStop, GradientStops};
pub use vector_types::{Gradient, GradientStop};
}
pub mod transform {

View File

@@ -3,10 +3,12 @@ use base64::Engine;
#[cfg(target_family = "wasm")]
use canvas_utils::{Canvas, CanvasHandle};
use core_types::color::SRGBA8;
use core_types::list::{Item, List};
use core_types::list::Item;
#[cfg(target_family = "wasm")]
use core_types::list::List;
#[cfg(target_family = "wasm")]
use core_types::math::bbox::Bbox;
#[cfg(target_family = "wasm")]
use core_types::ops::Convert;
use core_types::transform::Footprint;
#[cfg(target_family = "wasm")]
use core_types::{ATTR_EDITOR_MERGED_LAYERS, ATTR_TRANSFORM, WasmNotSend};
@@ -23,12 +25,11 @@ use graphic_types::IntoGraphicList;
#[cfg(target_family = "wasm")]
use graphic_types::Vector;
use graphic_types::raster_types::Image;
use graphic_types::raster_types::{CPU, Raster};
use graphic_types::raster_types::{CPU, GPU, Raster};
#[cfg(target_family = "wasm")]
use graphic_types::vector_types::gradient::GradientStops;
use graphic_types::vector_types::gradient::Gradient;
#[cfg(target_family = "wasm")]
use rendering::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
use std::sync::Arc;
fn parse_headers(headers: &str) -> reqwest::header::HeaderMap {
use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
@@ -51,11 +52,14 @@ async fn get_request(
_primary: (),
/// The web address to send the GET request to.
#[name("URL")]
url: String,
url: Item<String>,
/// Makes the request run in the background without waiting on a response. This is useful for triggering webhooks without blocking the continued execution of the graph.
discard_result: bool,
#[widget(ParsedWidgetOverride::Custom = "text_area")] headers: String,
) -> String {
discard_result: Item<bool>,
#[widget(ParsedWidgetOverride::Custom = "text_area")] headers: Item<String>,
) -> Item<String> {
let (url, headers) = (url.into_element(), headers.into_element());
let discard_result = *discard_result.element();
let header_map = parse_headers(&headers);
let request = reqwest::Client::new().get(url).headers(header_map);
@@ -68,13 +72,13 @@ async fn get_request(
tokio::spawn(async move {
let _ = request.send().await;
});
return String::new();
return Item::default();
}
let Ok(response) = request.send().await else {
return String::new();
return Item::default();
};
response.text().await.ok().unwrap_or_default()
Item::new_from_element(response.text().await.ok().unwrap_or_default())
}
/// Sends an HTTP POST request to a specified URL with the provided binary data and optionally waits for the response (unless discarded) which is output as a string.
@@ -84,16 +88,19 @@ async fn post_request(
_primary: (),
/// The web address to send the POST request to.
#[name("URL")]
url: String,
url: Item<String>,
/// The binary data to include in the body of the POST request.
body: List<u8>,
body: Item<Resource>,
/// Makes the request run in the background without waiting on a response. This is useful for triggering webhooks without blocking the continued execution of the graph.
discard_result: bool,
#[widget(ParsedWidgetOverride::Custom = "text_area")] headers: String,
) -> String {
discard_result: Item<bool>,
#[widget(ParsedWidgetOverride::Custom = "text_area")] headers: Item<String>,
) -> Item<String> {
let (url, headers) = (url.into_element(), headers.into_element());
let discard_result = *discard_result.element();
let mut header_map = parse_headers(&headers);
header_map.insert("Content-Type", "application/octet-stream".parse().unwrap());
let body_bytes: Vec<u8> = body.iter_element_values().copied().collect();
let body_bytes: Vec<u8> = body.element().as_ref().to_vec();
let request = reqwest::Client::new().post(url).body(body_bytes).headers(header_map);
if discard_result {
@@ -105,40 +112,42 @@ async fn post_request(
tokio::spawn(async move {
let _ = request.send().await;
});
return String::new();
return Item::default();
}
let Ok(response) = request.send().await else {
return String::new();
return Item::default();
};
response.text().await.ok().unwrap_or_default()
Item::new_from_element(response.text().await.ok().unwrap_or_default())
}
/// Converts a text string to raw binary data. Useful for transmission over HTTP or writing to files.
#[node_macro::node(category("Web Request"), name("String to Bytes"))]
fn string_to_bytes(_: impl Ctx, string: String) -> List<u8> {
string.into_bytes().into_iter().map(Item::new_from_element).collect()
fn string_to_bytes(_: impl Ctx, string: Item<String>) -> Item<Resource> {
Item::new_from_element(Resource::new(string.into_element().into_bytes()))
}
/// Converts extracted raw RGBA pixel data from an input image. Each pixel becomes 4 sequential bytes. Useful for transmission over HTTP or writing to files.
#[node_macro::node(category("Web Request"), name("Image to Bytes"))]
fn image_to_bytes(_: impl Ctx, image: List<Raster<CPU>>) -> List<u8> {
let Some(image) = image.element(0) else { return List::new() };
image
fn image_to_bytes(_: impl Ctx, image: Item<Raster<CPU>>) -> Item<Resource> {
let bytes: Vec<u8> = image
.element()
.data
.iter()
.flat_map(|color| {
let SRGBA8 { red, green, blue, alpha } = (*color).into();
[red, green, blue, alpha]
})
.map(Item::new_from_element)
.collect()
.collect();
Item::new_from_element(Resource::new(bytes))
}
/// Loads binary from URLs and local asset paths. Returns a transparent placeholder if the resource fails to load, allowing rendering to continue.
#[node_macro::node(category("Web Request"))]
async fn load_resource<'a: 'n>(_: impl Ctx, _primary: (), #[name("URL")] url: String) -> Arc<[u8]> {
let placeholder = || -> Arc<[u8]> { Arc::from(Vec::<u8>::new()) };
async fn load_resource<'a: 'n>(_: impl Ctx, _primary: (), #[name("URL")] url: Item<String>) -> Item<Resource> {
let url = url.into_element();
let placeholder = || -> Item<Resource> { Item::new_from_element(Resource::empty()) };
let response = match reqwest::Client::new().get(&url).send().await {
Ok(response) => response,
@@ -149,7 +158,7 @@ async fn load_resource<'a: 'n>(_: impl Ctx, _primary: (), #[name("URL")] url: St
};
match response.bytes().await {
Ok(bytes) => Arc::from(bytes.to_vec()),
Ok(bytes) => Item::new_from_element(Resource::new(bytes)),
Err(error) => {
log::error!("Failed to read HTTP response for `{url}`: {error}");
placeholder()
@@ -161,9 +170,10 @@ async fn load_resource<'a: 'n>(_: impl Ctx, _primary: (), #[name("URL")] url: St
///
/// Works with standard image format (PNG, JPEG, WebP, etc.). Automatically converts the color space to linear sRGB for accurate compositing.
#[node_macro::node(category("Web Request"))]
fn decode_image(_: impl Ctx, data: Arc<[u8]>) -> List<Raster<CPU>> {
fn decode_image(_: impl Ctx, data: Item<Resource>) -> Item<Raster<CPU>> {
let data = data.into_element();
let Some(image) = image::load_from_memory(data.as_ref()).ok() else {
return List::new();
return Item::default();
};
let image = image.to_rgba32f();
let image = Image {
@@ -180,13 +190,13 @@ fn decode_image(_: impl Ctx, data: Arc<[u8]>) -> List<Raster<CPU>> {
..Default::default()
};
List::new_from_element(Raster::new_cpu(image))
Item::new_from_element(Raster::new_cpu(image))
}
#[cfg(target_family = "wasm")]
#[node_macro::node(category(""))]
async fn create_canvas(_: impl Ctx) -> CanvasHandle {
CanvasHandle::new()
async fn create_canvas(_: impl Ctx) -> Item<CanvasHandle> {
Item::new_from_element(CanvasHandle::new())
}
/// Renders a view of the input graphic within an area defined by the *Footprint*.
@@ -199,17 +209,21 @@ async fn rasterize<T: WasmNotSend + Clone + 'n>(
List<Raster<CPU>>,
List<Graphic>,
List<Color>,
List<GradientStops>,
List<Gradient>,
)]
mut data: List<T>,
footprint: Footprint,
mut canvas: CanvasHandle,
data: List<T>,
footprint: Item<Footprint>,
canvas: Item<CanvasHandle>,
) -> List<Raster<CPU>>
where
List<T>: Render + Clone + graphic_types::IntoGraphicList,
{
let mut data = data;
let mut canvas = canvas.into_element();
use glam::{DAffine2, DVec2};
let footprint = footprint.into_element();
if footprint.transform.matrix2.determinant() == 0. {
log::trace!("Invalid footprint received for rasterization");
return List::new();
@@ -262,29 +276,48 @@ where
}
#[node_macro::node(category(""), inject_scope)]
pub async fn editor_api<'a: 'n>(_: impl Ctx, #[scope("editor-api")] editor_api: &'a PlatformEditorApi) -> &'a PlatformEditorApi {
pub async fn editor_api<'a: 'n>(_: impl Ctx, #[scope("editor-api")] editor_api: Item<&'a PlatformEditorApi>) -> Item<&'a PlatformEditorApi> {
editor_api
}
#[node_macro::node(category(""))]
pub async fn resource<'a: 'n>(_: impl Ctx, hash: ResourceHash, #[scope(editor_api::IDENTIFIER)] editor_api: &'a PlatformEditorApi) -> Resource {
let application_io = editor_api.application_io.as_ref().expect("ApplicationIo must be available when using resources");
application_io.load_resource(hash).await.unwrap_or_else(|| {
panic!("Resource {hash} not found");
})
pub async fn resource<'a: 'n>(
_: impl Ctx,
/// The scope-provided editor API giving access to the platform's resource storage.
#[scope(editor_api::IDENTIFIER)]
editor_api: Item<&'a PlatformEditorApi>,
/// The content hash identifying which stored resource to load.
hash: Item<ResourceHash>,
) -> Item<Resource> {
let hash = hash.into_element();
let application_io = editor_api.into_element().application_io.as_ref().expect("ApplicationIo must be available when using resources");
let resource = application_io.load_resource(hash).await.unwrap_or_else(|| panic!("Resource {hash} not found"));
Item::new_from_element(resource)
}
#[node_macro::node(category(""), inject_scope)]
pub async fn wgpu_executor<'a: 'n>(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: &'a PlatformEditorApi) -> &'a ::wgpu_executor::WgpuExecutor {
editor_api
pub async fn wgpu_executor<'a: 'n>(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: Item<&'a PlatformEditorApi>) -> Item<&'a ::wgpu_executor::WgpuExecutor> {
let executor = editor_api
.into_element()
.application_io
.as_ref()
.expect("ApplicationIo not not available")
.expect("ApplicationIo not available")
.gpu_executor()
.expect("GPU executor not available")
.expect("GPU executor not available");
Item::new_from_element(executor)
}
#[node_macro::node(category(""), inject_scope)]
pub async fn try_wgpu_executor<'a: 'n>(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: &'a PlatformEditorApi) -> Option<&'a ::wgpu_executor::WgpuExecutor> {
editor_api.application_io.as_ref()?.gpu_executor()
pub async fn try_wgpu_executor<'a: 'n>(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: Item<&'a PlatformEditorApi>) -> Item<Option<&'a ::wgpu_executor::WgpuExecutor>> {
let executor = editor_api.into_element().application_io.as_ref().and_then(|application_io| application_io.gpu_executor());
Item::new_from_element(executor)
}
/// Uploads image data from CPU memory into a GPU texture so that GPU-based nodes can process it.
#[node_macro::node(category("Debug"), memoize)]
pub async fn upload_texture<'a: 'n>(_: impl Ctx, content: Item<Raster<CPU>>, #[scope(wgpu_executor::IDENTIFIER)] executor: Item<&'a ::wgpu_executor::WgpuExecutor>) -> Item<Raster<GPU>> {
let executor = executor.into_element();
let (raster, attributes) = content.into_parts();
Item::from_parts(raster.convert(Footprint::DEFAULT, executor).await, attributes)
}

View File

@@ -1,5 +1,6 @@
use core_types::ExtractVarArgs;
use core_types::color::Linear;
use core_types::list::Item;
use core_types::transform::Footprint;
use core_types::uuid::generate_uuid;
use core_types::{Ctx, ExtractFootprint};
@@ -14,9 +15,9 @@ use wgpu_executor::{AsyncWgpuPipeline, WgpuExecutor, WgpuPipelineCache};
#[node_macro::node(category(""))]
async fn render_background<'a: 'n>(
ctx: impl Ctx + ExtractFootprint + ExtractVarArgs,
#[scope(composite_background_pipeline::IDENTIFIER)] pipeline: WgpuPipelineCache,
data: RenderOutput,
) -> RenderOutput {
#[scope(composite_background_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>,
data: Item<RenderOutput>,
) -> Item<RenderOutput> {
let footprint = ctx.footprint();
let render_params = ctx
.vararg(0)
@@ -28,7 +29,7 @@ async fn render_background<'a: 'n>(
return data;
}
let RenderOutput { data: foreground_data, metadata } = data;
let RenderOutput { data: foreground_data, metadata } = data.into_element();
let mut render_params = render_params.clone();
render_params.footprint = *footprint;
@@ -36,6 +37,7 @@ async fn render_background<'a: 'n>(
RenderOutputType::Texture(foreground_texture) => {
let doc_to_screen = render_params.footprint.transform.as_affine2();
let blended = pipeline
.into_element()
.run::<CompositeBackground>(&CompositeBackgroundArgs {
foreground: foreground_texture.as_ref(),
backgrounds: &metadata.backgrounds,
@@ -117,19 +119,19 @@ async fn render_background<'a: 'n>(
_ => unreachable!("Render background node received unsupported render output type"),
};
RenderOutput { data, metadata }
Item::new_from_element(RenderOutput { data, metadata })
}
#[node_macro::node(category(""), inject_scope)]
async fn composite_background_pipeline<'a: 'n>(
_ctx: impl Ctx,
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Option<&'a WgpuExecutor>,
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Item<Option<&'a WgpuExecutor>>,
#[data] pipeline: WgpuPipelineCache,
) -> WgpuPipelineCache {
if let Some(executor) = executor {
) -> Item<WgpuPipelineCache> {
if let Some(executor) = executor.into_element() {
executor.pipeline_init::<CompositeBackground>(pipeline);
}
pipeline.clone()
Item::new_from_element(pipeline.clone())
}
pub struct CompositeBackground {

View File

@@ -1,5 +1,6 @@
//! Tile-based render caching for efficient viewport panning.
use core_types::list::Item;
use core_types::math::bbox::AxisAlignedBbox;
use core_types::transform::{Footprint, RenderQuality, Transform};
use core_types::{CloneVarArgs, Context, Ctx, ExtractAll, ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime, OwnedContextImpl};
@@ -323,11 +324,11 @@ fn flood_fill(start: &TileCoord, tile_set: &HashSet<TileCoord>, visited: &mut Ha
#[node_macro::node(category(""))]
pub async fn render_output_cache<'a: 'n>(
ctx: impl Ctx + ExtractAll + CloneVarArgs + ExtractRealTime + ExtractAnimationTime + ExtractPointerPosition + Sync,
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Option<&'a WgpuExecutor>,
#[scope(crate::platform_application_io::editor_api::IDENTIFIER)] editor_api: &'a PlatformEditorApi,
data: impl Node<Context<'static>, Output = RenderOutput> + Send + Sync,
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Item<Option<&'a WgpuExecutor>>,
#[scope(crate::platform_application_io::editor_api::IDENTIFIER)] editor_api: Item<&'a PlatformEditorApi>,
data: impl Node<Context<'static>, Output = Item<RenderOutput>> + Send + Sync,
#[data] tile_cache: TileCache,
) -> RenderOutput {
) -> Item<RenderOutput> {
let footprint = ctx.footprint();
let Some(render_params) = ctx.vararg(0).ok().and_then(|v| v.downcast_ref::<RenderParams>()) else {
log::warn!("render_output_cache: missing or invalid render params, falling back to direct render");
@@ -351,7 +352,7 @@ pub async fn render_output_cache<'a: 'n>(
end: footprint.resolution.as_dvec2() - device_origin_offset,
};
let max_region_area = editor_api.editor_preferences.max_render_region_area();
let max_region_area = editor_api.into_element().editor_preferences.max_render_region_area();
let cache_key = CacheKey::new(
max_region_area,
@@ -389,15 +390,15 @@ pub async fn render_output_cache<'a: 'n>(
return data.eval(context.into_context()).await;
}
let executor = executor.expect("GPU executor not available");
let executor = executor.into_element().expect("GPU executor not available");
let output_texture = executor.request_texture(physical_resolution).await;
let combined_metadata = composite_cached_regions(&all_regions, &output_texture, &device_origin_offset, &footprint.transform, executor);
RenderOutput {
Item::new_from_element(RenderOutput {
data: RenderOutputType::Texture(output_texture),
metadata: combined_metadata,
}
})
}
async fn render_missing_region<F, Fut>(
@@ -410,7 +411,7 @@ async fn render_missing_region<F, Fut>(
) -> CachedRegion
where
F: Fn(Context<'static>) -> Fut,
Fut: std::future::Future<Output = RenderOutput>,
Fut: std::future::Future<Output = Item<RenderOutput>>,
{
let min_tile = region.tiles.iter().fold(IVec2::new(i32::MAX, i32::MAX), |acc, t| acc.min(IVec2::new(t.x, t.y)));
let max_tile = region.tiles.iter().fold(IVec2::new(i32::MIN, i32::MIN), |acc, t| acc.max(IVec2::new(t.x, t.y)));
@@ -428,7 +429,7 @@ where
let region_params = render_params.clone();
let region_ctx = OwnedContextImpl::from(ctx).with_footprint(region_footprint).with_vararg(Box::new(region_params)).into_context();
let mut result = render_fn(region_ctx).await;
let mut result = render_fn(region_ctx).await.into_element();
let RenderOutputType::Texture(texture) = result.data else {
unreachable!("render_missing_region: expected texture output from Vello render");

View File

@@ -1,4 +1,4 @@
use core_types::list::List;
use core_types::list::{Item, List};
use core_types::transform::{Footprint, Transform};
use core_types::{CloneVarArgs, ExtractAll, ExtractVarArgs};
use core_types::{Color, Context, Ctx, ExtractFootprint, OwnedContextImpl, WasmNotSend};
@@ -8,7 +8,7 @@ use graphic_types::raster_types::{CPU, Raster};
use graphic_types::{Artboard, Graphic, Vector};
use rendering::{Render, RenderMetadata, RenderOutputType as RenderOutputTypeRequest, RenderParams, SvgRender, SvgRenderOutput};
use std::sync::Arc;
use vector_types::GradientStops;
use vector_types::Gradient;
use wgpu_executor::{RenderContext, WgpuExecutor};
#[derive(Clone, dyn_any::DynAny)]
@@ -31,11 +31,11 @@ async fn render_intermediate<'a: 'n, T: 'static + Render + WasmNotSend + Send +
Context -> List<Vector>,
Context -> List<Raster<CPU>>,
Context -> List<Color>,
Context -> List<GradientStops>,
Context -> List<Gradient>,
Context -> List<String>,
)]
data: impl Node<Context<'static>, Output = T>,
) -> RenderIntermediate {
) -> Item<RenderIntermediate> {
let render_params = ctx
.vararg(0)
.expect("Did not find var args")
@@ -48,7 +48,7 @@ async fn render_intermediate<'a: 'n, T: 'static + Render + WasmNotSend + Send +
let footprint = Footprint::default();
let mut metadata = RenderMetadata::default();
data.collect_metadata(&mut metadata, footprint, None);
match &render_params.render_output_type {
let intermediate = match &render_params.render_output_type {
RenderOutputTypeRequest::Vello => {
let mut scene = vello::Scene::new();
@@ -70,15 +70,17 @@ async fn render_intermediate<'a: 'n, T: 'static + Render + WasmNotSend + Send +
metadata,
}
}
}
};
Item::new_from_element(intermediate)
}
#[node_macro::node(category(""))]
async fn render<'a: 'n>(
ctx: impl Ctx + ExtractFootprint + ExtractVarArgs,
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Option<&'a WgpuExecutor>,
data: RenderIntermediate,
) -> RenderOutput {
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Item<Option<&'a WgpuExecutor>>,
data: Item<RenderIntermediate>,
) -> Item<RenderOutput> {
let footprint = ctx.footprint();
let render_params = ctx
.vararg(0)
@@ -88,7 +90,7 @@ async fn render<'a: 'n>(
let mut render_params = render_params.clone();
render_params.footprint = *footprint;
let RenderIntermediate { ty, mut metadata } = data;
let RenderIntermediate { ty, mut metadata } = data.into_element();
metadata.apply_transform(footprint.transform);
let data = match (render_params.render_output_type, ty) {
@@ -131,6 +133,7 @@ async fn render<'a: 'n>(
}
let texture = executor
.into_element()
.expect("GPU executor not available")
.render_vello_scene(&transformed_scene, footprint.resolution, context, None)
.await
@@ -140,15 +143,20 @@ async fn render<'a: 'n>(
_ => unreachable!("Render node did not receive its requested data type"),
};
RenderOutput { data, metadata }
Item::new_from_element(RenderOutput { data, metadata })
}
#[node_macro::node(category(""))]
async fn create_context<'a: 'n>(
// Context injections are defined in the wrap_network_in_scope function
render_config: RenderConfig,
data: impl Node<Context<'static>, Output = RenderOutput>,
) -> RenderOutput {
// The executor boundary supplies the render config as the sole vararg (see `wrap_network_in_scope()`)
ctx: impl Ctx + ExtractAll + CloneVarArgs + Sync,
data: impl Node<Context<'static>, Output = Item<RenderOutput>>,
) -> Item<RenderOutput> {
let render_config = ctx.vararg(0).ok().and_then(|config| config.downcast_ref::<RenderConfig>()).copied().unwrap_or_else(|| {
log::error!("The boundary context is missing its render config vararg");
RenderConfig::default()
});
let render_output_type = match render_config.export_format {
ExportFormat::Svg => RenderOutputTypeRequest::Svg,
ExportFormat::Raster => RenderOutputTypeRequest::Vello,
@@ -179,6 +187,6 @@ async fn create_context<'a: 'n>(
let mut result = data.eval(ctx).await;
result.metadata.apply_transform(glam::DAffine2::from_scale(glam::DVec2::splat(1. / render_config.scale)));
result.element_mut().metadata.apply_transform(glam::DAffine2::from_scale(glam::DVec2::splat(1. / render_config.scale)));
result
}

View File

@@ -1,3 +1,4 @@
use core_types::list::Item;
use core_types::transform::{Footprint, Transform};
use core_types::{CloneVarArgs, Context, Ctx, ExtractAll, OwnedContextImpl};
use glam::{DAffine2, DVec2, UVec2, Vec2};
@@ -10,9 +11,9 @@ use wgpu_executor::{AsyncWgpuPipeline, WgpuExecutor, WgpuPipelineCache};
#[node_macro::node(category(""))]
pub async fn render_pixel_preview<'a: 'n>(
ctx: impl Ctx + ExtractAll + CloneVarArgs + Sync,
#[scope(pixel_preview_pipeline::IDENTIFIER)] pipeline: WgpuPipelineCache,
data: impl Node<Context<'static>, Output = RenderOutput> + Send + Sync,
) -> RenderOutput {
#[scope(pixel_preview_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>,
data: impl Node<Context<'static>, Output = Item<RenderOutput>> + Send + Sync,
) -> Item<RenderOutput> {
let Some(render_params) = ctx.vararg(0).ok().and_then(|v| v.downcast_ref::<RenderParams>()).cloned() else {
log::error!("invalid render params for pixel preview");
let context = OwnedContextImpl::from(ctx).into_context();
@@ -52,14 +53,17 @@ pub async fn render_pixel_preview<'a: 'n>(
};
let new_ctx = OwnedContextImpl::from(ctx).with_footprint(upstream_footprint).with_vararg(Box::new(render_params)).into_context();
let mut result = data.eval(new_ctx).await;
let mut result = data.eval(new_ctx).await.into_element();
let RenderOutputType::Texture(ref source_texture) = result.data else { return result };
let RenderOutputType::Texture(ref source_texture) = result.data else {
return Item::new_from_element(result);
};
let logical_transform = DAffine2::from_scale(DVec2::splat(1. / physical_scale)) * footprint.transform;
let transform = DAffine2::from_translation(-upstream_min) * logical_transform.inverse() * DAffine2::from_scale(logical_resolution);
let resampled = pipeline
.into_element()
.run::<PixelPreview>(&PixelPreviewArgs {
source: source_texture.as_ref(),
transform: &transform,
@@ -71,19 +75,19 @@ pub async fn render_pixel_preview<'a: 'n>(
result.metadata.apply_transform(footprint.transform * DAffine2::from_translation(upstream_min));
result
Item::new_from_element(result)
}
#[node_macro::node(category(""), inject_scope)]
async fn pixel_preview_pipeline<'a: 'n>(
_ctx: impl Ctx,
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Option<&'a WgpuExecutor>,
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Item<Option<&'a WgpuExecutor>>,
#[data] pipeline: WgpuPipelineCache,
) -> WgpuPipelineCache {
if let Some(executor) = executor {
) -> Item<WgpuPipelineCache> {
if let Some(executor) = executor.into_element() {
executor.pipeline_init::<PixelPreview>(pipeline);
}
pipeline.clone()
Item::new_from_element(pipeline.clone())
}
pub struct PixelPreview {

View File

@@ -1,11 +1,11 @@
use core_types::consts::{DEFAULT_FONT_SIZE, DEFAULT_LINE_HEIGHT};
use core_types::list::List;
use core_types::list::{Item, List};
use core_types::{ATTR_FONT, ATTR_FONT_SIZE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_TEXT_ALIGN, Ctx};
use graph_craft::application_io::resource::Resource;
use graphic_types::Vector;
pub use text_nodes::*;
/// Produces a styled `String[]` carrying all typographic attributes.
/// Produces a styled text string carrying all typographic attributes.
///
/// Use the **Text to Vector** node to convert this into vector geometry if desired.
#[node_macro::node(category("Text"))]
@@ -15,15 +15,15 @@ fn text(
/// The text content to be drawn.
#[widget(ParsedWidgetOverride::Custom = "text_area")]
#[default("Lorem ipsum")]
text: String,
text: Item<String>,
/// The loaded font file used to draw the text. The editor resolves the chosen typeface to these bytes via the resource system.
#[widget(ParsedWidgetOverride::Custom = "text_font")]
font: Resource,
font: Item<Resource>,
/// The font size used to draw the text.
#[unit(" px")]
#[default(24.)]
#[hard(1..)]
size: f64,
size: Item<f64>,
/// The line height ratio, relative to the font size. Each line is drawn lower than its previous line by the distance of *Size* × *Line Height*.
///
/// 0 means all lines overlap. 1 means all lines are spaced by just the font size. 1.2 is a common default for readable text. 2 means double-spaced text.
@@ -31,74 +31,87 @@ fn text(
#[hard(0..)]
#[step(0.1)]
#[default(1.2)]
line_height: f64,
line_height: Item<f64>,
/// Additional spacing, in pixels, added between each character.
#[unit(" px")]
#[step(0.1)]
letter_spacing: f64,
letter_spacing: Item<f64>,
/// The angle of faux italic slant applied to each glyph.
#[unit("°")]
#[hard(-85..85)]
letter_tilt: f64,
letter_tilt: Item<f64>,
/// Enables the maximum width constraint so lines can wrap.
#[widget(ParsedWidgetOverride::Hidden)]
has_max_width: bool,
has_max_width: Item<bool>,
/// The maximum width that the text block can occupy before wrapping to a new line. Otherwise, lines do not wrap.
#[unit(" px")]
#[hard(1..)]
#[widget(ParsedWidgetOverride::Custom = "optional_f64")]
max_width: f64,
max_width: Item<f64>,
/// Whether the *Max Height* property is enabled so that lines beyond it are not drawn.
#[widget(ParsedWidgetOverride::Hidden)]
has_max_height: bool,
has_max_height: Item<bool>,
/// The maximum height that the text block can occupy. Excess lines are not drawn.
#[unit(" px")]
#[hard(1..)]
#[widget(ParsedWidgetOverride::Custom = "optional_f64")]
max_height: f64,
max_height: Item<f64>,
/// The horizontal alignment of each line of text within its surrounding box. To have an effect on a single line of text, *Max Width* must be set.
#[widget(ParsedWidgetOverride::Custom = "text_align")]
align: TextAlign,
) -> List<String> {
let mut list = List::new_from_element(text);
align: Item<TextAlign>,
) -> Item<String> {
let text = text.into_element();
let font = font.into_element();
let (size, line_height, letter_spacing, letter_tilt) = (*size.element(), *line_height.element(), *letter_spacing.element(), *letter_tilt.element());
let (has_max_width, max_width, has_max_height, max_height) = (*has_max_width.element(), *max_width.element(), *has_max_height.element(), *max_height.element());
let align = align.into_element();
let mut item = Item::new_from_element(text);
if font != Resource::default() {
list.set_attribute(ATTR_FONT, 0, font);
item.set_attribute(ATTR_FONT, font);
}
if (size - DEFAULT_FONT_SIZE).abs() > f64::EPSILON {
list.set_attribute(ATTR_FONT_SIZE, 0, size);
item.set_attribute(ATTR_FONT_SIZE, size);
}
if (line_height - DEFAULT_LINE_HEIGHT).abs() > f64::EPSILON {
list.set_attribute(ATTR_LINE_HEIGHT, 0, line_height);
item.set_attribute(ATTR_LINE_HEIGHT, line_height);
}
if letter_spacing != 0. {
list.set_attribute(ATTR_LETTER_SPACING, 0, letter_spacing);
item.set_attribute(ATTR_LETTER_SPACING, letter_spacing);
}
if letter_tilt != 0. {
list.set_attribute(ATTR_LETTER_TILT, 0, letter_tilt);
item.set_attribute(ATTR_LETTER_TILT, letter_tilt);
}
if has_max_width {
list.set_attribute(ATTR_MAX_WIDTH, 0, Some(max_width));
item.set_attribute(ATTR_MAX_WIDTH, Some(max_width));
}
if has_max_height {
list.set_attribute(ATTR_MAX_HEIGHT, 0, Some(max_height));
item.set_attribute(ATTR_MAX_HEIGHT, Some(max_height));
}
if align != TextAlign::default() {
list.set_attribute(ATTR_TEXT_ALIGN, 0, align);
item.set_attribute(ATTR_TEXT_ALIGN, align);
}
list
item
}
/// Converts a styled `String[]` into vector geometry.
/// Converts a styled text string into a vector compound path.
#[node_macro::node(category("Text"), name("Text to Vector"))]
fn text_to_vector(
_: impl Ctx,
/// A styled list of text strings produced by the **Text** node (or any other `String[]` source).
#[implementations(List<String>)]
strings: List<String>,
/// Whether to split every letterform into its own vector item. Otherwise, a single vector compound path is produced.
separate_glyphs: bool,
) -> List<Vector> {
shape_text_list(&strings, separate_glyphs)
/// 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()
}
/// Splits a styled text string into a separate vector item for each of its glyphs (letterforms).
#[node_macro::node(category("Text"), name("Text to Vector Glyphs"))]
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> {
shape_text_item(&string, true)
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,8 +1,6 @@
use core_types::list::{ATTR_FILL, Item, List};
use core_types::uuid::NodeId;
use core_types::list::{ATTR_FILL, Item, ItemAttributeValues, List};
use core_types::{
ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_GRADIENT_TYPE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_SPREAD_METHOD, ATTR_TRANSFORM, BlendMode, Color,
Ctx,
ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_GRADIENT_TYPE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_SPREAD_METHOD, ATTR_TRANSFORM, Color, Ctx,
};
use glam::{DAffine2, DVec2};
use graphic_types::graphic::{bake_paint_transforms, set_paint_attribute};
@@ -34,8 +32,9 @@ async fn boolean_operation<I: graphic_types::IntoGraphicList>(
/// Subtraction cuts overlapping areas out from the last (Subtract Front) or first (Subtract Back) path.
/// Intersection cuts away all but the overlapping areas shared by every path.
/// Difference cuts away the overlapping areas shared by every path, leaving only the non-overlapping areas.
operation: BooleanOperation,
) -> List<Vector> {
operation: Item<BooleanOperation>,
) -> Item<Vector> {
let operation = operation.into_element();
let content = content.into_graphic_list();
// The first index is the bottom of the stack
@@ -60,7 +59,7 @@ async fn boolean_operation<I: graphic_types::IntoGraphicList>(
result_vector_list.element_mut(0).unwrap().merge_by_distance_spatial(merge_transform, 0.0001);
}
result_vector_list
result_vector_list.into_iter().next().unwrap_or_default()
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
@@ -183,6 +182,7 @@ fn flatten_vector(graphic_list: &List<Graphic>) -> List<Vector> {
.flat_map(|index| {
let graphic = graphic_list.element(index).unwrap();
match graphic.clone() {
Graphic::None => Vec::new(),
Graphic::Vector(vector) => {
// Apply the parent graphic's transform to each element of the `List<Vector>`
let parent_transform: DAffine2 = graphic_list.attribute_cloned_or_default(ATTR_TRANSFORM, index);
@@ -197,18 +197,16 @@ fn flatten_vector(graphic_list: &List<Graphic>) -> List<Vector> {
}
Graphic::RasterCPU(image) => {
let parent_transform: DAffine2 = graphic_list.attribute_cloned_or_default(ATTR_TRANSFORM, index);
let make_item = |transform, layer, blend_mode: BlendMode, opacity: f64, fill: f64, clip: bool| {
let make_item = |transform: DAffine2, source_attributes: &ItemAttributeValues| {
let mut subpath = Subpath::new_rectangle(DVec2::ZERO, DVec2::ONE);
subpath.apply_transform(transform);
let element = Vector::from_subpath(subpath);
let mut item = Item::new_from_element(element)
.with_attribute(ATTR_BLEND_MODE, blend_mode)
.with_attribute(ATTR_OPACITY, opacity)
.with_attribute(ATTR_OPACITY_FILL, fill)
.with_attribute(ATTR_CLIPPING_MASK, clip)
.with_attribute(ATTR_EDITOR_LAYER_PATH, layer);
let mut item = Item::new_from_element(element);
for key in [ATTR_BLEND_MODE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH] {
item.attributes_mut().insert_cloned_from(source_attributes, key);
}
set_paint_attribute(item.attributes_mut(), ATTR_FILL, List::new_from_element(Color::BLACK));
item
};
@@ -219,29 +217,23 @@ fn flatten_vector(graphic_list: &List<Graphic>) -> List<Vector> {
(0..image.len())
.map(|i| {
let row_transform: DAffine2 = image.attribute_cloned_or_default(ATTR_TRANSFORM, i);
let layer: List<NodeId> = image.attribute_cloned_or_default(ATTR_EDITOR_LAYER_PATH, i);
let blend_mode: BlendMode = image.attribute_cloned_or_default(ATTR_BLEND_MODE, i);
let opacity: f64 = image.attribute_cloned_or(ATTR_OPACITY, i, 1.);
let fill: f64 = image.attribute_cloned_or(ATTR_OPACITY_FILL, i, 1.);
let clip: bool = image.attribute_cloned_or_default(ATTR_CLIPPING_MASK, i);
make_item(parent_transform * row_transform, layer, blend_mode, opacity, fill, clip)
let source_attributes = image.clone_item_attributes(i);
make_item(parent_transform * row_transform, &source_attributes)
})
.collect::<Vec<_>>()
}
Graphic::RasterGPU(image) => {
let parent_transform: DAffine2 = graphic_list.attribute_cloned_or_default(ATTR_TRANSFORM, index);
let make_item = |transform, layer, blend_mode: BlendMode, opacity: f64, fill: f64, clip: bool| {
let make_item = |transform: DAffine2, source_attributes: &ItemAttributeValues| {
let mut subpath = Subpath::new_rectangle(DVec2::ZERO, DVec2::ONE);
subpath.apply_transform(transform);
let element = Vector::from_subpath(subpath);
let mut item = Item::new_from_element(element)
.with_attribute(ATTR_BLEND_MODE, blend_mode)
.with_attribute(ATTR_OPACITY, opacity)
.with_attribute(ATTR_OPACITY_FILL, fill)
.with_attribute(ATTR_CLIPPING_MASK, clip)
.with_attribute(ATTR_EDITOR_LAYER_PATH, layer);
let mut item = Item::new_from_element(element);
for key in [ATTR_BLEND_MODE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH] {
item.attributes_mut().insert_cloned_from(source_attributes, key);
}
set_paint_attribute(item.attributes_mut(), ATTR_FILL, List::new_from_element(Color::BLACK));
item
};
@@ -252,12 +244,8 @@ fn flatten_vector(graphic_list: &List<Graphic>) -> List<Vector> {
(0..image.len())
.map(|i| {
let row_transform: DAffine2 = image.attribute_cloned_or_default(ATTR_TRANSFORM, i);
let layer: List<NodeId> = image.attribute_cloned_or_default(ATTR_EDITOR_LAYER_PATH, i);
let blend_mode: BlendMode = image.attribute_cloned_or_default(ATTR_BLEND_MODE, i);
let opacity: f64 = image.attribute_cloned_or(ATTR_OPACITY, i, 1.);
let fill: f64 = image.attribute_cloned_or(ATTR_OPACITY_FILL, i, 1.);
let clip: bool = image.attribute_cloned_or_default(ATTR_CLIPPING_MASK, i);
make_item(parent_transform * row_transform, layer, blend_mode, opacity, fill, clip)
let source_attributes = image.clone_item_attributes(i);
make_item(parent_transform * row_transform, &source_attributes)
})
.collect::<Vec<_>>()
}

View File

@@ -12,34 +12,17 @@ impl Adjust<Color> for Color {
#[cfg(feature = "std")]
mod adjust_std {
use super::*;
use core_types::list::List;
use raster_types::{CPU, Raster};
use vector_types::GradientStops;
use vector_types::Gradient;
impl Adjust<Color> for List<Raster<CPU>> {
impl Adjust<Color> for Raster<CPU> {
fn adjust(&mut self, map_fn: impl Fn(&Color) -> Color) {
for element in self.iter_element_values_mut() {
for color in element.data_mut().data.iter_mut() {
*color = map_fn(color);
}
for color in self.data_mut().data.iter_mut() {
*color = map_fn(color);
}
}
}
impl Adjust<Color> for List<Color> {
fn adjust(&mut self, map_fn: impl Fn(&Color) -> Color) {
for element in self.iter_element_values_mut() {
*element = map_fn(element);
}
}
}
impl Adjust<Color> for List<GradientStops> {
fn adjust(&mut self, map_fn: impl Fn(&Color) -> Color) {
for element in self.iter_element_values_mut() {
element.adjust(&map_fn);
}
}
}
impl Adjust<Color> for GradientStops {
impl Adjust<Color> for Gradient {
fn adjust(&mut self, map_fn: impl Fn(&Color) -> Color) {
for color in self.color.iter_mut() {
*color = map_fn(color);

View File

@@ -4,10 +4,12 @@ use crate::adjust::Adjust;
use crate::cubic_spline::CubicSplines;
use core::fmt::Debug;
#[cfg(feature = "std")]
use core_types::list::List;
use core_types::list::Item;
use glam::Vec3;
use no_std_types::color::{Color, linear_to_srgb, srgb_to_linear};
use no_std_types::context::Ctx;
#[cfg(not(feature = "std"))]
use no_std_types::list::ShaderItem as Item;
use no_std_types::registry::types::{AngleF32, PercentageF32, SignedPercentageF32};
use node_macro::BufferStruct;
use num_enum::{FromPrimitive, IntoPrimitive};
@@ -16,7 +18,7 @@ use num_traits::float::Float;
#[cfg(feature = "std")]
use raster_types::{CPU, Raster};
#[cfg(feature = "std")]
use vector_types::GradientStops;
use vector_types::Gradient;
// TODO: Implement the following:
// Color Balance
@@ -53,15 +55,18 @@ pub enum LuminanceCalculation {
fn luminance<T: Adjust<Color>>(
_: impl Ctx,
#[implementations(
List<Raster<CPU>>,
List<Color>,
List<GradientStops>,
Raster<CPU>,
Color,
Gradient,
)]
#[gpu_image]
mut input: T,
luminance_calc: LuminanceCalculation,
) -> T {
input.adjust(|color| {
input: Item<T>,
luminance_calc: Item<LuminanceCalculation>,
) -> Item<T> {
let mut input = input;
let luminance_calc = luminance_calc.into_element();
input.element_mut().adjust(|color| {
let luminance = match luminance_calc {
LuminanceCalculation::SRGB => color.luminance_rec_709(),
LuminanceCalculation::Perceptual => color.luminance_perceptual(),
@@ -78,21 +83,25 @@ fn luminance<T: Adjust<Color>>(
fn gamma_correction<T: Adjust<Color>>(
_: impl Ctx,
#[implementations(
List<Raster<CPU>>,
List<Color>,
List<GradientStops>,
Raster<CPU>,
Color,
Gradient,
)]
#[gpu_image]
mut input: T,
input: Item<T>,
#[default(2.2)]
#[range]
#[hard(0.0001..)]
#[soft(0.01..10)]
gamma: f32,
inverse: bool,
) -> T {
gamma: Item<f32>,
inverse: Item<bool>,
) -> Item<T> {
let mut input = input;
let gamma = gamma.into_element();
let inverse = inverse.into_element();
let exponent = if inverse { 1. / gamma } else { gamma };
input.adjust(|color| color.apply_gamma_exponent(exponent));
input.element_mut().adjust(|color| color.apply_gamma_exponent(exponent));
input
}
@@ -100,15 +109,18 @@ fn gamma_correction<T: Adjust<Color>>(
fn extract_channel<T: Adjust<Color>>(
_: impl Ctx,
#[implementations(
List<Raster<CPU>>,
List<Color>,
List<GradientStops>,
Raster<CPU>,
Color,
Gradient,
)]
#[gpu_image]
mut input: T,
channel: RedGreenBlueAlpha,
) -> T {
input.adjust(|color| {
input: Item<T>,
channel: Item<RedGreenBlueAlpha>,
) -> Item<T> {
let mut input = input;
let channel = channel.into_element();
input.element_mut().adjust(|color| {
let extracted_value = match channel {
RedGreenBlueAlpha::Red => color.r(),
RedGreenBlueAlpha::Green => color.g(),
@@ -124,14 +136,15 @@ fn extract_channel<T: Adjust<Color>>(
fn make_opaque<T: Adjust<Color>>(
_: impl Ctx,
#[implementations(
List<Raster<CPU>>,
List<Color>,
List<GradientStops>,
Raster<CPU>,
Color,
Gradient,
)]
#[gpu_image]
mut input: T,
) -> T {
input.adjust(|color| {
input: Item<T>,
) -> Item<T> {
let mut input = input;
input.element_mut().adjust(|color| {
if color.a() == 0. {
return color.with_alpha(1.);
}
@@ -146,15 +159,19 @@ fn make_opaque<T: Adjust<Color>>(
fn brightness_contrast_classic<T: Adjust<Color>>(
_: impl Ctx,
#[implementations(
List<Raster<CPU>>,
List<Color>,
List<GradientStops>,
Raster<CPU>,
Color,
Gradient,
)]
#[gpu_image]
mut input: T,
brightness: SignedPercentageF32,
contrast: SignedPercentageF32,
) -> T {
input: Item<T>,
brightness: Item<SignedPercentageF32>,
contrast: Item<SignedPercentageF32>,
) -> Item<T> {
let mut input = input;
let brightness = brightness.into_element();
let contrast = contrast.into_element();
let brightness = brightness / 255.;
let contrast = contrast / 100.;
@@ -162,7 +179,7 @@ fn brightness_contrast_classic<T: Adjust<Color>>(
let offset = brightness * contrast + brightness - contrast / 2.;
input.adjust(|color| color.map_gamma_rgb(|c| (c + c * contrast + offset).clamp(0., 1.)));
input.element_mut().adjust(|color| color.map_gamma_rgb(|c| (c + c * contrast + offset).clamp(0., 1.)));
input
}
@@ -177,20 +194,25 @@ fn brightness_contrast_classic<T: Adjust<Color>>(
fn brightness_contrast<T: Adjust<Color>>(
_ctx: impl Ctx,
#[implementations(
List<Raster<CPU>>,
List<Color>,
List<GradientStops>,
Raster<CPU>,
Color,
Gradient,
)]
#[gpu_image]
mut input: T,
brightness: SignedPercentageF32,
contrast: SignedPercentageF32,
use_classic: bool,
) -> T {
input: Item<T>,
brightness: Item<SignedPercentageF32>,
contrast: Item<SignedPercentageF32>,
use_classic: Item<bool>,
) -> Item<T> {
let use_classic = use_classic.into_element();
if use_classic {
return brightness_contrast_classic(_ctx, input, brightness, contrast);
}
let mut input = input;
let brightness = brightness.into_element();
let contrast = contrast.into_element();
const WINDOW_SIZE: usize = 1024;
// Brightness LUT
@@ -241,7 +263,7 @@ fn brightness_contrast<T: Adjust<Color>>(
});
let lut_max = (combined_lut.len() - 1) as f32;
input.adjust(|color| color.map_gamma_rgb(|c| combined_lut[(c * lut_max).round() as usize]));
input.element_mut().adjust(|color| color.map_gamma_rgb(|c| combined_lut[(c * lut_max).round() as usize]));
input
}
@@ -258,19 +280,26 @@ fn brightness_contrast<T: Adjust<Color>>(
fn levels<T: Adjust<Color>>(
_: impl Ctx,
#[implementations(
List<Raster<CPU>>,
List<Color>,
List<GradientStops>,
Raster<CPU>,
Color,
Gradient,
)]
#[gpu_image]
mut image: T,
#[default(0.)] shadows: PercentageF32,
#[default(50.)] midtones: PercentageF32,
#[default(100.)] highlights: PercentageF32,
#[default(0.)] output_minimums: PercentageF32,
#[default(100.)] output_maximums: PercentageF32,
) -> T {
image.adjust(|color| {
image: Item<T>,
#[default(0.)] shadows: Item<PercentageF32>,
#[default(50.)] midtones: Item<PercentageF32>,
#[default(100.)] highlights: Item<PercentageF32>,
#[default(0.)] output_minimums: Item<PercentageF32>,
#[default(100.)] output_maximums: Item<PercentageF32>,
) -> Item<T> {
let mut image = image;
let shadows = shadows.into_element();
let midtones = midtones.into_element();
let highlights = highlights.into_element();
let output_minimums = output_minimums.into_element();
let output_maximums = output_maximums.into_element();
image.element_mut().adjust(|color| {
// Levels math operates in gamma space
let [mut r, mut g, mut b, a] = color.to_gamma_srgb_channels();
@@ -332,44 +361,52 @@ fn levels<T: Adjust<Color>>(
// Algorithm from:
// https://stackoverflow.com/a/55233732/775283
// Works the same for gamma and linear color
// TODO: Currently the un-List-wrapped `tint` Color is causing a type error. Put this back in the "Raster: Adjustment" category once that's fixed.
#[node_macro::node(name("Black & White"), category(""), properties("black_and_white_properties"), shader_node(PerPixelAdjust))]
#[node_macro::node(name("Black & White"), category("Raster: Adjustment"), properties("black_and_white_properties"), shader_node(PerPixelAdjust))]
fn black_and_white<T: Adjust<Color>>(
_: impl Ctx,
#[implementations(
List<Raster<CPU>>,
List<Color>,
List<GradientStops>,
Raster<CPU>,
Color,
Gradient,
)]
#[gpu_image]
mut image: T,
#[default(Color::BLACK)] tint: Color,
image: Item<T>,
#[default(Color::BLACK)] tint: Item<Color>,
#[default(40.)]
#[range]
#[soft(-200..300)]
reds: PercentageF32,
reds: Item<PercentageF32>,
#[default(60.)]
#[range]
#[soft(-200..300)]
yellows: PercentageF32,
yellows: Item<PercentageF32>,
#[default(40.)]
#[range]
#[soft(-200..300)]
greens: PercentageF32,
greens: Item<PercentageF32>,
#[default(60.)]
#[range]
#[soft(-200..300)]
cyans: PercentageF32,
cyans: Item<PercentageF32>,
#[default(20.)]
#[range]
#[soft(-200..300)]
blues: PercentageF32,
blues: Item<PercentageF32>,
#[default(80.)]
#[range]
#[soft(-200..300)]
magentas: PercentageF32,
) -> T {
image.adjust(|color| {
magentas: Item<PercentageF32>,
) -> Item<T> {
let mut image = image;
let tint = tint.into_element();
let reds = reds.into_element();
let yellows = yellows.into_element();
let greens = greens.into_element();
let cyans = cyans.into_element();
let blues = blues.into_element();
let magentas = magentas.into_element();
image.element_mut().adjust(|color| {
// Black & White channel weights are tuned for gamma-space values
let [r, g, b, alpha_part] = color.to_gamma_srgb_channels();
@@ -420,17 +457,22 @@ fn black_and_white<T: Adjust<Color>>(
fn hue_saturation<T: Adjust<Color>>(
_: impl Ctx,
#[implementations(
List<Raster<CPU>>,
List<Color>,
List<GradientStops>,
Raster<CPU>,
Color,
Gradient,
)]
#[gpu_image]
mut input: T,
hue_shift: AngleF32,
saturation_shift: SignedPercentageF32,
lightness_shift: SignedPercentageF32,
) -> T {
input.adjust(|color| {
input: Item<T>,
hue_shift: Item<AngleF32>,
saturation_shift: Item<SignedPercentageF32>,
lightness_shift: Item<SignedPercentageF32>,
) -> Item<T> {
let mut input = input;
let hue_shift = hue_shift.into_element();
let saturation_shift = saturation_shift.into_element();
let lightness_shift = lightness_shift.into_element();
input.element_mut().adjust(|color| {
// HSL operates on gamma-space channels
let [hue, saturation, lightness, alpha] = color.to_hsla();
@@ -452,14 +494,15 @@ fn hue_saturation<T: Adjust<Color>>(
fn invert<T: Adjust<Color>>(
_: impl Ctx,
#[implementations(
List<Raster<CPU>>,
List<Color>,
List<GradientStops>,
Raster<CPU>,
Color,
Gradient,
)]
#[gpu_image]
mut input: T,
) -> T {
input.adjust(|color| {
input: Item<T>,
) -> Item<T> {
let mut input = input;
input.element_mut().adjust(|color| {
// Invert in gamma space relative to alpha
let [r, g, b, a] = color.to_gamma_srgb_channels();
Color::from_gamma_srgb_channels(a - r, a - g, a - b, a)
@@ -473,17 +516,22 @@ fn invert<T: Adjust<Color>>(
fn threshold<T: Adjust<Color>>(
_: impl Ctx,
#[implementations(
List<Raster<CPU>>,
List<Color>,
List<GradientStops>,
Raster<CPU>,
Color,
Gradient,
)]
#[gpu_image]
mut image: T,
#[default(50.)] min_luminance: PercentageF32,
#[default(100.)] max_luminance: PercentageF32,
luminance_calc: LuminanceCalculation,
) -> T {
image.adjust(|color| {
image: Item<T>,
#[default(50.)] min_luminance: Item<PercentageF32>,
#[default(100.)] max_luminance: Item<PercentageF32>,
luminance_calc: Item<LuminanceCalculation>,
) -> Item<T> {
let mut image = image;
let min_luminance = min_luminance.into_element();
let max_luminance = max_luminance.into_element();
let luminance_calc = luminance_calc.into_element();
image.element_mut().adjust(|color| {
let min_luminance = srgb_to_linear(min_luminance / 100.);
let max_luminance = srgb_to_linear(max_luminance / 100.);
@@ -519,15 +567,18 @@ fn threshold<T: Adjust<Color>>(
fn vibrance<T: Adjust<Color>>(
_: impl Ctx,
#[implementations(
List<Raster<CPU>>,
List<Color>,
List<GradientStops>,
Raster<CPU>,
Color,
Gradient,
)]
#[gpu_image]
mut image: T,
vibrance: SignedPercentageF32,
) -> T {
image.adjust(|color| {
image: Item<T>,
vibrance: Item<SignedPercentageF32>,
) -> Item<T> {
let mut image = image;
let vibrance = vibrance.into_element();
image.element_mut().adjust(|color| {
let r_raw = color.r();
let g_raw = color.g();
let b_raw = color.b();
@@ -721,71 +772,78 @@ pub enum DomainWarpType {
fn channel_mixer<T: Adjust<Color>>(
_: impl Ctx,
#[implementations(
List<Raster<CPU>>,
List<Color>,
List<GradientStops>,
Raster<CPU>,
Color,
Gradient,
)]
#[gpu_image]
mut image: T,
image: Item<T>,
monochrome: bool,
monochrome: Item<bool>,
#[default(40.)]
#[name("Red")]
monochrome_r: f32,
monochrome_r: Item<f32>,
#[default(40.)]
#[name("Green")]
monochrome_g: f32,
monochrome_g: Item<f32>,
#[default(20.)]
#[name("Blue")]
monochrome_b: f32,
monochrome_b: Item<f32>,
#[default(0.)]
#[name("Constant")]
monochrome_c: f32,
monochrome_c: Item<f32>,
#[default(100.)]
#[name("(Red) Red")]
red_r: f32,
red_r: Item<f32>,
#[default(0.)]
#[name("(Red) Green")]
red_g: f32,
red_g: Item<f32>,
#[default(0.)]
#[name("(Red) Blue")]
red_b: f32,
red_b: Item<f32>,
#[default(0.)]
#[name("(Red) Constant")]
red_c: f32,
red_c: Item<f32>,
#[default(0.)]
#[name("(Green) Red")]
green_r: f32,
green_r: Item<f32>,
#[default(100.)]
#[name("(Green) Green")]
green_g: f32,
green_g: Item<f32>,
#[default(0.)]
#[name("(Green) Blue")]
green_b: f32,
green_b: Item<f32>,
#[default(0.)]
#[name("(Green) Constant")]
green_c: f32,
green_c: Item<f32>,
#[default(0.)]
#[name("(Blue) Red")]
blue_r: f32,
blue_r: Item<f32>,
#[default(0.)]
#[name("(Blue) Green")]
blue_g: f32,
blue_g: Item<f32>,
#[default(100.)]
#[name("(Blue) Blue")]
blue_b: f32,
blue_b: Item<f32>,
#[default(0.)]
#[name("(Blue) Constant")]
blue_c: f32,
blue_c: Item<f32>,
// Display-only properties (not used within the node)
_output_channel: RedGreenBlue,
) -> T {
image.adjust(|color| {
_output_channel: Item<RedGreenBlue>,
) -> Item<T> {
let mut image = image;
let monochrome = monochrome.into_element();
let (monochrome_r, monochrome_g, monochrome_b, monochrome_c) = (monochrome_r.into_element(), monochrome_g.into_element(), monochrome_b.into_element(), monochrome_c.into_element());
let (red_r, red_g, red_b, red_c) = (red_r.into_element(), red_g.into_element(), red_b.into_element(), red_c.into_element());
let (green_r, green_g, green_b, green_c) = (green_r.into_element(), green_g.into_element(), green_b.into_element(), green_c.into_element());
let (blue_r, blue_g, blue_b, blue_c) = (blue_r.into_element(), blue_g.into_element(), blue_b.into_element(), blue_c.into_element());
image.element_mut().adjust(|color| {
let [r, g, b, a] = color.to_gamma_srgb_channels();
let (out_r, out_g, out_b) = if monochrome {
@@ -853,63 +911,75 @@ pub enum SelectiveColorChoice {
fn selective_color<T: Adjust<Color>>(
_: impl Ctx,
#[implementations(
List<Raster<CPU>>,
List<Color>,
List<GradientStops>,
Raster<CPU>,
Color,
Gradient,
)]
#[gpu_image]
mut image: T,
image: Item<T>,
mode: RelativeAbsolute,
mode: Item<RelativeAbsolute>,
#[name("(Reds) Cyan")] r_c: f32,
#[name("(Reds) Magenta")] r_m: f32,
#[name("(Reds) Yellow")] r_y: f32,
#[name("(Reds) Black")] r_k: f32,
#[name("(Reds) Cyan")] r_c: Item<f32>,
#[name("(Reds) Magenta")] r_m: Item<f32>,
#[name("(Reds) Yellow")] r_y: Item<f32>,
#[name("(Reds) Black")] r_k: Item<f32>,
#[name("(Yellows) Cyan")] y_c: f32,
#[name("(Yellows) Magenta")] y_m: f32,
#[name("(Yellows) Yellow")] y_y: f32,
#[name("(Yellows) Black")] y_k: f32,
#[name("(Yellows) Cyan")] y_c: Item<f32>,
#[name("(Yellows) Magenta")] y_m: Item<f32>,
#[name("(Yellows) Yellow")] y_y: Item<f32>,
#[name("(Yellows) Black")] y_k: Item<f32>,
#[name("(Greens) Cyan")] g_c: f32,
#[name("(Greens) Magenta")] g_m: f32,
#[name("(Greens) Yellow")] g_y: f32,
#[name("(Greens) Black")] g_k: f32,
#[name("(Greens) Cyan")] g_c: Item<f32>,
#[name("(Greens) Magenta")] g_m: Item<f32>,
#[name("(Greens) Yellow")] g_y: Item<f32>,
#[name("(Greens) Black")] g_k: Item<f32>,
#[name("(Cyans) Cyan")] c_c: f32,
#[name("(Cyans) Magenta")] c_m: f32,
#[name("(Cyans) Yellow")] c_y: f32,
#[name("(Cyans) Black")] c_k: f32,
#[name("(Cyans) Cyan")] c_c: Item<f32>,
#[name("(Cyans) Magenta")] c_m: Item<f32>,
#[name("(Cyans) Yellow")] c_y: Item<f32>,
#[name("(Cyans) Black")] c_k: Item<f32>,
#[name("(Blues) Cyan")] b_c: f32,
#[name("(Blues) Magenta")] b_m: f32,
#[name("(Blues) Yellow")] b_y: f32,
#[name("(Blues) Black")] b_k: f32,
#[name("(Blues) Cyan")] b_c: Item<f32>,
#[name("(Blues) Magenta")] b_m: Item<f32>,
#[name("(Blues) Yellow")] b_y: Item<f32>,
#[name("(Blues) Black")] b_k: Item<f32>,
#[name("(Magentas) Cyan")] m_c: f32,
#[name("(Magentas) Magenta")] m_m: f32,
#[name("(Magentas) Yellow")] m_y: f32,
#[name("(Magentas) Black")] m_k: f32,
#[name("(Magentas) Cyan")] m_c: Item<f32>,
#[name("(Magentas) Magenta")] m_m: Item<f32>,
#[name("(Magentas) Yellow")] m_y: Item<f32>,
#[name("(Magentas) Black")] m_k: Item<f32>,
#[name("(Whites) Cyan")] w_c: f32,
#[name("(Whites) Magenta")] w_m: f32,
#[name("(Whites) Yellow")] w_y: f32,
#[name("(Whites) Black")] w_k: f32,
#[name("(Whites) Cyan")] w_c: Item<f32>,
#[name("(Whites) Magenta")] w_m: Item<f32>,
#[name("(Whites) Yellow")] w_y: Item<f32>,
#[name("(Whites) Black")] w_k: Item<f32>,
#[name("(Neutrals) Cyan")] n_c: f32,
#[name("(Neutrals) Magenta")] n_m: f32,
#[name("(Neutrals) Yellow")] n_y: f32,
#[name("(Neutrals) Black")] n_k: f32,
#[name("(Neutrals) Cyan")] n_c: Item<f32>,
#[name("(Neutrals) Magenta")] n_m: Item<f32>,
#[name("(Neutrals) Yellow")] n_y: Item<f32>,
#[name("(Neutrals) Black")] n_k: Item<f32>,
#[name("(Blacks) Cyan")] k_c: f32,
#[name("(Blacks) Magenta")] k_m: f32,
#[name("(Blacks) Yellow")] k_y: f32,
#[name("(Blacks) Black")] k_k: f32,
#[name("(Blacks) Cyan")] k_c: Item<f32>,
#[name("(Blacks) Magenta")] k_m: Item<f32>,
#[name("(Blacks) Yellow")] k_y: Item<f32>,
#[name("(Blacks) Black")] k_k: Item<f32>,
_colors: SelectiveColorChoice,
) -> T {
image.adjust(|color| {
_colors: Item<SelectiveColorChoice>,
) -> Item<T> {
let mut image = image;
let mode = mode.into_element();
let (r_c, r_m, r_y, r_k) = (r_c.into_element(), r_m.into_element(), r_y.into_element(), r_k.into_element());
let (y_c, y_m, y_y, y_k) = (y_c.into_element(), y_m.into_element(), y_y.into_element(), y_k.into_element());
let (g_c, g_m, g_y, g_k) = (g_c.into_element(), g_m.into_element(), g_y.into_element(), g_k.into_element());
let (c_c, c_m, c_y, c_k) = (c_c.into_element(), c_m.into_element(), c_y.into_element(), c_k.into_element());
let (b_c, b_m, b_y, b_k) = (b_c.into_element(), b_m.into_element(), b_y.into_element(), b_k.into_element());
let (m_c, m_m, m_y, m_k) = (m_c.into_element(), m_m.into_element(), m_y.into_element(), m_k.into_element());
let (w_c, w_m, w_y, w_k) = (w_c.into_element(), w_m.into_element(), w_y.into_element(), w_k.into_element());
let (n_c, n_m, n_y, n_k) = (n_c.into_element(), n_m.into_element(), n_y.into_element(), n_k.into_element());
let (k_c, k_m, k_y, k_k) = (k_c.into_element(), k_m.into_element(), k_y.into_element(), k_k.into_element());
image.element_mut().adjust(|color| {
let [r, g, b, a] = color.to_gamma_srgb_channels();
let min = |a: f32, b: f32, c: f32| a.min(b).min(c);
@@ -997,18 +1067,20 @@ fn selective_color<T: Adjust<Color>>(
fn posterize<T: Adjust<Color>>(
_: impl Ctx,
#[implementations(
List<Raster<CPU>>,
List<Color>,
List<GradientStops>,
Raster<CPU>,
Color,
Gradient,
)]
#[gpu_image]
mut input: T,
input: Item<T>,
#[default(4)]
#[hard(2..)]
levels: u32,
) -> T {
let levels = levels as f32;
input.adjust(|color| {
levels: Item<u32>,
) -> Item<T> {
let mut input = input;
let levels = levels.into_element() as f32;
input.element_mut().adjust(|color| {
let number_of_areas = levels.recip();
let size_of_areas = (levels - 1.).recip();
color.map_gamma_rgb(|c| (c / number_of_areas).floor() * size_of_areas)
@@ -1026,21 +1098,26 @@ fn posterize<T: Adjust<Color>>(
fn exposure<T: Adjust<Color>>(
_: impl Ctx,
#[implementations(
List<Raster<CPU>>,
List<Color>,
List<GradientStops>,
Raster<CPU>,
Color,
Gradient,
)]
#[gpu_image]
mut input: T,
exposure: f32,
offset: f32,
input: Item<T>,
exposure: Item<f32>,
offset: Item<f32>,
#[default(1.)]
#[range]
#[hard(0.0001..)]
#[soft(0.01..10)]
gamma_correction: f32,
) -> T {
input.adjust(|color| {
gamma_correction: Item<f32>,
) -> Item<T> {
let mut input = input;
let exposure = exposure.into_element();
let offset = offset.into_element();
let gamma_correction = gamma_correction.into_element();
input.element_mut().adjust(|color| {
let adjusted = color
// Exposure
.map_rgb(|c: f32| c * 2_f32.powf(exposure))

View File

@@ -1,14 +1,16 @@
use crate::adjust::Adjust;
#[cfg(feature = "std")]
use core_types::list::List;
use core_types::list::Item;
use no_std_types::Ctx;
use no_std_types::blending::BlendMode;
use no_std_types::color::{Color, Pixel};
#[cfg(not(feature = "std"))]
use no_std_types::list::ShaderItem as Item;
use no_std_types::registry::types::PercentageF32;
#[cfg(feature = "std")]
use raster_types::{CPU, Raster};
#[cfg(feature = "std")]
use vector_types::{GradientStop, GradientStops};
use vector_types::{Gradient, GradientStop};
pub trait Blend<P: Pixel> {
fn blend(&self, under: &Self, blend_fn: impl Fn(P, P) -> P) -> Self;
@@ -23,57 +25,22 @@ impl Blend<Color> for Color {
mod blend_std {
use super::*;
use core::cmp::Ordering;
use core_types::list::List;
use raster_types::Image;
use raster_types::Raster;
impl Blend<Color> for List<Raster<CPU>> {
impl Blend<Color> for Raster<CPU> {
fn blend(&self, under: &Self, blend_fn: impl Fn(Color, Color) -> Color) -> Self {
let mut result_list = self.clone();
let pair_count = result_list.len().min(under.len());
for index in 0..pair_count {
let Some(over) = result_list.element(index) else { break };
let Some(under_element) = under.element(index) else { break };
let data = over.data.iter().zip(under_element.data.iter()).map(|(a, b)| blend_fn(*a, *b)).collect();
let (width, height) = (over.width, over.height);
let data = self.data.iter().zip(under.data.iter()).map(|(a, b)| blend_fn(*a, *b)).collect();
*result_list.element_mut(index).unwrap() = Raster::new_cpu(Image {
data,
width,
height,
base64_string: None,
});
}
result_list
Raster::new_cpu(Image {
data,
width: self.width,
height: self.height,
base64_string: None,
})
}
}
impl Blend<Color> for List<Color> {
fn blend(&self, under: &Self, blend_fn: impl Fn(Color, Color) -> Color) -> Self {
let mut result_list = self.clone();
let pair_count = result_list.len().min(under.len());
for index in 0..pair_count {
let Some(over) = result_list.element(index) else { break };
let Some(under_element) = under.element(index) else { break };
let new_val = blend_fn(*over, *under_element);
*result_list.element_mut(index).unwrap() = new_val;
}
result_list
}
}
impl Blend<Color> for List<GradientStops> {
fn blend(&self, under: &Self, blend_fn: impl Fn(Color, Color) -> Color) -> Self {
let mut result_list = self.clone();
let pair_count = result_list.len().min(under.len());
for index in 0..pair_count {
let Some(over) = result_list.element(index) else { break };
let Some(under_element) = under.element(index) else { break };
let new_val = over.blend(under_element, &blend_fn);
*result_list.element_mut(index).unwrap() = new_val;
}
result_list
}
}
impl Blend<Color> for GradientStops {
impl Blend<Color> for Gradient {
fn blend(&self, under: &Self, blend_fn: impl Fn(Color, Color) -> Color) -> Self {
let mut combined_stops = self.position.iter().chain(under.position.iter()).copied().collect::<Vec<_>>();
combined_stops.dedup_by(|a, b| (*a - *b).abs() < 1e-6);
@@ -84,7 +51,7 @@ mod blend_std {
let color = blend_fn(over_color, under_color);
GradientStop { position, midpoint: 0.5, color }
});
GradientStops::new(stops)
Gradient::new(stops)
}
}
}
@@ -145,43 +112,54 @@ pub fn apply_blend_mode(foreground: Color, background: Color, blend_mode: BlendM
fn mix<T: Blend<Color> + Send>(
_: impl Ctx,
#[implementations(
List<Raster<CPU>>,
List<Color>,
List<GradientStops>,
Raster<CPU>,
Color,
Gradient,
)]
#[gpu_image]
over: T,
over: Item<T>,
#[expose]
#[implementations(
List<Raster<CPU>>,
List<Color>,
List<GradientStops>,
Raster<CPU>,
Color,
Gradient,
)]
#[gpu_image]
under: T,
blend_mode: BlendMode,
#[default(100.)] opacity: PercentageF32,
) -> T {
over.blend(&under, |a, b| blend_colors(a, b, blend_mode, opacity / 100.))
under: Item<T>,
blend_mode: Item<BlendMode>,
#[default(100.)] opacity: Item<PercentageF32>,
) -> Item<T> {
let mut over = over;
let blend_mode = blend_mode.into_element();
let opacity = opacity.into_element();
let blended = over.element().blend(under.element(), |a, b| blend_colors(a, b, blend_mode, opacity / 100.));
*over.element_mut() = blended;
over
}
#[node_macro::node(category("Raster: Adjustment"), shader_node(PerPixelAdjust))]
fn color_overlay<T: Adjust<Color>>(
_: impl Ctx,
#[implementations(
List<Raster<CPU>>,
List<Color>,
List<GradientStops>,
Raster<CPU>,
Color,
Gradient,
)]
#[gpu_image]
mut image: T,
#[default(Color::BLACK)] color: Color,
blend_mode: BlendMode,
#[default(100.)] opacity: PercentageF32,
) -> T {
image: Item<T>,
#[default(Color::BLACK)] color: Item<Color>,
blend_mode: Item<BlendMode>,
#[default(100.)] opacity: Item<PercentageF32>,
) -> Item<T> {
let mut image = image;
let color = color.into_element();
let blend_mode = blend_mode.into_element();
let opacity = opacity.into_element();
let opacity = (opacity / 100.).clamp(0., 1.);
image.adjust(|pixel| {
image.element_mut().adjust(|pixel| {
let image = pixel.map_rgb(|channel| channel * (1. - opacity));
// The apply blend mode function divides rgb by the alpha channel for the background. This undoes that.
@@ -197,7 +175,7 @@ fn color_overlay<T: Adjust<Color>>(
mod test {
use core_types::blending::BlendMode;
use core_types::color::Color;
use core_types::list::List;
use core_types::list::Item;
use raster_types::Image;
use raster_types::Raster;
@@ -212,8 +190,14 @@ mod test {
// 100% of the output should come from the multiplied value
let opacity = 100.;
let result = super::color_overlay((), List::new_from_element(Raster::new_cpu(image.clone())), overlay_color, BlendMode::Multiply, opacity);
let result = result.element(0).unwrap().clone();
let result = super::color_overlay(
(),
Item::new_from_element(Raster::new_cpu(image.clone())),
overlay_color.into(),
BlendMode::Multiply.into(),
opacity.into(),
);
let result = result.into_element();
// The output should just be the original green and alpha channels (as we multiply them by 1 and other channels by 0)
assert_eq!(result.data[0], Color::from_rgbaf32_unchecked(0., image_color.g(), 0., image_color.a()));

View File

@@ -1,5 +1,5 @@
use core_types::context::Ctx;
use core_types::list::List;
use core_types::list::Item;
use core_types::registry::types::Percentage;
use image::{DynamicImage, GenericImage, GenericImageView, GrayImage, ImageBuffer, Luma, Rgba, RgbaImage};
use ndarray::{Array2, ArrayBase, Dim, OwnedRepr};
@@ -8,33 +8,31 @@ use raster_types::{CPU, Raster};
use std::cmp::{max, min};
#[node_macro::node(category("Raster: Filter"))]
async fn dehaze(_: impl Ctx, image_frame: List<Raster<CPU>>, strength: Percentage) -> List<Raster<CPU>> {
image_frame
.into_iter()
.map(|mut row| {
let image = std::mem::replace(row.element_mut(), Raster::new_cpu(Image::default()));
// Prepare the image data for processing
let image_data = bytemuck::cast_vec(image.data.clone());
let image_buffer = image::Rgba32FImage::from_raw(image.width, image.height, image_data).expect("Failed to convert internal image format into image-rs data type.");
let dynamic_image: DynamicImage = image_buffer.into();
async fn dehaze(_: impl Ctx, image_frame: Item<Raster<CPU>>, strength: Item<Percentage>) -> Item<Raster<CPU>> {
let strength = *strength.element();
// Run the dehaze algorithm
let dehazed_dynamic_image = dehaze_image(dynamic_image, strength / 100.);
let (image, attributes) = image_frame.into_parts();
let (width, height) = (image.width, image.height);
// Prepare the image data for returning
let buffer = dehazed_dynamic_image.to_rgba32f().into_raw();
let color_vec = bytemuck::cast_vec(buffer);
let dehazed_image = Image {
width: image.width,
height: image.height,
data: color_vec,
base64_string: None,
};
// Prepare the image data for processing
let image_data = bytemuck::cast_vec(image.into_data().data);
let image_buffer = image::Rgba32FImage::from_raw(width, height, image_data).expect("Failed to convert internal image format into image-rs data type.");
let dynamic_image: DynamicImage = image_buffer.into();
*row.element_mut() = Raster::new_cpu(dehazed_image);
row
})
.collect()
// Run the dehaze algorithm
let dehazed_dynamic_image = dehaze_image(dynamic_image, strength / 100.);
// Prepare the image data for returning
let buffer = dehazed_dynamic_image.to_rgba32f().into_raw();
let color_vec = bytemuck::cast_vec(buffer);
let dehazed_image = Image {
width,
height,
data: color_vec,
base64_string: None,
};
Item::from_parts(Raster::new_cpu(dehazed_image), attributes)
}
// There is no real point in modifying these values because they do not change the final result all that much.

View File

@@ -1,7 +1,7 @@
use bytemuck::{Pod, Zeroable};
use core_types::color::{Alpha, Color, Pixel, RGB};
use core_types::context::Ctx;
use core_types::list::List;
use core_types::list::Item;
use core_types::registry::types::PixelLength;
use raster_types::Image;
use raster_types::{Bitmap, BitmapMut};
@@ -90,36 +90,31 @@ fn unpremultiply_gamma_to_linear(buffer: Image<PremultipliedGammaPixel>) -> Imag
async fn blur(
_: impl Ctx,
/// The image to be blurred.
image_frame: List<Raster<CPU>>,
image_frame: Item<Raster<CPU>>,
/// The radius of the blur kernel.
#[range]
#[hard(0..)]
#[soft(..100)]
radius: PixelLength,
radius: Item<PixelLength>,
/// Use a lower-quality box kernel instead of a circular Gaussian kernel. This is faster but produces boxy artifacts.
box_blur: bool,
box_blur: Item<bool>,
/// Opt to incorrectly apply the filter with color calculations in gamma space for compatibility with the results from other software.
gamma: bool,
) -> List<Raster<CPU>> {
image_frame
.into_iter()
.map(|mut row| {
let image = row.element().clone();
gamma: Item<bool>,
) -> Item<Raster<CPU>> {
let (radius, box_blur, gamma) = (*radius.element(), *box_blur.element(), *gamma.element());
// Run blur algorithm
let blurred_image = if radius < 0.1 {
// Minimum blur radius
image.clone()
} else if box_blur {
Raster::new_cpu(box_blur_algorithm(image.into_data(), radius, gamma))
} else {
Raster::new_cpu(gaussian_blur_algorithm(image.into_data(), radius, gamma))
};
let (image, attributes) = image_frame.into_parts();
*row.element_mut() = blurred_image;
row
})
.collect()
let blurred_image = if radius < 0.1 {
// Minimum blur radius
image
} else if box_blur {
Raster::new_cpu(box_blur_algorithm(image.into_data(), radius, gamma))
} else {
Raster::new_cpu(gaussian_blur_algorithm(image.into_data(), radius, gamma))
};
Item::from_parts(blurred_image, attributes)
}
/// Applies a median filter to reduce noise while preserving edges.
@@ -127,30 +122,25 @@ async fn blur(
async fn median_filter(
_: impl Ctx,
/// The image to be filtered.
image_frame: List<Raster<CPU>>,
image_frame: Item<Raster<CPU>>,
/// The radius of the filter kernel. Larger values remove more noise but may blur fine details.
#[range]
#[hard(0..)]
#[soft(..50)]
radius: PixelLength,
) -> List<Raster<CPU>> {
image_frame
.into_iter()
.map(|mut row| {
let image = row.element().clone();
radius: Item<PixelLength>,
) -> Item<Raster<CPU>> {
let radius = *radius.element();
// Apply median filter
let filtered_image = if radius < 0.5 {
// Minimum filter radius
image.clone()
} else {
Raster::new_cpu(median_filter_algorithm(image.into_data(), radius as u32))
};
let (image, attributes) = image_frame.into_parts();
*row.element_mut() = filtered_image;
row
})
.collect()
let filtered_image = if radius < 0.5 {
// Minimum filter radius
image
} else {
Raster::new_cpu(median_filter_algorithm(image.into_data(), radius as u32))
};
Item::from_parts(filtered_image, attributes)
}
// 1D gaussian kernel

View File

@@ -1,29 +1,31 @@
//! Not immediately shader compatible due to needing [`GradientStops`] as a param, which needs [`Vec`]
//! Not immediately shader compatible due to needing [`Gradient`] as a param, which needs [`Vec`]
use crate::adjust::Adjust;
use core_types::list::List;
use core_types::list::Item;
use core_types::{Color, Ctx};
use raster_types::{CPU, Raster};
use vector_types::GradientStops;
use vector_types::Gradient;
// Aims for interoperable compatibility with:
// https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=%27grdm%27%20%3D%20Gradient%20Map
// https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=Gradient%20settings%20(Photoshop%206.0)
#[node_macro::node(category("Raster: Adjustment"))]
async fn gradient_map<T: Adjust<Color>>(
async fn gradient_map<T: Adjust<Color> + Send>(
_: impl Ctx,
#[implementations(
List<Raster<CPU>>,
List<Color>,
List<GradientStops>,
Raster<CPU>,
Color,
Gradient,
)]
mut image: T,
gradient: List<GradientStops>,
reverse: bool,
) -> T {
let Some(gradient) = gradient.element(0) else { return image };
image: Item<T>,
gradient: Item<Gradient>,
reverse: Item<bool>,
) -> Item<T> {
let mut image = image;
let gradient = gradient.into_element();
let reverse = reverse.into_element();
image.adjust(|color| {
image.element_mut().adjust(|color| {
let intensity = color.luminance_rec_709();
let intensity = if reverse { 1. - intensity } else { intensity };
gradient.evaluate(intensity as f64)

View File

@@ -6,10 +6,10 @@ use raster_types::{CPU, Raster};
#[node_macro::node(category("Color"))]
async fn image_color_palette(
_: impl Ctx,
image: List<Raster<CPU>>,
image: Item<Raster<CPU>>,
#[default(4)]
#[hard(1..)]
count: u32,
count: Item<u32>,
) -> List<Color> {
const GRID: f32 = 3.;
@@ -19,24 +19,22 @@ async fn image_color_palette(
// Each bin stores `(red, green, blue, alpha)` tuples in sRGB gamma space; averaging in gamma space gives perceptually-uniform binning.
let mut color_bins: Vec<Vec<[f32; 4]>> = vec![Vec::new(); (bins + 1.) as usize];
for element in image.iter_element_values() {
for pixel in element.data.iter() {
let r = pixel.r() * GRID;
let g = pixel.g() * GRID;
let b = pixel.b() * GRID;
for pixel in image.element().data.iter() {
let r = pixel.r() * GRID;
let g = pixel.g() * GRID;
let b = pixel.b() * GRID;
let bin = (r * GRID + g * GRID + b * GRID) as usize;
let bin = (r * GRID + g * GRID + b * GRID) as usize;
histogram[bin] += 1;
color_bins[bin].push(pixel.to_gamma_srgb_channels());
}
histogram[bin] += 1;
color_bins[bin].push(pixel.to_gamma_srgb_channels());
}
let shorted = histogram.iter().enumerate().filter(|&(_, &count)| count > 0).map(|(i, _)| i).collect::<Vec<usize>>();
shorted
.iter()
.take(count as usize)
.take(*count.element() as usize)
.flat_map(|&i| {
let list = &color_bins[i];
@@ -69,13 +67,13 @@ mod test {
fn test_image_color_palette() {
let result = image_color_palette(
(),
List::new_from_element(Raster::new_cpu(Image {
Item::new_from_element(Raster::new_cpu(Image {
width: 100,
height: 100,
data: vec![Color::from_rgbaf32(0., 0., 0., 1.).unwrap(); 10000],
base64_string: None,
})),
1,
Item::new_from_element(1),
);
assert_eq!(futures::executor::block_on(result), List::new_from_element(Color::from_rgbaf32(0., 0., 0., 1.).unwrap()));
}

View File

@@ -3,7 +3,7 @@ use core_types::ATTR_TRANSFORM;
use core_types::color::Color;
use core_types::color::{Alpha, AlphaMut, Channel, LinearChannel, Luminance, RGBMut};
use core_types::context::{Ctx, ExtractFootprint};
use core_types::list::{Item, List};
use core_types::list::Item;
use core_types::math::bbox::Bbox;
use core_types::transform::Transform;
use dyn_any::DynAny;
@@ -31,270 +31,229 @@ impl From<std::io::Error> for Error {
}
#[node_macro::node(category("Debug"))]
pub fn sample_image(ctx: impl ExtractFootprint + Clone + Send, image_frame: List<Raster<CPU>>) -> List<Raster<CPU>> {
image_frame
.into_iter()
.filter_map(|row| {
let image_frame_transform: DAffine2 = row.attribute_cloned_or_default(ATTR_TRANSFORM);
let (image, mut attributes) = row.into_parts();
pub fn sample_image(ctx: impl ExtractFootprint + Clone + Send, image_frame: Item<Raster<CPU>>) -> Item<Raster<CPU>> {
let image_frame_transform: DAffine2 = image_frame.attribute_cloned_or_default(ATTR_TRANSFORM);
// Resize the image using the image crate
let data = bytemuck::cast_vec(image.data.clone());
let footprint = ctx.footprint();
let viewport_bounds = footprint.viewport_bounds_in_local_space();
let image_bounds = Bbox::from_transform(image_frame_transform).to_axis_aligned_bbox();
let intersection = viewport_bounds.intersect(&image_bounds);
let size = intersection.size();
let footprint = ctx.footprint();
let viewport_bounds = footprint.viewport_bounds_in_local_space();
let image_bounds = Bbox::from_transform(image_frame_transform).to_axis_aligned_bbox();
let intersection = viewport_bounds.intersect(&image_bounds);
let image_size = DAffine2::from_scale(DVec2::new(image.width as f64, image.height as f64));
let size = intersection.size();
let size_px = image_size.transform_vector2(size).as_uvec2();
// If the image would not be visible, return it unchanged
if size.x <= 0. || size.y <= 0. {
return image_frame;
}
// If the image would not be visible, add nothing.
if size.x <= 0. || size.y <= 0. {
return None;
}
let (image, mut attributes) = image_frame.into_parts();
let (width, height) = (image.width, image.height);
let image_buffer = ::image::Rgba32FImage::from_raw(image.width, image.height, data).expect("Failed to convert internal image format into image-rs data type.");
// Resize the image using the image crate
let data = bytemuck::cast_vec(image.into_data().data);
let image_size = DAffine2::from_scale(DVec2::new(width as f64, height as f64));
let size_px = image_size.transform_vector2(size).as_uvec2();
let dynamic_image: ::image::DynamicImage = image_buffer.into();
let offset = (intersection.start - image_bounds.start).max(DVec2::ZERO);
let offset_px = image_size.transform_vector2(offset).as_uvec2();
let cropped = dynamic_image.crop_imm(offset_px.x, offset_px.y, size_px.x, size_px.y);
let image_buffer = ::image::Rgba32FImage::from_raw(width, height, data).expect("Failed to convert internal image format into image-rs data type.");
let viewport_resolution_x = footprint.transform.transform_vector2(DVec2::X * size.x).length();
let viewport_resolution_y = footprint.transform.transform_vector2(DVec2::Y * size.y).length();
let mut new_width = size_px.x;
let mut new_height = size_px.y;
let dynamic_image: ::image::DynamicImage = image_buffer.into();
let offset = (intersection.start - image_bounds.start).max(DVec2::ZERO);
let offset_px = image_size.transform_vector2(offset).as_uvec2();
let cropped = dynamic_image.crop_imm(offset_px.x, offset_px.y, size_px.x, size_px.y);
// Only downscale the image for now
let resized = if new_width < image.width || new_height < image.height {
new_width = viewport_resolution_x as u32;
new_height = viewport_resolution_y as u32;
// TODO: choose filter based on quality requirements
cropped.resize_exact(new_width, new_height, ::image::imageops::Triangle)
} else {
cropped
};
let buffer = resized.to_rgba32f();
let buffer = buffer.into_raw();
let vec = bytemuck::cast_vec(buffer);
let image = Image {
width: new_width,
height: new_height,
data: vec,
base64_string: None,
};
// we need to adjust the offset if we truncate the offset calculation
let viewport_resolution_x = footprint.transform.transform_vector2(DVec2::X * size.x).length();
let viewport_resolution_y = footprint.transform.transform_vector2(DVec2::Y * size.y).length();
let mut new_width = size_px.x;
let mut new_height = size_px.y;
let new_transform = image_frame_transform * DAffine2::from_translation(offset) * DAffine2::from_scale(size);
attributes.insert(ATTR_TRANSFORM, new_transform);
// Only downscale the image for now
let resized = if new_width < width || new_height < height {
new_width = viewport_resolution_x as u32;
new_height = viewport_resolution_y as u32;
// TODO: choose filter based on quality requirements
cropped.resize_exact(new_width, new_height, ::image::imageops::Triangle)
} else {
cropped
};
let buffer = resized.to_rgba32f();
let buffer = buffer.into_raw();
let vec = bytemuck::cast_vec(buffer);
let image = Image {
width: new_width,
height: new_height,
data: vec,
base64_string: None,
};
// we need to adjust the offset if we truncate the offset calculation
Some(Item::from_parts(Raster::new_cpu(image), attributes))
})
.collect()
let new_transform = image_frame_transform * DAffine2::from_translation(offset) * DAffine2::from_scale(size);
attributes.insert(ATTR_TRANSFORM, new_transform);
Item::from_parts(Raster::new_cpu(image), attributes)
}
#[node_macro::node(category("Raster: Channels"))]
pub fn combine_channels(
_: impl Ctx,
_primary: (),
#[expose] red: List<Raster<CPU>>,
#[expose] green: List<Raster<CPU>>,
#[expose] blue: List<Raster<CPU>>,
#[expose] alpha: List<Raster<CPU>>,
) -> List<Raster<CPU>> {
let max_len = red.len().max(green.len()).max(blue.len()).max(alpha.len());
let red = red.into_iter().map(Some).chain(std::iter::repeat(None)).take(max_len);
let green = green.into_iter().map(Some).chain(std::iter::repeat(None)).take(max_len);
let blue = blue.into_iter().map(Some).chain(std::iter::repeat(None)).take(max_len);
let alpha = alpha.into_iter().map(Some).chain(std::iter::repeat(None)).take(max_len);
#[expose] red: Item<Raster<CPU>>,
#[expose] green: Item<Raster<CPU>>,
#[expose] blue: Item<Raster<CPU>>,
#[expose] alpha: Item<Raster<CPU>>,
) -> Item<Raster<CPU>> {
// 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));
red.zip(green)
.zip(blue)
.zip(alpha)
.filter_map(|(((red, green), blue), alpha)| {
// Turn any default zero-sized image items into None
let red = red.filter(|i| i.element().width > 0 && i.element().height > 0);
let green = green.filter(|i| i.element().width > 0 && i.element().height > 0);
let blue = blue.filter(|i| i.element().width > 0 && i.element().height > 0);
let alpha = alpha.filter(|i| i.element().width > 0 && i.element().height > 0);
// 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();
};
// Get this item's transform and alpha blending mode from the first non-empty channel
let attributes = [&red, &green, &blue, &alpha].iter().find_map(|i| i.as_ref()).map(|i| i.attributes().clone())?;
// 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();
};
if channel_dimensions.iter().flatten().any(|&(other_width, other_height)| other_width != width || other_height != height) {
return Item::default();
}
// Get the common width and height of the channels, which must have equal dimensions
let channel_dimensions = [
red.as_ref().map(|r| (r.element().width, r.element().height)),
green.as_ref().map(|g| (g.element().width, g.element().height)),
blue.as_ref().map(|b| (b.element().width, b.element().height)),
alpha.as_ref().map(|a| (a.element().width, a.element().height)),
];
if channel_dimensions.iter().all(Option::is_none)
|| channel_dimensions
.iter()
.flatten()
.any(|&(x, y)| channel_dimensions.iter().flatten().any(|&(other_x, other_y)| x != other_x || y != other_y))
{
return None;
// 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);
for y in 0..image.height() {
for x in 0..image.width() {
let image_pixel = image.get_pixel_mut(x, y).unwrap();
match red.as_ref().and_then(|r| r.element().get_pixel(x, y)) {
Some(r) => image_pixel.set_red(r.l().cast_linear_channel()),
None => image_pixel.set_red(Channel::from_linear(0.)),
}
let &(width, height) = channel_dimensions.iter().flatten().next()?;
// Create a new image for the output element
let mut image = Image::new(width, height, Color::TRANSPARENT);
// Iterate over all pixels in the image and set the color channels
for y in 0..image.height() {
for x in 0..image.width() {
let image_pixel = image.get_pixel_mut(x, y).unwrap();
if let Some(r) = red.as_ref().and_then(|r| r.element().get_pixel(x, y)) {
image_pixel.set_red(r.l().cast_linear_channel());
} else {
image_pixel.set_red(Channel::from_linear(0.));
}
if let Some(g) = green.as_ref().and_then(|g| g.element().get_pixel(x, y)) {
image_pixel.set_green(g.l().cast_linear_channel());
} else {
image_pixel.set_green(Channel::from_linear(0.));
}
if let Some(b) = blue.as_ref().and_then(|b| b.element().get_pixel(x, y)) {
image_pixel.set_blue(b.l().cast_linear_channel());
} else {
image_pixel.set_blue(Channel::from_linear(0.));
}
if let Some(a) = alpha.as_ref().and_then(|a| a.element().get_pixel(x, y)) {
image_pixel.set_alpha(a.l().cast_linear_channel());
} else {
image_pixel.set_alpha(Channel::from_linear(1.));
}
}
match green.as_ref().and_then(|g| g.element().get_pixel(x, y)) {
Some(g) => image_pixel.set_green(g.l().cast_linear_channel()),
None => image_pixel.set_green(Channel::from_linear(0.)),
}
match blue.as_ref().and_then(|b| b.element().get_pixel(x, y)) {
Some(b) => image_pixel.set_blue(b.l().cast_linear_channel()),
None => image_pixel.set_blue(Channel::from_linear(0.)),
}
match alpha.as_ref().and_then(|a| a.element().get_pixel(x, y)) {
Some(a) => image_pixel.set_alpha(a.l().cast_linear_channel()),
None => image_pixel.set_alpha(Channel::from_linear(1.)),
}
}
}
Some(Item::from_parts(Raster::new_cpu(image), attributes))
})
.collect()
Item::from_parts(Raster::new_cpu(image), attributes)
}
#[node_macro::node(category("Raster"))]
pub fn mask(
_: impl Ctx,
/// The image to be masked.
image: List<Raster<CPU>>,
image: Item<Raster<CPU>>,
/// The stencil to be used for masking.
#[expose]
stencil: List<Raster<CPU>>,
) -> List<Raster<CPU>> {
// TODO: Figure out what it means to support multiple stencil items?
let Some(stencil) = stencil.into_iter().next() else {
// No stencil provided so we return the original image
stencil: Item<Raster<CPU>>,
) -> Item<Raster<CPU>> {
// An absent stencil arrives as the default empty raster, leaving the image unmasked
if stencil.element().width == 0 || stencil.element().height == 0 {
return image;
};
}
let stencil_size = DVec2::new(stencil.element().width as f64, stencil.element().height as f64);
image
.into_iter()
.filter_map(|mut row| {
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();
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 {
return None;
}
if mask_size == DVec2::ZERO {
return row;
}
// Transforms a point from the background image to the foreground image
let transform_attribute: DAffine2 = row.attribute_cloned_or_default(ATTR_TRANSFORM);
let bg_to_fg = transform_attribute * DAffine2::from_scale(1. / image_size);
let stencil_transform_inverse = stencil_transform.inverse();
// Transforms a point from the background image to the foreground image
let transform_attribute: DAffine2 = row.attribute_cloned_or_default(ATTR_TRANSFORM);
let bg_to_fg = transform_attribute * DAffine2::from_scale(1. / image_size);
let stencil_transform_inverse = stencil_transform.inverse();
for y in 0..row.element().height {
for x in 0..row.element().width {
let image_point = DVec2::new(x as f64, y as f64);
let mask_point = bg_to_fg.transform_point2(image_point);
let local_mask_point = stencil_transform_inverse.transform_point2(mask_point);
let mask_point = stencil_transform.transform_point2(local_mask_point.clamp(DVec2::ZERO, DVec2::ONE));
let mask_point = (DAffine2::from_scale(stencil_size) * stencil_transform.inverse()).transform_point2(mask_point);
for y in 0..row.element().height {
for x in 0..row.element().width {
let image_point = DVec2::new(x as f64, y as f64);
let mask_point = bg_to_fg.transform_point2(image_point);
let local_mask_point = stencil_transform_inverse.transform_point2(mask_point);
let mask_point = stencil_transform.transform_point2(local_mask_point.clamp(DVec2::ZERO, DVec2::ONE));
let mask_point = (DAffine2::from_scale(stencil_size) * stencil_transform.inverse()).transform_point2(mask_point);
let image_pixel = row.element_mut().data_mut().get_pixel_mut(x, y).unwrap();
let mask_pixel = stencil.element().sample(mask_point);
*image_pixel = image_pixel.multiplied_alpha(mask_pixel.l().cast_linear_channel());
}
}
let image_pixel = row.element_mut().data_mut().get_pixel_mut(x, y).unwrap();
let mask_pixel = stencil.element().sample(mask_point);
*image_pixel = image_pixel.multiplied_alpha(mask_pixel.l().cast_linear_channel());
}
}
Some(row)
})
.collect()
row
}
#[node_macro::node(category(""))]
pub fn extend_image_to_bounds(_: impl Ctx, image: List<Raster<CPU>>, bounds: DAffine2) -> List<Raster<CPU>> {
image
.into_iter()
.map(|mut row| {
let row_transform: DAffine2 = row.attribute_cloned_or_default(ATTR_TRANSFORM);
let image_aabb = Bbox::unit().affine_transform(row_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 row;
}
pub fn extend_image_to_bounds(_: impl Ctx, image: Item<Raster<CPU>>, bounds: Item<DAffine2>) -> Item<Raster<CPU>> {
let bounds = *bounds.element();
let image_data = &row.element().data;
let (image_width, image_height) = (row.element().width, row.element().height);
if image_width == 0 || image_height == 0 {
return empty_image((), bounds, List::new_from_element(Color::TRANSPARENT)).into_iter().next().unwrap();
}
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;
}
let orig_image_scale = DVec2::new(image_width as f64, image_height as f64);
let layer_to_image_space = DAffine2::from_scale(orig_image_scale) * row_transform.inverse();
let bounds_in_image_space = Bbox::unit().affine_transform(layer_to_image_space * bounds).to_axis_aligned_bbox();
let (image, mut attributes) = image.into_parts();
let (image_width, image_height) = (image.width, image.height);
if image_width == 0 || image_height == 0 {
return empty_image((), Item::new_from_element(bounds), Item::new_from_element(Color::TRANSPARENT));
}
let new_start = bounds_in_image_space.start.floor().min(DVec2::ZERO);
let new_end = bounds_in_image_space.end.ceil().max(orig_image_scale);
let new_scale = new_end - new_start;
let orig_image_scale = DVec2::new(image_width as f64, image_height as f64);
let layer_to_image_space = DAffine2::from_scale(orig_image_scale) * image_transform.inverse();
let bounds_in_image_space = Bbox::unit().affine_transform(layer_to_image_space * bounds).to_axis_aligned_bbox();
// 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 offset_in_new_image = (-new_start).as_uvec2();
for y in 0..image_height {
let old_start = y * image_width;
let new_start = (y + offset_in_new_image.y) * new_image.width + offset_in_new_image.x;
let old_row = &image_data[old_start as usize..(old_start + image_width) as usize];
let new_row = &mut new_image.data[new_start as usize..(new_start + image_width) as usize];
new_row.copy_from_slice(old_row);
}
let new_start = bounds_in_image_space.start.floor().min(DVec2::ZERO);
let new_end = bounds_in_image_space.end.ceil().max(orig_image_scale);
let new_scale = new_end - new_start;
// Compute new transform.
// let layer_to_new_texture_space = (DAffine2::from_scale(1. / new_scale) * DAffine2::from_translation(new_start) * layer_to_image_space).inverse();
let new_texture_to_layer_space = row_transform * DAffine2::from_scale(1. / orig_image_scale) * DAffine2::from_translation(new_start) * DAffine2::from_scale(new_scale);
// 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 offset_in_new_image = (-new_start).as_uvec2();
for y in 0..image_height {
let old_start = y * image_width;
let new_start = (y + offset_in_new_image.y) * new_image.width + offset_in_new_image.x;
let old_row = &image.data[old_start as usize..(old_start + image_width) as usize];
let new_row = &mut new_image.data[new_start as usize..(new_start + image_width) as usize];
new_row.copy_from_slice(old_row);
}
*row.element_mut() = Raster::new_cpu(new_image);
row.set_attribute(ATTR_TRANSFORM, new_texture_to_layer_space);
row
})
.collect()
// Compute new transform.
// let layer_to_new_texture_space = (DAffine2::from_scale(1. / new_scale) * DAffine2::from_translation(new_start) * layer_to_image_space).inverse();
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)
}
#[node_macro::node(category("Debug"))]
pub fn empty_image(_: impl Ctx, transform: DAffine2, color: List<Color>) -> List<Raster<CPU>> {
pub fn empty_image(_: impl Ctx, transform: Item<DAffine2>, color: Item<Color>) -> Item<Raster<CPU>> {
let transform = transform.into_element();
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 color = color.element(0).copied().unwrap_or(Color::WHITE);
let image = Image::new(width, height, color);
let image = Image::new(width, height, color.into_element());
let mut result_list = List::new_from_element(Raster::new_cpu(image));
result_list.set_attribute(ATTR_TRANSFORM, 0, transform);
// Callers of empty_image can safely unwrap on returned `List`
result_list
Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, transform)
}
#[node_macro::node(category(""))]
pub fn image<'a: 'n>(_: impl Ctx, resource: Resource) -> List<Raster<CPU>> {
pub fn image<'a: 'n>(_: impl Ctx, resource: Item<Resource>) -> Item<Raster<CPU>> {
let resource = resource.into_element();
let image_data = resource.as_ref();
let Some(image) = ::image::load_from_memory(image_data).ok() else {
return List::new();
return Item::default();
};
let image = image.to_rgba32f();
let image = Image {
@@ -309,7 +268,7 @@ pub fn image<'a: 'n>(_: impl Ctx, resource: Resource) -> List<Raster<CPU>> {
height: image.height(),
..Default::default()
};
List::new_from_element(Raster::new_cpu(image))
Item::new_from_element(Raster::new_cpu(image))
}
/// Generates customizable procedural noise patterns.
@@ -318,36 +277,42 @@ pub fn image<'a: 'n>(_: impl Ctx, resource: Resource) -> List<Raster<CPU>> {
pub fn noise_pattern(
ctx: impl ExtractFootprint + Ctx,
_primary: (),
#[default(true)] clip: bool,
seed: u32,
#[default(true)] clip: Item<bool>,
seed: Item<u32>,
#[widget(ParsedWidgetOverride::Custom = "noise_properties_scale")]
#[default(10.)]
scale: f64,
#[widget(ParsedWidgetOverride::Custom = "noise_properties_noise_type")] noise_type: NoiseType,
#[widget(ParsedWidgetOverride::Custom = "noise_properties_domain_warp_type")] domain_warp_type: DomainWarpType,
scale: Item<f64>,
#[widget(ParsedWidgetOverride::Custom = "noise_properties_noise_type")] noise_type: Item<NoiseType>,
#[widget(ParsedWidgetOverride::Custom = "noise_properties_domain_warp_type")] domain_warp_type: Item<DomainWarpType>,
#[widget(ParsedWidgetOverride::Custom = "noise_properties_domain_warp_amplitude")]
#[default(100.)]
domain_warp_amplitude: f64,
#[widget(ParsedWidgetOverride::Custom = "noise_properties_fractal_type")] fractal_type: FractalType,
domain_warp_amplitude: Item<f64>,
#[widget(ParsedWidgetOverride::Custom = "noise_properties_fractal_type")] fractal_type: Item<FractalType>,
#[widget(ParsedWidgetOverride::Custom = "noise_properties_fractal_octaves")]
#[default(3)]
fractal_octaves: u32,
fractal_octaves: Item<u32>,
#[widget(ParsedWidgetOverride::Custom = "noise_properties_fractal_lacunarity")]
#[default(2.)]
fractal_lacunarity: f64,
fractal_lacunarity: Item<f64>,
#[widget(ParsedWidgetOverride::Custom = "noise_properties_fractal_gain")]
#[default(0.5)]
fractal_gain: f64,
#[widget(ParsedWidgetOverride::Custom = "noise_properties_fractal_weighted_strength")] fractal_weighted_strength: f64,
fractal_gain: Item<f64>,
#[widget(ParsedWidgetOverride::Custom = "noise_properties_fractal_weighted_strength")] fractal_weighted_strength: Item<f64>,
#[widget(ParsedWidgetOverride::Custom = "noise_properties_ping_pong_strength")]
#[default(2.)]
fractal_ping_pong_strength: f64,
#[widget(ParsedWidgetOverride::Custom = "noise_properties_cellular_distance_function")] cellular_distance_function: CellularDistanceFunction,
#[widget(ParsedWidgetOverride::Custom = "noise_properties_cellular_return_type")] cellular_return_type: CellularReturnType,
fractal_ping_pong_strength: Item<f64>,
#[widget(ParsedWidgetOverride::Custom = "noise_properties_cellular_distance_function")] cellular_distance_function: Item<CellularDistanceFunction>,
#[widget(ParsedWidgetOverride::Custom = "noise_properties_cellular_return_type")] cellular_return_type: Item<CellularReturnType>,
#[widget(ParsedWidgetOverride::Custom = "noise_properties_cellular_jitter")]
#[default(1.)]
cellular_jitter: f64,
) -> List<Raster<CPU>> {
cellular_jitter: Item<f64>,
) -> Item<Raster<CPU>> {
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());
let (noise_type, domain_warp_type, fractal_type) = (noise_type.into_element(), domain_warp_type.into_element(), fractal_type.into_element());
let (cellular_distance_function, cellular_return_type) = (cellular_distance_function.into_element(), cellular_return_type.into_element());
let footprint = ctx.footprint();
let viewport_bounds = footprint.viewport_bounds_in_local_space();
@@ -365,7 +330,7 @@ pub fn noise_pattern(
// If the image would not be visible, return an empty image
if size.x <= 0. || size.y <= 0. {
return List::new();
return Item::default();
}
let transform = DAffine2::from_translation(offset) * DAffine2::from_scale(size);
@@ -411,7 +376,7 @@ pub fn noise_pattern(
}
}
return List::new_from_item(Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, transform));
return Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, transform);
}
};
noise.set_noise_type(Some(noise_type));
@@ -469,11 +434,11 @@ pub fn noise_pattern(
}
}
List::new_from_item(Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, transform))
Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, transform)
}
#[node_macro::node(category("Raster: Pattern"))]
pub fn mandelbrot(ctx: impl ExtractFootprint + Send) -> List<Raster<CPU>> {
pub fn mandelbrot(ctx: impl ExtractFootprint + Send) -> Item<Raster<CPU>> {
let footprint = ctx.footprint();
let viewport_bounds = footprint.viewport_bounds_in_local_space();
@@ -485,7 +450,7 @@ pub fn mandelbrot(ctx: impl ExtractFootprint + Send) -> List<Raster<CPU>> {
// If the image would not be visible, return an empty image
if size.x <= 0. || size.y <= 0. {
return List::new();
return Item::default();
}
let scale = footprint.scale();
@@ -507,15 +472,13 @@ pub fn mandelbrot(ctx: impl ExtractFootprint + Send) -> List<Raster<CPU>> {
}
}
List::new_from_item(
Item::new_from_element(Raster::new_cpu(Image {
width,
height,
data,
..Default::default()
}))
.with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(offset) * DAffine2::from_scale(size)),
)
Item::new_from_element(Raster::new_cpu(Image {
width,
height,
data,
..Default::default()
}))
.with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(offset) * DAffine2::from_scale(size))
}
#[inline(always)]

View File

@@ -1,31 +1,42 @@
use crate::gcore::Context;
use core::f64::consts::TAU;
use core_types::list::List;
use core_types::list::{Item, List};
use core_types::registry::types::{Angle, PixelSize};
use core_types::{ATTR_TRANSFORM, CloneVarArgs, Color, Ctx, ExtractAll, InjectVarArgs, OwnedContextImpl};
use glam::{DAffine2, DVec2};
use graphic_types::{Graphic, Vector};
use raster_types::{CPU, Raster};
use vector_types::GradientStops;
use graphic_types::{Artboard, Graphic, Vector};
use raster_types::{CPU, GPU, Raster};
use vector_types::Gradient;
#[node_macro::node(category("Repeat"))]
async fn repeat<T: Into<Graphic> + Default + Send + Clone + 'static>(
async fn repeat<T: Send + Clone + 'static>(
ctx: impl ExtractAll + CloneVarArgs + Ctx,
#[implementations(
Context -> List<Graphic>,
Context -> List<String>,
Context -> List<bool>,
Context -> List<f32>,
Context -> List<f64>,
Context -> List<u32>,
Context -> List<u64>,
Context -> List<DVec2>,
Context -> List<DAffine2>,
Context -> List<Vector>,
Context -> List<Graphic>,
Context -> List<Raster<CPU>>,
Context -> List<Raster<GPU>>,
Context -> List<Color>,
Context -> List<GradientStops>,
Context -> List<Gradient>,
Context -> List<Artboard>,
)]
content: impl Node<'n, Context<'static>, Output = List<T>>,
#[default(1)]
#[hard(1..)]
count: u32,
reverse: bool,
count: Item<u32>,
reverse: Item<bool>,
) -> List<T> {
// Someday this node can have the option to generate infinitely instead of a fixed count (basically `std::iter::repeat`).
let (count, reverse) = (count.into_element(), reverse.into_element());
let count = count as usize;
let mut result_list = List::new();
@@ -45,24 +56,35 @@ async fn repeat<T: Into<Graphic> + Default + Send + Clone + 'static>(
}
#[node_macro::node(category("Repeat"))]
pub async fn repeat_array<T: Into<Graphic> + Default + Send + Clone + 'static>(
pub async fn repeat_array<T: Send + Clone + 'static>(
ctx: impl ExtractAll + CloneVarArgs + Ctx,
#[implementations(
Context -> List<Graphic>,
Context -> List<String>,
Context -> List<bool>,
Context -> List<f32>,
Context -> List<f64>,
Context -> List<u32>,
Context -> List<u64>,
Context -> List<DVec2>,
Context -> List<DAffine2>,
Context -> List<Vector>,
Context -> List<Graphic>,
Context -> List<Raster<CPU>>,
Context -> List<Raster<GPU>>,
Context -> List<Color>,
Context -> List<GradientStops>,
Context -> List<Gradient>,
Context -> List<Artboard>,
)]
content: impl Node<'n, Context<'static>, Output = List<T>>,
#[default(100., 100.)]
// TODO: When using a custom Properties panel layout in document_node_definitions.rs and this default is set, the widget weirdly doesn't show up in the Properties panel. Investigation is needed.
direction: PixelSize,
angle: Angle,
direction: Item<PixelSize>,
angle: Item<Angle>,
#[default(5)]
#[hard(1..)]
count: u32,
count: Item<u32>,
) -> List<T> {
let (direction, angle, count) = (direction.into_element(), angle.into_element(), count.into_element());
let angle = angle.to_radians();
// A single copy has no steps between copies, so the denominator is kept at 1 to avoid `0. / 0.` producing a NaN transform
let total = (count - 1).max(1) as f64;
@@ -93,24 +115,36 @@ pub async fn repeat_array<T: Into<Graphic> + Default + Send + Clone + 'static>(
}
#[node_macro::node(category("Repeat"))]
async fn repeat_radial<T: Into<Graphic> + Default + Send + Clone + 'static>(
async fn repeat_radial<T: Send + Clone + 'static>(
ctx: impl ExtractAll + CloneVarArgs + Ctx,
#[implementations(
Context -> List<Graphic>,
Context -> List<String>,
Context -> List<bool>,
Context -> List<f32>,
Context -> List<f64>,
Context -> List<u32>,
Context -> List<u64>,
Context -> List<DVec2>,
Context -> List<DAffine2>,
Context -> List<Vector>,
Context -> List<Graphic>,
Context -> List<Raster<CPU>>,
Context -> List<Raster<GPU>>,
Context -> List<Color>,
Context -> List<GradientStops>,
Context -> List<Gradient>,
Context -> List<Artboard>,
)]
content: impl Node<'n, Context<'static>, Output = List<T>>,
start_angle: Angle,
start_angle: Item<Angle>,
#[unit(" px")]
#[default(5)]
radius: f64,
radius: Item<f64>,
#[default(5)]
#[hard(1..)]
count: u32,
count: Item<u32>,
) -> List<T> {
let (start_angle, radius, count) = (start_angle.into_element(), radius.into_element(), count.into_element());
let mut result_list = List::new();
for index in 0..count {
@@ -137,19 +171,31 @@ async fn repeat_radial<T: Into<Graphic> + Default + Send + Clone + 'static>(
}
#[node_macro::node(category("Repeat"), name("Repeat on Points"))]
async fn repeat_on_points<T: Into<Graphic> + Default + Send + Clone + 'static>(
async fn repeat_on_points<T: Send + Clone + 'static>(
ctx: impl ExtractAll + CloneVarArgs + Sync + Ctx + InjectVarArgs,
points: List<Vector>,
#[implementations(
Context -> List<Graphic>,
Context -> List<String>,
Context -> List<bool>,
Context -> List<f32>,
Context -> List<f64>,
Context -> List<u32>,
Context -> List<u64>,
Context -> List<DVec2>,
Context -> List<DAffine2>,
Context -> List<Vector>,
Context -> List<Graphic>,
Context -> List<Raster<CPU>>,
Context -> List<Raster<GPU>>,
Context -> List<Color>,
Context -> List<GradientStops>,
Context -> List<Gradient>,
Context -> List<Artboard>,
)]
content: impl Node<'n, Context<'static>, Output = List<T>>,
reverse: bool,
reverse: Item<bool>,
) -> List<T> {
let reverse = reverse.into_element();
let mut result_list = List::new();
for points_index in 0..points.len() {
@@ -188,6 +234,7 @@ mod test {
use super::*;
use core_types::Ctx;
use core_types::Node;
use core_types::list::Item;
use core_types::transform::Footprint;
use glam::DVec2;
use graphene_core::ReadPositionNode;
@@ -199,6 +246,7 @@ mod test {
use std::pin::Pin;
use vector_nodes::generator_nodes::RectangleNode;
use vector_types::subpath::Subpath;
use vector_types::vector::misc::BoxCorners;
fn vector_node_from_bezpath(bezpath: BezPath) -> List<Vector> {
List::new_from_element(Vector::from_bezpath(bezpath))
@@ -215,21 +263,39 @@ mod test {
}
}
// Raises a generator's rank-0 `Item<Vector>` output to a singleton `List<Vector>` for the still-list-typed Repeat on Points content connector
#[derive(Clone)]
pub struct RaiseToListNode<N>(N);
impl<'i, I: 'i, N> Node<'i, I> for RaiseToListNode<N>
where
N: Node<'i, I, Output = Pin<Box<dyn Future<Output = Item<Vector>> + 'i + Send>>>,
{
type Output = Pin<Box<dyn Future<Output = List<Vector>> + 'i + Send>>;
fn eval(&'i self, input: I) -> Self::Output {
let future = self.0.eval(input);
Box::pin(async move { future.await.into() })
}
}
#[tokio::test]
async fn repeat_on_points_test() {
let context = OwnedContextImpl::default().into_context();
let rect = RectangleNode::new(
FutureWrapperNode(()),
ExtractXyNode::new(ReadPositionNode::new(FutureWrapperNode(()), FutureWrapperNode(0)), FutureWrapperNode(XY::Y)),
FutureWrapperNode(2_f64),
FutureWrapperNode(false),
FutureWrapperNode(0_f64),
FutureWrapperNode(false),
ExtractXyNode::new(
ReadPositionNode::new(FutureWrapperNode(()), FutureWrapperNode(Item::new_from_element(0_u32))),
FutureWrapperNode(Item::new_from_element(XY::Y)),
),
FutureWrapperNode(Item::new_from_element(2_f64)),
FutureWrapperNode(Item::new_from_element(BoxCorners::default())),
FutureWrapperNode(Item::new_from_element(false)),
FutureWrapperNode(Item::new_from_element(false)),
);
let positions = [DVec2::new(40., 20.), DVec2::ONE, DVec2::new(-42., 9.), DVec2::new(10., 345.)];
let points = List::new_from_element(Vector::from_subpath(Subpath::from_anchors(positions, false)));
let generated = super::repeat_on_points(context, points, &rect, false).await;
let generated = super::repeat_on_points(context, points, &RaiseToListNode(rect), Item::new_from_element(false)).await;
assert_eq!(generated.len(), positions.len());
for (position, index) in positions.into_iter().zip(0..generated.len()) {
let bounds = generated
@@ -250,12 +316,12 @@ mod test {
let repeated = super::repeat_array(
context,
&FutureWrapperNode(vector_node_from_bezpath(Rect::new(0., 0., 1., 1.).to_path(DEFAULT_ACCURACY))),
direction,
0.,
count,
Item::new_from_element(direction),
Item::new_from_element(0.),
Item::new_from_element(count),
)
.await;
let vector_list = vector_nodes::flatten_path(Footprint::default(), repeated).await;
let vector_list = List::new_from_item(vector_nodes::flatten_path(Footprint::default(), List::new_from_element(Graphic::Vector(repeated))).await);
let vector = vector_list.element(0).unwrap();
assert_eq!(vector.region_manipulator_groups().count(), 3);
for (index, (_, manipulator_groups)) in vector.region_manipulator_groups().enumerate() {
@@ -269,12 +335,12 @@ mod test {
let repeated = super::repeat_array(
context,
&FutureWrapperNode(vector_node_from_bezpath(Rect::new(0., 0., 1., 1.).to_path(DEFAULT_ACCURACY))),
DVec2::new(12., 10.),
45.,
1,
Item::new_from_element(DVec2::new(12., 10.)),
Item::new_from_element(45.),
Item::new_from_element(1),
)
.await;
let vector_list = vector_nodes::flatten_path(Footprint::default(), repeated).await;
let vector_list = List::new_from_item(vector_nodes::flatten_path(Footprint::default(), List::new_from_element(Graphic::Vector(repeated))).await);
let vector = vector_list.element(0).unwrap();
assert_eq!(vector.region_manipulator_groups().count(), 1);
@@ -291,12 +357,12 @@ mod test {
let repeated = super::repeat_array(
context,
&FutureWrapperNode(vector_node_from_bezpath(Rect::new(0., 0., 1., 1.).to_path(DEFAULT_ACCURACY))),
direction,
0.,
count,
Item::new_from_element(direction),
Item::new_from_element(0.),
Item::new_from_element(count),
)
.await;
let vector_list = vector_nodes::flatten_path(Footprint::default(), repeated).await;
let vector_list = List::new_from_item(vector_nodes::flatten_path(Footprint::default(), List::new_from_element(Graphic::Vector(repeated))).await);
let vector = vector_list.element(0).unwrap();
assert_eq!(vector.region_manipulator_groups().count(), 8);
for (index, (_, manipulator_groups)) in vector.region_manipulator_groups().enumerate() {
@@ -307,8 +373,15 @@ mod test {
#[tokio::test]
async fn repeat_radial() {
let context = OwnedContextImpl::default().into_context();
let repeated = super::repeat_radial(context, &FutureWrapperNode(vector_node_from_bezpath(Rect::new(-1., -1., 1., 1.).to_path(DEFAULT_ACCURACY))), 45., 4., 8).await;
let vector_list = vector_nodes::flatten_path(Footprint::default(), repeated).await;
let repeated = super::repeat_radial(
context,
&FutureWrapperNode(vector_node_from_bezpath(Rect::new(-1., -1., 1., 1.).to_path(DEFAULT_ACCURACY))),
Item::new_from_element(45.),
Item::new_from_element(4.),
Item::new_from_element(8),
)
.await;
let vector_list = List::new_from_item(vector_nodes::flatten_path(Footprint::default(), List::new_from_element(Graphic::Vector(repeated))).await);
let vector = vector_list.element(0).unwrap();
assert_eq!(vector.region_manipulator_groups().count(), 8);

View File

@@ -14,37 +14,44 @@ fn format_json(
_: impl Ctx,
/// The JSON string to reformat.
#[name("JSON")]
json: String,
json: Item<String>,
/// Removes optional spaces within curly brackets and after colons and commas.
compact: bool,
compact: Item<bool>,
/// Break arrays and objects across multiple lines when they exceed the line break length.
#[default(true)]
#[name("Multi-Line")]
multi_line: bool,
multi_line: Item<bool>,
/// The indentation string used for each nesting level. Escape sequences like `\t` (the tab character) are supported. Two or four spaces are also common choices.
#[default("\\t")]
indent: String,
indent: Item<String>,
/// The maximum line length before a container (array or object) is broken across lines. Set this to 0 to always break containers. (Requires *Multi-Line* to take effect.)
///
/// This is not a maximum line length guarantee. Deep nesting and long keys or values may exceed this length.
#[default(120)]
break_length: u32,
break_length: Item<u32>,
/// 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: bool,
) -> String {
let cleaned = strip_trailing_commas(&json);
break_nested: Item<bool>,
) -> Item<String> {
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 };
let indent = unescape_string(indent);
let colon = if compact { ":" } else { ": " };
let comma_space = if compact { "," } else { ", " };
let line_width = break_length as usize;
if multi_line {
let result = if multi_line {
format_value(&value, 0, &indent, colon, comma_space, compact, break_nested, line_width)
} else {
format_inline(&value, colon, comma_space, compact)
}
};
*json.element_mut() = result;
json
}
/// Strips trailing commas before `]` and `}` to accept JSON-with-trailing-commas input.
@@ -188,7 +195,7 @@ fn query_json(
_: impl Ctx,
/// The JSON string to extract a value from.
#[name("JSON")]
json: String,
json: Item<String>,
/// Determines which contained value to extract from within the JSON.
///
/// The path syntax is like JavaScript's accessor syntax that follows an array/object value. It also supports negative indexing to count backwards from the end. Additionally, `[]` accesses all array and object values instead of just one.
@@ -198,19 +205,29 @@ fn query_json(
/// Use `.size` or `["size"]` to get the `size` property of `{ "size": 10 }`. The latter form is required if the key contains spaces or special characters like `["this key with spaces!"]`.
/// Use chained accessors like `.fonts[0].name` to query deeper.
/// Use the `[]` accessor to query all elements, like `.fonts[].weights[]` to get every weight of every font.
path: String,
path: Item<String>,
/// Strips the surrounding double quotes from string values, returning the raw text. Other types are never wrapped in quotes.
#[default(true)]
unquote_strings: bool,
) -> String {
let cleaned = strip_trailing_commas(&json);
let Ok(value): Result<Value, _> = serde_json::from_str(&cleaned) else { return String::new() };
let Some(segments) = parse_json_path(path.trim()) else { return String::new() };
unquote_strings: Item<bool>,
) -> Item<String> {
let mut json = json;
let path = path.element().clone();
let unquote_strings = *unquote_strings.element();
let mut results = Vec::new();
resolve_all(&value, &segments, !unquote_strings, &mut results);
let cleaned = strip_trailing_commas(json.element());
results.into_iter().next().map(|(text, _ty)| text).unwrap_or_default()
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);
results.into_iter().next().map(|(text, _ty)| text).unwrap_or_default()
}
_ => String::new(),
};
*json.element_mut() = result;
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.
@@ -226,7 +243,7 @@ fn query_json_all(
_: impl Ctx,
/// The JSON string to extract values from.
#[name("JSON")]
json: String,
json: Item<String>,
/// Determines which contained values to extract from within the JSON.
///
/// The path syntax is like JavaScript's accessor syntax that follows an array/object value. It also supports negative indexing to count backwards from the end. Additionally, `[]` accesses all array and object values instead of just one.
@@ -236,17 +253,17 @@ fn query_json_all(
/// Use `.size` or `["size"]` to get the `size` property of `{ "size": 10 }`. The latter form is required if the key contains spaces or special characters like `["this key with spaces!"]`.
/// Use chained accessors like `.fonts[0].name` to query deeper.
/// Use the `[]` accessor to query all elements, like `.fonts[].weights[]` to get every weight of every font.
path: String,
path: Item<String>,
/// Strips the surrounding double quotes from string values, returning the raw text. Other types are never wrapped in quotes.
#[default(true)]
unquote_strings: bool,
unquote_strings: Item<bool>,
) -> List<String> {
let cleaned = strip_trailing_commas(&json);
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.trim()) else { return List::new() };
let Some(segments) = parse_json_path(path.element().trim()) else { return List::new() };
let mut results = Vec::new();
resolve_all(&value, &segments, !unquote_strings, &mut results);
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()
}

View File

@@ -184,34 +184,43 @@ pub enum StringCapitalization {
/// Constructs a string value which may be set to any plain text.
#[node_macro::node(category("Value"))]
fn string_value(_: impl Ctx, _primary: (), string: TextArea) -> String {
fn string_value(_: impl Ctx, _primary: (), string: Item<TextArea>) -> Item<String> {
string
}
/// Type-asserts a value to be a string.
#[node_macro::node(category("Debug"))]
fn as_string(_: impl Ctx, value: String) -> String {
fn as_string(_: impl Ctx, value: Item<String>) -> Item<String> {
value
}
/// Joins two strings together.
#[node_macro::node(category("Text"))]
fn string_concatenate(_: impl Ctx, #[implementations(String)] first: String, second: TextArea) -> String {
first + &second
fn string_concatenate(_: impl Ctx, #[implementations(String)] first: Item<String>, second: Item<TextArea>) -> Item<String> {
let mut first = first;
first.element_mut().push_str(second.element());
first
}
/// Replaces all occurrences of "From" with "To" in the input string.
#[node_macro::node(category("Text"))]
fn string_replace(_: impl Ctx, string: String, from: TextArea, to: TextArea) -> String {
string.replace(&from, &to)
fn string_replace(_: impl Ctx, string: Item<String>, from: Item<TextArea>, to: Item<TextArea>) -> Item<String> {
let mut string = string;
let result = string.element().replace(from.element().as_str(), to.element());
*string.element_mut() = result;
string
}
/// Extracts a substring from the input string, starting at "Start" and ending before "End".
///
/// Negative indices count from the end of the string. If the index of "Start" equals or exceeds "End", the result is an empty string.
#[node_macro::node(category("Text"))]
fn string_slice(_: impl Ctx, string: String, start: SignedInteger, end: SignedInteger) -> String {
let total_graphemes = string.graphemes(true).count();
fn string_slice(_: impl Ctx, string: Item<String>, start: Item<SignedInteger>, end: Item<SignedInteger>) -> Item<String> {
let mut string = string;
let (start, end) = (*start.element(), *end.element());
let total_graphemes = string.element().graphemes(true).count();
let start = if start < 0. {
total_graphemes.saturating_sub(start.abs() as usize)
@@ -224,11 +233,14 @@ fn string_slice(_: impl Ctx, string: String, start: SignedInteger, end: SignedIn
(end as usize).min(total_graphemes)
};
if start >= end {
return String::new();
}
let result = if start >= end {
String::new()
} else {
string.element().graphemes(true).skip(start).take(end - start).collect()
};
string.graphemes(true).skip(start).take(end - start).collect()
*string.element_mut() = result;
string
}
/// Clips the string to a maximum character length, optionally appending a suffix (like "…") when truncation occurs. Strings already within the limit are not modified.
@@ -236,27 +248,30 @@ fn string_slice(_: impl Ctx, string: String, start: SignedInteger, end: SignedIn
fn string_truncate(
_: impl Ctx,
/// The string to truncate.
string: String,
string: Item<String>,
/// The maximum number of characters allowed, including the suffix if one is appended.
#[default(80)]
length: u32,
length: Item<u32>,
/// A suffix appended to indicate truncation occurred, unless empty. Its length counts towards the character budget.
#[default("")]
suffix: String,
) -> String {
let max_length = length as usize;
let grapheme_count = string.graphemes(true).count();
suffix: Item<String>,
) -> Item<String> {
let mut string = string;
let max_length = *length.element() as usize;
let grapheme_count = string.element().graphemes(true).count();
if grapheme_count <= max_length {
return string;
}
let suffix: String = suffix.graphemes(true).take(max_length).collect();
let suffix: String = suffix.element().graphemes(true).take(max_length).collect();
let keep = max_length - suffix.graphemes(true).count();
let mut truncated: String = string.graphemes(true).take(keep).collect();
let mut truncated: String = string.element().graphemes(true).take(keep).collect();
truncated.push_str(&suffix);
truncated
*string.element_mut() = truncated;
string
}
/// Formats a number as a string with control over decimal places, decimal separator, and thousands grouping.
@@ -264,25 +279,31 @@ fn string_truncate(
fn format_number(
_: impl Ctx,
/// The number to format as a string.
number: f64,
number: Item<f64>,
/// The amount of digits after the decimal point. The value is rounded to fit. Set to 0 to show only whole numbers.
#[default(2)]
decimal_places: u32,
decimal_places: Item<u32>,
/// The character(s) used as the decimal point.
#[default(".")]
decimal_separator: String,
decimal_separator: Item<String>,
/// Always show the exact number of decimal places, even if they are trailing zeros.
#[default(true)]
fixed_decimals: bool,
fixed_decimals: Item<bool>,
/// Whether to group digits with a thousands separator.
use_thousands_separator: bool,
use_thousands_separator: Item<bool>,
/// The character(s) inserted between digit groups.
#[default(",")]
thousands_separator: String,
thousands_separator: Item<String>,
/// Don't group 4-digit numbers with a thousands separator (only start grouping at 10,000 and above).
#[name("Start at 10,000")]
start_at_10000: bool,
) -> String {
start_at_10000: Item<bool>,
) -> Item<String> {
let (number, attributes) = number.into_parts();
let (decimal_places, fixed_decimals, use_thousands_separator, start_at_10000) =
(*decimal_places.element(), *fixed_decimals.element(), *use_thousands_separator.element(), *start_at_10000.element());
let decimal_separator = decimal_separator.element().clone();
let thousands_separator = thousands_separator.element().clone();
// Find the maximum meaningful decimal precision by detecting where float noise begins.
// This works correctly whether the value originated as f32 or f64, since we find the
// shortest decimal representation that round-trips back to the same f64 value.
@@ -337,36 +358,38 @@ fn format_number(
};
// Build the final string
let Some(decimal_string) = decimal_string else {
if fixed_decimals && requested_places > 0 {
let result = match decimal_string {
None if fixed_decimals && requested_places > 0 => {
let zeros = "0".repeat(requested_places);
return format!("{sign}{grouped_whole}{decimal_separator}{zeros}");
format!("{sign}{grouped_whole}{decimal_separator}{zeros}")
}
None => format!("{sign}{grouped_whole}"),
Some(decimal_string) if fixed_decimals => format!("{sign}{grouped_whole}{decimal_separator}{decimal_string}"),
Some(decimal_string) => {
let trimmed = decimal_string.trim_end_matches('0');
if trimmed.is_empty() {
format!("{sign}{grouped_whole}")
} else {
format!("{sign}{grouped_whole}{decimal_separator}{trimmed}")
}
}
return format!("{sign}{grouped_whole}");
};
if fixed_decimals {
format!("{sign}{grouped_whole}{decimal_separator}{decimal_string}")
} else {
let trimmed = decimal_string.trim_end_matches('0');
if trimmed.is_empty() {
format!("{sign}{grouped_whole}")
} else {
format!("{sign}{grouped_whole}{decimal_separator}{trimmed}")
}
}
Item::from_parts(result, attributes)
}
/// Parses a string into a number. Falls back to the chosen value if the string is not a valid number.
#[node_macro::node(category("Text"))]
#[node_macro::node(category("Text"), name("String to Number"))]
fn string_to_number(
_: impl Ctx,
/// The string containing a number. Surrounding whitespace is ignored, a decimal point (.) may be included, sign prefixes (+/-) are respected, and scientific notation (e.g. "1e-3") is supported.
string: String,
string: Item<String>,
/// The value of the result if the string cannot be parsed as a valid number.
fallback: f64,
) -> f64 {
string.trim().parse::<f64>().unwrap_or(fallback)
fallback: Item<f64>,
) -> Item<f64> {
let (string, attributes) = string.into_parts();
Item::from_parts(string.trim().parse::<f64>().unwrap_or(*fallback.element()), attributes)
}
/// Removes leading and/or trailing whitespace from a string. Common whitespace characters include spaces, tabs, and newlines.
@@ -374,20 +397,26 @@ fn string_to_number(
fn string_trim(
_: impl Ctx,
/// The string that may contain leading and trailing whitespace that should be removed.
string: String,
string: Item<String>,
/// Whether the start of the string should have its whitespace removed.
#[default(true)]
start: bool,
start: Item<bool>,
/// Whether the end of the string should have its whitespace removed.
#[default(true)]
end: bool,
) -> String {
match (start, end) {
(true, true) => string.trim().to_string(),
(true, false) => string.trim_start().to_string(),
(false, true) => string.trim_end().to_string(),
(false, false) => string,
}
end: Item<bool>,
) -> Item<String> {
let mut string = string;
let (start, end) = (*start.element(), *end.element());
let result = match (start, end) {
(true, true) => string.element().trim().to_string(),
(true, false) => string.element().trim_start().to_string(),
(false, true) => string.element().trim_end().to_string(),
(false, false) => return string,
};
*string.element_mut() = result;
string
}
/// Converts between literal escape sequences and their corresponding control characters within a string.
@@ -398,12 +427,18 @@ fn string_trim(
fn string_escape(
_: impl Ctx,
/// The string that contains either literal escape sequences or control characters to be converted to the opposite representation.
string: String,
string: Item<String>,
/// Convert the control characters back into their escape sequence representations.
#[default(true)]
unescape: bool,
) -> String {
if unescape { unescape_string(string) } else { escape_string(string) }
unescape: Item<bool>,
) -> Item<String> {
let mut string = string;
let input = std::mem::take(string.element_mut());
let result = if *unescape.element() { unescape_string(input) } else { escape_string(input) };
*string.element_mut() = result;
string
}
/// Reverses the sequence of characters making up the string so it reads back-to-front. ("Backwards text" becomes "txet sdrawkcaB".)
@@ -411,9 +446,13 @@ fn string_escape(
fn string_reverse(
_: impl Ctx,
/// The string to be reversed.
string: String,
) -> String {
string.graphemes(true).rev().collect()
string: Item<String>,
) -> Item<String> {
let mut string = string;
let result: String = string.element().graphemes(true).rev().collect();
*string.element_mut() = result;
string
}
/// Repeats the string a given number of times, optionally with a separator between each repetition.
@@ -421,31 +460,35 @@ fn string_reverse(
fn string_repeat(
_: impl Ctx,
/// The string to be repeated.
string: String,
string: Item<String>,
/// The number of times the string should appear in the output.
#[default(2)]
#[hard(1..)]
count: u32,
count: Item<u32>,
/// The string placed between each repetition.
#[default("\\n")]
separator: String,
separator: Item<String>,
/// Whether to convert escape sequences found in the separator into their corresponding characters:
/// "\n" (newline), "\r" (carriage return), "\t" (tab), "\0" (null), and "\\" (backslash).
#[default(true)]
separator_escaping: bool,
) -> String {
let separator = if separator_escaping { unescape_string(separator) } else { separator };
separator_escaping: Item<bool>,
) -> Item<String> {
let mut string = string;
let separator = separator.element().clone();
let separator = if *separator_escaping.element() { unescape_string(separator) } else { separator };
let count = count as usize;
let count = *count.element() as usize;
let mut result = String::with_capacity((string.len() + separator.len()) * count);
let mut result = String::with_capacity((string.element().len() + separator.len()) * count);
for i in 0..count {
if i > 0 {
result.push_str(&separator);
}
result.push_str(&string);
result.push_str(string.element());
}
result
*string.element_mut() = result;
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.
@@ -453,21 +496,25 @@ fn string_repeat(
fn string_pad(
_: impl Ctx,
/// The string to be padded to a target length.
string: String,
string: Item<String>,
/// The target character length after padding. When "Up To" is set, this length concerns only the portion before (or after) that substring.
#[default(10)]
length: u32,
length: Item<u32>,
/// The repeated substring used to fill the remaining space. A multi-charcter substring may end partway through its final repetition.
#[default("#")]
padding: String,
padding: Item<String>,
/// Pad only the length of the string encountered before the start of the first (or after the end of the last) occurrence of this substring, if given and present (otherwise the full string is considered).
///
/// For example, this can pad numbers with leading zeros to align them before the decimal point.
up_to: String,
up_to: Item<String>,
/// Pad at the end of the string instead of the start.
from_end: bool,
) -> String {
let target_length = length as usize;
from_end: Item<bool>,
) -> Item<String> {
let mut string = string;
let target_length = *length.element() as usize;
let padding = padding.element().clone();
let up_to = up_to.element().clone();
let from_end = *from_end.element();
if padding.is_empty() {
return string;
@@ -475,9 +522,9 @@ fn string_pad(
// Split the string at the "up to" substring if provided, and only pad that portion
if !up_to.is_empty()
&& let Some(position) = if from_end { string.rfind(&*up_to) } else { string.find(&*up_to) }
&& let Some(position) = if from_end { string.element().rfind(&*up_to) } else { string.element().find(&*up_to) }
{
let (before, after) = string.split_at(position);
let (before, after) = string.element().split_at(position);
if from_end {
// Pad the portion after the substring
@@ -488,7 +535,10 @@ fn string_pad(
}
let pad_length = target_length - current_length;
let padding: String = padding.graphemes(true).cycle().take(pad_length).collect();
return format!("{before}{up_to}{after_substring}{padding}");
let result = format!("{before}{up_to}{after_substring}{padding}");
*string.element_mut() = result;
return string;
} else {
// Pad the portion before the substring
let current_length = before.graphemes(true).count();
@@ -497,11 +547,14 @@ fn string_pad(
}
let pad_length = target_length - current_length;
let padding: String = padding.graphemes(true).cycle().take(pad_length).collect();
return format!("{padding}{before}{after}");
let result = format!("{padding}{before}{after}");
*string.element_mut() = result;
return string;
}
}
let current_length = string.graphemes(true).count();
let current_length = string.element().graphemes(true).count();
if current_length >= target_length {
return string;
}
@@ -509,7 +562,10 @@ fn string_pad(
let pad_length = target_length - current_length;
let padding: String = padding.graphemes(true).cycle().take(pad_length).collect();
if from_end { string + &padding } else { padding + &string }
let result = if from_end { string.element().clone() + &padding } else { padding + string.element() };
*string.element_mut() = result;
string
}
/// Checks whether the string contains the given substring. Optionally restricts the match to only the start and/or end of the string.
@@ -517,20 +573,26 @@ fn string_pad(
fn string_contains(
_: impl Ctx,
/// The string to search within.
string: String,
string: Item<String>,
/// The substring to search for.
substring: String,
substring: Item<String>,
/// Only match if the substring appears at the start of the string.
at_start: bool,
at_start: Item<bool>,
/// Only match if the substring appears at the end of the string.
at_end: bool,
) -> bool {
match (at_start, at_end) {
(true, true) => string.starts_with(&*substring) && string.ends_with(&*substring),
(true, false) => string.starts_with(&*substring),
(false, true) => string.ends_with(&*substring),
(false, false) => string.contains(&*substring),
}
at_end: Item<bool>,
) -> Item<bool> {
let (string, attributes) = string.into_parts();
let substring = substring.element().as_str();
let (at_start, at_end) = (*at_start.element(), *at_end.element());
let result = match (at_start, at_end) {
(true, true) => string.starts_with(substring) && string.ends_with(substring),
(true, false) => string.starts_with(substring),
(false, true) => string.ends_with(substring),
(false, false) => string.contains(substring),
};
Item::from_parts(result, attributes)
}
/// Similar to the **String Contains** node, this searches within the input string for the first (or last) occurrence of a substring and returns the index of where that begins, or -1 if not found.
@@ -538,28 +600,35 @@ fn string_contains(
fn string_find_index(
_: impl Ctx,
/// The string to search within.
string: String,
string: Item<String>,
/// The substring to search for.
substring: String,
substring: Item<String>,
/// Find the start index of the last occurrence instead of the first.
from_end: bool,
) -> f64 {
from_end: Item<bool>,
) -> Item<f64> {
let (string, attributes) = string.into_parts();
let substring = substring.element().as_str();
let from_end = *from_end.element();
if substring.is_empty() {
return if from_end { string.graphemes(true).count() as f64 } else { 0. };
let result = if from_end { string.graphemes(true).count() as f64 } else { 0. };
return Item::from_parts(result, attributes);
}
if from_end {
let result = if from_end {
// Search backwards by finding all byte-level matches and taking the last one
string
.rmatch_indices(&*substring)
.rmatch_indices(substring)
.next()
.map_or(-1., |(byte_index, _)| string[..byte_index].graphemes(true).count() as f64)
} else {
string
.match_indices(&*substring)
.match_indices(substring)
.next()
.map_or(-1., |(byte_index, _)| string[..byte_index].graphemes(true).count() as f64)
}
};
Item::from_parts(result, attributes)
}
/// Counts the number of occurrences of a substring within the string.
@@ -567,22 +636,25 @@ fn string_find_index(
fn string_occurrences(
_: impl Ctx,
/// The string to search within.
string: String,
string: Item<String>,
/// The substring to count occurrences of.
substring: String,
substring: Item<String>,
/// Whether to count overlapping occurrences, using the substring as a sliding window.
///
/// For example, "aa" occurs twice in "aaaa" without overlapping but three times with overlapping.
overlapping: bool,
) -> f64 {
overlapping: Item<bool>,
) -> Item<f64> {
let (string, attributes) = string.into_parts();
let substring = substring.element().as_str();
if substring.is_empty() {
return 0.;
return Item::from_parts(0., attributes);
}
// NON-OVERLAPPING: Simple linear scan.
// O(n), where n = string length
if !overlapping {
return string.matches(&*substring).count() as f64;
if !*overlapping.element() {
return Item::from_parts(string.matches(substring).count() as f64, attributes);
}
// OVERLAPPING: KMP (Knuth-Morris-Pratt) algorithm.
@@ -628,7 +700,7 @@ fn string_occurrences(
}
}
count as f64
Item::from_parts(count as f64, attributes)
}
/// Converts a string's capitalization style to another of the common upper and lower case patterns, optionally joining words with a chosen separator.
@@ -636,47 +708,49 @@ fn string_occurrences(
fn string_capitalization(
_: impl Ctx,
/// The string to have its letter capitalization converted.
string: String,
string: Item<String>,
/// The capitalization style to apply.
capitalization: StringCapitalization,
capitalization: Item<StringCapitalization>,
/// Whether to split the string into words and reconnect with the chosen joiner. When disabled, the existing word structure separators are preserved.
use_joiner: bool,
use_joiner: Item<bool>,
/// The string placed between each word.
joiner: String,
) -> String {
joiner: Item<String>,
) -> Item<String> {
let mut string = string;
let capitalization = *capitalization.element();
let use_joiner = *use_joiner.element();
let joiner = joiner.element().clone();
let input = std::mem::take(string.element_mut());
// When the joiner is enabled, apply word-level casing and optionally reconnect words with the selected joiner
if use_joiner {
let result = if use_joiner {
match capitalization {
// Simple case mappings that preserve the string's existing structure
StringCapitalization::LowerCase => string.to_lowercase(),
StringCapitalization::UpperCase => string.to_uppercase(),
StringCapitalization::LowerCase => input.to_lowercase(),
StringCapitalization::UpperCase => input.to_uppercase(),
// Word-aware capitalizations that split on word boundaries and rejoin with the joiner
StringCapitalization::CapitalCase => Converter::new().set_boundaries(&Boundary::defaults()).set_pattern(pattern::capital).set_delim(&joiner).convert(&string),
StringCapitalization::CapitalCase => Converter::new().set_boundaries(&Boundary::defaults()).set_pattern(pattern::capital).set_delim(&joiner).convert(&input),
StringCapitalization::HeadlineCase => {
// First split into words with convert_case so word boundaries like "AlphaNumeric" are detected consistently with other modes,
// then apply the titlecase crate for smart capitalization (lowercasing short words like "of", "the", etc.),
// then rejoin with the custom joiner without mangling the capitalization
let spaced = Converter::new().set_boundaries(&Boundary::defaults()).set_pattern(pattern::capital).set_delim(" ").convert(&string);
let spaced = Converter::new().set_boundaries(&Boundary::defaults()).set_pattern(pattern::capital).set_delim(" ").convert(&input);
let headline = titlecase::titlecase(&spaced);
Converter::new().set_boundaries(&[Boundary::SPACE]).set_pattern(pattern::noop).set_delim(&joiner).convert(&headline)
}
StringCapitalization::SentenceCase => Converter::new()
.set_boundaries(&Boundary::defaults())
.set_pattern(pattern::sentence)
.set_delim(&joiner)
.convert(&string),
StringCapitalization::CamelCase => Converter::new().set_boundaries(&Boundary::defaults()).set_pattern(pattern::camel).set_delim(&joiner).convert(&string),
StringCapitalization::SentenceCase => Converter::new().set_boundaries(&Boundary::defaults()).set_pattern(pattern::sentence).set_delim(&joiner).convert(&input),
StringCapitalization::CamelCase => Converter::new().set_boundaries(&Boundary::defaults()).set_pattern(pattern::camel).set_delim(&joiner).convert(&input),
}
}
// When the joiner is disabled, apply only character-level casing while preserving the string's existing structure
else {
match capitalization {
StringCapitalization::LowerCase => string.to_lowercase(),
StringCapitalization::UpperCase => string.to_uppercase(),
StringCapitalization::LowerCase => input.to_lowercase(),
StringCapitalization::UpperCase => input.to_uppercase(),
StringCapitalization::CapitalCase => {
let mut capitalize_next = true;
string.chars().fold(String::with_capacity(string.len()), |mut result, c| {
input.chars().fold(String::with_capacity(input.len()), |mut result, c| {
if c.is_whitespace() || c == '_' || c == '-' {
capitalize_next = true;
result.push(c);
@@ -689,9 +763,9 @@ fn string_capitalization(
result
})
}
StringCapitalization::HeadlineCase => titlecase::titlecase(&string),
StringCapitalization::HeadlineCase => titlecase::titlecase(&input),
StringCapitalization::SentenceCase => {
let mut chars = string.chars();
let mut chars = input.chars();
match chars.next() {
Some(first) => first.to_uppercase().to_string() + &chars.as_str().to_lowercase(),
None => String::new(),
@@ -699,7 +773,7 @@ fn string_capitalization(
}
StringCapitalization::CamelCase => {
let mut capitalize_next = false;
string.chars().fold(String::with_capacity(string.len()), |mut result, c| {
input.chars().fold(String::with_capacity(input.len()), |mut result, c| {
if c.is_whitespace() || c == '_' || c == '-' {
capitalize_next = true;
result.push(c);
@@ -713,15 +787,20 @@ fn string_capitalization(
})
}
}
}
};
*string.element_mut() = result;
string
}
// TODO: Return u32, u64, or usize instead of f64 after #1621 is resolved and has allowed us to implement automatic type conversion in the node graph for nodes with generic type inputs.
// TODO: (Currently automatic type conversion only works for concrete types, via the Graphene preprocessor and not the full Graphene type system.)
/// Counts the number of characters in a string.
#[node_macro::node(category("Text"))]
fn string_length(_: impl Ctx, string: String) -> f64 {
string.graphemes(true).count() as f64
fn string_length(_: impl Ctx, string: Item<String>) -> Item<f64> {
let (string, attributes) = string.into_parts();
Item::from_parts(string.graphemes(true).count() as f64, attributes)
}
/// Splits a string into a list of substrings based on the specified delimiter. This is the inverse of the **String Join** node.
@@ -731,18 +810,19 @@ fn string_length(_: impl Ctx, string: String) -> f64 {
fn string_split(
_: impl Ctx,
/// The string to split into substrings.
string: String,
string: Item<String>,
/// The character(s) that separate the substrings. These are not included in the outputs.
#[default("\\n")]
delimiter: String,
delimiter: Item<String>,
/// Whether to convert escape sequences found in the delimiter into their corresponding characters:
/// "\n" (newline), "\r" (carriage return), "\t" (tab), "\0" (null), and "\\" (backslash).
#[default(true)]
delimiter_escaping: bool,
delimiter_escaping: Item<bool>,
) -> List<String> {
let delimiter = if delimiter_escaping { unescape_string(delimiter) } else { delimiter };
let delimiter = delimiter.element().clone();
let delimiter = if *delimiter_escaping.element() { unescape_string(delimiter) } else { delimiter };
string.split(&delimiter).map(str::to_string).map(Item::new_from_element).collect()
string.element().split(&delimiter).map(str::to_string).map(Item::new_from_element).collect()
}
/// Joins a list of strings together with a separator between each pair. This is the inverse of the **String Split** node.
@@ -755,15 +835,18 @@ fn string_join(
strings: List<String>,
/// The text placed between each pair of strings.
#[default(", ")]
separator: String,
separator: Item<String>,
/// Whether to convert escape sequences found in the separator into their corresponding characters:
/// "\n" (newline), "\r" (carriage return), "\t" (tab), "\0" (null), and "\\" (backslash).
#[default(true)]
separator_escaping: bool,
) -> String {
separator_escaping: Item<bool>,
) -> Item<String> {
let (separator, separator_escaping) = (separator.into_element(), separator_escaping.into_element());
let separator = if separator_escaping { unescape_string(separator) } else { separator };
strings.iter_element_values().map(|s| s.as_str()).collect::<Vec<_>>().join(&separator)
let joined = strings.iter_element_values().map(|s| s.as_str()).collect::<Vec<_>>().join(&separator);
Item::new_from_element(joined)
}
/// Iterates over a list of strings, evaluating the mapped operation for each one. Use the **Read String** node to access the current string inside the loop.
@@ -772,18 +855,17 @@ async fn map_string(
ctx: impl Ctx + CloneVarArgs + ExtractAll,
strings: List<String>,
#[expose]
#[implementations(Context -> String)]
mapped: impl Node<Context<'static>, Output = String>,
#[implementations(Context -> Item<String>)]
mapped: impl Node<Context<'static>, Output = Item<String>>,
) -> List<String> {
let mut result = List::new();
for (i, row) in strings.into_iter().enumerate() {
let string = row.into_element();
let owned_ctx = OwnedContextImpl::from(ctx.clone());
let owned_ctx = owned_ctx.with_vararg(Box::new(string)).with_index(i);
let owned_ctx = owned_ctx.with_vararg(Box::new(row)).with_index(i);
let mapped_string = mapped.eval(owned_ctx.into_context()).await;
result.push(Item::new_from_element(mapped_string));
result.push(mapped_string);
}
result
@@ -791,15 +873,19 @@ async fn map_string(
/// Reads the current string from within a **Map String** node's loop.
#[node_macro::node(category("Context"))]
fn read_string(ctx: impl Ctx + ExtractVarArgs) -> String {
let Ok(var_arg) = ctx.vararg(0) else { return String::new() };
fn read_string(ctx: impl Ctx + ExtractVarArgs) -> Item<String> {
let Ok(var_arg) = ctx.vararg(0) else { return Item::new_from_element(String::new()) };
let var_arg = var_arg as &dyn std::any::Any;
var_arg.downcast_ref::<String>().cloned().unwrap_or_default()
var_arg.downcast_ref::<Item<String>>().cloned().unwrap_or_default()
}
/// Converts a value to a JSON string representation.
#[node_macro::node(category("Debug"))]
fn serialize<T: serde::Serialize>(_: impl Ctx, #[implementations(String, bool, f64, u32, u64, DVec2, DAffine2)] value: T) -> String {
serde_json::to_string(&value).unwrap_or_else(|_| "Serialization Error".to_string())
fn serialize<T: serde::Serialize>(_: impl Ctx, #[implementations(String, bool, f64, u32, u64, DVec2, DAffine2)] value: Item<T>) -> Item<String> {
let (value, attributes) = value.into_parts();
let result = serde_json::to_string(&value).unwrap_or_else(|_| "Serialization Error".to_string());
Item::from_parts(result, attributes)
}

View File

@@ -201,7 +201,7 @@ impl PathBuilder {
}
}
// "Separate Glyphs" off: widen the accumulated AABBs and bundle as one override `Vector`
// Glyph separation off: widen the accumulated AABBs and bundle as one override `Vector`
if !self.merged_click_target_bboxes.is_empty() {
let mut bboxes = self.merged_click_target_bboxes;
widen_horizontal_gaps(&mut bboxes, &self.merged_click_target_baselines);

View File

@@ -7,18 +7,22 @@ use core_types::{ATTR_END, ATTR_NAME, ATTR_START, Ctx};
fn regex_contains(
_: impl Ctx,
/// The string to search within.
string: String,
string: Item<String>,
/// The regular expression pattern to search for.
pattern: String,
pattern: Item<String>,
/// Match letters regardless of case.
case_insensitive: bool,
case_insensitive: Item<bool>,
/// Make `^` and `$` match the start and end of each line, not just the whole string.
multiline: bool,
multiline: Item<bool>,
/// Only match if the pattern appears at the start of the string.
at_start: bool,
at_start: Item<bool>,
/// Only match if the pattern appears at the end of the string.
at_end: bool,
) -> bool {
at_end: Item<bool>,
) -> Item<bool> {
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)",
@@ -34,29 +38,34 @@ fn regex_contains(
let Ok(regex) = fancy_regex::Regex::new(&anchored_pattern) else {
log::error!("Invalid regex pattern: {pattern}");
return false;
return Item::from_parts(false, attributes);
};
regex.is_match(&string).unwrap_or(false)
Item::from_parts(regex.is_match(&string).unwrap_or(false), 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.
#[node_macro::node(category("Text: Regex"))]
fn regex_replace(
_: impl Ctx,
string: String,
string: Item<String>,
/// The regular expression pattern to search for.
pattern: String,
pattern: Item<String>,
/// The replacement string. Use `$0` for the whole match and `$1`, `$2`, etc. for capture groups.
replacement: String,
replacement: Item<String>,
/// Replace all matches. When disabled, only the first match is replaced.
#[default(true)]
replace_all: bool,
replace_all: Item<bool>,
/// Match letters regardless of case.
case_insensitive: bool,
case_insensitive: Item<bool>,
/// Make `^` and `$` match the start and end of each line, not just the whole string.
multiline: bool,
) -> String {
multiline: Item<bool>,
) -> Item<String> {
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)",
@@ -70,11 +79,14 @@ fn regex_replace(
return string;
};
if replace_all {
regex.replace_all(&string, replacement.as_str()).into_owned()
let result = if replace_all {
regex.replace_all(string.element(), replacement.as_str()).into_owned()
} else {
regex.replace(&string, replacement.as_str()).into_owned()
}
regex.replace(string.element(), replacement.as_str()).into_owned()
};
*string.element_mut() = result;
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).
@@ -87,16 +99,20 @@ fn regex_replace(
fn regex_find(
_: impl Ctx,
/// The string to search within.
string: String,
string: Item<String>,
/// The regular expression pattern to search for.
pattern: String,
pattern: Item<String>,
/// Which non-overlapping occurrence of the pattern to return, starting from 0 for the first match. Negative indices count backwards from the last match.
match_index: SignedInteger,
match_index: Item<SignedInteger>,
/// Match letters regardless of case.
case_insensitive: bool,
case_insensitive: Item<bool>,
/// Make `^` and `$` match the start and end of each line, not just the whole string.
multiline: bool,
multiline: Item<bool>,
) -> List<String> {
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();
}
@@ -118,7 +134,7 @@ fn regex_find(
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: Vec<_> = regex.captures_iter(string).filter_map(|c| c.ok()).collect();
let match_index = match_index as i32;
let resolved_index = if match_index < 0 {
@@ -158,14 +174,18 @@ fn regex_find(
fn regex_find_all(
_: impl Ctx,
/// The string to search within.
string: String,
string: Item<String>,
/// The regular expression pattern to search for.
pattern: String,
pattern: Item<String>,
/// Match letters regardless of case.
case_insensitive: bool,
case_insensitive: Item<bool>,
/// Make `^` and `$` match the start and end of each line, not just the whole string.
multiline: bool,
multiline: Item<bool>,
) -> List<String> {
let string = string.element();
let pattern = pattern.element();
let (case_insensitive, multiline) = (*case_insensitive.element(), *multiline.element());
if pattern.is_empty() {
return List::new();
}
@@ -184,7 +204,7 @@ fn regex_find_all(
};
regex
.find_iter(&string)
.find_iter(string)
.filter_map(|m| m.ok())
.map(|m| {
Item::new_from_element(m.as_str().to_string())
@@ -201,16 +221,19 @@ fn regex_find_all(
fn regex_split(
_: impl Ctx,
/// The string to split into substrings.
string: String,
string: Item<String>,
/// The regular expression pattern to split on. Matches are consumed and not included in the output.
pattern: String,
pattern: Item<String>,
/// Match letters regardless of case.
case_insensitive: bool,
case_insensitive: Item<bool>,
/// Make `^` and `$` match the start and end of each line, not just the whole string.
multiline: bool,
multiline: Item<bool>,
) -> List<String> {
let pattern = pattern.element().clone();
let (case_insensitive, multiline) = (*case_insensitive.element(), *multiline.element());
if pattern.is_empty() {
return List::new_from_element(string);
return List::new_from_item(string);
}
let flags = match (case_insensitive, multiline) {
@@ -223,8 +246,8 @@ fn regex_split(
let Ok(regex) = fancy_regex::Regex::new(&full_pattern) else {
log::error!("Invalid regex pattern: {pattern}");
return List::new_from_element(string);
return List::new_from_item(string);
};
regex.split(&string).filter_map(|s| s.ok()).map(|s| s.to_string()).map(Item::new_from_element).collect()
regex.split(string.element()).filter_map(|s| s.ok()).map(|s| s.to_string()).map(Item::new_from_element).collect()
}

View File

@@ -1,8 +1,7 @@
use super::TypesettingConfig;
use super::text_context::TextContext;
use core_types::blending::BlendMode;
use core_types::list::List;
use core_types::uuid::NodeId;
use core_types::list::{Item, List, NodeIdPath};
use core_types::{
ATTR_BLEND_MODE, ATTR_EDITOR_LAYER_PATH, ATTR_FONT, ATTR_FONT_SIZE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_OPACITY, ATTR_OPACITY_FILL,
ATTR_TEXT_ALIGN, ATTR_TRANSFORM,
@@ -23,60 +22,71 @@ pub fn lines_clipping(text: &str, font: &Resource, typesetting: TypesettingConfi
TextContext::with_thread_local(|ctx| ctx.lines_clipping(text, font, typesetting))
}
/// Shapes each string item of a styled `List<String>` 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.
/// 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> {
let text = item.element();
if text.is_empty() {
return 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 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_cloned_or::<Option<f64>>(ATTR_MAX_WIDTH, defaults.max_width),
max_height: item.attribute_cloned_or::<Option<f64>>(ATTR_MAX_HEIGHT, defaults.max_height),
align: item.attribute_cloned_or(ATTR_TEXT_ALIGN, defaults.align),
};
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();
let opacity = item.attribute::<f64>(ATTR_OPACITY).copied();
let opacity_fill = item.attribute::<f64>(ATTR_OPACITY_FILL).copied();
let mut result = List::new();
for mut produced in vectors.into_iter() {
if transform != DAffine2::IDENTITY {
let local = produced.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM);
produced.set_attribute(ATTR_TRANSFORM, transform * local);
}
if let Some(layer_path) = &layer_path {
produced.set_attribute(ATTR_EDITOR_LAYER_PATH, layer_path.clone());
}
if let Some(blend_mode) = blend_mode {
produced.set_attribute(ATTR_BLEND_MODE, blend_mode);
}
if let Some(opacity) = opacity {
produced.set_attribute(ATTR_OPACITY, opacity);
}
if let Some(opacity_fill) = opacity_fill {
produced.set_attribute(ATTR_OPACITY_FILL, opacity_fill);
}
result.push(produced);
}
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> {
let mut result = List::new();
for index in 0..strings.len() {
let Some(text) = strings.element(index) else { continue };
if text.is_empty() {
continue;
}
// Use fallback font when none is explicitly attached.
let font: Resource = {
let f: Resource = strings.attribute_cloned_or_default(ATTR_FONT, index);
if f.is_empty() { super::FALLBACK_FONT_RESOURCE.clone() } else { f }
};
let defaults = TypesettingConfig::default();
let typesetting = TypesettingConfig {
font_size: strings.attribute_cloned_or(ATTR_FONT_SIZE, index, defaults.font_size),
line_height_ratio: strings.attribute_cloned_or(ATTR_LINE_HEIGHT, index, defaults.line_height_ratio),
letter_spacing: strings.attribute_cloned_or(ATTR_LETTER_SPACING, index, defaults.letter_spacing),
letter_tilt: strings.attribute_cloned_or(ATTR_LETTER_TILT, index, defaults.letter_tilt),
max_width: strings.attribute_cloned_or::<Option<f64>>(ATTR_MAX_WIDTH, index, defaults.max_width),
max_height: strings.attribute_cloned_or::<Option<f64>>(ATTR_MAX_HEIGHT, index, defaults.max_height),
align: strings.attribute_cloned_or(ATTR_TEXT_ALIGN, index, defaults.align),
};
let vectors = to_path(text, &font, typesetting, separate_glyphs);
let transform = strings.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM, index);
let layer_path = strings.attribute_cloned_or_default::<List<NodeId>>(ATTR_EDITOR_LAYER_PATH, index);
let blend_mode = strings.attribute::<BlendMode>(ATTR_BLEND_MODE, index).copied();
let opacity = strings.attribute::<f64>(ATTR_OPACITY, index).copied();
let opacity_fill = strings.attribute::<f64>(ATTR_OPACITY_FILL, index).copied();
for mut item in vectors.into_iter() {
if transform != DAffine2::IDENTITY {
let local = item.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM);
item.set_attribute(ATTR_TRANSFORM, transform * local);
}
if !layer_path.is_empty() {
item.set_attribute(ATTR_EDITOR_LAYER_PATH, layer_path.clone());
}
if let Some(blend_mode) = blend_mode {
item.set_attribute(ATTR_BLEND_MODE, blend_mode);
}
if let Some(opacity) = opacity {
item.set_attribute(ATTR_OPACITY, opacity);
}
if let Some(opacity_fill) = opacity_fill {
item.set_attribute(ATTR_OPACITY_FILL, opacity_fill);
}
result.push(item);
let Some(item) = strings.clone_item(index) else { continue };
for produced in shape_text_item(&item, separate_glyphs).into_iter() {
result.push(produced);
}
}

View File

@@ -1,37 +1,38 @@
use core::f64;
use core_types::color::Color;
use core_types::list::{List, ListDyn};
use core_types::list::{Item, List};
use core_types::transform::{ApplyTransform, ScaleType, Transform};
use core_types::{ATTR_TRANSFORM, CloneVarArgs, Context, Ctx, ExtractAll, InjectFootprint, ModifyFootprint, OwnedContextImpl};
use glam::{DAffine2, DMat2, DVec2};
use graphic_types::Graphic;
use graphic_types::Vector;
use graphic_types::raster_types::{CPU, GPU, Raster};
use vector_types::GradientStops;
use graphic_types::{Artboard, Graphic, Vector};
use vector_types::Gradient;
/// Applies the specified transform to the input value, which may be a graphic type or another transform.
/// Applies the specified transform to the input content.
#[node_macro::node(category("Math: Transform"))]
async fn transform<T: ApplyTransform + 'n + 'static>(
async fn transform<T: 'n + Send + 'static>(
ctx: impl Ctx + CloneVarArgs + ExtractAll + ModifyFootprint,
#[implementations(
Context -> DAffine2,
Context -> DVec2,
Context -> List<Graphic>,
Context -> List<String>,
Context -> List<Vector>,
Context -> List<Raster<CPU>>,
Context -> List<Raster<GPU>>,
Context -> List<Color>,
Context -> List<GradientStops>,
Context -> Item<DAffine2>,
Context -> Item<DVec2>,
Context -> Item<Graphic>,
Context -> Item<String>,
Context -> Item<Vector>,
Context -> Item<Raster<CPU>>,
Context -> Item<Raster<GPU>>,
Context -> Item<Color>,
Context -> Item<Gradient>,
)]
content: impl Node<Context<'static>, Output = T>,
#[widget(ParsedWidgetOverride::Custom = "transform_translation")] translation: DVec2,
#[widget(ParsedWidgetOverride::Custom = "transform_rotation")] rotation: f64,
content: impl Node<Context<'static>, Output = Item<T>>,
#[widget(ParsedWidgetOverride::Custom = "transform_translation")] translation: Item<DVec2>,
#[widget(ParsedWidgetOverride::Custom = "transform_rotation")] rotation: Item<f64>,
#[widget(ParsedWidgetOverride::Custom = "transform_scale")]
#[default(1., 1.)]
scale: DVec2,
#[widget(ParsedWidgetOverride::Custom = "transform_skew")] skew: DVec2,
) -> T {
scale: Item<DVec2>,
#[widget(ParsedWidgetOverride::Custom = "transform_skew")] skew: Item<DVec2>,
) -> Item<T> {
let (translation, rotation, scale, skew) = (*translation.element(), *rotation.element(), *scale.element(), *skew.element());
let trs = DAffine2::from_scale_angle_translation(scale, rotation.to_radians(), translation);
let skew = DAffine2::from_cols_array(&[1., skew.y.to_radians().tan(), skew.x.to_radians().tan(), 1., 0., 0.]);
let matrix = trs * skew;
@@ -44,11 +45,43 @@ async fn transform<T: ApplyTransform + 'n + 'static>(
ctx = ctx.with_footprint(footprint);
}
let mut transform_target = content.eval(ctx.into_context()).await;
let mut item = content.eval(ctx.into_context()).await;
transform_target.left_apply_transform(&matrix);
item.left_apply_transform(&matrix);
transform_target
item
}
/// The whole-`List` counterpart of `transform`, composing the matrix onto every item of a rank-1 content wire.
/// Registered under the `TransformNode` identifier by manual registry rows, since the macro's element-wise variants require an `Item`-peeling primary.
#[node_macro::node(category(""), skip_impl)]
async fn transform_list<T: 'n + Send + 'static>(
ctx: impl Ctx + CloneVarArgs + ExtractAll + ModifyFootprint,
content: impl Node<Context<'static>, Output = List<T>>,
translation: Item<DVec2>,
rotation: Item<f64>,
scale: Item<DVec2>,
skew: Item<DVec2>,
) -> List<T> {
let (translation, rotation, scale, skew) = (*translation.element(), *rotation.element(), *scale.element(), *skew.element());
let trs = DAffine2::from_scale_angle_translation(scale, rotation.to_radians(), translation);
let skew = DAffine2::from_cols_array(&[1., skew.y.to_radians().tan(), skew.x.to_radians().tan(), 1., 0., 0.]);
let matrix = trs * skew;
let footprint = ctx.try_footprint().copied();
let mut ctx = OwnedContextImpl::from(ctx);
if let Some(mut footprint) = footprint {
footprint.apply_transform(&matrix);
ctx = ctx.with_footprint(footprint);
}
let mut list = content.eval(ctx.into_context()).await;
list.left_apply_transform(&matrix);
list
}
/// Resets the desired components of the input transform to their default values. If all components are reset, the output will be set to the identity transform.
@@ -57,98 +90,113 @@ async fn transform<T: ApplyTransform + 'n + 'static>(
fn reset_transform<T>(
_: impl Ctx,
#[implementations(
List<Graphic>,
List<Vector>,
List<Raster<CPU>>,
List<Raster<GPU>>,
List<Color>,
List<GradientStops>,
Graphic,
Vector,
Raster<CPU>,
Raster<GPU>,
Color,
Gradient,
String,
)]
mut content: List<T>,
#[default(true)] reset_translation: bool,
reset_rotation: bool,
reset_scale: bool,
) -> List<T> {
for row_transform in content.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM) {
if reset_translation {
row_transform.translation = DVec2::ZERO;
}
content: Item<T>,
#[default(true)] reset_translation: Item<bool>,
reset_rotation: Item<bool>,
reset_scale: Item<bool>,
) -> Item<T> {
let mut content = content;
let (reset_translation, reset_rotation, reset_scale) = (*reset_translation.element(), *reset_rotation.element(), *reset_scale.element());
match (reset_rotation, reset_scale) {
(true, true) => row_transform.matrix2 = DMat2::IDENTITY,
(true, false) => {
let scale = row_transform.scale_magnitudes();
row_transform.matrix2 = DMat2::from_diagonal(scale);
}
(false, true) => {
let rotation = row_transform.decompose_rotation();
row_transform.matrix2 = DMat2::from_angle(rotation);
}
(false, false) => {}
}
let item_transform = content.attribute_mut_or_insert_default::<DAffine2>(ATTR_TRANSFORM);
if reset_translation {
item_transform.translation = DVec2::ZERO;
}
match (reset_rotation, reset_scale) {
(true, true) => item_transform.matrix2 = DMat2::IDENTITY,
(true, false) => {
let scale = item_transform.scale_magnitudes();
item_transform.matrix2 = DMat2::from_diagonal(scale);
}
(false, true) => {
let rotation = item_transform.decompose_rotation();
item_transform.matrix2 = DMat2::from_angle(rotation);
}
(false, false) => {}
}
content
}
/// Overwrites the transform of each item in the input `List` with the specified transform.
/// Overwrites the transform of the input content with the specified transform.
#[node_macro::node(category("Math: Transform"))]
fn replace_transform<T>(
_: impl Ctx + InjectFootprint,
#[implementations(
List<Graphic>,
List<Vector>,
List<Raster<CPU>>,
List<Raster<GPU>>,
List<Color>,
List<GradientStops>,
Graphic,
Vector,
Raster<CPU>,
Raster<GPU>,
Color,
Gradient,
String,
)]
mut content: List<T>,
transform: DAffine2,
) -> List<T> {
for row_transform in content.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM) {
*row_transform = transform.transform();
}
content: Item<T>,
transform: Item<DAffine2>,
) -> Item<T> {
let mut content = content;
let transform = *transform.element();
content.set_attribute(ATTR_TRANSFORM, transform.transform());
content
}
// TODO: Figure out how this node should behave once #2982 is implemented.
/// Obtains the transform of the first item in the input `List`, if present.
/// Obtains the transform of the input content.
#[node_macro::node(category("Math: Transform"), path(core_types::vector))]
async fn extract_transform(_: impl Ctx, content: ListDyn) -> DAffine2 {
content.attribute::<DAffine2>(ATTR_TRANSFORM, 0).copied().unwrap_or_default()
fn extract_transform<T: 'n + Send>(_: impl Ctx, #[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String, Artboard)] content: Item<T>) -> Item<DAffine2> {
Item::new_from_element(content.attribute_cloned_or_default(ATTR_TRANSFORM))
}
/// Produces the inverse of the input transform, which is the transform that undoes the effect of the original transform.
#[node_macro::node(category("Math: Transform"))]
fn invert_transform(_: impl Ctx, transform: DAffine2) -> DAffine2 {
transform.inverse()
fn invert_transform(_: impl Ctx, transform: Item<DAffine2>) -> Item<DAffine2> {
let (transform, attributes) = transform.into_parts();
let result = transform.inverse();
Item::from_parts(result, attributes)
}
/// Extracts the translation component from the input transform.
#[node_macro::node(category("Math: Transform"))]
fn decompose_translation(_: impl Ctx, transform: DAffine2) -> DVec2 {
transform.translation
fn decompose_translation(_: impl Ctx, transform: Item<DAffine2>) -> Item<DVec2> {
Item::new_from_element(transform.into_element().translation)
}
/// Extracts the rotation component (in degrees) from the input transform.
#[node_macro::node(category("Math: Transform"))]
fn decompose_rotation(_: impl Ctx, transform: DAffine2) -> f64 {
transform.decompose_rotation().to_degrees()
fn decompose_rotation(_: impl Ctx, transform: Item<DAffine2>) -> Item<f64> {
Item::new_from_element(transform.into_element().decompose_rotation().to_degrees())
}
/// Extracts the scale component from the input transform.
/// **Magnitude** returns the visual length of each axis (always positive, includes any skew contribution).
/// **Pure** returns the isolated scale factors with rotation and skew stripped away (can be negative for flipped axes).
#[node_macro::node(category("Math: Transform"))]
fn decompose_scale(_: impl Ctx, transform: DAffine2, scale_type: ScaleType) -> DVec2 {
match scale_type {
fn decompose_scale(_: impl Ctx, transform: Item<DAffine2>, scale_type: Item<ScaleType>) -> Item<DVec2> {
let transform = transform.into_element();
let scale_type = scale_type.into_element();
let result = match scale_type {
ScaleType::Magnitude => transform.scale_magnitudes(),
ScaleType::Pure => transform.decompose_scale(),
}
};
Item::new_from_element(result)
}
/// Extracts the skew angle (in degrees) from the input transform.
#[node_macro::node(category("Math: Transform"))]
fn decompose_skew(_: impl Ctx, transform: DAffine2) -> f64 {
transform.decompose_skew().atan().to_degrees()
fn decompose_skew(_: impl Ctx, transform: Item<DAffine2>) -> Item<f64> {
Item::new_from_element(transform.into_element().decompose_skew().atan().to_degrees())
}

View File

@@ -1,59 +1,14 @@
use core_types::list::List;
use core_types::list::{Item, List};
use core_types::registry::types::{Angle, PixelLength, PixelSize};
use core_types::{CacheHash, Ctx};
use dyn_any::DynAny;
use glam::DVec2;
use graphic_types::Vector;
use vector_types::subpath;
use vector_types::vector::misc::{ArcType, AsU64, GridType};
use vector_types::vector::misc::{ArcType, AsU64, BoxCorners, GridType};
use vector_types::vector::misc::{HandleId, SpiralType};
use vector_types::vector::{PointId, SegmentId, StrokeId};
trait CornerRadius {
fn generate(self, size: DVec2, clamped: bool) -> List<Vector>;
}
impl CornerRadius for f64 {
fn generate(self, size: DVec2, clamped: bool) -> List<Vector> {
let clamped_radius = if clamped { self.clamp(0., size.x.min(size.y).max(0.) / 2.) } else { self };
List::new_from_element(Vector::from_subpath(subpath::Subpath::new_rounded_rectangle(size / -2., size / 2., [clamped_radius; 4])))
}
}
impl CornerRadius for List<f64> {
fn generate(self, size: DVec2, clamped: bool) -> List<Vector> {
// Expand to four corners using the CSS `border-radius` shorthand rules.
// - `[a]` → `[a, a, a, a]`
// - `[a, b]` → `[a, b, a, b]`
// - `[a, b, c]` → `[a, b, c, b]`
// - `[a, b, c, d, …]` → `[a, b, c, d]`
// - `[]` → `[0, 0, 0, 0]`
let values: Vec<f64> = self.iter_element_values().copied().collect();
let radii: [f64; 4] = match values.as_slice() {
[] => [0., 0., 0., 0.],
&[a] => [a, a, a, a],
&[a, b] => [a, b, a, b],
&[a, b, c] => [a, b, c, b],
&[a, b, c, d, ..] => [a, b, c, d],
};
let clamped_radius = if clamped {
// Algorithm follows the CSS spec: <https://drafts.csswg.org/css-backgrounds/#corner-overlap>
let mut scale_factor: f64 = 1.;
for i in 0..4 {
let side_length = if i % 2 == 0 { size.x } else { size.y };
let adjacent_corner_radius_sum = radii[i] + radii[(i + 1) % 4];
if side_length < adjacent_corner_radius_sum {
scale_factor = scale_factor.min(side_length / adjacent_corner_radius_sum);
}
}
radii.map(|x| x * scale_factor)
} else {
radii
};
List::new_from_element(Vector::from_subpath(subpath::Subpath::new_rounded_rectangle(size / -2., size / 2., clamped_radius)))
}
}
/// Generates a circle shape with a chosen radius.
#[node_macro::node(category("Vector: Shape"))]
fn circle(
@@ -61,10 +16,10 @@ fn circle(
_primary: (),
#[unit(" px")]
#[default(50.)]
radius: f64,
) -> List<Vector> {
let radius = radius.abs();
List::new_from_element(Vector::from_subpath(subpath::Subpath::new_ellipse(DVec2::splat(-radius), DVec2::splat(radius))))
radius: Item<f64>,
) -> Item<Vector> {
let radius = radius.element().abs();
Item::new_from_element(Vector::from_subpath(subpath::Subpath::new_ellipse(DVec2::splat(-radius), DVec2::splat(radius))))
}
/// Generates an arc shape forming a portion of a circle which may be open, closed, or a pie slice.
@@ -74,15 +29,16 @@ fn arc(
_primary: (),
#[unit(" px")]
#[default(50.)]
radius: f64,
start_angle: Angle,
radius: Item<f64>,
start_angle: Item<Angle>,
#[default(270.)]
#[range]
#[soft(0..360)]
sweep_angle: Angle,
arc_type: ArcType,
) -> List<Vector> {
List::new_from_element(Vector::from_subpath(subpath::Subpath::new_arc(
sweep_angle: Item<Angle>,
arc_type: Item<ArcType>,
) -> Item<Vector> {
let (radius, start_angle, sweep_angle, arc_type) = (*radius.element(), *start_angle.element(), *sweep_angle.element(), arc_type.into_element());
Item::new_from_element(Vector::from_subpath(subpath::Subpath::new_arc(
radius,
start_angle / 360. * std::f64::consts::TAU,
sweep_angle / 360. * std::f64::consts::TAU,
@@ -99,20 +55,27 @@ fn arc(
fn spiral(
_: impl Ctx,
_primary: (),
spiral_type: SpiralType,
#[default(5.)] turns: f64,
#[default(0.)] start_angle: f64,
#[default(0.)] inner_radius: f64,
#[default(25)] outer_radius: f64,
#[default(90.)] angular_resolution: f64,
) -> List<Vector> {
List::new_from_element(Vector::from_subpath(subpath::Subpath::new_spiral(
spiral_type: Item<SpiralType>,
#[default(5.)] turns: Item<f64>,
#[default(0.)] start_angle: Item<f64>,
#[default(0.)] inner_radius: Item<f64>,
#[default(25)] outer_radius: Item<f64>,
#[default(90.)] angular_resolution: Item<f64>,
) -> Item<Vector> {
let (turns, start_angle, inner_radius, outer_radius, angular_resolution) = (
*turns.element(),
*start_angle.element(),
*inner_radius.element(),
*outer_radius.element(),
*angular_resolution.element(),
);
Item::new_from_element(Vector::from_subpath(subpath::Subpath::new_spiral(
inner_radius,
outer_radius,
turns,
start_angle.to_radians(),
angular_resolution.to_radians(),
spiral_type,
spiral_type.into_element(),
)))
}
@@ -123,12 +86,12 @@ fn ellipse(
_primary: (),
#[unit(" px")]
#[default(50)]
radius_x: f64,
radius_x: Item<f64>,
#[unit(" px")]
#[default(25)]
radius_y: f64,
) -> List<Vector> {
let radius = DVec2::new(radius_x, radius_y);
radius_y: Item<f64>,
) -> Item<Vector> {
let radius = DVec2::new(*radius_x.element(), *radius_y.element());
let corner1 = -radius;
let corner2 = radius;
@@ -141,25 +104,57 @@ fn ellipse(
.push([HandleId::end(ellipse.segment_domain.ids()[i]), HandleId::primary(ellipse.segment_domain.ids()[(i + 1) % len])]);
}
List::new_from_element(ellipse)
Item::new_from_element(ellipse)
}
/// Generates a rectangle shape with the chosen width and height. It may also have rounded corners if desired.
#[node_macro::node(category("Vector: Shape"), properties("rectangle_properties"))]
fn rectangle<T: CornerRadius>(
fn rectangle(
_: impl Ctx,
_primary: (),
#[unit(" px")]
#[default(100)]
width: f64,
width: Item<f64>,
#[unit(" px")]
#[default(100)]
height: f64,
_individual_corner_radii: bool, // TODO: Move this to the bottom once we have a migration capability
#[implementations(f64, List<f64>)] corner_radius: T,
#[default(true)] clamped: bool,
) -> List<Vector> {
corner_radius.generate(DVec2::new(width, height), clamped)
height: Item<f64>,
corner_radius: Item<BoxCorners>,
#[default(true)] clamped: Item<bool>,
_individual_corner_radii: Item<bool>,
) -> Item<Vector> {
let size = DVec2::new(*width.element(), *height.element());
let radii = corner_radius.element().to_corner_values();
// 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.));
let mut scale_factor: f64 = 1.;
for i in 0..4 {
let side_length = if i % 2 == 0 { size.x } else { size.y };
let adjacent_corner_radius_sum = radii[i] + radii[(i + 1) % 4];
if side_length < adjacent_corner_radius_sum {
scale_factor = scale_factor.min((side_length / adjacent_corner_radius_sum).max(0.));
}
}
radii.map(|radius| radius * scale_factor)
} else {
radii
};
Item::new_from_element(Vector::from_subpath(subpath::Subpath::new_rounded_rectangle(size / -2., size / 2., radii)))
}
/// Builds a set of four corner values, such as a rectangle's corner radii, from a list of one, two, three, or four values.
#[node_macro::node(category("Vector: Shape"))]
fn box_corners(
_: impl Ctx,
/// The corner values, filling the four corners clockwise from the top-left. Give one value for all corners, two for opposite pairs, three for top-left, the two sides, then bottom-right, or four for each corner.
values: List<f64>,
) -> Item<BoxCorners> {
let values: Vec<f64> = values.iter_element_values().copied().collect();
Item::new_from_element(BoxCorners::from(values))
}
/// Generates an regular polygon shape like a triangle, square, pentagon, hexagon, heptagon, octagon, or any higher n-gon.
@@ -170,14 +165,14 @@ fn regular_polygon<T: AsU64>(
#[default(6)]
#[hard(3..)]
#[implementations(u32, u64, f64)]
sides: T,
sides: Item<T>,
#[unit(" px")]
#[default(50)]
radius: f64,
) -> List<Vector> {
let points = sides.as_u64();
let radius: f64 = radius * 2.;
List::new_from_element(Vector::from_subpath(subpath::Subpath::new_regular_polygon(DVec2::splat(-radius), points, radius)))
radius: Item<f64>,
) -> Item<Vector> {
let points = sides.element().as_u64();
let radius: f64 = *radius.element() * 2.;
Item::new_from_element(Vector::from_subpath(subpath::Subpath::new_regular_polygon(DVec2::splat(-radius), points, radius)))
}
/// Generates an n-pointed star shape with inner and outer points at chosen radii from the center.
@@ -188,19 +183,19 @@ fn star<T: AsU64>(
#[default(5)]
#[hard(2..)]
#[implementations(u32, u64, f64)]
sides: T,
sides: Item<T>,
#[unit(" px")]
#[default(50)]
radius_1: f64,
radius_1: Item<f64>,
#[unit(" px")]
#[default(25)]
radius_2: f64,
) -> List<Vector> {
let points = sides.as_u64();
let diameter: f64 = radius_1 * 2.;
let inner_diameter = radius_2 * 2.;
radius_2: Item<f64>,
) -> Item<Vector> {
let points = sides.element().as_u64();
let diameter: f64 = *radius_1.element() * 2.;
let inner_diameter = *radius_2.element() * 2.;
List::new_from_element(Vector::from_subpath(subpath::Subpath::new_star_polygon(DVec2::splat(-diameter), points, diameter, inner_diameter)))
Item::new_from_element(Vector::from_subpath(subpath::Subpath::new_star_polygon(DVec2::splat(-diameter), points, diameter, inner_diameter)))
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
@@ -226,15 +221,18 @@ fn qr_code(
_primary: (),
#[widget(ParsedWidgetOverride::Custom = "text_area")]
#[default("https://graphite.art")]
text: String,
#[widget(ParsedWidgetOverride::Hidden)] has_size: bool,
text: Item<String>,
#[widget(ParsedWidgetOverride::Hidden)] has_size: Item<bool>,
#[unit(" px")]
#[hard(1..)]
#[widget(ParsedWidgetOverride::Custom = "optional_f64")]
size: f64,
error_correction: QRCodeErrorCorrectionLevel,
#[default(false)] individual_squares: bool,
) -> List<Vector> {
size: Item<f64>,
error_correction: Item<QRCodeErrorCorrectionLevel>,
individual_squares: Item<bool>,
) -> Item<Vector> {
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());
let ecc = match error_correction {
QRCodeErrorCorrectionLevel::Low => qrcodegen::QrCodeEcc::Low,
QRCodeErrorCorrectionLevel::Medium => qrcodegen::QrCodeEcc::Medium,
@@ -242,7 +240,9 @@ fn qr_code(
QRCodeErrorCorrectionLevel::High => qrcodegen::QrCodeEcc::High,
};
let Ok(qr_code) = qrcodegen::QrCode::encode_text(&text, ecc) else { return List::default() };
let Ok(qr_code) = qrcodegen::QrCode::encode_text(&text, ecc) else {
return Item::new_from_element(Vector::default());
};
let mut vector = match individual_squares {
true => {
@@ -271,7 +271,7 @@ fn qr_code(
vector.transform(glam::DAffine2::from_scale(DVec2::splat(size / qr_code.size() as f64)));
}
List::new_from_element(vector)
Item::new_from_element(vector)
}
/// Generates an arrow from the origin to the chosen coordinate.
@@ -279,17 +279,18 @@ fn qr_code(
fn arrow(
_: impl Ctx,
_primary: (),
#[default(100., 0.)] arrow_to: PixelSize,
#[default(10)] shaft_width: PixelLength,
#[default(30)] head_width: PixelLength,
#[default(20)] head_length: PixelLength,
) -> List<Vector> {
List::new_from_element(Vector::from_subpath(subpath::Subpath::new_arrow(DVec2::ZERO, arrow_to, shaft_width, head_width, head_length)))
#[default(100., 0.)] arrow_to: Item<PixelSize>,
#[default(10)] shaft_width: Item<PixelLength>,
#[default(30)] head_width: Item<PixelLength>,
#[default(20)] head_length: Item<PixelLength>,
) -> Item<Vector> {
let (arrow_to, shaft_width, head_width, head_length) = (*arrow_to.element(), *shaft_width.element(), *head_width.element(), *head_length.element());
Item::new_from_element(Vector::from_subpath(subpath::Subpath::new_arrow(DVec2::ZERO, arrow_to, shaft_width, head_width, head_length)))
}
#[node_macro::node(category("Vector: Shape"))]
fn line(_: impl Ctx, _primary: (), #[default(100., 100.)] line_to: PixelSize) -> List<Vector> {
List::new_from_element(Vector::from_subpath(subpath::Subpath::new_line(DVec2::ZERO, line_to)))
fn line(_: impl Ctx, _primary: (), #[default(100., 100.)] line_to: Item<PixelSize>) -> Item<Vector> {
Item::new_from_element(Vector::from_subpath(subpath::Subpath::new_line(DVec2::ZERO, *line_to.element())))
}
trait GridSpacing {
@@ -311,17 +312,19 @@ impl GridSpacing for DVec2 {
fn grid<T: GridSpacing>(
_: impl Ctx,
_primary: (),
grid_type: GridType,
grid_type: Item<GridType>,
#[unit(" px")]
#[hard(0..)]
#[default(10)]
#[implementations(f64, DVec2)]
spacing: T,
#[default(10)] columns: u32,
#[default(10)] rows: u32,
#[default(30., 30.)] angles: DVec2,
) -> List<Vector> {
let (x_spacing, y_spacing) = spacing.as_dvec2().into();
spacing: Item<T>,
#[default(10)] columns: Item<u32>,
#[default(10)] rows: Item<u32>,
#[default(30., 30.)] angles: Item<DVec2>,
) -> Item<Vector> {
let (grid_type, columns, rows, angles) = (grid_type.into_element(), *columns.element(), *rows.element(), *angles.element());
let (x_spacing, y_spacing) = spacing.element().as_dvec2().into();
let (angle_a, angle_b) = angles.into();
let mut vector = Vector::default();
@@ -402,23 +405,28 @@ fn grid<T: GridSpacing>(
}
}
List::new_from_element(vector)
Item::new_from_element(vector)
}
#[cfg(test)]
mod tests {
use super::*;
fn item<T>(value: T) -> Item<T> {
Item::new_from_element(value)
}
#[test]
fn isometric_grid_test() {
// Doesn't crash with weird angles
grid((), (), GridType::Isometric, 0., 5, 5, (0., 0.).into());
grid((), (), GridType::Isometric, 90., 5, 5, (90., 90.).into());
grid((), (), item(GridType::Isometric), item(0.), item(5_u32), item(5_u32), item((0., 0.).into()));
grid((), (), item(GridType::Isometric), item(90.), item(5_u32), item(5_u32), item((90., 90.).into()));
// Works properly
let grid = grid((), (), GridType::Isometric, 10., 5, 5, (30., 30.).into());
assert_eq!(grid.element(0).unwrap().point_domain.ids().len(), 5 * 5);
assert_eq!(grid.element(0).unwrap().segment_bezier_iter().count(), 4 * 5 + 4 * 9);
for (_, bezier, _, _) in grid.element(0).unwrap().segment_bezier_iter() {
let grid = grid((), (), item(GridType::Isometric), item(10.), item(5_u32), item(5_u32), item((30., 30.).into()));
assert_eq!(grid.element().point_domain.ids().len(), 5 * 5);
assert_eq!(grid.element().segment_bezier_iter().count(), 4 * 5 + 4 * 9);
for (_, bezier, _, _) in grid.element().segment_bezier_iter() {
assert_eq!(bezier.handles, subpath::BezierHandles::Linear);
assert!(
((bezier.start - bezier.end).length() - 10.).abs() < 1e-5,
@@ -430,10 +438,10 @@ mod tests {
#[test]
fn skew_isometric_grid_test() {
let grid = grid((), (), GridType::Isometric, 10., 5, 5, (40., 30.).into());
assert_eq!(grid.element(0).unwrap().point_domain.ids().len(), 5 * 5);
assert_eq!(grid.element(0).unwrap().segment_bezier_iter().count(), 4 * 5 + 4 * 9);
for (_, bezier, _, _) in grid.element(0).unwrap().segment_bezier_iter() {
let grid = grid((), (), item(GridType::Isometric), item(10.), item(5_u32), item(5_u32), item((40., 30.).into()));
assert_eq!(grid.element().point_domain.ids().len(), 5 * 5);
assert_eq!(grid.element().segment_bezier_iter().count(), 4 * 5 + 4 * 9);
for (_, bezier, _, _) in grid.element().segment_bezier_iter() {
assert_eq!(bezier.handles, subpath::BezierHandles::Linear);
let vector = bezier.start - bezier.end;
let angle = (vector.angle_to(DVec2::X).to_degrees() + 180.) % 180.;
@@ -443,8 +451,16 @@ mod tests {
#[test]
fn qr_code_test() {
let qr = qr_code((), (), "https://graphite.art".to_string(), false, 1., QRCodeErrorCorrectionLevel::Low, true);
assert!(qr.element(0).unwrap().point_domain.ids().len() > 0);
assert!(qr.element(0).unwrap().segment_domain.ids().len() > 0);
let qr = qr_code(
(),
(),
item("https://graphite.art".to_string()),
item(false),
item(1.),
item(QRCodeErrorCorrectionLevel::Low),
item(true),
);
assert!(!qr.element().point_domain.ids().is_empty());
assert!(!qr.element().segment_domain.ids().is_empty());
}
}

View File

@@ -1,50 +1,41 @@
use core_types::list::List;
use core_types::list::{Item, List, NodeIdPath};
use core_types::transform::BakeTransform;
use core_types::uuid::NodeId;
use core_types::{ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_TRANSFORM, Ctx};
use glam::DAffine2;
use glam::{DAffine2, DVec2};
use graphic_types::Vector;
use vector_types::vector::VectorModification;
/// Applies a differential modification to a vector path, associating changes made by the Pen and Path tools to indices of edited points and segments.
#[node_macro::node(category(""))]
async fn path_modify(_ctx: impl Ctx, mut vector: List<Vector>, modification: Box<VectorModification>, node_path: List<NodeId>) -> List<Vector> {
use core_types::list::Item;
async fn path_modify(_ctx: impl Ctx, vector: Item<Vector>, modification: Item<Box<VectorModification>>, node_path: Item<NodeIdPath>) -> Item<Vector> {
let mut vector = vector;
modification.into_element().apply(vector.element_mut());
if vector.is_empty() {
vector.push(Item::default());
}
modification.apply(vector.element_mut(0).expect("push should give one item"));
// Drop stale click-target override so hit testing uses the geometry the user is now editing
vector.remove_attribute(ATTR_EDITOR_CLICK_TARGET);
// Drop the stale click-target override so hit testing uses the geometry the user is now editing
vector.remove_attribute::<Vector>(ATTR_EDITOR_CLICK_TARGET);
// Set the path to the encapsulating subgraph (drop our own trailing entry from `node_path`),
// matching the `path_of_subgraph` proto so editor tools can route data back to the parent layer.
let node_path = node_path.into_element().0;
let subgraph_path: List<NodeId> = {
let len = node_path.len();
node_path.into_iter().take(len.saturating_sub(1)).collect()
};
let existing: List<NodeId> = vector.attribute_cloned_or_default(ATTR_EDITOR_LAYER_PATH, 0);
vector.set_attribute(ATTR_EDITOR_LAYER_PATH, 0, if existing.is_empty() { subgraph_path } else { existing });
let existing = vector.attribute_cloned_or_default::<NodeIdPath>(ATTR_EDITOR_LAYER_PATH).0;
let layer_path = if existing.is_empty() { subgraph_path } else { existing };
vector.set_attribute(ATTR_EDITOR_LAYER_PATH, NodeIdPath(layer_path));
if vector.len() > 1 {
warn!("The path modify ran on {} vector items. Only the first can be modified.", vector.len());
}
vector
}
/// Applies the vector path's local transformation to its geometry and resets the transform to the identity.
/// Bakes the content's transform attribute into its underlying value, removing the attribute.
#[node_macro::node(category("Vector"))]
async fn apply_transform(_ctx: impl Ctx, mut vector: List<Vector>) -> List<Vector> {
let (elements, transforms) = vector.element_and_attribute_slices_mut::<DAffine2>(ATTR_TRANSFORM);
for (element, transform) in elements.iter_mut().zip(transforms.iter_mut()) {
for (_, point) in element.point_domain.positions_mut() {
*point = transform.transform_point2(*point);
}
element.segment_domain.transform(*transform);
*transform = DAffine2::IDENTITY;
async fn bake_transform<T: BakeTransform + 'n + Send + 'static>(_ctx: impl Ctx, #[implementations(Vector, DAffine2, DVec2)] content: Item<T>) -> Item<T> {
let mut content = content;
if let Some(transform) = content.remove_attribute::<DAffine2>(ATTR_TRANSFORM) {
content.element_mut().bake_transform(&transform);
}
vector
content
}

File diff suppressed because it is too large Load Diff