mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-10-03 01:48:11 +08:00
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:
@@ -0,0 +1,23 @@
|
||||
[package]
|
||||
name = "blending-nodes"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
description = "Blending operation nodes for Graphene"
|
||||
authors = ["Graphite Authors <contact@graphite.art>"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
[features]
|
||||
default = ["serde"]
|
||||
|
||||
[dependencies]
|
||||
# Local dependencies
|
||||
core-types = { workspace = true }
|
||||
vector-types = { workspace = true }
|
||||
graphic-types = { workspace = true }
|
||||
node-macro = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
glam = { workspace = true }
|
||||
|
||||
# Optional workspace dependencies
|
||||
serde = { workspace = true, optional = true }
|
||||
@@ -0,0 +1,64 @@
|
||||
use core_types::attribute::{Attr, BlendMode as BlendModeAttr, ClippingMask, Opacity, OpacityFill};
|
||||
use core_types::registry::types::Percentage;
|
||||
use core_types::{BlendMode, Ctx};
|
||||
|
||||
/// 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>(
|
||||
_: impl Ctx,
|
||||
/// The layer stack that will be composited when rendering.
|
||||
(element, _content_blend_mode): (T, Attr<BlendModeAttr>),
|
||||
/// The choice of equation that controls how brightness and color blends between overlapping pixels.
|
||||
blend_mode: BlendMode,
|
||||
) -> (T, Attr<BlendModeAttr>) {
|
||||
(element, Attr(blend_mode))
|
||||
}
|
||||
|
||||
/// Modifies the opacity and/or fill of the input graphics by multiplying the existing values by these percentages.
|
||||
/// 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>(
|
||||
_: impl Ctx,
|
||||
/// The layer stack that will be composited when rendering.
|
||||
(element, content_opacity, content_fill): (T, Attr<Opacity>, Attr<OpacityFill>),
|
||||
/// Whether the *Opacity* property is enabled, multiplying the existing opacity by the chosen percentage.
|
||||
#[widget(ParsedWidgetOverride::Hidden)]
|
||||
#[default(true)]
|
||||
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: Item<Percentage>,
|
||||
/// Whether the *Fill* property is enabled, multiplying the existing fill by the chosen percentage.
|
||||
#[widget(ParsedWidgetOverride::Hidden)]
|
||||
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, Attr<Opacity>, Attr<OpacityFill>) {
|
||||
let opacity = match has_opacity {
|
||||
true => *content_opacity * (opacity / 100.),
|
||||
false => *content_opacity,
|
||||
};
|
||||
let fill = match has_fill {
|
||||
true => *content_fill * (fill / 100.),
|
||||
false => *content_fill,
|
||||
};
|
||||
(element, Attr(opacity), Attr(fill))
|
||||
}
|
||||
|
||||
/// 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>(
|
||||
_: impl Ctx,
|
||||
/// The layer stack that will be composited when rendering.
|
||||
(element, _content_clip): (T, Attr<ClippingMask>),
|
||||
/// Whether the content inherits the alpha of the content beneath it.
|
||||
clip: bool,
|
||||
) -> (T, Attr<ClippingMask>) {
|
||||
(element, Attr(clip))
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
[package]
|
||||
name = "brush-nodes"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
description = "Brush rendering nodes for Graphene"
|
||||
authors = ["Graphite Authors <contact@graphite.art>"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
[features]
|
||||
default = ["serde"]
|
||||
serde = ["dep:serde", "core-types/serde", "raster-types/serde", "raster-nodes/serde"]
|
||||
|
||||
[dependencies]
|
||||
# Local dependencies
|
||||
dyn-any = { workspace = true }
|
||||
core-types = { workspace = true }
|
||||
graphene-hash = { workspace = true }
|
||||
raster-types = { workspace = true }
|
||||
raster-nodes = { workspace = true }
|
||||
node-macro = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
glam = { workspace = true }
|
||||
|
||||
# Optional workspace dependencies
|
||||
serde = { workspace = true, optional = true, features = ["derive"] }
|
||||
|
||||
[dev-dependencies]
|
||||
# Workspace dependencies
|
||||
tokio = { workspace = true }
|
||||
@@ -0,0 +1,493 @@
|
||||
use crate::brush_cache::BrushCache;
|
||||
use crate::brush_stroke::{BrushStroke, BrushStyle};
|
||||
use core_types::attribute::{Attr, BlendMode as BlendModeAttr, ClippingMask, EditorLayerPath, Opacity, OpacityFill, Transform as TransformAttr};
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use core_types::color::{Alpha, Color, Pixel, Sample};
|
||||
use core_types::extent::{LevelIn, ListIn};
|
||||
use core_types::gpoll::{Extent, GPoll, GraphError, Interrupt};
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::math::bbox::{AxisAlignedBbox, Bbox};
|
||||
use core_types::transform::Transform;
|
||||
use core_types::uuid::NodeId;
|
||||
use core_types::{ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM};
|
||||
use core_types::{Ctx, ExtractIndex, InjectIndex};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use raster_nodes::blending_nodes::blend_colors;
|
||||
use raster_nodes::std_nodes::{empty_image_core, extend_image_to_bounds_core};
|
||||
use raster_types::BitmapMut;
|
||||
use raster_types::Image;
|
||||
use raster_types::{CPU, Raster};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, dyn_any::DynAny)]
|
||||
pub struct BrushStampGenerator<P: Pixel + Alpha> {
|
||||
color: P,
|
||||
feather_exponent: f32,
|
||||
transform: DAffine2,
|
||||
}
|
||||
|
||||
impl<P: Pixel + Alpha> Transform for BrushStampGenerator<P> {
|
||||
fn transform(&self) -> DAffine2 {
|
||||
self.transform
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel + Alpha> Sample for BrushStampGenerator<P> {
|
||||
type Pixel = P;
|
||||
|
||||
#[inline]
|
||||
fn sample(&self, position: DVec2, area: DVec2) -> Option<P> {
|
||||
let position = self.transform.inverse().transform_point2(position);
|
||||
let area = self.transform.inverse().transform_vector2(area);
|
||||
let aa_blur_radius = area.length() as f32 * 2.;
|
||||
let center = DVec2::splat(0.5);
|
||||
|
||||
let distance = (position + area / 2. - center).length() as f32 * 2.;
|
||||
|
||||
let edge_opacity = 1. - (1. - aa_blur_radius).powf(self.feather_exponent);
|
||||
let result = if distance < 1. - aa_blur_radius {
|
||||
1. - distance.powf(self.feather_exponent)
|
||||
} else if distance < 1. {
|
||||
// TODO: Replace this with a proper analytical AA implementation
|
||||
edge_opacity * ((1. - distance) / aa_blur_radius)
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
|
||||
use core_types::color::Channel;
|
||||
Some(self.color.multiplied_alpha(P::AlphaChannel::from_linear(result)))
|
||||
}
|
||||
}
|
||||
|
||||
/// Controls the brush shape with diameter and hardness, plus color and opacity (via flow).
|
||||
/// The feather exponent is calculated from hardness to determine edge softness.
|
||||
/// Used internally to create the brush texture before stamping it repeatedly along a stroke path.
|
||||
#[node_macro::node(category(""), skip_impl)]
|
||||
fn brush_stamp_generator(_: impl Ctx, #[unit(" px")] diameter: f64, color: Color, hardness: f64, flow: f64) -> BrushStampGenerator<Color> {
|
||||
// Diameter
|
||||
let radius = diameter / 2.;
|
||||
|
||||
// Hardness
|
||||
let hardness = hardness / 100.;
|
||||
let feather_exponent = 1. / (1. - hardness) as f32;
|
||||
|
||||
// Flow
|
||||
let flow = flow / 100.;
|
||||
|
||||
// Color
|
||||
let color = color.apply_opacity(flow as f32);
|
||||
|
||||
let transform = DAffine2::from_scale_angle_translation(DVec2::splat(diameter), 0., -DVec2::splat(radius));
|
||||
BrushStampGenerator { color, feather_exponent, transform }
|
||||
}
|
||||
|
||||
/// 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: Fn(Color, Color) -> Color>(_: impl Ctx, mut target: List<Raster<CPU>>, texture: Raster<CPU>, positions: Vec<DVec2>, blend_mode: BlendFn) -> List<Raster<CPU>> {
|
||||
if positions.is_empty() {
|
||||
return target;
|
||||
}
|
||||
|
||||
let (elements, transforms) = target.element_and_attribute_slices_mut::<DAffine2>(ATTR_TRANSFORM);
|
||||
for (element, transform_attribute) in elements.iter_mut().zip(transforms.iter()) {
|
||||
let target_width = element.width;
|
||||
let target_height = element.height;
|
||||
let target_size = DVec2::new(target_width as f64, target_height as f64);
|
||||
|
||||
let texture_size = DVec2::new(texture.width as f64, texture.height as f64);
|
||||
|
||||
let document_to_target = DAffine2::from_translation(-texture_size / 2.) * DAffine2::from_scale(target_size) * transform_attribute.inverse();
|
||||
|
||||
for position in &positions {
|
||||
let start = document_to_target.transform_point2(*position).round();
|
||||
let stop = start + texture_size;
|
||||
|
||||
// Half-open integer ranges [start, stop).
|
||||
let clamp_start = start.clamp(DVec2::ZERO, target_size).as_uvec2();
|
||||
let clamp_stop = stop.clamp(DVec2::ZERO, target_size).as_uvec2();
|
||||
|
||||
let blit_area_offset = (clamp_start.as_dvec2() - start).as_uvec2().min(texture_size.as_uvec2());
|
||||
let blit_area_dimensions = (clamp_stop - clamp_start).min(texture_size.as_uvec2() - blit_area_offset);
|
||||
|
||||
// Tight blitting loop. Eagerly assert bounds to hopefully eliminate bounds check inside loop.
|
||||
let texture_index = |x: u32, y: u32| -> usize { (y as usize * texture.width as usize) + (x as usize) };
|
||||
let target_index = |x: u32, y: u32| -> usize { (y as usize * target_width as usize) + (x as usize) };
|
||||
|
||||
let max_y = (blit_area_offset.y + blit_area_dimensions.y).saturating_sub(1);
|
||||
let max_x = (blit_area_offset.x + blit_area_dimensions.x).saturating_sub(1);
|
||||
assert!(texture_index(max_x, max_y) < texture.data.len());
|
||||
assert!(target_index(max_x, max_y) < element.data.len());
|
||||
|
||||
for y in blit_area_offset.y..blit_area_offset.y + blit_area_dimensions.y {
|
||||
for x in blit_area_offset.x..blit_area_offset.x + blit_area_dimensions.x {
|
||||
let src_pixel = texture.data[texture_index(x, y)];
|
||||
let dst_pixel = &mut element.data_mut().data[target_index(x + clamp_start.x, y + clamp_start.y)];
|
||||
*dst_pixel = blend_mode(src_pixel, *dst_pixel);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
target
|
||||
}
|
||||
|
||||
pub 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 = {
|
||||
let mut item = Item::new_from_element(empty_image_core(transform, Color::TRANSPARENT));
|
||||
item.set_attribute(ATTR_TRANSFORM, transform);
|
||||
item
|
||||
};
|
||||
let image = blend_stamp_closure(stamp, blank_texture, |a, b| blend_colors(a, b, BlendMode::Normal, 1.));
|
||||
|
||||
image.into_element()
|
||||
}
|
||||
|
||||
pub fn blend_with_mode(background: Item<Raster<CPU>>, foreground: Item<Raster<CPU>>, blend_mode: BlendMode, opacity: f64) -> Item<Raster<CPU>> {
|
||||
let opacity = opacity as f32 / 100.;
|
||||
match std::hint::black_box(blend_mode) {
|
||||
// Normal group
|
||||
BlendMode::Normal => blend_image_closure(foreground, background, |a, b| blend_colors(a, b, BlendMode::Normal, opacity)),
|
||||
// Darken group
|
||||
BlendMode::Darken => blend_image_closure(foreground, background, |a, b| blend_colors(a, b, BlendMode::Darken, opacity)),
|
||||
BlendMode::Multiply => blend_image_closure(foreground, background, |a, b| blend_colors(a, b, BlendMode::Multiply, opacity)),
|
||||
BlendMode::ColorBurn => blend_image_closure(foreground, background, |a, b| blend_colors(a, b, BlendMode::ColorBurn, opacity)),
|
||||
BlendMode::LinearBurn => blend_image_closure(foreground, background, |a, b| blend_colors(a, b, BlendMode::LinearBurn, opacity)),
|
||||
BlendMode::DarkerColor => blend_image_closure(foreground, background, |a, b| blend_colors(a, b, BlendMode::DarkerColor, opacity)),
|
||||
// Lighten group
|
||||
BlendMode::Lighten => blend_image_closure(foreground, background, |a, b| blend_colors(a, b, BlendMode::Lighten, opacity)),
|
||||
BlendMode::Screen => blend_image_closure(foreground, background, |a, b| blend_colors(a, b, BlendMode::Screen, opacity)),
|
||||
BlendMode::ColorDodge => blend_image_closure(foreground, background, |a, b| blend_colors(a, b, BlendMode::ColorDodge, opacity)),
|
||||
BlendMode::LinearDodge => blend_image_closure(foreground, background, |a, b| blend_colors(a, b, BlendMode::LinearDodge, opacity)),
|
||||
BlendMode::LighterColor => blend_image_closure(foreground, background, |a, b| blend_colors(a, b, BlendMode::LighterColor, opacity)),
|
||||
// Contrast group
|
||||
BlendMode::Overlay => blend_image_closure(foreground, background, |a, b| blend_colors(a, b, BlendMode::Overlay, opacity)),
|
||||
BlendMode::SoftLight => blend_image_closure(foreground, background, |a, b| blend_colors(a, b, BlendMode::SoftLight, opacity)),
|
||||
BlendMode::HardLight => blend_image_closure(foreground, background, |a, b| blend_colors(a, b, BlendMode::HardLight, opacity)),
|
||||
BlendMode::VividLight => blend_image_closure(foreground, background, |a, b| blend_colors(a, b, BlendMode::VividLight, opacity)),
|
||||
BlendMode::LinearLight => blend_image_closure(foreground, background, |a, b| blend_colors(a, b, BlendMode::LinearLight, opacity)),
|
||||
BlendMode::PinLight => blend_image_closure(foreground, background, |a, b| blend_colors(a, b, BlendMode::PinLight, opacity)),
|
||||
BlendMode::HardMix => blend_image_closure(foreground, background, |a, b| blend_colors(a, b, BlendMode::HardMix, opacity)),
|
||||
// Inversion group
|
||||
BlendMode::Difference => blend_image_closure(foreground, background, |a, b| blend_colors(a, b, BlendMode::Difference, opacity)),
|
||||
BlendMode::Exclusion => blend_image_closure(foreground, background, |a, b| blend_colors(a, b, BlendMode::Exclusion, opacity)),
|
||||
BlendMode::Subtract => blend_image_closure(foreground, background, |a, b| blend_colors(a, b, BlendMode::Subtract, opacity)),
|
||||
BlendMode::Divide => blend_image_closure(foreground, background, |a, b| blend_colors(a, b, BlendMode::Divide, opacity)),
|
||||
// Component group
|
||||
BlendMode::Hue => blend_image_closure(foreground, background, |a, b| blend_colors(a, b, BlendMode::Hue, opacity)),
|
||||
BlendMode::Saturation => blend_image_closure(foreground, background, |a, b| blend_colors(a, b, BlendMode::Saturation, opacity)),
|
||||
BlendMode::Color => blend_image_closure(foreground, background, |a, b| blend_colors(a, b, BlendMode::Color, opacity)),
|
||||
BlendMode::Luminosity => blend_image_closure(foreground, background, |a, b| blend_colors(a, b, BlendMode::Luminosity, opacity)),
|
||||
// Other utility blend modes (hidden from the normal list)
|
||||
BlendMode::Erase => blend_image_closure(foreground, background, |a, b| blend_colors(a, b, BlendMode::Erase, opacity)),
|
||||
BlendMode::Restore => blend_image_closure(foreground, background, |a, b| blend_colors(a, b, BlendMode::Restore, opacity)),
|
||||
BlendMode::MultiplyAlpha => blend_image_closure(foreground, background, |a, b| blend_colors(a, b, BlendMode::MultiplyAlpha, opacity)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Lane 0 of the materialized background as the legacy item the brush core works
|
||||
/// on; an empty level starts from a blank item, as the pre-flip node did.
|
||||
fn legacy_background(background: core_types::node::List<'_, Raster<CPU>>) -> Item<Raster<CPU>> {
|
||||
if background.is_empty() {
|
||||
return Item::default();
|
||||
}
|
||||
let lane = background.lane(0);
|
||||
let mut item = Item::new_from_element(background.element_ref(0).clone());
|
||||
item.set_attribute(ATTR_TRANSFORM, lane.attr::<TransformAttr>());
|
||||
item.set_attribute(ATTR_BLEND_MODE, lane.attr::<BlendModeAttr>());
|
||||
item.set_attribute(ATTR_OPACITY, lane.attr::<Opacity>());
|
||||
item.set_attribute(ATTR_OPACITY_FILL, lane.attr::<OpacityFill>());
|
||||
item.set_attribute(ATTR_CLIPPING_MASK, lane.attr::<ClippingMask>());
|
||||
item
|
||||
}
|
||||
|
||||
/// The brushed image replaces the whole background level with one lane.
|
||||
fn brush_extent(_background: ListIn<'_, Raster<CPU>>, _trace: ListIn<'_, BrushStroke>, _level: LevelIn) -> GPoll<Extent> {
|
||||
GPoll::Final(Extent::Exactly(1))
|
||||
}
|
||||
|
||||
/// Generates the brush strokes painted with the Brush tool as a raster image.
|
||||
/// If an input image is supplied, strokes are drawn on top of it, expanding bounds as needed.
|
||||
#[node_macro::node(category("Raster"), extent(brush_extent))]
|
||||
fn brush<'e>(
|
||||
ctx: impl Ctx + ExtractArena<'e> + ExtractIndex + InjectIndex + Copy,
|
||||
/// Optional raster content that may be drawn onto.
|
||||
background: IList<Raster<CPU>>,
|
||||
/// The list of brush stroke paths drawn by the Brush tool, with each including both its coordinates and styles.
|
||||
trace: IList<BrushStroke>,
|
||||
/// Internal cache data used to accelerate rendering of the brush content.
|
||||
#[data]
|
||||
cache: BrushCache,
|
||||
) -> Result<
|
||||
IList<(
|
||||
Raster<CPU>,
|
||||
Attr<'e, TransformAttr>,
|
||||
Attr<'e, BlendModeAttr>,
|
||||
Attr<'e, Opacity>,
|
||||
Attr<'e, OpacityFill>,
|
||||
Attr<'e, ClippingMask>,
|
||||
Attr<'e, EditorLayerPath>,
|
||||
)>,
|
||||
Interrupt,
|
||||
> {
|
||||
if ctx.innermost_index() > 0 {
|
||||
return Err(GraphError::past_end().into());
|
||||
}
|
||||
// The layer path only rides through, so it is read off the source lane
|
||||
// rather than round-tripped as a legacy list attribute.
|
||||
let layer_path: Vec<NodeId> = match background.is_empty() {
|
||||
true => Vec::new(),
|
||||
false => background.lane(0).attr::<EditorLayerPath>().to_vec(),
|
||||
};
|
||||
let strokes: Vec<BrushStroke> = (0..trace.len()).map(|row| trace.element_ref(row).clone()).collect();
|
||||
let actual_image = brush_core(legacy_background(background), strokes, cache);
|
||||
|
||||
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_path = ctx
|
||||
.arena()
|
||||
.alloc(layer_path)
|
||||
.ok_or_else(|| {
|
||||
Interrupt::from(GraphError {
|
||||
kind: core_types::gpoll::ErrorKind::ArenaExhausted,
|
||||
trace: Vec::new(),
|
||||
})
|
||||
})?
|
||||
.0;
|
||||
|
||||
Ok((
|
||||
actual_image.into_element(),
|
||||
Attr(transform),
|
||||
Attr(blend_mode),
|
||||
Attr(opacity),
|
||||
Attr(fill),
|
||||
Attr(clip),
|
||||
Attr(layer_path.as_slice()),
|
||||
))
|
||||
}
|
||||
|
||||
/// The pre-flip brush body, on legacy items: one background item plus every
|
||||
/// stroke in order, returning the painted image.
|
||||
fn brush_core(list_item: Item<Raster<CPU>>, strokes: Vec<BrushStroke>, cache: &BrushCache) -> Item<Raster<CPU>> {
|
||||
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] };
|
||||
let background_bbox = AxisAlignedBbox { start, end };
|
||||
let stroke_bbox = strokes.iter().map(|s| s.bounding_box()).reduce(|a, b| a.union(&b)).unwrap_or(AxisAlignedBbox::ZERO);
|
||||
let bbox = if background_bbox.size().length() < 0.1 {
|
||||
stroke_bbox
|
||||
} else {
|
||||
stroke_bbox.union(&background_bbox)
|
||||
};
|
||||
let background_bounds = bbox.to_transform();
|
||||
|
||||
let mut draw_strokes: Vec<_> = strokes.iter().filter(|s| !matches!(s.style.blend_mode, BlendMode::Erase | BlendMode::Restore)).cloned().collect();
|
||||
|
||||
let mut brush_plan = cache.compute_brush_plan(list_item, &draw_strokes);
|
||||
|
||||
// TODO: Find a way to handle more than one item
|
||||
let mut actual_image = {
|
||||
let background = brush_plan.background;
|
||||
let transform: DAffine2 = background.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let (element, attributes) = background.into_parts();
|
||||
let (element, transform) = extend_image_to_bounds_core(element, transform, background_bounds);
|
||||
let mut item = Item::from_parts(element, attributes);
|
||||
item.set_attribute(ATTR_TRANSFORM, transform);
|
||||
item
|
||||
};
|
||||
|
||||
let final_stroke_idx = brush_plan.strokes.len().saturating_sub(1);
|
||||
for (idx, stroke) in brush_plan.strokes.into_iter().enumerate() {
|
||||
// Create brush texture.
|
||||
// TODO: apply rotation from layer to stamp for non-rotationally-symmetric brushes.
|
||||
let mut brush_texture = cache.get_cached_brush(&stroke.style);
|
||||
if brush_texture.is_none() {
|
||||
let tex = create_brush_texture(&stroke.style);
|
||||
cache.store_brush(stroke.style.clone(), tex.clone());
|
||||
brush_texture = Some(tex);
|
||||
}
|
||||
let brush_texture = brush_texture.unwrap();
|
||||
|
||||
// Compute transformation from stroke texture space into layer space, and create the stroke texture.
|
||||
let skip = if idx == 0 { brush_plan.first_stroke_point_skip } else { 0 };
|
||||
let positions: Vec<_> = stroke.compute_blit_points().into_iter().skip(skip).collect();
|
||||
let stroke_texture = if idx == 0 && positions.is_empty() {
|
||||
core::mem::take(&mut brush_plan.first_stroke_texture)
|
||||
} else {
|
||||
let mut bbox = stroke.bounding_box();
|
||||
bbox.start = bbox.start.floor();
|
||||
bbox.end = bbox.end.floor();
|
||||
let stroke_size = bbox.size() + DVec2::splat(stroke.style.diameter);
|
||||
// For numerical stability we want to place the first blit point at a stable, integer offset in layer space.
|
||||
let snap_offset = positions[0].floor() - positions[0];
|
||||
let stroke_origin_in_layer = bbox.start - snap_offset - DVec2::splat(stroke.style.diameter / 2.);
|
||||
let stroke_to_layer = DAffine2::from_translation(stroke_origin_in_layer) * DAffine2::from_scale(stroke_size);
|
||||
|
||||
let blit_target = if idx == 0 {
|
||||
let target = core::mem::take(&mut brush_plan.first_stroke_texture);
|
||||
let transform: DAffine2 = target.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let (element, attributes) = target.into_parts();
|
||||
let (element, transform) = extend_image_to_bounds_core(element, transform, stroke_to_layer);
|
||||
let mut item = Item::from_parts(element, attributes);
|
||||
item.set_attribute(ATTR_TRANSFORM, transform);
|
||||
List::new_from_item(item)
|
||||
} else {
|
||||
let mut item = Item::new_from_element(empty_image_core(stroke_to_layer, Color::TRANSPARENT));
|
||||
item.set_attribute(ATTR_TRANSFORM, stroke_to_layer);
|
||||
List::new_from_item(item)
|
||||
};
|
||||
|
||||
let list = blit(&(), blit_target, brush_texture, positions, |a, b| blend_colors(a, b, BlendMode::Normal, 1.));
|
||||
assert_eq!(list.len(), 1);
|
||||
list.into_iter().next().unwrap_or_default()
|
||||
};
|
||||
|
||||
// Cache image before doing final blend, and store final stroke texture.
|
||||
if idx == final_stroke_idx {
|
||||
cache.cache_results(core::mem::take(&mut draw_strokes), actual_image.clone(), stroke_texture.clone());
|
||||
}
|
||||
|
||||
// TODO: Is this the correct way to do opacity in blending?
|
||||
actual_image = blend_with_mode(actual_image, stroke_texture, stroke.style.blend_mode, (stroke.style.color.a() * 100.) as f64);
|
||||
}
|
||||
|
||||
let has_erase_or_restore_strokes = strokes.iter().any(|s| matches!(s.style.blend_mode, BlendMode::Erase | BlendMode::Restore));
|
||||
if has_erase_or_restore_strokes {
|
||||
let opaque_image = Image::new(bbox.size().x as u32, bbox.size().y as u32, Color::WHITE);
|
||||
let mut erase_restore_mask = Item::new_from_element(Raster::new_cpu(opaque_image)).with_attribute(ATTR_TRANSFORM, background_bounds);
|
||||
|
||||
for stroke in strokes {
|
||||
let mut brush_texture = cache.get_cached_brush(&stroke.style);
|
||||
if brush_texture.is_none() {
|
||||
let tex = create_brush_texture(&stroke.style);
|
||||
cache.store_brush(stroke.style.clone(), tex.clone());
|
||||
brush_texture = Some(tex);
|
||||
}
|
||||
let brush_texture = brush_texture.unwrap();
|
||||
let positions: Vec<_> = stroke.compute_blit_points().into_iter().collect();
|
||||
|
||||
// For mask composition: Erase subtracts alpha, Restore adds alpha, and Draw acts like Restore to allow repainting erased areas.
|
||||
let mask_blend_mode = match stroke.style.blend_mode {
|
||||
BlendMode::Erase => BlendMode::Erase,
|
||||
BlendMode::Restore => BlendMode::Restore,
|
||||
_ => BlendMode::Restore,
|
||||
};
|
||||
|
||||
erase_restore_mask = blit(&(), List::new_from_item(erase_restore_mask), brush_texture, positions, move |a, b| {
|
||||
blend_colors(a, b, mask_blend_mode, 1.)
|
||||
})
|
||||
.into_iter()
|
||||
.next()
|
||||
.unwrap_or_default();
|
||||
}
|
||||
|
||||
actual_image = blend_image_closure(erase_restore_mask, actual_image, |a, b| blend_colors(a, b, BlendMode::MultiplyAlpha, 1.));
|
||||
}
|
||||
|
||||
actual_image
|
||||
}
|
||||
|
||||
pub fn blend_image_closure(foreground: Item<Raster<CPU>>, mut background: Item<Raster<CPU>>, map_fn: impl Fn(Color, Color) -> Color) -> Item<Raster<CPU>> {
|
||||
let foreground_size = DVec2::new(foreground.element().width as f64, foreground.element().height as f64);
|
||||
let background_size = DVec2::new(background.element().width as f64, background.element().height as f64);
|
||||
|
||||
// Transforms a point from the background image to the foreground image
|
||||
let foreground_transform: DAffine2 = foreground.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let background_transform: DAffine2 = background.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let background_to_foreground = DAffine2::from_scale(foreground_size) * foreground_transform.inverse() * background_transform * DAffine2::from_scale(1. / background_size);
|
||||
|
||||
// Footprint of the foreground image (0, 0)..(1, 1) in the background image space
|
||||
let background_aabb = Bbox::unit().affine_transform(background_transform.inverse() * foreground_transform).to_axis_aligned_bbox();
|
||||
|
||||
// Clamp the foreground image to the background image
|
||||
let start = (background_aabb.start * background_size).max(DVec2::ZERO).as_uvec2();
|
||||
let end = (background_aabb.end * background_size).min(background_size).as_uvec2();
|
||||
|
||||
for y in start.y..end.y {
|
||||
for x in start.x..end.x {
|
||||
let background_point = DVec2::new(x as f64, y as f64);
|
||||
let foreground_point = background_to_foreground.transform_point2(background_point);
|
||||
|
||||
let source_pixel = foreground.element().sample(foreground_point);
|
||||
let Some(destination_pixel) = background.element_mut().data_mut().get_pixel_mut(x, y) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
*destination_pixel = map_fn(source_pixel, *destination_pixel);
|
||||
}
|
||||
}
|
||||
|
||||
background
|
||||
}
|
||||
|
||||
pub fn blend_stamp_closure(foreground: BrushStampGenerator<Color>, mut background: Item<Raster<CPU>>, map_fn: impl Fn(Color, Color) -> Color) -> Item<Raster<CPU>> {
|
||||
let background_size = DVec2::new(background.element().width as f64, background.element().height as f64);
|
||||
|
||||
// Transforms a point from the background image to the foreground image
|
||||
let background_transform: DAffine2 = background.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let background_to_foreground = background_transform * DAffine2::from_scale(1. / background_size);
|
||||
|
||||
// Footprint of the foreground image (0, 0)..(1, 1) in the background image space
|
||||
let background_aabb = Bbox::unit().affine_transform(background_transform.inverse() * foreground.transform()).to_axis_aligned_bbox();
|
||||
|
||||
// Clamp the foreground image to the background image
|
||||
let start = (background_aabb.start * background_size).max(DVec2::ZERO).as_uvec2();
|
||||
let end = (background_aabb.end * background_size).min(background_size).as_uvec2();
|
||||
|
||||
let area = background_to_foreground.transform_point2(DVec2::new(1., 1.)) - background_to_foreground.transform_point2(DVec2::ZERO);
|
||||
for y in start.y..end.y {
|
||||
for x in start.x..end.x {
|
||||
let background_point = DVec2::new(x as f64, y as f64);
|
||||
let foreground_point = background_to_foreground.transform_point2(background_point);
|
||||
|
||||
let Some(source_pixel) = foreground.sample(foreground_point, area) else { continue };
|
||||
let Some(destination_pixel) = background.element_mut().data_mut().get_pixel_mut(x, y) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
*destination_pixel = map_fn(source_pixel, *destination_pixel);
|
||||
}
|
||||
}
|
||||
|
||||
background
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
use crate::brush_stroke::BrushStroke;
|
||||
use core_types::transform::Transform;
|
||||
use glam::DAffine2;
|
||||
|
||||
#[test]
|
||||
fn test_brush_texture() {
|
||||
let size = 20.;
|
||||
let image = brush_stamp_generator(&(), size, Color::BLACK, 100., 100.);
|
||||
assert_eq!(image.transform(), DAffine2::from_scale_angle_translation(DVec2::splat(size.ceil()), 0., -DVec2::splat(size / 2.)));
|
||||
// center pixel should be BLACK
|
||||
assert_eq!(image.sample(DVec2::splat(0.), DVec2::ONE), Some(Color::BLACK));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_brush_output_size() {
|
||||
let image = brush_core(
|
||||
Item::new_from_element(Raster::new_cpu(Image::<Color>::default())),
|
||||
vec![BrushStroke {
|
||||
trace: vec![crate::brush_stroke::BrushInputSample { position: DVec2::ZERO }],
|
||||
style: BrushStyle {
|
||||
color: Color::BLACK,
|
||||
diameter: 20.,
|
||||
hardness: 20.,
|
||||
flow: 20.,
|
||||
spacing: 20.,
|
||||
blend_mode: BlendMode::Normal,
|
||||
},
|
||||
}],
|
||||
&BrushCache::default(),
|
||||
);
|
||||
assert_eq!(image.element().width, 20);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
use crate::brush_stroke::BrushStroke;
|
||||
use crate::brush_stroke::BrushStyle;
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
use core_types::graphene_hash::CacheHashWrapper;
|
||||
use core_types::list::Item;
|
||||
use raster_types::CPU;
|
||||
use raster_types::Raster;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct BrushCacheImpl {
|
||||
// The full previous input that was cached.
|
||||
prev_input: Vec<BrushStroke>,
|
||||
|
||||
// The strokes that have been fully processed and blended into the background.
|
||||
background: Item<Raster<CPU>>,
|
||||
blended_image: Item<Raster<CPU>>,
|
||||
last_stroke_texture: Item<Raster<CPU>>,
|
||||
|
||||
// A cache for brush textures.
|
||||
brush_texture_cache: HashMap<CacheHashWrapper<BrushStyle>, Raster<CPU>>,
|
||||
}
|
||||
|
||||
impl BrushCacheImpl {
|
||||
fn compute_brush_plan(&mut self, mut background: Item<Raster<CPU>>, input: &[BrushStroke]) -> BrushPlan {
|
||||
// Do background invalidation.
|
||||
if background != self.background {
|
||||
self.background = background.clone();
|
||||
return BrushPlan {
|
||||
strokes: input.to_vec(),
|
||||
background,
|
||||
..Default::default()
|
||||
};
|
||||
}
|
||||
|
||||
// Do blended_image invalidation.
|
||||
let blended_strokes = &self.prev_input[..self.prev_input.len().saturating_sub(1)];
|
||||
let num_blended_strokes = blended_strokes.len();
|
||||
if input.get(..num_blended_strokes) != Some(blended_strokes) {
|
||||
return BrushPlan {
|
||||
strokes: input.to_vec(),
|
||||
background,
|
||||
..Default::default()
|
||||
};
|
||||
}
|
||||
|
||||
// Take our previous blended image (and invalidate the cache).
|
||||
// Since we're about to replace our cache anyway, this saves a clone.
|
||||
background = std::mem::take(&mut self.blended_image);
|
||||
|
||||
// Check if the first non-blended stroke is an extension of the last one.
|
||||
// Transform is set to ZERO (not the default IDENTITY) as a sentinel to mark this item as uninitialized.
|
||||
let mut first_stroke_texture = Item::new_from_element(Raster::<CPU>::default()).with_attribute(ATTR_TRANSFORM, glam::DAffine2::ZERO);
|
||||
let mut first_stroke_point_skip = 0;
|
||||
let strokes = input[num_blended_strokes..].to_vec();
|
||||
if !strokes.is_empty() && self.prev_input.len() > num_blended_strokes {
|
||||
let last_stroke = &self.prev_input[num_blended_strokes];
|
||||
let same_style = strokes[0].style == last_stroke.style;
|
||||
let prev_points = last_stroke.compute_blit_points();
|
||||
let new_points = strokes[0].compute_blit_points();
|
||||
let is_point_prefix = new_points.get(..prev_points.len()) == Some(&prev_points);
|
||||
if same_style && is_point_prefix {
|
||||
first_stroke_texture = std::mem::take(&mut self.last_stroke_texture);
|
||||
first_stroke_point_skip = prev_points.len();
|
||||
}
|
||||
}
|
||||
|
||||
self.prev_input = Vec::new();
|
||||
BrushPlan {
|
||||
strokes,
|
||||
background,
|
||||
first_stroke_texture,
|
||||
first_stroke_point_skip,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cache_results(&mut self, input: Vec<BrushStroke>, blended_image: Item<Raster<CPU>>, last_stroke_texture: Item<Raster<CPU>>) {
|
||||
self.prev_input = input;
|
||||
self.blended_image = blended_image;
|
||||
self.last_stroke_texture = last_stroke_texture;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct BrushPlan {
|
||||
pub strokes: Vec<BrushStroke>,
|
||||
pub background: Item<Raster<CPU>>,
|
||||
pub first_stroke_texture: Item<Raster<CPU>>,
|
||||
pub first_stroke_point_skip: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct BrushCache(Arc<Mutex<BrushCacheImpl>>);
|
||||
|
||||
impl BrushCache {
|
||||
pub fn compute_brush_plan(&self, background: Item<Raster<CPU>>, input: &[BrushStroke]) -> BrushPlan {
|
||||
let mut inner = self.0.lock().unwrap();
|
||||
inner.compute_brush_plan(background, input)
|
||||
}
|
||||
|
||||
pub fn cache_results(&self, input: Vec<BrushStroke>, blended_image: Item<Raster<CPU>>, last_stroke_texture: Item<Raster<CPU>>) {
|
||||
let mut inner = self.0.lock().unwrap();
|
||||
inner.cache_results(input, blended_image, last_stroke_texture)
|
||||
}
|
||||
|
||||
pub fn get_cached_brush(&self, style: &BrushStyle) -> Option<Raster<CPU>> {
|
||||
let inner = self.0.lock().unwrap();
|
||||
inner.brush_texture_cache.get(&CacheHashWrapper(style.clone())).cloned()
|
||||
}
|
||||
|
||||
pub fn store_brush(&self, style: BrushStyle, brush: Raster<CPU>) {
|
||||
let mut inner = self.0.lock().unwrap();
|
||||
inner.brush_texture_cache.insert(CacheHashWrapper(style), brush);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
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;
|
||||
/// The style of a brush.
|
||||
#[derive(Clone, Debug, CacheHash, DynAny)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct BrushStyle {
|
||||
pub color: Color,
|
||||
pub diameter: f64,
|
||||
pub hardness: f64,
|
||||
pub flow: f64,
|
||||
pub spacing: f64, // Spacing as a fraction of the diameter.
|
||||
pub blend_mode: BlendMode,
|
||||
}
|
||||
|
||||
impl Default for BrushStyle {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
color: Color::BLACK,
|
||||
diameter: 40.,
|
||||
hardness: 50.,
|
||||
flow: 100.,
|
||||
spacing: 50., // Percentage of diameter.
|
||||
blend_mode: BlendMode::Normal,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for BrushStyle {}
|
||||
|
||||
impl PartialEq for BrushStyle {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.color == other.color
|
||||
&& self.diameter.to_bits() == other.diameter.to_bits()
|
||||
&& self.hardness.to_bits() == other.hardness.to_bits()
|
||||
&& self.flow.to_bits() == other.flow.to_bits()
|
||||
&& self.spacing.to_bits() == other.spacing.to_bits()
|
||||
&& self.blend_mode == other.blend_mode
|
||||
}
|
||||
}
|
||||
|
||||
/// A single sample of brush parameters across the brush stroke.
|
||||
#[derive(Clone, Debug, PartialEq, core_types::CacheHash, DynAny)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct BrushInputSample {
|
||||
pub position: DVec2,
|
||||
}
|
||||
|
||||
/// The parameters for a single stroke brush.
|
||||
#[derive(Clone, Debug, PartialEq, core_types::CacheHash, Default, DynAny)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct BrushStroke {
|
||||
pub style: BrushStyle,
|
||||
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.;
|
||||
self.compute_blit_points()
|
||||
.iter()
|
||||
.map(|pos| AxisAlignedBbox {
|
||||
start: *pos + DVec2::new(-radius, -radius),
|
||||
end: *pos + DVec2::new(radius, radius),
|
||||
})
|
||||
.reduce(|a, b| a.union(&b))
|
||||
.unwrap_or(AxisAlignedBbox::ZERO)
|
||||
}
|
||||
|
||||
pub fn compute_blit_points(&self) -> Vec<DVec2> {
|
||||
// We always travel in a straight line towards the next user input,
|
||||
// placing a blit point every time we travelled our spacing distance.
|
||||
let spacing_dist = self.style.spacing / 100. * self.style.diameter;
|
||||
|
||||
let Some(first_sample) = self.trace.first() else {
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
let mut cur_pos = first_sample.position;
|
||||
let mut result = vec![cur_pos];
|
||||
let mut dist_until_next_blit = spacing_dist;
|
||||
for sample in &self.trace[1..] {
|
||||
// Travel to the next sample.
|
||||
let delta = sample.position - cur_pos;
|
||||
let mut dist_left = delta.length();
|
||||
let unit_step = delta / dist_left;
|
||||
|
||||
while dist_left >= dist_until_next_blit {
|
||||
// Take a step to the next blit point.
|
||||
cur_pos += dist_until_next_blit * unit_step;
|
||||
dist_left -= dist_until_next_blit;
|
||||
|
||||
// Blit.
|
||||
result.push(cur_pos);
|
||||
dist_until_next_blit = spacing_dist;
|
||||
}
|
||||
|
||||
// Take the partial step to land at the sample.
|
||||
dist_until_next_blit -= dist_left;
|
||||
cur_pos = sample.position;
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
pub mod brush;
|
||||
mod brush_cache;
|
||||
pub mod brush_stroke;
|
||||
|
||||
pub mod migrations {
|
||||
use crate::brush_stroke::BrushStroke;
|
||||
|
||||
// TODO: Eventually remove this migration document upgrade code
|
||||
pub fn migrate_to_brush_strokes<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Vec<BrushStroke>, D::Error> {
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
struct LegacyTable {
|
||||
#[serde(alias = "instances", alias = "instance")]
|
||||
element: Vec<BrushStroke>,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum BrushStrokesFormat {
|
||||
Strokes(Vec<BrushStroke>),
|
||||
List(LegacyTable),
|
||||
}
|
||||
|
||||
Ok(match BrushStrokesFormat::deserialize(deserializer)? {
|
||||
BrushStrokesFormat::Strokes(strokes) => strokes,
|
||||
BrushStrokesFormat::List(list) => list.element,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
[package]
|
||||
name = "graphene-core"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
description = "Core utility nodes for Graphene"
|
||||
authors = ["Graphite Authors <contact@graphite.art>"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
[features]
|
||||
default = ["serde"]
|
||||
serde = ["dep:serde", "core-types/serde", "raster-types/serde", "graphic-types/serde"]
|
||||
wasm = [
|
||||
"core-types/wasm",
|
||||
"raster-types/wasm",
|
||||
"graphic-types/wasm",
|
||||
"tsify",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[dependencies]
|
||||
# Local dependencies
|
||||
core-types = { workspace = true }
|
||||
graphene-hash = { workspace = true }
|
||||
raster-types = { workspace = true }
|
||||
graphic-types = { workspace = true }
|
||||
node-macro = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
dyn-any = { workspace = true }
|
||||
glam = { workspace = true }
|
||||
log = { workspace = true }
|
||||
|
||||
# Optional workspace dependencies
|
||||
serde = { workspace = true, optional = true }
|
||||
tsify = { workspace = true, optional = true }
|
||||
wasm-bindgen = { workspace = true, optional = true }
|
||||
@@ -0,0 +1,175 @@
|
||||
use core_types::gpoll::GPoll;
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::transform::Footprint;
|
||||
use core_types::{CacheHash, Color, Context, Ctx, DeriveCtx, ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::vector_types::Gradient;
|
||||
use graphic_types::{Artboard, Graphic, Vector};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
|
||||
const DAY: f64 = 1000. * 3600. * 24.;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, dyn_any::DynAny, Default, Hash, CacheHash, node_macro::ChoiceType)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub enum RealTimeMode {
|
||||
#[label("UTC")]
|
||||
Utc,
|
||||
Year,
|
||||
Hour,
|
||||
Minute,
|
||||
#[default]
|
||||
Second,
|
||||
Millisecond,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum AnimationTimeMode {
|
||||
AnimationTime,
|
||||
FrameNumber,
|
||||
}
|
||||
|
||||
/// Produces a chosen representation of the current real time and date (in UTC) based on the system clock.
|
||||
#[node_macro::node(category("Animation"))]
|
||||
fn real_time(
|
||||
ctx: impl Ctx + ExtractRealTime,
|
||||
_primary: (),
|
||||
/// The time and date component to be produced as a number.
|
||||
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
|
||||
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.
|
||||
#[node_macro::node(category("Animation"))]
|
||||
fn animation_time(
|
||||
ctx: impl Ctx + ExtractAnimationTime,
|
||||
_primary: (),
|
||||
#[default(1)]
|
||||
#[unit("/sec")]
|
||||
rate: Item<f64>,
|
||||
) -> Item<f64> {
|
||||
Item::new_from_element(ctx.try_animation_time().unwrap_or_default() * *rate.element())
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Debug"))]
|
||||
fn quantize_real_time<T>(
|
||||
ctx: impl Ctx + ExtractRealTime + DeriveCtx,
|
||||
#[implementations(
|
||||
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>,
|
||||
)]
|
||||
value: impl Node<Context<'_>, Output = T>,
|
||||
#[default(1)]
|
||||
#[unit("sec")]
|
||||
quantum: Item<f64>,
|
||||
) -> GPoll<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;
|
||||
}
|
||||
let quantized_time = quantized_time * 1000.;
|
||||
let scope = ctx.scope().with_real_time(Some(quantized_time));
|
||||
value.eval(&ctx.with_scope(&scope))
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Debug"))]
|
||||
fn quantize_animation_time<T>(
|
||||
ctx: impl Ctx + ExtractAnimationTime + DeriveCtx,
|
||||
#[implementations(
|
||||
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>,
|
||||
)]
|
||||
value: impl Node<Context<'_>, Output = T>,
|
||||
#[default(1)]
|
||||
#[unit("sec")]
|
||||
quantum: Item<f64>,
|
||||
) -> GPoll<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;
|
||||
}
|
||||
let scope = ctx.scope().with_animation_time(Some(quantized_time));
|
||||
value.eval(&ctx.with_scope(&scope))
|
||||
}
|
||||
|
||||
/// 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) -> 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
|
||||
// #[node_macro::node(category("Animation"))]
|
||||
// fn month(ctx: impl Ctx + ExtractRealTime) -> f64 {
|
||||
// ((ctx.try_real_time().unwrap_or_default() / DAY / 365.25 % 1.) * 12.).floor()
|
||||
// }
|
||||
// #[node_macro::node(category("Animation"))]
|
||||
// fn day(ctx: impl Ctx + ExtractRealTime) -> f64 {
|
||||
// (ctx.try_real_time().unwrap_or_default() / DAY
|
||||
// }
|
||||
@@ -0,0 +1,155 @@
|
||||
use core_types::gpoll::{Extent, GPoll, GraphError, Interrupt};
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::{Color, ExtractVarArgs};
|
||||
use core_types::{Ctx, ExtractIndex, ExtractIndices, ExtractPosition};
|
||||
use glam::DVec2;
|
||||
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) -> Item<Graphic<'static>> {
|
||||
let Ok(var_arg) = ctx.vararg(0) else { return Default::default() };
|
||||
let var_arg = var_arg as &dyn std::any::Any;
|
||||
|
||||
var_arg.downcast_ref().cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Context"), path(graphene_core::vector))]
|
||||
fn read_vector(ctx: impl Ctx + ExtractVarArgs) -> Item<Vector> {
|
||||
let Ok(var_arg) = ctx.vararg(0) else { return Default::default() };
|
||||
let var_arg = var_arg as &dyn std::any::Any;
|
||||
|
||||
var_arg.downcast_ref().cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Context"), path(graphene_core::vector))]
|
||||
fn read_raster(ctx: impl Ctx + ExtractVarArgs) -> Item<Raster<CPU>> {
|
||||
let Ok(var_arg) = ctx.vararg(0) else { return Default::default() };
|
||||
let var_arg = var_arg as &dyn std::any::Any;
|
||||
|
||||
var_arg.downcast_ref().cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Context"), path(graphene_core::vector))]
|
||||
fn read_color(ctx: impl Ctx + ExtractVarArgs) -> Item<Color> {
|
||||
let Ok(var_arg) = ctx.vararg(0) else { return Default::default() };
|
||||
let var_arg = var_arg as &dyn std::any::Any;
|
||||
|
||||
var_arg.downcast_ref().cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Context"), path(graphene_core::vector))]
|
||||
fn read_gradient(ctx: impl Ctx + ExtractVarArgs) -> Item<Gradient> {
|
||||
let Ok(var_arg) = ctx.vararg(0) else { return Default::default() };
|
||||
let var_arg = var_arg as &dyn std::any::Any;
|
||||
|
||||
var_arg.downcast_ref().cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The mapped row riding as vararg 0, in the production single-item shape.
|
||||
fn vararg_list<T: 'static>(ctx: &impl ExtractVarArgs) -> Option<&List<T>> {
|
||||
let arg = ctx.vararg(0).ok()?;
|
||||
(arg as &dyn std::any::Any).downcast_ref::<List<T>>()
|
||||
}
|
||||
|
||||
/// Lanes of a leveled vararg source: one per item, none without a row,
|
||||
/// matching the legacy empty-list return.
|
||||
fn vararg_lanes<T: 'static>(ctx: &impl ExtractVarArgs, level: u8) -> GPoll<Extent> {
|
||||
match level {
|
||||
0 => GPoll::Final(Extent::Exactly(vararg_list::<T>(ctx).map_or(0, List::len))),
|
||||
_ => GPoll::Final(Extent::Exactly(1)),
|
||||
}
|
||||
}
|
||||
|
||||
fn vararg_element<T: Clone + 'static>(ctx: &(impl ExtractVarArgs + ExtractIndex)) -> Result<T, Interrupt> {
|
||||
vararg_list::<T>(ctx)
|
||||
.and_then(|list| list.element(ctx.index() as usize))
|
||||
.cloned()
|
||||
.ok_or_else(|| GraphError::new("vararg row addressed past its items").into())
|
||||
}
|
||||
|
||||
/// Rank-model vararg source: the mapped row's items as lanes, elements only.
|
||||
#[node_macro::node(category("Test"), extent_raw(read_graphic_row_extent))]
|
||||
pub fn read_graphic_row(ctx: impl Ctx + ExtractVarArgs + ExtractIndex) -> Result<IList<Graphic<'static>>, Interrupt> {
|
||||
vararg_element(ctx)
|
||||
}
|
||||
|
||||
fn read_graphic_row_extent<C: Ctx + ExtractVarArgs>(_: &ReadGraphicRowNode, ctx: &C, level: u8) -> GPoll<Extent> {
|
||||
vararg_lanes::<Graphic>(ctx, level)
|
||||
}
|
||||
|
||||
/// Rank-model vararg source: the mapped row's items as lanes, elements only.
|
||||
#[node_macro::node(category("Test"), extent_raw(read_vector_row_extent))]
|
||||
pub fn read_vector_row(ctx: impl Ctx + ExtractVarArgs + ExtractIndex) -> Result<IList<Vector>, Interrupt> {
|
||||
vararg_element(ctx)
|
||||
}
|
||||
|
||||
fn read_vector_row_extent<C: Ctx + ExtractVarArgs>(_: &ReadVectorRowNode, ctx: &C, level: u8) -> GPoll<Extent> {
|
||||
vararg_lanes::<Vector>(ctx, level)
|
||||
}
|
||||
|
||||
/// Rank-model vararg source: the mapped row's items as lanes, elements only.
|
||||
#[node_macro::node(category("Test"), extent_raw(read_raster_row_extent))]
|
||||
pub fn read_raster_row(ctx: impl Ctx + ExtractVarArgs + ExtractIndex) -> Result<IList<Raster<CPU>>, Interrupt> {
|
||||
vararg_element(ctx)
|
||||
}
|
||||
|
||||
fn read_raster_row_extent<C: Ctx + ExtractVarArgs>(_: &ReadRasterRowNode, ctx: &C, level: u8) -> GPoll<Extent> {
|
||||
vararg_lanes::<Raster<CPU>>(ctx, level)
|
||||
}
|
||||
|
||||
/// Rank-model vararg source: the mapped row's items as lanes, elements only.
|
||||
#[node_macro::node(category("Test"), extent_raw(read_color_row_extent))]
|
||||
pub fn read_color_row(ctx: impl Ctx + ExtractVarArgs + ExtractIndex) -> Result<IList<Color>, Interrupt> {
|
||||
vararg_element(ctx)
|
||||
}
|
||||
|
||||
fn read_color_row_extent<C: Ctx + ExtractVarArgs>(_: &ReadColorRowNode, ctx: &C, level: u8) -> GPoll<Extent> {
|
||||
vararg_lanes::<Color>(ctx, level)
|
||||
}
|
||||
|
||||
/// Rank-model vararg source: the mapped row's items as lanes, elements only.
|
||||
#[node_macro::node(category("Test"), extent_raw(read_gradient_row_extent))]
|
||||
pub fn read_gradient_row(ctx: impl Ctx + ExtractVarArgs + ExtractIndex) -> Result<IList<GradientStops>, Interrupt> {
|
||||
vararg_element(ctx)
|
||||
}
|
||||
|
||||
fn read_gradient_row_extent<C: Ctx + ExtractVarArgs>(_: &ReadGradientRowNode, ctx: &C, level: u8) -> GPoll<Extent> {
|
||||
vararg_lanes::<GradientStops>(ctx, level)
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Context"), path(core_types::vector))]
|
||||
fn read_position(
|
||||
ctx: impl Ctx + ExtractPosition,
|
||||
_primary: (),
|
||||
/// 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: 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.
|
||||
// TODO: (Currently automatic type conversion only works for concrete types, via the Graphene preprocessor and not the full Graphene type system.)
|
||||
/// Produces the index of the current iteration of a loop by reading from the evaluation context, which is supplied by downstream nodes such as *Repeat*.
|
||||
///
|
||||
/// Nested loops can enable 2D or higher-dimensional iteration by using the *Loop Level* parameter to read the index from outer levels of loops.
|
||||
#[node_macro::node(category("Context"), path(core_types::vector))]
|
||||
fn read_index(
|
||||
// `loop_level` is a runtime input, so no level is statically known and the
|
||||
// whole chain has to survive nullification.
|
||||
ctx: impl Ctx + ExtractIndices,
|
||||
_primary: (),
|
||||
/// 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: Item<u32>,
|
||||
) -> Item<f64> {
|
||||
let loop_level = *loop_level.element();
|
||||
// The chain's innermost entry is the consuming input's own lane from the
|
||||
// decompose-and-promote split; the loops the reader counts sit above it.
|
||||
Item::new_from_element(ctx.try_index().and_then(|mut iter| iter.nth(loop_level as usize + 1)).unwrap_or(0) as f64)
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
use core_types::context::{ContextFeatures, ContextModification, Ctx, DeriveCtx, IndexLink, nullify_index_levels};
|
||||
use core_types::gpoll::{ErrorKind, GraphError, Interrupt};
|
||||
|
||||
/// Filters out what should be unused components of the context based on the specified requirements.
|
||||
/// This node is inserted by the compiler to "zero out" unused context components.
|
||||
#[node_macro::node(category(""))]
|
||||
fn context_modification<T>(
|
||||
ctx: impl Ctx + DeriveCtx,
|
||||
/// The data to pass through, evaluated with the stripped down context.
|
||||
value: impl Node<Context<'_>, Output = T>,
|
||||
/// The parts of the context to keep when evaluating the input value. All other parts are nullified.
|
||||
modification: ContextModification,
|
||||
) -> Result<T, Interrupt> {
|
||||
let scope = ctx.scope().nullified(modification.features, Some(modification.sources()));
|
||||
let exhausted = || {
|
||||
Interrupt::from(GraphError {
|
||||
kind: ErrorKind::ArenaExhausted,
|
||||
trace: Vec::new(),
|
||||
})
|
||||
};
|
||||
let index = match modification.features.contains(ContextFeatures::INDEX) {
|
||||
true => nullify_index_levels(ctx.index_head(), modification.index_levels, scope.arena()).ok_or_else(exhausted)?,
|
||||
false => IndexLink { index: 0, outer: None },
|
||||
};
|
||||
value.eval(&ctx.nullified(modification.features, index, &scope))
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
use core_types::Ctx;
|
||||
use core_types::list::Item;
|
||||
use glam::{DAffine2, DVec2};
|
||||
|
||||
/// 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: Item<T>) -> Item<T> {
|
||||
// KEEP THIS `debug!()` - It acts as the output for the debug node itself
|
||||
log::debug!("{value:#?}");
|
||||
value
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
use core_types::list::Item;
|
||||
use core_types::{CacheHash, Ctx};
|
||||
use dyn_any::DynAny;
|
||||
use glam::{DVec2, IVec2, UVec2};
|
||||
|
||||
/// Obtains the X or Y component of a vec2.
|
||||
///
|
||||
/// 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: 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.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[widget(Radio)]
|
||||
pub enum XY {
|
||||
#[default]
|
||||
X,
|
||||
Y,
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
pub mod animation;
|
||||
pub mod context;
|
||||
pub mod context_modification;
|
||||
pub mod debug;
|
||||
pub mod extract_xy;
|
||||
pub mod memo;
|
||||
pub mod ops;
|
||||
#[cfg(test)]
|
||||
mod record;
|
||||
|
||||
// Re-export all nodes
|
||||
pub use animation::*;
|
||||
pub use context::*;
|
||||
pub use context_modification::*;
|
||||
pub use debug::*;
|
||||
pub use extract_xy::*;
|
||||
pub use memo::*;
|
||||
pub use ops::*;
|
||||
@@ -0,0 +1,697 @@
|
||||
use core_types::context::{Ctx, CtxSnapshot, DeriveCtx, ExtractAll, ModifyIndex};
|
||||
use core_types::gpoll::{Finality, GPoll};
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::record::{FrameClaim, LevelStatus, MaterializedSpan, OwnedRecord, Promotion, Served};
|
||||
use core_types::registry::cache_key;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
|
||||
/// The memo entry: the deep copies survive a persistent flush, while the span
|
||||
/// serves lanes straight out of the persistent region (generation-guarded), so
|
||||
/// a hit before the next flush allocates nothing.
|
||||
#[derive(Debug)]
|
||||
pub struct MemoLevel {
|
||||
key: u64,
|
||||
/// The persistent region the level was promoted into, resolvable only
|
||||
/// while that region's epoch is live.
|
||||
span: Option<MaterializedSpan>,
|
||||
lanes: Vec<OwnedRecord>,
|
||||
finality: Finality,
|
||||
}
|
||||
|
||||
/// Helps speed up repeated renders in a computationally-heavy part of the node graph.
|
||||
///
|
||||
/// Stores a deep copy of the last record (a scalar input) or the last whole
|
||||
/// level (a leveled input) that flowed through this node and replays it on
|
||||
/// subsequent renders if the context has not changed. The owned copies survive
|
||||
/// a persistent flush, so this is the memo for content whose recomputation is
|
||||
/// expensive. A leveled input's cache key normalizes the addressed lane away,
|
||||
/// so per-lane pulls share one materialization of the content instead of
|
||||
/// re-evaluating it per lane.
|
||||
#[node_macro::node(category("General"), path(graphene_core::memo))]
|
||||
fn memoize<'e, 'l>(
|
||||
ctx: impl Ctx + CacheHash + DeriveCtx + ExtractArena<'e> + ModifyIndex + Copy,
|
||||
#[data] cache: Arc<Mutex<Option<MemoLevel>>>,
|
||||
content: impl Node<Context<'_>>,
|
||||
slot: FrameClaim<'e, 'l>,
|
||||
) -> GPoll<Served<'e>> {
|
||||
// A scalar input's value may depend on the consuming lane (index readers),
|
||||
// so only a leveled input, whose level covers every lane by construction,
|
||||
// keys with the lane normalized away.
|
||||
let leveled = content.layout().depth > 0;
|
||||
let lane = match leveled {
|
||||
true => ctx.index() as usize,
|
||||
false => 0,
|
||||
};
|
||||
let key = match leveled {
|
||||
true => {
|
||||
let mut keyed = *ctx;
|
||||
keyed.set_index(0);
|
||||
cache_key(&keyed)
|
||||
}
|
||||
false => cache_key(&ctx),
|
||||
};
|
||||
let mut slot = slot;
|
||||
let promotion = Promotion::new(ctx.arena(), slot.frames().bounds(), ctx.scope().persistent());
|
||||
let persistent = ctx.scope().persistent();
|
||||
let finalized = |value: Served<'e>, finality: &Finality| match finality {
|
||||
Finality::AllFinal => GPoll::Final(value),
|
||||
Finality::Partial => GPoll::Partial(value),
|
||||
};
|
||||
// The claim is this node's output frame: a hit fills it from the cached
|
||||
// bytes, and every valueless exit drops it with the frame still claimed.
|
||||
let serve = |entry: &MemoLevel, mut slot: FrameClaim<'e, 'l>| {
|
||||
if lane >= entry.lanes.len() {
|
||||
// The cached level ends here; the past-end signal serves drains.
|
||||
return GPoll::Error(Box::new(core_types::gpoll::GraphError::past_end()));
|
||||
}
|
||||
if let Some(span) = entry.span
|
||||
&& let Some(src) = span.lane(persistent, lane, content.layout())
|
||||
{
|
||||
// SAFETY: the span resolved in generation, so the lane is live and
|
||||
// immutable at the layout it was promoted under.
|
||||
unsafe { slot.fill_copy(src) };
|
||||
// SAFETY: the copy images a complete record of this layout.
|
||||
return finalized(unsafe { slot.finish_served() }, &entry.finality);
|
||||
}
|
||||
match entry.lanes[lane].replay_into(&mut slot, ctx.arena()) {
|
||||
// SAFETY: the replay completes the record in the frame.
|
||||
Some(()) => finalized(unsafe { slot.finish_served() }, &entry.finality),
|
||||
None => GPoll::arena_exhausted(),
|
||||
}
|
||||
};
|
||||
if let Some(entry) = cache.lock().unwrap().as_ref()
|
||||
&& entry.key == key
|
||||
{
|
||||
return serve(entry, slot);
|
||||
}
|
||||
if leveled {
|
||||
return match content.materialize_level(ctx, ctx.arena()) {
|
||||
LevelStatus::Batch(batch, finality) => {
|
||||
let layout = content.layout();
|
||||
// SAFETY: the batch came from this input, so it carries the input's layout.
|
||||
let lanes: Vec<OwnedRecord> = (0..batch.len()).map(|index| unsafe { OwnedRecord::copy_out(layout, batch.get(index).rec()) }).collect();
|
||||
let entry = MemoLevel {
|
||||
key,
|
||||
// SAFETY: as above.
|
||||
span: unsafe { MaterializedSpan::to_persistent(&batch, &promotion) },
|
||||
lanes,
|
||||
finality,
|
||||
};
|
||||
let result = serve(&entry, slot);
|
||||
*cache.lock().unwrap() = Some(entry);
|
||||
result
|
||||
}
|
||||
LevelStatus::Pending => GPoll::Pending,
|
||||
LevelStatus::Error(error) => GPoll::Error(Box::new(error)),
|
||||
};
|
||||
}
|
||||
// The output layout is the content's, so the claim is the content's frame.
|
||||
let result = content.serve(ctx, slot);
|
||||
let publishable = match &result {
|
||||
GPoll::Final(served) => Some((served.record(), Finality::AllFinal)),
|
||||
GPoll::Partial(served) => Some((served.record(), Finality::Partial)),
|
||||
GPoll::Pending | GPoll::Fallback(_) | GPoll::Error(_) => None,
|
||||
};
|
||||
if let Some((value, finality)) = publishable {
|
||||
let layout = content.layout();
|
||||
// SAFETY: the value came from this input, so it carries the input's
|
||||
// layout, and one record of it is a batch of one lane.
|
||||
let batch = unsafe { core_types::node::RecordBatch::new(layout.rec(value).ptr(), 1, layout) };
|
||||
// SAFETY: as above.
|
||||
let copy = unsafe { OwnedRecord::copy_out(layout, layout.rec(value)) };
|
||||
*cache.lock().unwrap() = Some(MemoLevel {
|
||||
key,
|
||||
// SAFETY: as above.
|
||||
span: unsafe { MaterializedSpan::to_persistent(&batch, &promotion) },
|
||||
lanes: vec![copy],
|
||||
finality,
|
||||
});
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// The span memo's entry: the span resolves only while the persistent epoch
|
||||
/// that published it is live, so a flush costs a re-publish and nothing else.
|
||||
#[derive(Debug)]
|
||||
pub struct SpanLevel {
|
||||
key: u64,
|
||||
span: MaterializedSpan,
|
||||
finality: Finality,
|
||||
}
|
||||
|
||||
/// The cheap memo the compiler inserts at context boundaries: a published
|
||||
/// level lives in the persistent region and serves cross-evaluation hits by
|
||||
/// byte copy until the next flush, which costs a re-publish rather than a deep
|
||||
/// copy.
|
||||
#[node_macro::node(category(""), path(graphene_core::memo))]
|
||||
fn frame_memo<'e, 'l>(
|
||||
ctx: impl Ctx + CacheHash + DeriveCtx + ExtractArena<'e> + ModifyIndex + Copy,
|
||||
#[data] cache: Arc<Mutex<Option<SpanLevel>>>,
|
||||
content: impl Node<Context<'_>>,
|
||||
slot: FrameClaim<'e, 'l>,
|
||||
) -> GPoll<Served<'e>> {
|
||||
// A scalar input's value may depend on the consuming lane (index readers),
|
||||
// so only a leveled input, whose level covers every lane by construction,
|
||||
// keys with the lane normalized away.
|
||||
let leveled = content.layout().depth > 0;
|
||||
let lane = match leveled {
|
||||
true => ctx.index() as usize,
|
||||
false => 0,
|
||||
};
|
||||
let key = match leveled {
|
||||
true => {
|
||||
let mut keyed = *ctx;
|
||||
keyed.set_index(0);
|
||||
cache_key(&keyed)
|
||||
}
|
||||
false => cache_key(&ctx),
|
||||
};
|
||||
let mut slot = slot;
|
||||
let promotion = Promotion::new(ctx.arena(), slot.frames().bounds(), ctx.scope().persistent());
|
||||
let persistent = ctx.scope().persistent();
|
||||
let finalized = |value: Served<'e>, finality: Finality| match finality {
|
||||
Finality::AllFinal => GPoll::Final(value),
|
||||
Finality::Partial => GPoll::Partial(value),
|
||||
};
|
||||
// The claim is this node's output frame: a hit fills it from the published
|
||||
// bytes, and every valueless exit drops it with the frame still claimed.
|
||||
let serve = |src: *const u8, finality: Finality, mut slot: FrameClaim<'e, 'l>| {
|
||||
// SAFETY: the source images a complete record of this layout, and the
|
||||
// span resolved in generation, so its parked payloads are live.
|
||||
unsafe { slot.fill_copy(src) };
|
||||
// SAFETY: the copy images a complete record of this layout.
|
||||
finalized(unsafe { slot.finish_served() }, finality)
|
||||
};
|
||||
let past_end = || GPoll::Error(Box::new(core_types::gpoll::GraphError::past_end()));
|
||||
let entry = cache.lock().unwrap().as_ref().filter(|entry| entry.key == key).map(|entry| (entry.span, entry.finality));
|
||||
// A span that no longer resolves was flushed.
|
||||
if let Some((span, finality)) = entry
|
||||
&& let Some(published) = span.batch(persistent, content.layout())
|
||||
{
|
||||
if lane >= published.len() {
|
||||
// The cached level ends here; the past-end signal serves drains.
|
||||
return past_end();
|
||||
}
|
||||
return serve(published.get(lane).rec().ptr(), finality, slot);
|
||||
}
|
||||
if leveled {
|
||||
return match content.materialize_level(ctx, ctx.arena()) {
|
||||
LevelStatus::Batch(batch, finality) => {
|
||||
// SAFETY: the batch came from this input, so it carries the input's layout.
|
||||
let span = unsafe { MaterializedSpan::to_persistent(&batch, &promotion) };
|
||||
*cache.lock().unwrap() = span.map(|span| SpanLevel { key, span, finality });
|
||||
match lane < batch.len() {
|
||||
// The publishing evaluation reads the resident batch, not the copy.
|
||||
true => serve(batch.get(lane).rec().ptr(), finality, slot),
|
||||
false => past_end(),
|
||||
}
|
||||
}
|
||||
LevelStatus::Pending => GPoll::Pending,
|
||||
LevelStatus::Error(error) => GPoll::Error(Box::new(error)),
|
||||
};
|
||||
}
|
||||
// The output layout is the content's, so the claim is the content's frame.
|
||||
let result = content.serve(ctx, slot);
|
||||
let publishable = match &result {
|
||||
GPoll::Final(served) => Some((served.record(), Finality::AllFinal)),
|
||||
GPoll::Partial(served) => Some((served.record(), Finality::Partial)),
|
||||
GPoll::Pending | GPoll::Fallback(_) | GPoll::Error(_) => None,
|
||||
};
|
||||
if let Some((value, finality)) = publishable {
|
||||
let layout = content.layout();
|
||||
// SAFETY: the value came from this input, so it carries the input's
|
||||
// layout, and one record of it is a batch of one lane.
|
||||
let batch = unsafe { core_types::node::RecordBatch::new(layout.rec(value).ptr(), 1, layout) };
|
||||
// SAFETY: as above.
|
||||
let span = unsafe { MaterializedSpan::to_persistent(&batch, &promotion) };
|
||||
*cache.lock().unwrap() = span.map(|span| SpanLevel { key, span, finality });
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
type MonitorValue = Arc<Mutex<Option<CtxSnapshot>>>;
|
||||
|
||||
/// The Monitor node is used by the editor to access the data flowing through
|
||||
/// it. It stores only the evaluation context: the output is pure over
|
||||
/// (context, source generations), so introspection recreates it by
|
||||
/// re-evaluating this input with the rehydrated snapshot.
|
||||
#[node_macro::node(category(""), path(graphene_core::memo), serialize(serialize_monitor), properties("monitor_properties"))]
|
||||
fn monitor<'e, 'l>(
|
||||
ctx: impl Ctx + DeriveCtx + ExtractAll + ExtractArena<'e> + ModifyIndex + Copy,
|
||||
#[data] io: MonitorValue,
|
||||
content: impl Node<Context<'_>>,
|
||||
slot: FrameClaim<'e, 'l>,
|
||||
) -> GPoll<Served<'e>> {
|
||||
if ctx.index() == 0 {
|
||||
*io.lock().unwrap() = Some(CtxSnapshot::capture(ctx));
|
||||
}
|
||||
content.serve(ctx, slot)
|
||||
}
|
||||
|
||||
fn serialize_monitor(io: &MonitorValue) -> Option<Arc<dyn std::any::Any + Send + Sync>> {
|
||||
let io = io.lock().unwrap();
|
||||
io.as_ref().map(|snapshot| Arc::new(snapshot.clone()) as Arc<dyn std::any::Any + Send + Sync>)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use core_types::SourceId;
|
||||
use core_types::arena::Arena;
|
||||
use core_types::context::{ContextImpl, EvalScope};
|
||||
use core_types::node::Node;
|
||||
use core_types::record::LiftedSource;
|
||||
use core_types::registry::{SourceHandle, ErasedRecordNode};
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
|
||||
fn lifted<T: Clone + Send + Sync + core_types::StaticTypeSized>(value: T) -> LiftedSource<T, impl for<'c> Fn(&ContextImpl<'c>) -> GPoll<T>>
|
||||
where
|
||||
T::Static: Clone + Send + Sync,
|
||||
{
|
||||
LiftedSource::new(move |_: &ContextImpl<'_>| GPoll::Final(value.clone()))
|
||||
}
|
||||
|
||||
fn counting() -> LiftedSource<u32, impl for<'c> Fn(&ContextImpl<'c>) -> GPoll<u32>> {
|
||||
let count = AtomicU32::new(0);
|
||||
LiftedSource::new(move |_: &ContextImpl<'_>| GPoll::Final(count.fetch_add(1, Ordering::Relaxed) + 1))
|
||||
}
|
||||
|
||||
fn partial_counting() -> LiftedSource<u32, impl for<'c> Fn(&ContextImpl<'c>) -> GPoll<u32>> {
|
||||
let count = AtomicU32::new(0);
|
||||
LiftedSource::new(move |_: &ContextImpl<'_>| GPoll::Partial(count.fetch_add(1, Ordering::Relaxed) + 1))
|
||||
}
|
||||
|
||||
fn scope_fixture<'a>(generations: &'a [(SourceId, u64)], arena: &'a Arena) -> EvalScope<'a> {
|
||||
EvalScope::new(Some(0.5), None, None, generations, arena)
|
||||
}
|
||||
|
||||
fn element_layout<T: Clone + Send + Sync + core_types::StaticTypeSized>() -> core_types::record::Layout
|
||||
where
|
||||
T::Static: Clone + Send + Sync,
|
||||
{
|
||||
core_types::record::Layout::default().with_writes(0, core_types::record::element_write::<T>(), &[])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn monitor_serialize_recreates_the_value_from_its_snapshot() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let layout = element_layout::<u32>();
|
||||
let monitor = MonitorNode::new(lifted::<u32>(11u32), &layout);
|
||||
let handle = SourceHandle::new_record::<u32>(Arc::new(monitor) as Arc<ErasedRecordNode>);
|
||||
assert!(handle.serialize().is_none(), "no snapshot before the first eval");
|
||||
|
||||
let edge = handle.duplicate().downcast_record::<u32>().unwrap();
|
||||
let GPoll::Final(_) = core_types::record::serve_input(&edge, &ctx, &frames) else {
|
||||
panic!("expected a final record");
|
||||
};
|
||||
|
||||
let io = handle.serialize().expect("the eval landed a snapshot");
|
||||
let snapshot = io.downcast_ref::<CtxSnapshot>().expect("the monitor serializes its context snapshot");
|
||||
let ctx = snapshot.rehydrate(&scope).expect("the arena holds the chains");
|
||||
let GPoll::Final(served) = core_types::record::capture(&edge, &ctx, &frames) else {
|
||||
panic!("expected a final record");
|
||||
};
|
||||
assert_eq!(served.element::<u32>(), 11);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_leveled_monitor_recreates_the_whole_extent() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(1 << 12).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let source = core_types::value::LeveledValueSource::new(vec![10u32, 20, 30]);
|
||||
let layout = Node::<ContextImpl>::layout(&source).clone();
|
||||
let monitor = MonitorNode::new(source, &layout);
|
||||
let handle = SourceHandle::new_record::<u32>(Arc::new(monitor) as Arc<ErasedRecordNode>);
|
||||
|
||||
let edge = handle.duplicate().downcast_record::<u32>().unwrap();
|
||||
let GPoll::Final(_) = core_types::record::serve_input(&edge, &ctx, &frames) else {
|
||||
panic!("expected a final record");
|
||||
};
|
||||
|
||||
let io = handle.serialize().expect("the eval landed a snapshot");
|
||||
let snapshot = io.downcast_ref::<CtxSnapshot>().expect("the monitor serializes its context snapshot");
|
||||
let ctx = snapshot.rehydrate(&scope).expect("the arena holds the chains");
|
||||
let LevelStatus::Batch(batch, _) = core_types::record::materialize_level(&edge, &ctx, &arena, &frames) else {
|
||||
panic!("expected a materialized level");
|
||||
};
|
||||
assert_eq!(batch.len(), 3, "the recreation holds the whole extent, not the addressed lane");
|
||||
let lanes = unsafe { core_types::node::List::<u32>::new(batch) };
|
||||
let values: Vec<u32> = (0..lanes.len()).map(|lane| *lanes.element_ref(lane)).collect();
|
||||
assert_eq!(values, vec![10, 20, 30]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memo_copy_out_consults_the_deep_element_clone() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
#[derive(Clone, Debug, PartialEq, dyn_any::DynAny)]
|
||||
struct Payload(String, u32);
|
||||
unsafe fn deep(ptr: *const u8) -> Box<dyn std::any::Any + Send + Sync> {
|
||||
let value = unsafe { core_types::record::borrow_element::<Payload>(core_types::record::Rec::new(ptr)) };
|
||||
Box::new(Payload(value.0.clone(), value.1 + 1))
|
||||
}
|
||||
unsafe fn deep_repark(value: &(dyn std::any::Any + Send + Sync), dst: *mut u8, arena: &Arena) -> Option<()> {
|
||||
let value = value.downcast_ref::<Payload>().expect("an element replays at its own type");
|
||||
unsafe { core_types::record::write_element(dst, Payload(value.0.clone(), value.1 + 1), arena) }
|
||||
}
|
||||
core_types::record::register_deep_element_clone::<Payload>(deep, deep_repark);
|
||||
|
||||
let arena = Arena::new(4096).unwrap();
|
||||
let persistent = Arena::new(4096).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena).with_persistent(&persistent);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let layout = element_layout::<Payload>();
|
||||
let memoized = MemoizeNode::new(lifted::<Payload>(Payload("deep".to_string(), 0)), &layout);
|
||||
let memoized = core_types::record::RecordExtract::<Payload, _>::new(memoized, &layout);
|
||||
|
||||
assert_eq!(memoized.eval(&ctx, &frames), GPoll::Final(Payload("deep".to_string(), 0)), "the miss serves the live value");
|
||||
assert_eq!(
|
||||
memoized.eval(&ctx, &frames),
|
||||
GPoll::Final(Payload("deep".to_string(), 2)),
|
||||
"promoting across regions runs both halves of the deep glue"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_promote_within_one_region_shares_instead_of_cloning() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
#[derive(Clone, Debug, PartialEq, dyn_any::DynAny)]
|
||||
struct Shared(String, u32);
|
||||
unsafe fn deep(ptr: *const u8) -> Box<dyn std::any::Any + Send + Sync> {
|
||||
let value = unsafe { core_types::record::borrow_element::<Shared>(core_types::record::Rec::new(ptr)) };
|
||||
Box::new(Shared(value.0.clone(), value.1 + 1))
|
||||
}
|
||||
unsafe fn deep_repark(value: &(dyn std::any::Any + Send + Sync), dst: *mut u8, arena: &Arena) -> Option<()> {
|
||||
let value = value.downcast_ref::<Shared>().expect("an element replays at its own type");
|
||||
unsafe { core_types::record::write_element(dst, Shared(value.0.clone(), value.1 + 1), arena) }
|
||||
}
|
||||
core_types::record::register_deep_element_clone::<Shared>(deep, deep_repark);
|
||||
|
||||
let arena = Arena::new(4096).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let layout = element_layout::<Shared>();
|
||||
let memoized = MemoizeNode::new(lifted::<Shared>(Shared("shared".to_string(), 0)), &layout);
|
||||
let memoized = core_types::record::RecordExtract::<Shared, _>::new(memoized, &layout);
|
||||
|
||||
assert_eq!(memoized.eval(&ctx, &frames), GPoll::Final(Shared("shared".to_string(), 0)), "the miss serves the live value");
|
||||
assert_eq!(
|
||||
memoized.eval(&ctx, &frames),
|
||||
GPoll::Final(Shared("shared".to_string(), 0)),
|
||||
"a payload already living as long as the span is shared, so no glue runs"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memoize_caches_across_evals() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let layout = element_layout::<u32>();
|
||||
let memoized = MemoizeNode::new(counting(), &layout);
|
||||
let memoized = core_types::record::RecordExtract::<u32, _>::new(memoized, &layout);
|
||||
|
||||
assert_eq!(memoized.eval(&ctx, &frames), GPoll::Final(1));
|
||||
assert_eq!(memoized.eval(&ctx, &frames), GPoll::Final(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memo_invalidates_on_generation_bump() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let source: SourceId = 7;
|
||||
let before = [(source, 1)];
|
||||
let after = [(source, 2)];
|
||||
let scope_before = scope_fixture(&before, &arena);
|
||||
let scope_after = scope_fixture(&after, &arena);
|
||||
|
||||
let layout = element_layout::<u32>();
|
||||
let memoized = MemoizeNode::new(counting(), &layout);
|
||||
let memoized = core_types::record::RecordExtract::<u32, _>::new(memoized, &layout);
|
||||
|
||||
assert_eq!(memoized.eval(&ContextImpl::root(&scope_before), &frames), GPoll::Final(1));
|
||||
assert_eq!(memoized.eval(&ContextImpl::root(&scope_before), &frames), GPoll::Final(1));
|
||||
assert_eq!(memoized.eval(&ContextImpl::root(&scope_after), &frames), GPoll::Final(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memo_replays_partiality_on_hit() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let layout = element_layout::<u32>();
|
||||
let memoized = MemoizeNode::new(partial_counting(), &layout);
|
||||
let memoized = core_types::record::RecordExtract::<u32, _>::new(memoized, &layout);
|
||||
|
||||
assert_eq!(memoized.eval(&ctx, &frames), GPoll::Partial(1));
|
||||
assert_eq!(memoized.eval(&ctx, &frames), GPoll::Partial(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memoized_edges_stack_and_rewire() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let layout = element_layout::<u32>();
|
||||
let edge = SourceHandle::new_record::<u32>(Arc::new(counting()) as Arc<ErasedRecordNode>);
|
||||
let memoized = SourceHandle::new_record::<u32>(Arc::new(MemoizeNode::new(edge.downcast_record::<u32>().unwrap(), &layout)) as Arc<ErasedRecordNode>);
|
||||
let stacked = MemoizeNode::new(memoized.downcast_record::<u32>().unwrap(), &layout);
|
||||
let stacked = core_types::record::RecordExtract::<u32, _>::new(stacked, &layout);
|
||||
|
||||
assert_eq!(stacked.eval(&ctx, &frames), GPoll::Final(1));
|
||||
assert_eq!(stacked.eval(&ctx, &frames), GPoll::Final(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cross_evaluation_hit_serves_the_promoted_payload() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let mut arena = Arena::new(4096).unwrap();
|
||||
let persistent = Arena::new(4096).unwrap();
|
||||
let generations = [];
|
||||
|
||||
let layout = element_layout::<String>();
|
||||
let memo = MemoizeNode::new(lifted::<String>("promoted".to_string()), &layout);
|
||||
let served_at = |arena: &Arena| {
|
||||
let scope = scope_fixture(&generations, arena).with_persistent(&persistent);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
let GPoll::Final(value) = core_types::record::serve_input(&memo, &ctx, &frames) else {
|
||||
panic!("the memo must serve a final record");
|
||||
};
|
||||
let element: &String = unsafe { core_types::record::borrow_element(layout.rec(&value)) };
|
||||
assert_eq!(element, "promoted");
|
||||
std::ptr::from_ref(element)
|
||||
};
|
||||
|
||||
served_at(&arena);
|
||||
let first = served_at(&arena);
|
||||
arena.reset();
|
||||
let second = served_at(&arena);
|
||||
assert_eq!(first, second, "a hit copies the promoted bytes rather than re-parking the payload");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flush_invalidates_every_span_memo_entry() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(4096).unwrap();
|
||||
let mut persistent = Arena::new(4096).unwrap();
|
||||
let generations = [];
|
||||
|
||||
let layout = element_layout::<u32>();
|
||||
let memoized = FrameMemoNode::new(counting(), &layout);
|
||||
let memoized = core_types::record::RecordExtract::<u32, _>::new(memoized, &layout);
|
||||
let eval = |persistent: &Arena| {
|
||||
let scope = scope_fixture(&generations, &arena).with_persistent(persistent);
|
||||
memoized.eval(&ContextImpl::root(&scope), &frames)
|
||||
};
|
||||
|
||||
assert_eq!(eval(&persistent), GPoll::Final(1));
|
||||
assert_eq!(eval(&persistent), GPoll::Final(1), "the published level serves the hit");
|
||||
persistent.reset();
|
||||
assert_eq!(eval(&persistent), GPoll::Final(2), "the flush invalidates the span");
|
||||
assert_eq!(eval(&persistent), GPoll::Final(2), "the miss re-published the level");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_owned_tier_survives_a_flush_without_recomputing() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(4096).unwrap();
|
||||
let mut persistent = Arena::new(4096).unwrap();
|
||||
let generations = [];
|
||||
|
||||
let layout = element_layout::<u32>();
|
||||
let memoized = MemoizeNode::new(counting(), &layout);
|
||||
let memoized = core_types::record::RecordExtract::<u32, _>::new(memoized, &layout);
|
||||
let eval = |persistent: &Arena, generations: &[(SourceId, u64)]| {
|
||||
let scope = scope_fixture(generations, &arena).with_persistent(persistent);
|
||||
memoized.eval(&ContextImpl::root(&scope), &frames)
|
||||
};
|
||||
|
||||
assert_eq!(eval(&persistent, &generations), GPoll::Final(1));
|
||||
assert_eq!(eval(&persistent, &generations), GPoll::Final(1), "the promoted level serves the hit");
|
||||
persistent.reset();
|
||||
assert_eq!(eval(&persistent, &generations), GPoll::Final(1), "the owned copies replay across the flush");
|
||||
let bumped = [(7 as SourceId, 3)];
|
||||
assert_eq!(eval(&persistent, &bumped), GPoll::Final(2), "only a key change recomputes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_span_never_resolves_against_another_region() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(4096).unwrap();
|
||||
let promoted = Arena::new(4096).unwrap();
|
||||
let foreign = Arena::new(4096).unwrap();
|
||||
let generations = [];
|
||||
|
||||
let layout = element_layout::<u32>();
|
||||
let memoized = FrameMemoNode::new(counting(), &layout);
|
||||
let memoized = core_types::record::RecordExtract::<u32, _>::new(memoized, &layout);
|
||||
let eval = |persistent: &Arena| {
|
||||
let scope = scope_fixture(&generations, &arena).with_persistent(persistent);
|
||||
memoized.eval(&ContextImpl::root(&scope), &frames)
|
||||
};
|
||||
|
||||
assert_eq!(eval(&promoted), GPoll::Final(1));
|
||||
assert_eq!(eval(&promoted), GPoll::Final(1));
|
||||
assert_eq!(eval(&foreign), GPoll::Final(2), "a stale or foreign span misses like an absent one");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refused_promote_recomputes_and_marks_the_region() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(4096).unwrap();
|
||||
let persistent = Arena::new(0).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena).with_persistent(&persistent);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let layout = element_layout::<u32>();
|
||||
let memoized = FrameMemoNode::new(counting(), &layout);
|
||||
let memoized = core_types::record::RecordExtract::<u32, _>::new(memoized, &layout);
|
||||
|
||||
assert_eq!(memoized.eval(&ctx, &frames), GPoll::Final(1));
|
||||
assert_eq!(memoized.eval(&ctx, &frames), GPoll::Final(2), "an unpublished level recomputes");
|
||||
assert!(persistent.exhausted(), "the refused promote marks the region for a flush");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refused_promote_leaves_the_owned_tier_serving() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(4096).unwrap();
|
||||
let persistent = Arena::new(0).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena).with_persistent(&persistent);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let layout = element_layout::<u32>();
|
||||
let memoized = MemoizeNode::new(counting(), &layout);
|
||||
let memoized = core_types::record::RecordExtract::<u32, _>::new(memoized, &layout);
|
||||
|
||||
assert_eq!(memoized.eval(&ctx, &frames), GPoll::Final(1));
|
||||
assert_eq!(memoized.eval(&ctx, &frames), GPoll::Final(1), "the owned tier answers where the promote was refused");
|
||||
assert!(persistent.exhausted(), "the refused promote marks the region for a flush");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_leveled_memo_signals_past_end_beyond_the_level() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(1 << 12).unwrap();
|
||||
let persistent = Arena::new(1 << 12).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena).with_persistent(&persistent);
|
||||
|
||||
let source = core_types::value::LeveledValueSource::new(vec![10u32, 20, 30]);
|
||||
let layout = Node::<ContextImpl>::layout(&source).clone();
|
||||
let memo = MemoizeNode::new(source, &layout);
|
||||
let at = |lane: u64| {
|
||||
let mut ctx = ContextImpl::root(&scope);
|
||||
core_types::context::InjectIndex::set_index(&mut ctx, lane);
|
||||
core_types::record::serve_input(&memo, &ctx, &frames)
|
||||
};
|
||||
|
||||
let GPoll::Final(value) = at(1) else {
|
||||
panic!("the level covers lane 1");
|
||||
};
|
||||
assert_eq!(unsafe { core_types::record::read_element::<u32>(layout.rec(&value)) }, 20);
|
||||
let GPoll::Error(error) = at(3) else {
|
||||
panic!("lane 3 is past the level");
|
||||
};
|
||||
assert_eq!(error.kind, core_types::gpoll::ErrorKind::PastEnd);
|
||||
let GPoll::Error(error) = at(3) else {
|
||||
panic!("the cached level answers the drain the same way");
|
||||
};
|
||||
assert_eq!(error.kind, core_types::gpoll::ErrorKind::PastEnd);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frame_memo_shares_one_record_copy_per_frame() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(4096).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let layout = element_layout::<String>();
|
||||
let memo = FrameMemoNode::new(lifted::<String>("lent out".to_string()), &layout);
|
||||
|
||||
let GPoll::Final(first) = core_types::record::serve_input(&memo, &ctx, &frames) else {
|
||||
panic!("the miss must publish the record");
|
||||
};
|
||||
let GPoll::Final(second) = core_types::record::serve_input(&memo, &ctx, &frames) else {
|
||||
panic!("the hit must revive the published record");
|
||||
};
|
||||
let first: &String = unsafe { core_types::record::borrow_element(layout.rec(&first)) };
|
||||
let second: &String = unsafe { core_types::record::borrow_element(layout.rec(&second)) };
|
||||
assert_eq!(first, "lent out");
|
||||
assert!(std::ptr::eq(first, second), "the hit shares the parked payload");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_span_memo_hit_crosses_evaluations_on_one_payload() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let mut arena = Arena::new(4096).unwrap();
|
||||
let persistent = Arena::new(4096).unwrap();
|
||||
let generations = [];
|
||||
|
||||
let layout = element_layout::<String>();
|
||||
let memo = FrameMemoNode::new(lifted::<String>("published".to_string()), &layout);
|
||||
let served_at = |arena: &Arena| {
|
||||
let scope = scope_fixture(&generations, arena).with_persistent(&persistent);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
let GPoll::Final(value) = core_types::record::serve_input(&memo, &ctx, &frames) else {
|
||||
panic!("the span memo must serve a final record");
|
||||
};
|
||||
let element: &String = unsafe { core_types::record::borrow_element(layout.rec(&value)) };
|
||||
assert_eq!(element, "published");
|
||||
std::ptr::from_ref(element)
|
||||
};
|
||||
|
||||
served_at(&arena);
|
||||
let first = served_at(&arena);
|
||||
arena.reset();
|
||||
let second = served_at(&arena);
|
||||
assert_eq!(first, second, "the hit names the published payload rather than re-parking it");
|
||||
assert!(persistent.contains(first.cast::<u8>()), "the payload the hits share lives in the persistent region");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
use core_types::{Ctx, ExtractFootprint, ops::Convert, transform::Footprint};
|
||||
use std::marker::PhantomData;
|
||||
|
||||
// Re-export TypeNode from core-types for convenience
|
||||
pub use core_types::ops::TypeNode;
|
||||
|
||||
/// Passes-through the input value without changing it. This is useful for rerouting wires for organization purposes.
|
||||
#[node_macro::node(category("General"), skip_impl)]
|
||||
fn passthrough<'i, T: 'i + Send>(_: impl Ctx, content: T) -> T {
|
||||
content
|
||||
}
|
||||
|
||||
#[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()
|
||||
}
|
||||
|
||||
#[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
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
pub fn passthrough_node() {
|
||||
assert_eq!(passthrough((), &4), &4);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "graphic-nodes"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
authors.workspace = true
|
||||
|
||||
[dependencies]
|
||||
# Local dependencies
|
||||
core-types = { workspace = true }
|
||||
graphic-types = { workspace = true }
|
||||
vector-types = { workspace = true }
|
||||
raster-types = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
dyn-any = { workspace = true }
|
||||
glam = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
node-macro = { workspace = true }
|
||||
@@ -0,0 +1,60 @@
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::transform::TransformMut;
|
||||
use core_types::{ATTR_BACKGROUND, ATTR_CLIP, ATTR_DIMENSIONS, ATTR_LOCATION, 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::GradientStops;
|
||||
|
||||
/// Constructs a single-element `Artboard[]` with the given content and metadata stored as row attributes.
|
||||
#[node_macro::node(category(""))]
|
||||
pub async fn create_artboard<T: IntoGraphicList>(
|
||||
ctx: impl ExtractAll + CloneVarArgs + Ctx,
|
||||
/// Graphics to include within the artboard.
|
||||
#[implementations(
|
||||
Context -> List<Graphic>,
|
||||
Context -> List<Vector>,
|
||||
Context -> List<String>,
|
||||
Context -> List<Raster<CPU>>,
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<GradientStops>,
|
||||
Context -> DAffine2,
|
||||
)]
|
||||
content: impl Node<Context<'static>, Output = T>,
|
||||
/// Coordinate of the top-left corner of the artboard within the document.
|
||||
location: DVec2,
|
||||
/// Width and height of the artboard within the document.
|
||||
dimensions: DVec2,
|
||||
/// Color of the artboard background.
|
||||
background: List<Color>,
|
||||
/// Whether to cut off the contained content that extends outside the artboard, or keep it visible.
|
||||
#[default(true)]
|
||||
clip: bool,
|
||||
) -> List<Artboard> {
|
||||
let footprint = ctx.try_footprint().copied();
|
||||
let mut new_ctx = OwnedContextImpl::from(ctx);
|
||||
if let Some(mut footprint) = footprint {
|
||||
footprint.translate(location);
|
||||
new_ctx = new_ctx.with_footprint(footprint);
|
||||
}
|
||||
let content = content.eval(new_ctx.into_context()).await.into_graphic_list();
|
||||
|
||||
// Normalize so `location` is the top-left corner and `dimensions` are positive (allowing negative input
|
||||
// dimensions to represent dragging from the opposite corner). Compute the corner using the raw signed
|
||||
// dimensions before clamping, otherwise negative inputs collapse to the original corner instead of inverting.
|
||||
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);
|
||||
|
||||
// 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),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,714 @@
|
||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use core_types::list::{AttributeDyn, AttributeValueDyn, Item, List, ListDyn};
|
||||
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};
|
||||
|
||||
/// 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.
|
||||
/// 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>(
|
||||
_: impl Ctx,
|
||||
/// The list of data.
|
||||
#[implementations(
|
||||
List<String>,
|
||||
List<Artboard>,
|
||||
List<Graphic>,
|
||||
List<Vector>,
|
||||
List<Raster<CPU>>,
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<GradientStops>,
|
||||
)]
|
||||
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,
|
||||
) -> T {
|
||||
let index = index as i32;
|
||||
|
||||
if index < 0 {
|
||||
list.omit_index_from_end(index.unsigned_abs() as usize)
|
||||
} else {
|
||||
list.omit_index(index as usize)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// 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>(
|
||||
_: impl Ctx,
|
||||
/// The `List` of data to extract from.
|
||||
#[implementations(
|
||||
List<String>,
|
||||
List<f64>,
|
||||
List<u8>,
|
||||
List<NodeId>,
|
||||
List<Color>,
|
||||
List<GradientStops>,
|
||||
List<Vector>,
|
||||
List<Raster<CPU>>,
|
||||
List<Graphic>,
|
||||
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 {
|
||||
let len = list.len();
|
||||
let index = index as i32;
|
||||
let resolved = if index < 0 {
|
||||
let from_end = index.unsigned_abs() as usize;
|
||||
if from_end > len {
|
||||
return T::default();
|
||||
}
|
||||
len - from_end
|
||||
} else {
|
||||
index as usize
|
||||
};
|
||||
list.element(resolved).cloned().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>,
|
||||
)]
|
||||
content: List<Item>,
|
||||
#[implementations(
|
||||
Context -> List<Graphic>,
|
||||
Context -> List<Vector>,
|
||||
Context -> List<Raster<CPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<GradientStops>,
|
||||
Context -> List<String>,
|
||||
)]
|
||||
mapped: impl Node<Context<'static>, Output = List<Item>>,
|
||||
) -> List<Item> {
|
||||
let mut rows = List::new();
|
||||
|
||||
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 list = mapped.eval(owned_ctx.into_context()).await;
|
||||
|
||||
rows.extend(list);
|
||||
}
|
||||
|
||||
rows
|
||||
}
|
||||
|
||||
#[node_macro::node(category("General"))]
|
||||
async fn mirror<T: 'n + Send + Clone>(
|
||||
_: impl Ctx,
|
||||
#[implementations(
|
||||
List<Graphic>,
|
||||
List<Vector>,
|
||||
List<String>,
|
||||
List<Raster<CPU>>,
|
||||
List<Color>,
|
||||
List<GradientStops>,
|
||||
)]
|
||||
content: List<T>,
|
||||
#[default(ReferencePoint::Center)] relative_to_bounds: ReferencePoint,
|
||||
#[unit(" px")] offset: f64,
|
||||
#[range]
|
||||
#[soft(-90..90)]
|
||||
angle: Angle,
|
||||
#[default(true)] keep_original: bool,
|
||||
) -> List<T>
|
||||
where
|
||||
List<T>: BoundingBox,
|
||||
{
|
||||
// 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 reference_point_location = relative_to_bounds.point_in_bounding_box((bounding_box[0], bounding_box[1]).into());
|
||||
let mirror_reference_point = reference_point_location.map(|point| point + normal * offset);
|
||||
|
||||
// Create the reflection matrix
|
||||
let reflection = DAffine2::from_mat2_translation(
|
||||
glam::DMat2::from_cols(
|
||||
DVec2::new(1. - 2. * normal.x * normal.x, -2. * normal.y * normal.x),
|
||||
DVec2::new(-2. * normal.x * normal.y, 1. - 2. * normal.y * normal.y),
|
||||
),
|
||||
DVec2::ZERO,
|
||||
);
|
||||
|
||||
// Apply reflection around the reference point
|
||||
let reflected_transform = if let Some(mirror_reference_point) = mirror_reference_point {
|
||||
DAffine2::from_translation(mirror_reference_point) * reflection * DAffine2::from_translation(-mirror_reference_point)
|
||||
} else {
|
||||
reflection * DAffine2::from_translation(DVec2::from_angle(angle.to_radians()) * DVec2::splat(-offset))
|
||||
};
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
result_list
|
||||
}
|
||||
|
||||
/// Returns the path identifying the subgraph (network) that contains this proto node — i.e. the input `node_path`
|
||||
/// with its own trailing entry dropped. The terminating element of the returned path is the document node whose
|
||||
/// encapsulated network we live in, so the path doubles as a unique reference to that node at any nesting depth.
|
||||
/// Used as the value source for stamping the `editor:layer_path` attribute on each item of a layer's output, which lets
|
||||
/// 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> {
|
||||
let len = node_path.len();
|
||||
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
|
||||
/// 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<DAffine2>,
|
||||
List<BlendMode>,
|
||||
List<GradientType>,
|
||||
List<GradientSpreadMethod>,
|
||||
)]
|
||||
mut content: List<T>,
|
||||
/// The attribute name (key) to write or replace.
|
||||
name: 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>,
|
||||
) -> List<T> {
|
||||
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;
|
||||
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,
|
||||
) -> List<Vector> {
|
||||
let mut result = List::with_capacity(content.len());
|
||||
for index in 0..content.len() {
|
||||
let Some(value) = content.attribute::<Vector>(&name, index) else { continue };
|
||||
result.push(Item::new_from_element(value.clone()));
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Reads a named numeric attribute (`f64`, `u64`, or `u32`) from the input list, outputting each value as an element of a new `f64[]`. Integer values are converted to `f64`.
|
||||
#[node_macro::node(category("Attributes: Read"))]
|
||||
fn read_attribute_number(
|
||||
_: impl Ctx,
|
||||
content: ListDyn,
|
||||
/// The attribute name (key) to read.
|
||||
name: String,
|
||||
) -> List<f64> {
|
||||
let mut result = List::with_capacity(content.len());
|
||||
for index in 0..content.len() {
|
||||
let value = content
|
||||
.attribute::<f64>(&name, index)
|
||||
.copied()
|
||||
.or_else(|| content.attribute::<u64>(&name, index).map(|v| *v as f64))
|
||||
.or_else(|| content.attribute::<u32>(&name, index).map(|v| *v as f64));
|
||||
let Some(value) = value else { continue };
|
||||
result.push(Item::new_from_element(value));
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Reads a named `bool` attribute from the input list, outputting each value as an element of a new `bool[]`.
|
||||
#[node_macro::node(category("Attributes: Read"))]
|
||||
fn read_attribute_bool(
|
||||
_: impl Ctx,
|
||||
content: ListDyn,
|
||||
/// The attribute name (key) to read.
|
||||
name: String,
|
||||
) -> List<bool> {
|
||||
let mut result = List::with_capacity(content.len());
|
||||
for index in 0..content.len() {
|
||||
let Some(value) = content.attribute::<bool>(&name, index) else { continue };
|
||||
result.push(Item::new_from_element(*value));
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Reads a named `String` attribute from the input list, outputting each value as an element of a new `String[]`.
|
||||
#[node_macro::node(category("Attributes: Read"))]
|
||||
fn read_attribute_string(
|
||||
_: impl Ctx,
|
||||
content: ListDyn,
|
||||
/// The attribute name (key) to read.
|
||||
name: String,
|
||||
) -> List<String> {
|
||||
let mut result = List::with_capacity(content.len());
|
||||
for index in 0..content.len() {
|
||||
let Some(value) = content.attribute::<String>(&name, index) else { continue };
|
||||
result.push(Item::new_from_element(value.clone()));
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Reads a named `DAffine2` transform attribute from the input list, outputting each value as an element of a new `DAffine2[]`.
|
||||
#[node_macro::node(category("Attributes: Read"))]
|
||||
fn read_attribute_transform(
|
||||
_: impl Ctx,
|
||||
content: ListDyn,
|
||||
/// The attribute name (key) to read.
|
||||
name: String,
|
||||
) -> List<DAffine2> {
|
||||
let mut result = List::with_capacity(content.len());
|
||||
for index in 0..content.len() {
|
||||
let Some(value) = content.attribute::<DAffine2>(&name, index) else { continue };
|
||||
result.push(Item::new_from_element(*value));
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Reads a named `Color` attribute from the input list, outputting each value as an element of a new `Color[]`.
|
||||
#[node_macro::node(category("Attributes: Read"))]
|
||||
fn read_attribute_color(
|
||||
_: impl Ctx,
|
||||
content: ListDyn,
|
||||
/// The attribute name (key) to read.
|
||||
name: String,
|
||||
) -> List<Color> {
|
||||
let mut result = List::with_capacity(content.len());
|
||||
for index in 0..content.len() {
|
||||
let Some(value) = content.attribute::<Color>(&name, index) else { continue };
|
||||
result.push(Item::new_from_element(*value));
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Reads a named `BlendMode` attribute from the input list, outputting each value as an element of a new `BlendMode[]`.
|
||||
#[node_macro::node(category("Attributes: Read"))]
|
||||
fn read_attribute_blend_mode(
|
||||
_: impl Ctx,
|
||||
content: ListDyn,
|
||||
/// The attribute name (key) to read.
|
||||
name: String,
|
||||
) -> List<BlendMode> {
|
||||
let mut result = List::with_capacity(content.len());
|
||||
for index in 0..content.len() {
|
||||
let Some(value) = content.attribute::<BlendMode>(&name, index) else { continue };
|
||||
result.push(Item::new_from_element(*value));
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Reads a named `GradientType` attribute from the input list, outputting each value as an element of a new `GradientType[]`.
|
||||
#[node_macro::node(category("Attributes: Read"))]
|
||||
fn read_attribute_gradient_type(
|
||||
_: impl Ctx,
|
||||
content: ListDyn,
|
||||
/// The attribute name (key) to read.
|
||||
name: String,
|
||||
) -> List<GradientType> {
|
||||
let mut result = List::with_capacity(content.len());
|
||||
for index in 0..content.len() {
|
||||
let Some(value) = content.attribute::<GradientType>(&name, index) else { continue };
|
||||
result.push(Item::new_from_element(*value));
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Reads a named `GradientSpreadMethod` attribute from the input list, outputting each value as an element of a new `GradientSpreadMethod[]`.
|
||||
#[node_macro::node(category("Attributes: Read"))]
|
||||
fn read_attribute_spread_method(
|
||||
_: impl Ctx,
|
||||
content: ListDyn,
|
||||
/// The attribute name (key) to read.
|
||||
name: String,
|
||||
) -> List<GradientSpreadMethod> {
|
||||
let mut result = List::with_capacity(content.len());
|
||||
for index in 0..content.len() {
|
||||
let Some(value) = content.attribute::<GradientSpreadMethod>(&name, index) else { continue };
|
||||
result.push(Item::new_from_element(*value));
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Reads a named `GradientStops` attribute from the input list, outputting each value as an element of a new `GradientStops[]`.
|
||||
#[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> {
|
||||
let mut result = List::with_capacity(content.len());
|
||||
for index in 0..content.len() {
|
||||
let Some(value) = content.attribute::<GradientStops>(&name, index) else { continue };
|
||||
result.push(Item::new_from_element(value.clone()));
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Reads a named `Artboard` attribute from the input list, outputting each value as an element of a new `Artboard[]`.
|
||||
#[node_macro::node(category("Attributes: Read"))]
|
||||
fn read_attribute_artboard(
|
||||
_: impl Ctx,
|
||||
content: ListDyn,
|
||||
/// The attribute name (key) to read.
|
||||
name: String,
|
||||
) -> List<Artboard> {
|
||||
let mut result = List::with_capacity(content.len());
|
||||
for index in 0..content.len() {
|
||||
let Some(value) = content.attribute::<Artboard>(&name, index) else { continue };
|
||||
result.push(Item::new_from_element(value.clone()));
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Reads a named `Raster` attribute from the input list, outputting each value as an element of a new `Raster[]`.
|
||||
#[node_macro::node(category("Attributes: Read"))]
|
||||
fn read_attribute_raster(
|
||||
_: impl Ctx,
|
||||
content: ListDyn,
|
||||
/// The attribute name (key) to read.
|
||||
name: String,
|
||||
) -> List<Raster<CPU>> {
|
||||
let mut result = List::with_capacity(content.len());
|
||||
for index in 0..content.len() {
|
||||
let Some(value) = content.attribute::<Raster<CPU>>(&name, index) else { continue };
|
||||
result.push(Item::new_from_element(value.clone()));
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Joins two `List`s of the same type, extending the base `List` with the items from the new `List`.
|
||||
#[node_macro::node(category("General"))]
|
||||
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>)]
|
||||
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>)]
|
||||
new: List<T>,
|
||||
) -> List<T> {
|
||||
let mut base = base;
|
||||
base.extend(new);
|
||||
|
||||
base
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// Performs an obsolete function as part of a migration from an older document format.
|
||||
/// Users are advised to delete this node and replace it with a new one.
|
||||
#[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>,
|
||||
#[expose]
|
||||
#[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<String>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<GradientStops>)]
|
||||
new: List<T>,
|
||||
nested_node_path: List<NodeId>,
|
||||
) -> 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()
|
||||
};
|
||||
|
||||
let mut base = base;
|
||||
for mut row in new.into_iter() {
|
||||
row.set_attribute(ATTR_EDITOR_LAYER_PATH, layer);
|
||||
base.push(row);
|
||||
}
|
||||
|
||||
base
|
||||
}
|
||||
|
||||
/// Nests the input graphical content in a wrapper graphic. This essentially "groups" the input.
|
||||
/// The inverse of this node is 'Flatten Graphic'.
|
||||
#[node_macro::node(category("General"))]
|
||||
pub async fn wrap_graphic<T: Into<Graphic> + 'n>(
|
||||
_: impl Ctx,
|
||||
#[implementations(
|
||||
List<Graphic>,
|
||||
List<Vector>,
|
||||
List<Raster<CPU>>,
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<GradientStops>,
|
||||
List<String>,
|
||||
DAffine2,
|
||||
DVec2,
|
||||
)]
|
||||
content: T,
|
||||
) -> List<Graphic> {
|
||||
List::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[]`.
|
||||
/// If it is already a `Graphic[]`, it is not wrapped again. Use the 'Wrap Graphic' node if wrapping is always desired.
|
||||
#[node_macro::node(category("General"))]
|
||||
pub async fn to_graphic<T: IntoGraphicList>(
|
||||
_: impl Ctx,
|
||||
#[implementations(
|
||||
List<Graphic>,
|
||||
List<Vector>,
|
||||
List<Raster<CPU>>,
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<GradientStops>,
|
||||
List<String>,
|
||||
)]
|
||||
content: T,
|
||||
) -> List<Graphic> {
|
||||
content.into_graphic_list()
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
// 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() {
|
||||
let Some(current_element) = current_graphic_list.element(index) else { continue };
|
||||
let current_element = current_element.clone();
|
||||
let current_transform: DAffine2 = current_graphic_list.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
|
||||
let recurse = fully_flatten || recursion_depth == 0;
|
||||
|
||||
match current_element {
|
||||
// If we're allowed to recurse, flatten any graphics we encounter
|
||||
Graphic::Graphic(mut current_element) if recurse => {
|
||||
// Apply the parent graphic's transform to all child elements
|
||||
for graphic_transform in current_element.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM) {
|
||||
*graphic_transform = current_transform * *graphic_transform;
|
||||
}
|
||||
|
||||
flatten_list(output_graphic_list, current_element, fully_flatten, recursion_depth + 1);
|
||||
}
|
||||
// Push any leaf elements we encounter: either `Graphic::Graphic(...)` values beyond the recursion depth, or non-`Graphic::Graphic` variants (e.g. `Graphic::Vector`, `Graphic::Raster*`, `Graphic::Color`, `Graphic::Gradient`, `Graphic::Text`)
|
||||
_ => {
|
||||
let attributes = current_graphic_list.clone_item_attributes(index);
|
||||
output_graphic_list.push(Item::from_parts(current_element, attributes));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut output = List::new();
|
||||
flatten_list(&mut output, content, fully_flatten, 0);
|
||||
|
||||
output
|
||||
}
|
||||
|
||||
/// Converts a `Graphic[]` into a `Vector[]` by deeply flattening any vector content it contains, and discarding any non-vector content.
|
||||
#[node_macro::node(category("Vector"))]
|
||||
pub async fn flatten_vector<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Vector>)] content: T) -> List<Vector> {
|
||||
let graphic_list = content.into_graphic_list();
|
||||
let mut output: List<Vector> = graphic_list.clone().into_flattened_list();
|
||||
|
||||
// TODO: Replace this snapshot hack with per-layer metadata driven by each layer's Monitor node.
|
||||
// TODO: Flattening here erases the upstream `List<Graphic>` hierarchy that editor metadata collection walks
|
||||
// TODO: to populate `upstream_footprints` / `local_transforms` / `click_targets` per child layer. As a workaround
|
||||
// TODO: we stash the pre-flattened list on the output so `List<Vector>::collect_metadata` can recurse into it,
|
||||
// TODO: which conflates render output with editor metadata and forces the pre-compensation dance below.
|
||||
// TODO: The cleaner fix is to drive each layer's metadata from its own Monitor's captured `(Context, List<Graphic>)`,
|
||||
// TODO: at which point this attribute (and the equivalents in Boolean Operation, Solidify Stroke, Flatten Path,
|
||||
// TODO: Morph, Rasterize) become unnecessary.
|
||||
if !output.is_empty() {
|
||||
// Item 0 carries a composed transform inherited from the flattened input, but the merged_layers
|
||||
// already holds the original transforms; pre-compensate by item 0's inverse so the renderer's
|
||||
// `upstream_footprint *= item_0_transform` recursion cancels out and leaves the originals intact.
|
||||
let mut graphic_list = graphic_list;
|
||||
let item_0_transform: DAffine2 = output.attribute_cloned_or_default(ATTR_TRANSFORM, 0);
|
||||
if item_0_transform.matrix2.determinant().abs() > f64::EPSILON {
|
||||
let inverse = item_0_transform.inverse();
|
||||
for transform in graphic_list.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM) {
|
||||
*transform = inverse * *transform;
|
||||
}
|
||||
}
|
||||
|
||||
output.set_attribute(ATTR_EDITOR_MERGED_LAYERS, 0, graphic_list);
|
||||
}
|
||||
|
||||
output
|
||||
}
|
||||
|
||||
/// Converts a `Graphic[]` into a `Raster[]` by deeply flattening any raster content it contains, and discarding any non-raster content.
|
||||
#[node_macro::node(category("Raster"))]
|
||||
pub async fn flatten_raster<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Raster<CPU>>)] content: T) -> List<Raster<CPU>> {
|
||||
content.into_flattened_list()
|
||||
}
|
||||
|
||||
/// Converts a `Graphic[]` into a `Color[]` by deeply flattening any color content it contains, and discarding any non-color content.
|
||||
#[node_macro::node(category("General"))]
|
||||
pub async fn flatten_color<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Color>)] content: T) -> List<Color> {
|
||||
content.into_flattened_list()
|
||||
}
|
||||
|
||||
/// Converts a `Graphic[]` into a `GradientStops[]` 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> {
|
||||
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> {
|
||||
let colors = colors.into_flattened_list::<Color>();
|
||||
let total_colors = colors.len();
|
||||
|
||||
if total_colors == 0 {
|
||||
return List::new_from_element(GradientStops::new(vec![
|
||||
GradientStop {
|
||||
position: 0.,
|
||||
midpoint: 0.5,
|
||||
color: Color::BLACK,
|
||||
},
|
||||
GradientStop {
|
||||
position: 1.,
|
||||
midpoint: 0.5,
|
||||
color: Color::BLACK,
|
||||
},
|
||||
]));
|
||||
}
|
||||
|
||||
if let (1, Some(&single_color)) = (total_colors, colors.element(0)) {
|
||||
return List::new_from_element(GradientStops::new(vec![
|
||||
GradientStop {
|
||||
position: 0.,
|
||||
midpoint: 0.5,
|
||||
color: single_color,
|
||||
},
|
||||
GradientStop {
|
||||
position: 1.,
|
||||
midpoint: 0.5,
|
||||
color: single_color,
|
||||
},
|
||||
]));
|
||||
}
|
||||
|
||||
let colors = colors.into_iter().enumerate().map(|(index, row)| GradientStop {
|
||||
position: index as f64 / (total_colors - 1) as f64,
|
||||
midpoint: 0.5,
|
||||
color: row.into_element(),
|
||||
});
|
||||
List::new_from_element(GradientStops::new(colors))
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
pub mod artboard;
|
||||
pub mod graphic;
|
||||
pub mod record;
|
||||
|
||||
// Re-export all nodes
|
||||
pub use artboard::*;
|
||||
pub use graphic::*;
|
||||
@@ -0,0 +1,970 @@
|
||||
//! Pilot record nodes over the production graphic types: element-space
|
||||
//! expanders whose ragged nesting lives inside `Graphic` values, ahead of the
|
||||
//! flip. Wiring is by hand until the compiler pass constructs layouts.
|
||||
|
||||
use core_types::attribute::{Attr, Transform};
|
||||
use core_types::context::{DeriveCtx, ExtractIndex, IndexLink, InjectIndex};
|
||||
use core_types::extent::{ExtentIn, LevelIn, ListIn, ValueIn};
|
||||
use core_types::gpoll::{Extent, GPoll, GraphError, Interrupt};
|
||||
use core_types::{ATTR_TRANSFORM, Color, Ctx};
|
||||
use glam::DAffine2;
|
||||
use graphic_types::Vector;
|
||||
use graphic_types::graphic::Graphic;
|
||||
use raster_types::{CPU, Raster};
|
||||
use vector_types::{GradientStop, GradientStops};
|
||||
|
||||
/// Whether the walk can descend into a group: the run holds `Graphic`
|
||||
/// elements.
|
||||
pub(crate) fn group_expands(group: &core_types::record::Group) -> bool {
|
||||
group.content.typed_lanes::<Graphic>().is_some()
|
||||
}
|
||||
|
||||
pub(crate) fn group_leaf_count(group: &core_types::record::Group, fully_flatten: bool, depth: usize) -> usize {
|
||||
let lanes = group.content.typed_lanes::<Graphic>().expect("guarded by group_expands");
|
||||
(0..lanes.len()).map(|lane| leaf_count(lanes.element_ref(lane), fully_flatten, depth + 1)).sum()
|
||||
}
|
||||
|
||||
pub(crate) fn group_locate<'e>(group: &core_types::record::Group<'e>, transform: DAffine2, fully_flatten: bool, depth: usize, remaining: &mut usize) -> Option<(Graphic<'e>, DAffine2)> {
|
||||
let item = &group.content;
|
||||
let lanes = item.typed_lanes::<Graphic>().expect("guarded by group_expands");
|
||||
let field = core_types::record::FieldOffset::<Transform>::of(item.layout(), 0);
|
||||
(0..lanes.len()).find_map(|lane| {
|
||||
let lane_transform = item.lanes().get(lane).attr_at(field);
|
||||
locate(lanes.element_ref(lane), transform * lane_transform, fully_flatten, depth + 1, remaining)
|
||||
})
|
||||
}
|
||||
|
||||
/// Leaf rows a graphic expands to: its children's counts when the walk
|
||||
/// descends (top rows always, deeper groups only in a full flatten), one for
|
||||
/// itself otherwise.
|
||||
pub(crate) fn leaf_count(graphic: &Graphic, fully_flatten: bool, depth: usize) -> usize {
|
||||
match graphic {
|
||||
Graphic::Graphic(children) if fully_flatten || depth == 0 => (0..children.len())
|
||||
.map(|index| children.element(index).map_or(0, |child| leaf_count(child, fully_flatten, depth + 1)))
|
||||
.sum(),
|
||||
Graphic::Group(group) if (fully_flatten || depth == 0) && group_expands(group) => group_leaf_count(group, fully_flatten, depth),
|
||||
_ => 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// The `remaining`-th leaf of `graphic` in walk order, with the transforms
|
||||
/// along its path composed onto `transform`.
|
||||
pub(crate) fn locate<'e>(graphic: &Graphic<'e>, transform: DAffine2, fully_flatten: bool, depth: usize, remaining: &mut usize) -> Option<(Graphic<'e>, DAffine2)> {
|
||||
match graphic {
|
||||
Graphic::Graphic(children) if fully_flatten || depth == 0 => (0..children.len()).find_map(|index| {
|
||||
let child = children.element(index)?;
|
||||
let child_transform: DAffine2 = children.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
locate(child, transform * child_transform, fully_flatten, depth + 1, remaining)
|
||||
}),
|
||||
Graphic::Group(group) if (fully_flatten || depth == 0) && group_expands(group) => group_locate(group, transform, fully_flatten, depth, remaining),
|
||||
_ if *remaining == 0 => Some((graphic.clone(), transform)),
|
||||
_ => {
|
||||
*remaining -= 1;
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Rank-model Flatten: one flat level holding the content's leaves, each with
|
||||
/// the transforms along its path composed; a group beyond the walk's depth
|
||||
/// rides as a leaf with its embedded transforms untouched.
|
||||
#[node_macro::node(category("Test"), extent(flatten_extent))]
|
||||
fn flatten(ctx: impl Ctx + ExtractIndex + InjectIndex + Copy, content: IList<Graphic<'static>>, fully_flatten: bool) -> Result<IList<(Graphic<'static>, Attr<Transform>)>, Interrupt> {
|
||||
let mut remaining = ctx.index() as usize;
|
||||
for row in 0..content.len() {
|
||||
let graphic = content.element_ref(row);
|
||||
let count = leaf_count(graphic, fully_flatten, 0);
|
||||
if remaining >= count {
|
||||
remaining -= count;
|
||||
continue;
|
||||
}
|
||||
let transform: DAffine2 = content.lane(row).attr::<Transform>();
|
||||
if let Some((leaf, composed)) = locate(graphic, transform, fully_flatten, 0, &mut remaining) {
|
||||
return Ok((leaf, Attr(composed)));
|
||||
}
|
||||
}
|
||||
Err(GraphError::new("flatten addressed past its leaf count").into())
|
||||
}
|
||||
|
||||
/// The level holds one row per leaf of the walk.
|
||||
fn flatten_extent(content: ListIn<'_, Graphic>, fully_flatten: ValueIn<'_, bool>, level: LevelIn) -> GPoll<Extent> {
|
||||
match level.top() {
|
||||
true => fully_flatten
|
||||
.get()
|
||||
.zip(content.get())
|
||||
.map(|(fully_flatten, content)| Extent::Exactly((0..content.len()).map(|row| leaf_count(content.element_ref(row), fully_flatten, 0)).sum())),
|
||||
false => GPoll::Final(Extent::Exactly(1)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Rank-model Wrap: the content level as one group element on a one-lane
|
||||
/// level, the inverse of flatten's one-level descent.
|
||||
#[node_macro::node(category("Test"), extent(wrap_extent))]
|
||||
fn wrap<'e>(_: impl Ctx, content: IList<Graphic<'e>>) -> Result<IList<Graphic<'e>>, Interrupt> {
|
||||
let item = content.as_group_item();
|
||||
Ok(Graphic::Group(core_types::record::Group { row: None, content: item }))
|
||||
}
|
||||
|
||||
/// The collected group is the level's single lane.
|
||||
fn wrap_extent(_content: ListIn<'_, Graphic>, _level: LevelIn) -> GPoll<Extent> {
|
||||
GPoll::Final(Extent::Exactly(1))
|
||||
}
|
||||
|
||||
/// Rank-model colors-to-gradient: the color level folds into one gradient
|
||||
/// with evenly spaced stops.
|
||||
#[node_macro::node(category("Test"))]
|
||||
fn to_gradient(_: impl Ctx, colors: IList<Color>) -> GradientStops {
|
||||
let stop = |position: f64, color: Color| GradientStop { position, midpoint: 0.5, color };
|
||||
match colors.len() {
|
||||
0 => GradientStops::new(vec![stop(0., Color::BLACK), stop(1., Color::BLACK)]),
|
||||
1 => GradientStops::new(vec![stop(0., colors.get(0)), stop(1., colors.get(0))]),
|
||||
total => GradientStops::new((0..total).map(|index| stop(index as f64 / (total - 1) as f64, colors.get(index)))),
|
||||
}
|
||||
}
|
||||
|
||||
/// One content row as the production vararg shape: a single-item legacy list
|
||||
/// carrying the row's element only, so the list's dyn-hash is a complete
|
||||
/// cache key over the observables.
|
||||
pub(crate) fn vararg_row<Row: Clone + Send + Sync + 'static>(content: core_types::node::List<'_, Row>, row: usize) -> core_types::list::List<Row> {
|
||||
core_types::list::List::new_from_element(content.element_ref(row).clone())
|
||||
}
|
||||
|
||||
/// Rank-model Map: one subgraph invocation per content row, the row riding as
|
||||
/// a vararg; the subgraph's own level nests under the content level. The
|
||||
/// levels report a lower bound; consumers drain to the past-end signal.
|
||||
#[node_macro::node(category("Test"))]
|
||||
fn map<Row: Clone + Send + Sync + core_types::CacheHash + 'static, T>(
|
||||
ctx: impl Ctx + DeriveCtx + ExtractIndex + InjectIndex + Copy,
|
||||
#[implementations(Graphic, Vector, Raster<CPU>, Color, GradientStops, String)] content: IList<Row>,
|
||||
mapped: impl Node<Context<'_>, Output = IList<T>>,
|
||||
) -> Result<IList<IList<T>>, Interrupt> {
|
||||
let mut remaining = ctx.index();
|
||||
for row in 0..content.len() {
|
||||
let item = vararg_row(content, row);
|
||||
let scoped = ctx.push_vararg(&item);
|
||||
let lanes = mapped.inner_extent_at(&scoped.ctx(), row as u64)?;
|
||||
if remaining >= lanes {
|
||||
remaining -= lanes;
|
||||
continue;
|
||||
}
|
||||
let mut frame = IndexLink { index: 0, outer: None };
|
||||
return mapped.eval(&scoped.ctx().push_level(&mut frame, row as u64, remaining));
|
||||
}
|
||||
Err(GraphError::past_end().into())
|
||||
}
|
||||
|
||||
/// Rank-model flat-map (the production Map): map's walk with the subgraph's
|
||||
/// lanes concatenated into one flat level. The level reports a lower bound;
|
||||
/// consumers drain to the past-end signal.
|
||||
#[node_macro::node(category("Test"))]
|
||||
fn flat_map<Row: Clone + Send + Sync + core_types::CacheHash + 'static, T>(
|
||||
ctx: impl Ctx + DeriveCtx + ExtractIndex + InjectIndex + Copy,
|
||||
#[implementations(Graphic, Vector, Raster<CPU>, Color, GradientStops, String)] content: IList<Row>,
|
||||
mapped: impl Node<Context<'_>, Output = IList<T>>,
|
||||
) -> Result<IList<T>, Interrupt> {
|
||||
let mut remaining = ctx.index();
|
||||
for row in 0..content.len() {
|
||||
let item = vararg_row(content, row);
|
||||
let scoped = ctx.push_vararg(&item);
|
||||
let lanes = mapped.inner_extent_at(&scoped.ctx(), row as u64)?;
|
||||
if remaining >= lanes {
|
||||
remaining -= lanes;
|
||||
continue;
|
||||
}
|
||||
let mut frame = IndexLink { index: 0, outer: None };
|
||||
return mapped.eval(&scoped.ctx().push_level(&mut frame, row as u64, remaining));
|
||||
}
|
||||
Err(GraphError::past_end().into())
|
||||
}
|
||||
|
||||
/// Rank-model level collapse: two nested levels become one flat level. The
|
||||
/// flat index already spans the input's depth, so the eval forwards it.
|
||||
#[node_macro::node(category("Test"), extent(flatten_levels_extent))]
|
||||
fn flatten_levels<T>(ctx: impl Ctx + DeriveCtx + ExtractIndex, content: impl Node<Context<'_>, Output = IList<IList<T>>>) -> Result<IList<T>, Interrupt> {
|
||||
let head = ctx.index_head();
|
||||
content.eval(&ctx.promoted(&head, ctx.index()))
|
||||
}
|
||||
|
||||
/// The collapsed level's extent is the sum of the inner extents across the
|
||||
/// outer copies; the product composite cannot express a ragged total. A
|
||||
/// lower-bound level keeps the sum a lower bound.
|
||||
fn flatten_levels_extent(content: ExtentIn<'_>, level: LevelIn) -> GPoll<Extent> {
|
||||
match level.top() {
|
||||
true => {
|
||||
let outer = match content.at_copy(0, LevelIn { level: 1, depth: 2 }) {
|
||||
GPoll::Final(Extent::Exactly(outer)) => outer,
|
||||
GPoll::Final(Extent::AtLeast(bound)) => return GPoll::Final(Extent::AtLeast(bound)),
|
||||
GPoll::Final(Extent::Free) => return GPoll::error("flatten over an unbounded outer level"),
|
||||
other => return other,
|
||||
};
|
||||
let mut total = 0;
|
||||
for copy in 0..outer {
|
||||
match content.at_copy(copy as u64, LevelIn { level: 0, depth: 2 }) {
|
||||
GPoll::Final(Extent::Exactly(count)) => total += count,
|
||||
GPoll::Final(Extent::AtLeast(count)) => return GPoll::Final(Extent::AtLeast(total + count)),
|
||||
GPoll::Final(Extent::Free) => return GPoll::error("flatten over an unbounded inner level"),
|
||||
other => return other,
|
||||
}
|
||||
}
|
||||
GPoll::Final(Extent::Exactly(total))
|
||||
}
|
||||
false => GPoll::Final(Extent::Exactly(1)),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use core_types::SourceId;
|
||||
use core_types::arena::Arena;
|
||||
use core_types::attribute::Attribute as AttributeMarker;
|
||||
use core_types::context::{ContextImpl, EvalScope, ExtractArena};
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::node::Node;
|
||||
use core_types::record::{self, FrameClaim, Layout, RecordSource, Served};
|
||||
use core_types::value::ValueSource;
|
||||
|
||||
struct GraphicSource {
|
||||
layout: Layout,
|
||||
rows: Vec<(Graphic<'static>, DAffine2)>,
|
||||
}
|
||||
|
||||
impl<C: ExtractIndex> Node<C> for GraphicSource {
|
||||
fn serve<'e, 'l>(&self, input: &C, slot: FrameClaim<'e, 'l>) -> GPoll<Served<'e>>
|
||||
where
|
||||
C: ExtractArena<ArenaRef = &'e Arena>,
|
||||
{
|
||||
let (graphic, transform) = &self.rows[input.innermost_index() as usize % self.rows.len()];
|
||||
let mut frame = slot;
|
||||
let arena = ExtractArena::arena(input);
|
||||
if frame.element(graphic.clone(), arena).is_none() {
|
||||
return GPoll::arena_exhausted();
|
||||
}
|
||||
write_attr_at::<Transform>(&mut frame, &self.layout, *transform);
|
||||
// SAFETY: the writes above complete the record of this layout.
|
||||
GPoll::Final(unsafe { frame.finish_served() })
|
||||
}
|
||||
|
||||
fn extent_at<'x>(&self, _input: &C, _level: u8, _frames: &core_types::record::Frames<'x>) -> GPoll<Extent>
|
||||
where
|
||||
C: ExtractArena<ArenaRef = &'x Arena>,
|
||||
{
|
||||
GPoll::Final(Extent::Exactly(self.rows.len()))
|
||||
}
|
||||
|
||||
fn layout(&self) -> &Layout {
|
||||
&self.layout
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes a field at the layout's resolved offset, the wiring-proven pairing
|
||||
/// a generated node performs.
|
||||
fn write_field_at<T: Copy + 'static>(frame: &mut FrameClaim<'_, '_>, layout: &Layout, name: &str, level: u8, value: T) {
|
||||
let field = layout
|
||||
.fields
|
||||
.iter()
|
||||
.find(|field| field.name == name && field.level == level)
|
||||
.expect("the layout carries the written field");
|
||||
assert_eq!(field.type_id, std::any::TypeId::of::<T>(), "the field was declared at this value type");
|
||||
// SAFETY: the offset is this layout's own, at the field's declared type.
|
||||
unsafe { frame.attr_at(field.offset, value) };
|
||||
}
|
||||
|
||||
/// [`write_field_at`] for a census marker at level 0.
|
||||
fn write_attr_at<A: core_types::attribute::Attribute>(frame: &mut FrameClaim<'_, '_>, layout: &Layout, value: A::Value<'static>)
|
||||
where
|
||||
A::Value<'static>: Copy + 'static,
|
||||
{
|
||||
write_field_at(frame, layout, A::NAME, 0, value);
|
||||
}
|
||||
fn scope_fixture<'a>(generations: &'a [(SourceId, u64)], arena: &'a Arena) -> EvalScope<'a> {
|
||||
EvalScope::new(Some(0.5), None, None, generations, arena)
|
||||
}
|
||||
|
||||
fn install<N: Node<ContextImpl<'static>>>(mut node: N, meta: record::LayoutMeta, inputs: &[Option<&Layout>]) -> N {
|
||||
// The fixtures wire constants into every eager input, which the compiler
|
||||
// pass records as lane-invariant.
|
||||
let resolved = record::RecordLayout {
|
||||
lane_invariant: u32::MAX,
|
||||
..meta.resolve(inputs)
|
||||
};
|
||||
<N as Node<ContextImpl<'static>>>::set_layout(&mut node, resolved);
|
||||
node
|
||||
}
|
||||
|
||||
fn install_flip<N: Node<ContextImpl<'static>>>(mut node: N, layout: &Layout) -> N {
|
||||
let bundle = record::RecordLayout {
|
||||
frame_bytes: layout.frame_bytes(),
|
||||
plan: Vec::new(),
|
||||
layout: layout.clone(),
|
||||
lane_invariant: u32::MAX,
|
||||
};
|
||||
<N as Node<ContextImpl<'static>>>::set_layout(&mut node, bundle);
|
||||
node
|
||||
}
|
||||
|
||||
fn graphic_layout() -> Layout {
|
||||
Layout::default().with_writes(1, record::element_write_hashed::<Graphic>(), &[record::FieldWrite::of::<Transform>(0)])
|
||||
}
|
||||
|
||||
fn text(label: &str) -> Graphic<'static> {
|
||||
Graphic::Text(label.to_string())
|
||||
}
|
||||
|
||||
fn group(children: Vec<(Graphic<'static>, DAffine2)>) -> Graphic<'static> {
|
||||
let mut list = List::new();
|
||||
for (index, (child, transform)) in children.into_iter().enumerate() {
|
||||
list.push(Item::new_from_element(child));
|
||||
list.set_attribute(ATTR_TRANSFORM, index, transform);
|
||||
}
|
||||
Graphic::Graphic(list)
|
||||
}
|
||||
|
||||
fn text_of<'a>(graphic: &'a Graphic<'_>) -> &'a str {
|
||||
let Graphic::Text(text) = graphic else {
|
||||
panic!("expected a text leaf, got {graphic:?}");
|
||||
};
|
||||
text
|
||||
}
|
||||
|
||||
fn translation(x: f64) -> DAffine2 {
|
||||
DAffine2::from_translation(glam::DVec2::new(x, 0.))
|
||||
}
|
||||
|
||||
/// [a, G[b, H[c]]] with translations picked so each composed path is a
|
||||
/// distinct sum.
|
||||
fn fixture_rows() -> Vec<(Graphic<'static>, DAffine2)> {
|
||||
vec![
|
||||
(text("a"), translation(1.)),
|
||||
(
|
||||
group(vec![(text("b"), translation(20.)), (group(vec![(text("c"), translation(300.))]), translation(4000.))]),
|
||||
translation(0.5),
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
macro_rules! build {
|
||||
($layout:ident, $rows:expr, $fully:expr) => {
|
||||
install(
|
||||
FlattenNode::new(
|
||||
RecordSource::new(
|
||||
GraphicSource {
|
||||
layout: $layout.clone(),
|
||||
rows: $rows,
|
||||
},
|
||||
&$layout,
|
||||
&$layout,
|
||||
),
|
||||
ValueSource::new($fully),
|
||||
),
|
||||
flatten_layout_meta(),
|
||||
&[Some(&$layout)],
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
/// A subgraph source deriving its rows from the vararg: a `Text` row of
|
||||
/// string `s` expands to `s.len()` lanes labeled `s{k}`, each translated
|
||||
/// by `k`. The vararg is attr-less, so the content rows' transforms must
|
||||
/// not reach these lanes.
|
||||
struct PerRowSource {
|
||||
layout: Layout,
|
||||
}
|
||||
|
||||
fn vararg_text<C: core_types::ExtractVarArgs>(input: &C) -> Option<String> {
|
||||
let arg = core_types::ExtractVarArgs::vararg(input, 0).ok()?;
|
||||
let list = arg.downcast_ref::<core_types::list::List<Graphic>>()?;
|
||||
let Graphic::Text(text) = list.element(0)? else { return None };
|
||||
Some(text.clone())
|
||||
}
|
||||
|
||||
impl<C: ExtractIndex + core_types::ExtractVarArgs> Node<C> for PerRowSource {
|
||||
fn serve<'e, 'l>(&self, input: &C, slot: FrameClaim<'e, 'l>) -> GPoll<Served<'e>>
|
||||
where
|
||||
C: ExtractArena<ArenaRef = &'e Arena>,
|
||||
{
|
||||
let Some(label) = vararg_text(input) else {
|
||||
return GPoll::error("the subgraph fixture expects a text vararg");
|
||||
};
|
||||
let lane = input.innermost_index();
|
||||
let graphic = text(&format!("{label}{lane}"));
|
||||
let translated = DAffine2::from_translation(glam::DVec2::new(lane as f64, 0.));
|
||||
let mut frame = slot;
|
||||
let arena = ExtractArena::arena(input);
|
||||
if frame.element(graphic, arena).is_none() {
|
||||
return GPoll::arena_exhausted();
|
||||
}
|
||||
write_attr_at::<Transform>(&mut frame, &self.layout, translated);
|
||||
// SAFETY: the writes above complete the record of this layout.
|
||||
GPoll::Final(unsafe { frame.finish_served() })
|
||||
}
|
||||
|
||||
fn extent_at<'x>(&self, input: &C, _level: u8, _frames: &core_types::record::Frames<'x>) -> GPoll<Extent>
|
||||
where
|
||||
C: ExtractArena<ArenaRef = &'x Arena>,
|
||||
{
|
||||
match vararg_text(input) {
|
||||
Some(label) => GPoll::Final(Extent::Exactly(label.len())),
|
||||
None => GPoll::error("the subgraph fixture expects a text vararg"),
|
||||
}
|
||||
}
|
||||
|
||||
fn layout(&self) -> &Layout {
|
||||
&self.layout
|
||||
}
|
||||
}
|
||||
|
||||
fn ragged_rows() -> Vec<(Graphic<'static>, DAffine2)> {
|
||||
vec![(text("ab"), translation(10.)), (text("xyz"), translation(20.))]
|
||||
}
|
||||
|
||||
fn routing_meta(source: u8, level_delta: i8) -> record::LayoutMeta {
|
||||
record::LayoutMeta {
|
||||
sources: vec![source],
|
||||
reads: vec![],
|
||||
element: record::ElementSpec::Carried,
|
||||
writes: vec![],
|
||||
removes: vec![],
|
||||
level_delta,
|
||||
folded: None,
|
||||
}
|
||||
}
|
||||
|
||||
const RAGGED_FLAT: [(&str, f64); 5] = [("ab0", 0.), ("ab1", 1.), ("xyz0", 0.), ("xyz1", 1.), ("xyz2", 2.)];
|
||||
|
||||
#[test]
|
||||
fn map_scans_ragged_rows() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(1 << 16).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let layout = graphic_layout();
|
||||
let node = install(
|
||||
MapNode::<_, _, Graphic>::new(
|
||||
RecordSource::new(
|
||||
GraphicSource {
|
||||
layout: layout.clone(),
|
||||
rows: ragged_rows(),
|
||||
},
|
||||
&layout,
|
||||
&layout,
|
||||
),
|
||||
PerRowSource { layout: layout.clone() },
|
||||
&layout,
|
||||
),
|
||||
routing_meta(1, 1),
|
||||
&[Some(&layout), Some(&layout)],
|
||||
);
|
||||
let out = Node::<ContextImpl>::layout(&node).clone();
|
||||
assert_eq!(out.depth, 2);
|
||||
// The extent-fn-less levels report a lower bound; addressing below
|
||||
// proves the lanes are all reachable regardless.
|
||||
assert_eq!(node.extent_at(&ctx, 1, &frames.reborrow()), GPoll::Final(Extent::AtLeast(0)));
|
||||
assert_eq!(node.extent_at(&ctx, 0, &frames.reborrow()), GPoll::Final(Extent::AtLeast(0)));
|
||||
|
||||
let head = ctx.index_head();
|
||||
for (lane, &(label, x)) in RAGGED_FLAT.iter().enumerate() {
|
||||
let GPoll::Final(record) = record::capture(&node, &ctx.promoted(&head, lane as u64), &frames) else {
|
||||
panic!("expected a final record");
|
||||
};
|
||||
assert_eq!(text_of(&record.element::<Graphic>()), label, "lane {lane}");
|
||||
let transform: DAffine2 = record.attr::<Transform>();
|
||||
assert_eq!(transform.translation.x, x, "lane {lane}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flat_map_matches_flatten_of_map() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(1 << 16).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let layout = graphic_layout();
|
||||
let flat = install(
|
||||
FlatMapNode::<_, _, Graphic>::new(
|
||||
RecordSource::new(
|
||||
GraphicSource {
|
||||
layout: layout.clone(),
|
||||
rows: ragged_rows(),
|
||||
},
|
||||
&layout,
|
||||
&layout,
|
||||
),
|
||||
PerRowSource { layout: layout.clone() },
|
||||
&layout,
|
||||
),
|
||||
routing_meta(1, 0),
|
||||
&[Some(&layout), Some(&layout)],
|
||||
);
|
||||
let mapped = install(
|
||||
MapNode::<_, _, Graphic>::new(
|
||||
RecordSource::new(
|
||||
GraphicSource {
|
||||
layout: layout.clone(),
|
||||
rows: ragged_rows(),
|
||||
},
|
||||
&layout,
|
||||
&layout,
|
||||
),
|
||||
PerRowSource { layout: layout.clone() },
|
||||
&layout,
|
||||
),
|
||||
routing_meta(1, 1),
|
||||
&[Some(&layout), Some(&layout)],
|
||||
);
|
||||
let map_out = Node::<ContextImpl>::layout(&mapped).clone();
|
||||
let composed = install(FlattenLevelsNode::new(mapped, &map_out), routing_meta(0, -1), &[Some(&map_out)]);
|
||||
|
||||
let flat_out = Node::<ContextImpl>::layout(&flat).clone();
|
||||
let composed_out = Node::<ContextImpl>::layout(&composed).clone();
|
||||
assert_eq!(flat_out.depth, 1);
|
||||
assert_eq!(composed_out.depth, 1);
|
||||
// Both spellings report the same lower bound; the lane loop below is
|
||||
// the law.
|
||||
assert_eq!(flat.extent_at(&ctx, 0, &frames.reborrow()), GPoll::Final(Extent::AtLeast(0)));
|
||||
assert_eq!(composed.extent_at(&ctx, 0, &frames.reborrow()), GPoll::Final(Extent::AtLeast(0)));
|
||||
|
||||
let head = ctx.index_head();
|
||||
for (lane, &(label, x)) in RAGGED_FLAT.iter().enumerate() {
|
||||
let scoped = ctx.promoted(&head, lane as u64);
|
||||
let GPoll::Final(direct) = record::capture(&flat, &scoped, &frames) else {
|
||||
panic!("expected a final record from flat_map");
|
||||
};
|
||||
let direct_label = text_of(&direct.element::<Graphic>()).to_string();
|
||||
let direct_x: DAffine2 = direct.attr::<Transform>();
|
||||
let GPoll::Final(value) = record::capture(&composed, &scoped, &frames) else {
|
||||
panic!("expected a final record from flatten(map)");
|
||||
};
|
||||
assert_eq!(text_of(&value.element::<Graphic>()), direct_label, "lane {lane}");
|
||||
let composed_x: DAffine2 = value.attr::<Transform>();
|
||||
assert_eq!(composed_x, direct_x, "lane {lane}");
|
||||
assert_eq!((direct_label.as_str(), direct_x.translation.x), (label, x), "lane {lane}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flat_map_registers_one_row_per_content_type() {
|
||||
let entries = _flat_map_mod::flat_map_entries();
|
||||
assert_eq!(entries.len(), 6, "one registry row per content implementation");
|
||||
let content_types: Vec<core_types::Type> = entries.iter().map(|entry| entry.io.inputs[0].clone()).collect();
|
||||
assert_eq!(content_types[0], core_types::registry::record_source_type::<Graphic>());
|
||||
assert_eq!(content_types[1], core_types::registry::record_source_type::<Vector>());
|
||||
assert_eq!(content_types[5], core_types::registry::record_source_type::<String>());
|
||||
// The subject and the output stay erased across rows.
|
||||
assert_eq!(entries[0].io.inputs[1], entries[5].io.inputs[1]);
|
||||
assert_eq!(entries[0].io.return_value, entries[5].io.return_value);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flat_map_batch_matches_per_lane_eval() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(1 << 16).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let layout = graphic_layout();
|
||||
let node = install(
|
||||
FlatMapNode::<_, _, Graphic>::new(
|
||||
RecordSource::new(
|
||||
GraphicSource {
|
||||
layout: layout.clone(),
|
||||
rows: ragged_rows(),
|
||||
},
|
||||
&layout,
|
||||
&layout,
|
||||
),
|
||||
PerRowSource { layout: layout.clone() },
|
||||
&layout,
|
||||
),
|
||||
routing_meta(1, 0),
|
||||
&[Some(&layout), Some(&layout)],
|
||||
);
|
||||
let out = Node::<ContextImpl>::layout(&node).clone();
|
||||
let head = ctx.index_head();
|
||||
let scoped = ctx.promoted(&head, 0);
|
||||
|
||||
let mut scratch = vec![std::mem::MaybeUninit::<u64>::uninit(); 5 * out.lane_stride() / 8];
|
||||
let core_types::node::BatchStatus::Filled(batch, ..) = node.eval_batch(&scoped, 0..5, Some(&mut scratch), &frames) else {
|
||||
panic!("expected a filled batch");
|
||||
};
|
||||
let batch = batch.into_shared();
|
||||
assert_eq!(batch.len(), 5);
|
||||
let offset = out.offset_of(<Transform as AttributeMarker>::NAME, 0).unwrap();
|
||||
for lane in 0..5 {
|
||||
let GPoll::Final(record) = record::capture(&node, &ctx.promoted(&head, lane as u64), &frames) else {
|
||||
panic!("expected a final record");
|
||||
};
|
||||
let single = text_of(&record.element::<Graphic>()).to_string();
|
||||
assert_eq!(text_of(unsafe { record::borrow_element::<Graphic>(batch.get(lane).rec()) }), single, "lane {lane}");
|
||||
let batched: DAffine2 = unsafe { batch.get(lane).rec().read(offset) };
|
||||
let direct: DAffine2 = record.attr::<Transform>();
|
||||
assert_eq!(batched, direct, "lane {lane}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flatten_expands_one_level() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(1 << 16).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let layout = graphic_layout();
|
||||
let node = build!(layout, fixture_rows(), false);
|
||||
let out = Node::<ContextImpl>::layout(&node).clone();
|
||||
assert_eq!(out.depth, 1);
|
||||
assert_eq!(node.extent_at(&ctx, 0, &frames.reborrow()), GPoll::Final(Extent::Exactly(3)));
|
||||
|
||||
let head = ctx.index_head();
|
||||
// Lane 2 is the unexpanded subgroup H, riding as a leaf at G's depth.
|
||||
let expected: [(&str, f64); 2] = [("a", 1.), ("b", 20.5)];
|
||||
for (lane, &(label, x)) in expected.iter().enumerate() {
|
||||
let GPoll::Final(record) = record::capture(&node, &ctx.promoted(&head, lane as u64), &frames) else {
|
||||
panic!("expected a final record");
|
||||
};
|
||||
assert_eq!(text_of(&record.element::<Graphic>()), label, "lane {lane}");
|
||||
let transform: DAffine2 = record.attr::<Transform>();
|
||||
assert_eq!(transform.translation.x, x, "lane {lane}");
|
||||
}
|
||||
|
||||
let GPoll::Final(record) = record::capture(&node, &ctx.promoted(&head, 2), &frames) else {
|
||||
panic!("expected a final record");
|
||||
};
|
||||
let Graphic::Graphic(children) = record.element::<Graphic>() else {
|
||||
panic!("lane 2 keeps the subgroup element");
|
||||
};
|
||||
assert_eq!(children.len(), 1);
|
||||
assert_eq!(text_of(children.element(0).unwrap()), "c");
|
||||
assert_eq!(
|
||||
children.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM, 0).translation.x,
|
||||
300.,
|
||||
"embedded transforms ride untouched"
|
||||
);
|
||||
let transform: DAffine2 = record.attr::<Transform>();
|
||||
assert_eq!(transform.translation.x, 4000.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wire_materializes_into_a_group_for_the_renderer() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(1 << 16).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let source = core_types::value::LeveledValueSource::new(vec![text("a"), text("b")]);
|
||||
match graphic_types::boundary::materialize_group(&source, &ctx, &arena, &frames) {
|
||||
graphic_types::boundary::LevelGroup::Group(group, _) => {
|
||||
let list = graphic_types::graphic::group_to_legacy_list(&group);
|
||||
assert_eq!(list.len(), 2);
|
||||
}
|
||||
_ => panic!("expected a materialized group"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_level_batch_converts_to_its_legacy_list() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(1 << 16).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let source = core_types::value::LeveledValueSource::new(vec![1.5f64, 2.5]);
|
||||
let layout = Node::<ContextImpl>::layout(&source).clone();
|
||||
let record::LevelStatus::Batch(batch, _) = record::materialize_level(&source, &ctx, &arena, &frames) else {
|
||||
panic!("expected a batch");
|
||||
};
|
||||
let legacy = graphic_types::boundary::batch_to_legacy(&layout, batch, &arena).expect("f64 is in the legacy vocabulary");
|
||||
let list = legacy.downcast_ref::<List<f64>>().unwrap();
|
||||
assert_eq!(list.len(), 2);
|
||||
assert_eq!(list.element(0).copied(), Some(1.5));
|
||||
assert_eq!(list.element(1).copied(), Some(2.5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrap_collects_the_level_into_a_group() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(1 << 16).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let layout = graphic_layout();
|
||||
let rows = vec![(text("a"), translation(1.)), (text("b"), translation(2.))];
|
||||
let node = install(
|
||||
WrapNode::new(RecordSource::new(GraphicSource { layout: layout.clone(), rows }, &layout, &layout), &layout),
|
||||
wrap_layout_meta(),
|
||||
&[Some(&layout)],
|
||||
);
|
||||
let out = Node::<ContextImpl>::layout(&node).clone();
|
||||
assert_eq!(out.depth, 1);
|
||||
assert_eq!(node.extent_at(&ctx, 0, &frames.reborrow()), GPoll::Final(Extent::Exactly(1)), "the group is the level's single lane");
|
||||
|
||||
let head = ctx.index_head();
|
||||
let GPoll::Final(value) = record::serve_input(&node, &ctx.promoted(&head, 0), &frames) else {
|
||||
panic!("expected a final record");
|
||||
};
|
||||
let Graphic::Group(group) = (unsafe { record::borrow_element::<Graphic>(out.rec(&value)) }) else {
|
||||
panic!("expected a group element");
|
||||
};
|
||||
assert!(group.row.is_none());
|
||||
let item = &group.content;
|
||||
assert_eq!(item.len(), 2);
|
||||
let lanes = item.typed_lanes::<Graphic>().expect("the run holds the adopted graphic lanes");
|
||||
let offset = item.layout().offset_of(ATTR_TRANSFORM, 0).unwrap();
|
||||
for (lane, (label, x)) in [("a", 1.), ("b", 2.)].into_iter().enumerate() {
|
||||
assert_eq!(text_of(lanes.element_ref(lane)), label, "lane {lane}");
|
||||
let transform: DAffine2 = unsafe { item.lanes().get(lane).rec().read(offset) };
|
||||
assert_eq!(transform.translation.x, x, "lane {lane}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_element_deep_copies_to_its_owned_form_and_replays() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(1 << 16).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let layout = graphic_layout();
|
||||
let rows = vec![(text("a"), translation(1.)), (text("b"), translation(2.))];
|
||||
let node = install(
|
||||
WrapNode::new(RecordSource::new(GraphicSource { layout: layout.clone(), rows }, &layout, &layout), &layout),
|
||||
wrap_layout_meta(),
|
||||
&[Some(&layout)],
|
||||
);
|
||||
let out = Node::<ContextImpl>::layout(&node).clone();
|
||||
|
||||
let head = ctx.index_head();
|
||||
let GPoll::Final(value) = record::serve_input(&node, &ctx.promoted(&head, 0), &frames) else {
|
||||
panic!("expected a final record");
|
||||
};
|
||||
let copy = unsafe { (out.element.clone_out)(out.rec(&value).ptr()) };
|
||||
|
||||
let replay_arena = Arena::new(1 << 16).unwrap();
|
||||
// Word storage: a parked element slot holds an 8-aligned reference.
|
||||
let mut slot = [0u64; 1];
|
||||
unsafe { (out.element.repark)(&*copy, slot.as_mut_ptr().cast(), &replay_arena) }.expect("the arena holds the replay");
|
||||
// SAFETY: the re-park wrote a parked `Graphic` element into `slot`.
|
||||
let Graphic::Group(group) = (unsafe { record::borrow_element::<Graphic>(record::Rec::new(slot.as_ptr().cast())) }) else {
|
||||
panic!("the replay restores the group element");
|
||||
};
|
||||
let item = &group.content;
|
||||
assert_eq!(item.len(), 2);
|
||||
let lanes = item.typed_lanes::<Graphic>().expect("the run holds the adopted graphic lanes");
|
||||
let offset = item.layout().offset_of(ATTR_TRANSFORM, 0).unwrap();
|
||||
for (lane, (label, x)) in [("a", 1.), ("b", 2.)].into_iter().enumerate() {
|
||||
assert_eq!(text_of(lanes.element_ref(lane)), label, "lane {lane}");
|
||||
let transform: DAffine2 = unsafe { item.lanes().get(lane).rec().read(offset) };
|
||||
assert_eq!(transform.translation.x, x, "lane {lane}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colors_fold_into_evenly_spaced_stops() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
struct ColorSource {
|
||||
layout: Layout,
|
||||
colors: Vec<Color>,
|
||||
}
|
||||
|
||||
impl<C: ExtractIndex> Node<C> for ColorSource {
|
||||
fn serve<'e, 'l>(&self, input: &C, slot: FrameClaim<'e, 'l>) -> GPoll<Served<'e>>
|
||||
where
|
||||
C: ExtractArena<ArenaRef = &'e Arena>,
|
||||
{
|
||||
let color = self.colors[input.innermost_index() as usize];
|
||||
let mut frame = slot;
|
||||
let arena = ExtractArena::arena(input);
|
||||
if frame.element(color, arena).is_none() {
|
||||
return GPoll::arena_exhausted();
|
||||
}
|
||||
// SAFETY: the writes above complete the record of this layout.
|
||||
GPoll::Final(unsafe { frame.finish_served() })
|
||||
}
|
||||
|
||||
fn extent_at<'x>(&self, _input: &C, _level: u8, _frames: &core_types::record::Frames<'x>) -> GPoll<Extent>
|
||||
where
|
||||
C: ExtractArena<ArenaRef = &'x Arena>,
|
||||
{
|
||||
GPoll::Final(Extent::Exactly(self.colors.len()))
|
||||
}
|
||||
|
||||
fn layout(&self) -> &Layout {
|
||||
&self.layout
|
||||
}
|
||||
}
|
||||
|
||||
let arena = Arena::new(1 << 16).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let layout = Layout::default().with_writes(1, record::element_write_hashed::<Color>(), &[]);
|
||||
let out = Layout::default().with_writes(0, record::element_write_hashed::<GradientStops>(), &[]);
|
||||
let build = |colors: Vec<Color>| install_flip(ToGradientNode::new(RecordSource::new(ColorSource { layout: layout.clone(), colors }, &layout, &layout), &layout), &out);
|
||||
let stops_of = |colors: Vec<Color>| {
|
||||
let node = build(colors);
|
||||
let GPoll::Final(record) = record::capture(&node, &ctx, &frames) else {
|
||||
panic!("expected a final record");
|
||||
};
|
||||
record.element::<GradientStops>()
|
||||
};
|
||||
|
||||
let three = stops_of(vec![Color::BLACK, Color::WHITE, Color::BLACK]);
|
||||
assert_eq!(three.iter().map(|stop| stop.position).collect::<Vec<_>>(), vec![0., 0.5, 1.]);
|
||||
assert_eq!(three.iter().map(|stop| stop.color).collect::<Vec<_>>(), vec![Color::BLACK, Color::WHITE, Color::BLACK]);
|
||||
|
||||
let single = stops_of(vec![Color::WHITE]);
|
||||
assert_eq!(single.iter().map(|stop| (stop.position, stop.color)).collect::<Vec<_>>(), vec![(0., Color::WHITE), (1., Color::WHITE)]);
|
||||
|
||||
let empty = stops_of(Vec::new());
|
||||
assert_eq!(empty.iter().map(|stop| (stop.position, stop.color)).collect::<Vec<_>>(), vec![(0., Color::BLACK), (1., Color::BLACK)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_converts_to_its_legacy_list() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(1 << 16).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let layout = graphic_layout();
|
||||
let rows = vec![(text("a"), translation(1.)), (text("b"), translation(2.))];
|
||||
let node = install(
|
||||
WrapNode::new(RecordSource::new(GraphicSource { layout: layout.clone(), rows }, &layout, &layout), &layout),
|
||||
wrap_layout_meta(),
|
||||
&[Some(&layout)],
|
||||
);
|
||||
let out = Node::<ContextImpl>::layout(&node).clone();
|
||||
let head = ctx.index_head();
|
||||
let GPoll::Final(value) = record::serve_input(&node, &ctx.promoted(&head, 0), &frames) else {
|
||||
panic!("expected a final record");
|
||||
};
|
||||
let Graphic::Group(group) = (unsafe { record::borrow_element::<Graphic>(out.rec(&value)) }) else {
|
||||
panic!("expected a group element");
|
||||
};
|
||||
|
||||
let legacy = graphic_types::graphic::group_to_legacy_list(group);
|
||||
assert_eq!(legacy.len(), 2);
|
||||
for (index, (label, x)) in [("a", 1.), ("b", 2.)].into_iter().enumerate() {
|
||||
assert_eq!(text_of(legacy.element(index).unwrap()), label, "item {index}");
|
||||
assert_eq!(legacy.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM, index).translation.x, x, "item {index}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flatten_reverses_wrap() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(1 << 16).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let layout = graphic_layout();
|
||||
let rows = vec![(text("a"), translation(1.)), (text("b"), translation(2.))];
|
||||
let wrapped = install(
|
||||
WrapNode::new(RecordSource::new(GraphicSource { layout: layout.clone(), rows }, &layout, &layout), &layout),
|
||||
wrap_layout_meta(),
|
||||
&[Some(&layout)],
|
||||
);
|
||||
let wrap_out = Node::<ContextImpl>::layout(&wrapped).clone();
|
||||
let head = ctx.index_head();
|
||||
let group = {
|
||||
// SAFETY: the element is cloned out inside the scope, so no borrow
|
||||
// into the frame escapes it. The clone is shallow, so the `'static`
|
||||
// the `GraphicSource` rows infer launders a borrow of `arena`: it is
|
||||
// contained because `arena` outlives every use below and this test
|
||||
// never resets it, so the interior stays resident for the whole
|
||||
// generation the group is read in.
|
||||
let scope = frames.scope();
|
||||
let GPoll::Final(value) = record::serve_input(&wrapped, &ctx.promoted(&head, 0), &scope) else {
|
||||
panic!("expected a final record");
|
||||
};
|
||||
unsafe { record::borrow_element::<Graphic>(wrap_out.rec(&value)) }.clone()
|
||||
};
|
||||
|
||||
// One row holding the wrapped group flattens back to the lanes, the
|
||||
// group's identity transform composed onto each child's.
|
||||
let node = build!(layout, vec![(group, DAffine2::IDENTITY)], false);
|
||||
assert_eq!(node.extent_at(&ctx, 0, &frames.reborrow()), GPoll::Final(Extent::Exactly(2)));
|
||||
|
||||
let head = ctx.index_head();
|
||||
for (lane, &(label, x)) in [("a", 1.), ("b", 2.)].iter().enumerate() {
|
||||
let GPoll::Final(record) = record::capture(&node, &ctx.promoted(&head, lane as u64), &frames) else {
|
||||
panic!("expected a final record");
|
||||
};
|
||||
assert_eq!(text_of(&record.element::<Graphic>()), label, "lane {lane}");
|
||||
let transform: DAffine2 = record.attr::<Transform>();
|
||||
assert_eq!(transform.translation.x, x, "lane {lane}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flatten_fully_composes_the_path() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(1 << 16).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let mut rows = fixture_rows();
|
||||
rows.push((group(vec![]), translation(9.)));
|
||||
let layout = graphic_layout();
|
||||
let node = build!(layout, rows, true);
|
||||
assert_eq!(node.extent_at(&ctx, 0, &frames.reborrow()), GPoll::Final(Extent::Exactly(3)), "the empty group contributes no leaves");
|
||||
|
||||
let head = ctx.index_head();
|
||||
let expected: [(&str, f64); 3] = [("a", 1.), ("b", 20.5), ("c", 4300.5)];
|
||||
for (lane, &(label, x)) in expected.iter().enumerate() {
|
||||
let GPoll::Final(record) = record::capture(&node, &ctx.promoted(&head, lane as u64), &frames) else {
|
||||
panic!("expected a final record");
|
||||
};
|
||||
assert_eq!(text_of(&record.element::<Graphic>()), label, "lane {lane}");
|
||||
let transform: DAffine2 = record.attr::<Transform>();
|
||||
assert_eq!(transform.translation.x, x, "lane {lane}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flatten_batch_matches_per_lane_eval() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(1 << 16).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let layout = graphic_layout();
|
||||
let node = build!(layout, fixture_rows(), true);
|
||||
let out = Node::<ContextImpl>::layout(&node).clone();
|
||||
let head = ctx.index_head();
|
||||
let scoped = ctx.promoted(&head, 0);
|
||||
|
||||
let mut scratch = vec![std::mem::MaybeUninit::<u64>::uninit(); 3 * out.lane_stride() / 8];
|
||||
let core_types::node::BatchStatus::Filled(batch, ..) = node.eval_batch(&scoped, 0..3, Some(&mut scratch), &frames) else {
|
||||
panic!("expected a filled batch");
|
||||
};
|
||||
let batch = batch.into_shared();
|
||||
assert_eq!(batch.len(), 3);
|
||||
let offset = out.offset_of(<Transform as AttributeMarker>::NAME, 0).unwrap();
|
||||
for lane in 0..3 {
|
||||
let GPoll::Final(record) = record::capture(&node, &ctx.promoted(&head, lane as u64), &frames) else {
|
||||
panic!("expected a final record");
|
||||
};
|
||||
let single = text_of(&record.element::<Graphic>()).to_string();
|
||||
assert_eq!(text_of(unsafe { record::borrow_element::<Graphic>(batch.get(lane).rec()) }), single, "lane {lane}");
|
||||
let batched: DAffine2 = unsafe { batch.get(lane).rec().read(offset) };
|
||||
let direct: DAffine2 = record.attr::<Transform>();
|
||||
assert_eq!(batched, direct, "lane {lane}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
[package]
|
||||
name = "graphene-std"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
description = "Graphene standard library"
|
||||
authors = ["Graphite Authors <contact@graphite.art>"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
[features]
|
||||
default = ["wgpu"]
|
||||
gpu = []
|
||||
wgpu = ["gpu", "graph-craft/wgpu", "graphene-application-io/wgpu", "graphene-canvas-utils?/wgpu"]
|
||||
wasm = [
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
"web-sys",
|
||||
"graphene-application-io/wasm",
|
||||
"image/png",
|
||||
"core-types/wasm",
|
||||
"vector-types/wasm",
|
||||
"graphic-types/wasm",
|
||||
"text-nodes/wasm",
|
||||
"raster-nodes/wasm",
|
||||
"vector-nodes/wasm",
|
||||
"graphene-core/wasm",
|
||||
"graph-craft/wasm",
|
||||
"dep:graphene-canvas-utils"
|
||||
]
|
||||
image-compare = []
|
||||
vello = ["gpu"]
|
||||
resvg = []
|
||||
shader-nodes = ["raster-nodes/shader-nodes"]
|
||||
|
||||
[dependencies]
|
||||
# Local dependencies
|
||||
dyn-any = { workspace = true }
|
||||
graph-craft = { workspace = true }
|
||||
wgpu-executor = { workspace = true }
|
||||
core-types = { workspace = true }
|
||||
vector-types = { workspace = true }
|
||||
graphic-types = { workspace = true }
|
||||
blending-nodes = { workspace = true }
|
||||
text-nodes = { workspace = true }
|
||||
transform-nodes = { workspace = true }
|
||||
vector-nodes = { workspace = true }
|
||||
path-bool-nodes = { workspace = true }
|
||||
math-nodes = { workspace = true }
|
||||
rendering = { workspace = true }
|
||||
graphene-application-io = { workspace = true }
|
||||
raster-nodes = { workspace = true }
|
||||
brush-nodes = { workspace = true }
|
||||
graphene-core = { workspace = true }
|
||||
graphic-nodes = { workspace = true }
|
||||
repeat-nodes = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
log = { workspace = true }
|
||||
glam = { workspace = true }
|
||||
node-macro = { workspace = true }
|
||||
reqwest = { workspace = true }
|
||||
image = { workspace = true }
|
||||
base64 = { workspace = true }
|
||||
wgpu = { workspace = true }
|
||||
bytemuck = { workspace = true }
|
||||
|
||||
# Optional local dependencies
|
||||
graphene-canvas-utils = { workspace = true, optional = true }
|
||||
|
||||
# Optional workspace dependencies
|
||||
wasm-bindgen = { workspace = true, optional = true }
|
||||
wasm-bindgen-futures = { workspace = true, optional = true }
|
||||
tokio = { workspace = true, optional = true }
|
||||
vello = { workspace = true }
|
||||
vello_encoding = { workspace = true }
|
||||
web-sys = { workspace = true, optional = true, features = [
|
||||
"Window",
|
||||
"CanvasRenderingContext2d",
|
||||
"ImageData",
|
||||
"Document",
|
||||
"Navigator",
|
||||
"Gpu",
|
||||
"HtmlCanvasElement",
|
||||
"HtmlImageElement",
|
||||
"ImageBitmapRenderingContext",
|
||||
] }
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { workspace = true }
|
||||
@@ -0,0 +1,119 @@
|
||||
pub mod platform_application_io;
|
||||
pub mod render_background;
|
||||
pub mod render_cache;
|
||||
pub mod render_node;
|
||||
pub mod render_pixel_preview;
|
||||
pub mod runtime;
|
||||
pub mod text;
|
||||
pub use blending_nodes;
|
||||
pub use brush_nodes as brush;
|
||||
pub use core_types::*;
|
||||
pub use graphene_application_io as application_io;
|
||||
pub use graphene_core;
|
||||
pub use graphene_core::debug;
|
||||
pub use graphic_nodes;
|
||||
pub use graphic_types::{Artboard, Graphic, Vector};
|
||||
pub use math_nodes;
|
||||
pub use path_bool_nodes;
|
||||
pub use raster_nodes;
|
||||
pub use repeat_nodes;
|
||||
pub use text_nodes;
|
||||
pub use transform_nodes;
|
||||
pub use vector_nodes;
|
||||
pub use vector_types;
|
||||
|
||||
/// Backward compatibility re-exports
|
||||
pub mod vector {
|
||||
pub use graphic_types::Vector;
|
||||
pub use vector_types::vector::{VectorModification, VectorModificationType, misc, style};
|
||||
pub use vector_types::*;
|
||||
|
||||
// Re-export commonly used types and submodules
|
||||
pub use vector_types::vector::algorithms;
|
||||
pub use vector_types::vector::click_target;
|
||||
pub use vector_types::vector::misc::HandleId;
|
||||
pub use vector_types::vector::{PointId, RegionId, SegmentId, StrokeId};
|
||||
pub use vector_types::vector::{deserialize_hashmap, serialize_hashmap, serialize_hashmap_as_sorted_object};
|
||||
|
||||
// Re-export HandleExt trait and NoHashBuilder
|
||||
pub use vector_types::vector::HandleExt;
|
||||
pub use vector_types::vector::NoHashBuilder;
|
||||
|
||||
// Re-export vector node modules and functions
|
||||
pub use vector_nodes::*;
|
||||
}
|
||||
|
||||
pub mod graphic {
|
||||
pub use graphic_nodes::graphic::*;
|
||||
pub use graphic_types::graphic::*;
|
||||
}
|
||||
|
||||
pub mod artboard {
|
||||
pub use graphic_nodes::artboard::*;
|
||||
pub use graphic_types::artboard::*;
|
||||
}
|
||||
|
||||
pub mod subpath {
|
||||
pub use vector_types::subpath::*;
|
||||
}
|
||||
|
||||
pub mod gradient {
|
||||
pub use vector_types::{Gradient, GradientStop};
|
||||
}
|
||||
|
||||
pub mod transform {
|
||||
pub use core_types::transform::*;
|
||||
pub use vector_types::ReferencePoint;
|
||||
}
|
||||
|
||||
pub mod repeat {
|
||||
pub use repeat_nodes::repeat_nodes::*;
|
||||
}
|
||||
|
||||
pub mod math {
|
||||
pub use core_types::math::quad;
|
||||
|
||||
pub mod math_ext {
|
||||
pub use vector_types::{QuadExt, RectExt};
|
||||
}
|
||||
}
|
||||
|
||||
pub mod context {
|
||||
pub use graphene_core::context::*;
|
||||
}
|
||||
|
||||
// Re-export graphene_core modules for backward compatibility
|
||||
pub mod ops {
|
||||
pub use core_types::ops::*;
|
||||
pub use graphene_core::ops::*;
|
||||
}
|
||||
|
||||
pub mod extract_xy {
|
||||
pub use graphene_core::extract_xy::*;
|
||||
}
|
||||
|
||||
pub mod animation {
|
||||
pub use graphene_core::animation::*;
|
||||
}
|
||||
|
||||
/// stop gap solutions until all paths have been replaced with their absolute ones
|
||||
pub mod renderer {
|
||||
pub use core_types::math::quad::Quad;
|
||||
pub use core_types::math::rect::Rect;
|
||||
pub use rendering::*;
|
||||
}
|
||||
|
||||
pub mod raster {
|
||||
pub use graphic_types::raster_types::*;
|
||||
pub use raster_nodes::adjustments::*;
|
||||
pub use raster_nodes::*;
|
||||
}
|
||||
|
||||
pub mod raster_types {
|
||||
pub use graphic_types::raster_types::*;
|
||||
}
|
||||
|
||||
pub mod memo {
|
||||
pub use core_types::memo::*;
|
||||
pub use graphene_core::memo::*;
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
#[cfg(target_family = "wasm")]
|
||||
use base64::Engine;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use canvas_utils::{Canvas, CanvasHandle};
|
||||
#[cfg(target_family = "wasm")]
|
||||
use core_types::attribute::{Attr, OwnedAttr, Transform};
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::gpoll::GPoll;
|
||||
use core_types::list::Item;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use core_types::list::List;
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
use core_types::math::bbox::Bbox;
|
||||
use core_types::ops::Convert;
|
||||
use core_types::runtime::SourceFuture;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use core_types::transform::Footprint;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use core_types::{ATTR_TRANSFORM, WasmNotSend};
|
||||
use core_types::{Color, Ctx};
|
||||
pub use graph_craft::application_io::resource::{Resource, ResourceHash};
|
||||
pub use graph_craft::application_io::*;
|
||||
pub use graph_craft::document::value::RenderOutputType;
|
||||
#[cfg(target_family = "wasm")]
|
||||
pub use graphene_canvas_utils as canvas_utils;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use graphic_types::Graphic;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use graphic_types::IntoGraphicList;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use graphic_types::Vector;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use graphic_types::markers::EditorMergedLayers;
|
||||
use graphic_types::raster_types::Image;
|
||||
use graphic_types::raster_types::{CPU, GPU, Raster};
|
||||
#[cfg(target_family = "wasm")]
|
||||
use graphic_types::vector_types::gradient::Gradient;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use rendering::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
|
||||
|
||||
fn parse_headers(headers: &str) -> reqwest::header::HeaderMap {
|
||||
use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
|
||||
|
||||
let mut header_map = HeaderMap::new();
|
||||
for line in headers.lines() {
|
||||
if let Some((key, value)) = line.split_once(':') {
|
||||
let Ok(header_name) = HeaderName::from_bytes(key.trim().as_bytes()) else { continue };
|
||||
let Ok(header_value) = HeaderValue::from_str(value.trim()) else { continue };
|
||||
header_map.insert(header_name, header_value);
|
||||
}
|
||||
}
|
||||
header_map
|
||||
}
|
||||
|
||||
/// Sends an HTTP GET request to a specified URL and optionally waits for the response (unless discarded) which is output as a string.
|
||||
#[node_macro::node(category("Web Request"))]
|
||||
async fn get_request(
|
||||
_: impl Ctx,
|
||||
_primary: (),
|
||||
/// The web address to send the GET request to.
|
||||
#[name("URL")]
|
||||
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: 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);
|
||||
|
||||
if discard_result {
|
||||
#[cfg(target_family = "wasm")]
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
let _ = request.send().await;
|
||||
});
|
||||
#[cfg(all(not(target_family = "wasm"), feature = "tokio"))]
|
||||
tokio::spawn(async move {
|
||||
let _ = request.send().await;
|
||||
});
|
||||
return Item::default();
|
||||
}
|
||||
|
||||
let Ok(response) = request.send().await else {
|
||||
return Item::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.
|
||||
#[node_macro::node(category("Web Request"))]
|
||||
async fn post_request(
|
||||
_: impl Ctx,
|
||||
_primary: (),
|
||||
/// The web address to send the POST request to.
|
||||
#[name("URL")]
|
||||
url: Item<String>,
|
||||
/// The binary data to include in the body of the POST request.
|
||||
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: 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.element().as_ref().to_vec();
|
||||
let request = reqwest::Client::new().post(url).body(body_bytes).headers(header_map);
|
||||
|
||||
if discard_result {
|
||||
#[cfg(target_family = "wasm")]
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
let _ = request.send().await;
|
||||
});
|
||||
#[cfg(all(not(target_family = "wasm"), feature = "tokio"))]
|
||||
tokio::spawn(async move {
|
||||
let _ = request.send().await;
|
||||
});
|
||||
return Item::default();
|
||||
}
|
||||
|
||||
let Ok(response) = request.send().await else {
|
||||
return Item::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: 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: 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]
|
||||
})
|
||||
.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(_: 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,
|
||||
Err(error) => {
|
||||
log::error!("HTTP request for `{url}` failed: {error}");
|
||||
return placeholder();
|
||||
}
|
||||
};
|
||||
|
||||
match response.bytes().await {
|
||||
Ok(bytes) => Item::new_from_element(Resource::new(bytes)),
|
||||
Err(error) => {
|
||||
log::error!("Failed to read HTTP response for `{url}`: {error}");
|
||||
placeholder()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts raw binary data to a raster image.
|
||||
///
|
||||
/// 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: Item<Resource>) -> Item<Raster<CPU>> {
|
||||
let data = data.into_element();
|
||||
let Some(image) = image::load_from_memory(data.as_ref()).ok() else {
|
||||
return Item::default();
|
||||
};
|
||||
let image = image.to_rgba32f();
|
||||
let image = Image {
|
||||
data: image
|
||||
.chunks(4)
|
||||
.map(|pixel| {
|
||||
// Decoded bytes are unassociated gamma sRGB; premultiply in gamma then lift to linear
|
||||
let a = pixel[3];
|
||||
Color::from_gamma_srgb_channels(pixel[0] * a, pixel[1] * a, pixel[2] * a, a)
|
||||
})
|
||||
.collect(),
|
||||
width: image.width(),
|
||||
height: image.height(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
Item::new_from_element(Raster::new_cpu(image))
|
||||
}
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
#[node_macro::node(category(""))]
|
||||
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*.
|
||||
#[cfg(target_family = "wasm")]
|
||||
#[node_macro::node(category(""))]
|
||||
async fn rasterize<T: WasmNotSend + Clone>(
|
||||
_: impl Ctx,
|
||||
_: (),
|
||||
#[implementations(
|
||||
List<Vector>,
|
||||
List<Raster<CPU>>,
|
||||
List<Graphic>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
)]
|
||||
data: List<T>,
|
||||
footprint: Item<Footprint>,
|
||||
canvas: Item<CanvasHandle>,
|
||||
) -> (Raster<CPU>, Attr<Transform>, OwnedAttr<EditorMergedLayers>)
|
||||
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");
|
||||
// A zero-size raster renders as nothing, matching the legacy empty list
|
||||
return (Raster::new_cpu(Image::default()), Attr(DAffine2::IDENTITY), OwnedAttr::new(None));
|
||||
}
|
||||
|
||||
// Snapshot the input as a List<Graphic> so the renderer can recurse into the original child layers
|
||||
// when collecting metadata, exposing their click targets to editor tools (same mechanism as Boolean Operation).
|
||||
// The copy is owned before the first await: the input's arena content dies with the spawning evaluation.
|
||||
let upstream_graphic_list = data.clone().into_graphic_list();
|
||||
let merged_layers = OwnedAttr::new(Some(&upstream_graphic_list));
|
||||
|
||||
let mut render = SvgRender::new();
|
||||
let aabb = Bbox::from_transform(footprint.transform).to_axis_aligned_bbox();
|
||||
let size = aabb.size();
|
||||
let resolution = footprint.resolution;
|
||||
let render_params = RenderParams {
|
||||
footprint,
|
||||
for_export: true,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
for transform in data.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM) {
|
||||
*transform = DAffine2::from_translation(-aabb.start) * *transform;
|
||||
}
|
||||
data.render_svg(&mut render, &render_params);
|
||||
render.format_svg(DVec2::ZERO, size);
|
||||
let svg_string = render.svg.to_svg_string();
|
||||
|
||||
canvas.set_resolution(resolution);
|
||||
let context = canvas.context();
|
||||
|
||||
let preamble = "data:image/svg+xml;base64,";
|
||||
let mut base64_string = String::with_capacity(preamble.len() + svg_string.len() * 4);
|
||||
base64_string.push_str(preamble);
|
||||
base64::engine::general_purpose::STANDARD.encode_string(svg_string, &mut base64_string);
|
||||
|
||||
let image_data = web_sys::HtmlImageElement::new().unwrap();
|
||||
image_data.set_src(base64_string.as_str());
|
||||
wasm_bindgen_futures::JsFuture::from(image_data.decode()).await.unwrap();
|
||||
context
|
||||
.draw_image_with_html_image_element_and_dw_and_dh(&image_data, 0., 0., resolution.x as f64, resolution.y as f64)
|
||||
.unwrap();
|
||||
|
||||
let rasterized = context.get_image_data(0, 0, resolution.x as i32, resolution.y as i32).unwrap();
|
||||
|
||||
let image = Image::from_image_data(&rasterized.data().0, resolution.x as u32, resolution.y as u32);
|
||||
(Raster::new_cpu(image), Attr(footprint.transform), merged_layers)
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), inject_scope)]
|
||||
pub fn editor_api(_: impl Ctx, #[scope("editor-api")] editor_api: Item<Arc<PlatformEditorApi>>) -> Item<Arc<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");
|
||||
})
|
||||
}
|
||||
|
||||
#[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
|
||||
.application_io
|
||||
.as_ref()
|
||||
.expect("ApplicationIo not not available")
|
||||
.gpu_executor()
|
||||
.expect("GPU executor not available")
|
||||
}
|
||||
|
||||
#[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()
|
||||
}
|
||||
@@ -0,0 +1,499 @@
|
||||
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};
|
||||
use glam::{Affine2, UVec2, Vec2};
|
||||
use graph_craft::document::value::{RenderOutput, RenderOutputType};
|
||||
use graphic_types::raster_types::Texture;
|
||||
use rendering::{RenderParams, SvgRender, SvgRenderOutput};
|
||||
use std::fmt::Write;
|
||||
use wgpu::util::DeviceExt;
|
||||
use wgpu_executor::{WgpuExecutor, WgpuPipeline, WgpuPipelineCache};
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
fn render_background(
|
||||
ctx: impl Ctx + ExtractFootprint + ExtractVarArgs,
|
||||
#[scope(composite_background_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>,
|
||||
data: Item<RenderOutput>,
|
||||
) -> Item<RenderOutput> {
|
||||
let footprint = ctx.footprint();
|
||||
let render_params = ctx
|
||||
.vararg(0)
|
||||
.expect("Did not find var args")
|
||||
.downcast_ref::<RenderParams>()
|
||||
.expect("Downcasting render params yielded invalid type");
|
||||
|
||||
if !render_params.to_canvas() || render_params.viewport_zoom <= 0.0 {
|
||||
return data;
|
||||
}
|
||||
|
||||
let RenderOutput { data: foreground_data, metadata } = data.into_element();
|
||||
let mut render_params = render_params.clone();
|
||||
render_params.footprint = *footprint;
|
||||
|
||||
let data = match foreground_data {
|
||||
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,
|
||||
document_to_screen: doc_to_screen,
|
||||
zoom: render_params.viewport_zoom.to_f32(),
|
||||
});
|
||||
|
||||
RenderOutputType::Texture(blended)
|
||||
}
|
||||
RenderOutputType::Svg {
|
||||
svg: foreground_svg,
|
||||
image_data: foreground_images,
|
||||
} => {
|
||||
let mut render = SvgRender::new();
|
||||
|
||||
let logical_transform = glam::DAffine2::from_scale(glam::DVec2::splat(1.0 / render_params.scale)) * render_params.footprint.transform;
|
||||
|
||||
if render_params.viewport_zoom > 0. {
|
||||
let draw_checkerboard = |render: &mut SvgRender, rect: vello::kurbo::Rect, pattern_origin: glam::DVec2, checker_id_prefix: &str| {
|
||||
let checker_id = format!("{checker_id_prefix}-{}", generate_uuid());
|
||||
let cell_size = 8. / render_params.viewport_zoom;
|
||||
let pattern_size = cell_size * 2.;
|
||||
|
||||
write!(
|
||||
&mut render.svg_defs,
|
||||
r##"<pattern id="{checker_id}" x="{}" y="{}" width="{pattern_size}" height="{pattern_size}" patternUnits="userSpaceOnUse"><rect width="{pattern_size}" height="{pattern_size}" fill="#ffffff" /><rect x="{cell_size}" y="0" width="{cell_size}" height="{cell_size}" fill="#cccccc" /><rect x="0" y="{cell_size}" width="{cell_size}" height="{cell_size}" fill="#cccccc" /></pattern>"##,
|
||||
pattern_origin.x,
|
||||
pattern_origin.y,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
render.leaf_tag("rect", |attributes| {
|
||||
attributes.push("x", rect.x0.to_string());
|
||||
attributes.push("y", rect.y0.to_string());
|
||||
attributes.push("width", rect.width().to_string());
|
||||
attributes.push("height", rect.height().to_string());
|
||||
attributes.push("fill", format!("url(#{checker_id})"));
|
||||
});
|
||||
};
|
||||
|
||||
if metadata.backgrounds.is_empty() {
|
||||
if render_params.scale > 0. {
|
||||
let logical_resolution = render_params.footprint.resolution.as_dvec2() / render_params.scale;
|
||||
let logical_footprint = Footprint {
|
||||
transform: logical_transform,
|
||||
resolution: logical_resolution.round().as_uvec2().max(glam::UVec2::ONE),
|
||||
..render_params.footprint
|
||||
};
|
||||
let bounds = logical_footprint.viewport_bounds_in_local_space();
|
||||
let min = bounds.start.floor();
|
||||
let max = bounds.end.ceil();
|
||||
|
||||
if min.is_finite() && max.is_finite() {
|
||||
let rect = vello::kurbo::Rect::new(min.x, min.y, max.x, max.y);
|
||||
draw_checkerboard(&mut render, rect, glam::DVec2::ZERO, "checkered-viewport");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for background in &metadata.backgrounds {
|
||||
let [a, b] = [background.location, background.location + background.dimensions];
|
||||
let rect = vello::kurbo::Rect::new(a.x.min(b.x), a.y.min(b.y), a.x.max(b.x), a.y.max(b.y));
|
||||
draw_checkerboard(&mut render, rect, glam::DVec2::new(rect.x0, rect.y0), "checkered-artboard");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let logical_resolution = render_params.footprint.resolution.as_dvec2() / render_params.scale;
|
||||
render.wrap_with_transform(logical_transform, Some(logical_resolution));
|
||||
|
||||
let background = SvgRenderOutput::from(render);
|
||||
assert!(background.svg_defs.is_empty());
|
||||
|
||||
let svg = format!("{}{}", background.svg, foreground_svg);
|
||||
let image_data = foreground_images;
|
||||
|
||||
RenderOutputType::Svg { svg, image_data }
|
||||
}
|
||||
_ => unreachable!("Render background node received unsupported render output type"),
|
||||
};
|
||||
|
||||
Item::new_from_element(RenderOutput { data, metadata })
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), inject_scope)]
|
||||
fn composite_background_pipeline(
|
||||
_ctx: impl Ctx,
|
||||
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Item<Option<wgpu_executor::WgpuExecutorHandle>>,
|
||||
#[data] pipeline: WgpuPipelineCache,
|
||||
) -> Item<WgpuPipelineCache> {
|
||||
if let Some(executor) = executor.into_element() {
|
||||
executor.pipeline_init::<CompositeBackground>(pipeline);
|
||||
}
|
||||
Item::new_from_element(pipeline.clone())
|
||||
}
|
||||
|
||||
pub struct CompositeBackground {
|
||||
checker_rect_pipeline: wgpu::RenderPipeline,
|
||||
checker_viewport_pipeline: wgpu::RenderPipeline,
|
||||
fullscreen_pipeline: wgpu::RenderPipeline,
|
||||
checker_bind_group_layout: wgpu::BindGroupLayout,
|
||||
fullscreen_bind_group_layout: wgpu::BindGroupLayout,
|
||||
sampler: wgpu::Sampler,
|
||||
}
|
||||
|
||||
pub struct CompositeBackgroundArgs<'a> {
|
||||
foreground: &'a wgpu::Texture,
|
||||
backgrounds: &'a [rendering::Background],
|
||||
document_to_screen: Affine2,
|
||||
zoom: f32,
|
||||
}
|
||||
|
||||
impl WgpuPipeline for CompositeBackground {
|
||||
type Args<'a> = CompositeBackgroundArgs<'a>;
|
||||
type Out = Texture;
|
||||
|
||||
fn create(executor: &WgpuExecutor) -> Self {
|
||||
let device = &executor.context().device;
|
||||
let format = wgpu::TextureFormat::Rgba8Unorm;
|
||||
let checker_rect_shader = device.create_shader_module(wgpu::include_wgsl!("render_background_checker_rect.wgsl"));
|
||||
let checker_viewport_shader = device.create_shader_module(wgpu::include_wgsl!("render_background_checker_viewport.wgsl"));
|
||||
let fullscreen_shader = device.create_shader_module(wgpu::include_wgsl!("render_background_fullscreen.wgsl"));
|
||||
|
||||
let checker_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("background_checker_bind_group_layout"),
|
||||
entries: &[wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
}],
|
||||
});
|
||||
|
||||
let checker_rect_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("background_checker_rect_pipeline_layout"),
|
||||
bind_group_layouts: &[Some(&checker_bind_group_layout)],
|
||||
immediate_size: 0,
|
||||
});
|
||||
|
||||
let checker_viewport_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("background_checker_viewport_pipeline_layout"),
|
||||
bind_group_layouts: &[Some(&checker_bind_group_layout)],
|
||||
immediate_size: 0,
|
||||
});
|
||||
|
||||
let fullscreen_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("background_fullscreen_bind_group_layout"),
|
||||
entries: &[
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Texture {
|
||||
multisampled: false,
|
||||
view_dimension: wgpu::TextureViewDimension::D2,
|
||||
sample_type: wgpu::TextureSampleType::Float { filterable: true },
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
let fullscreen_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("background_fullscreen_pipeline_layout"),
|
||||
bind_group_layouts: &[Some(&fullscreen_bind_group_layout)],
|
||||
immediate_size: 0,
|
||||
});
|
||||
|
||||
let checker_rect_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("background_checker_rect_pipeline"),
|
||||
layout: Some(&checker_rect_pipeline_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &checker_rect_shader,
|
||||
entry_point: Some("vs_main"),
|
||||
compilation_options: Default::default(),
|
||||
buffers: &[],
|
||||
},
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &checker_rect_shader,
|
||||
entry_point: Some("fs_main"),
|
||||
compilation_options: Default::default(),
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
format,
|
||||
blend: Some(wgpu::BlendState::ALPHA_BLENDING),
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
}),
|
||||
primitive: wgpu::PrimitiveState {
|
||||
topology: wgpu::PrimitiveTopology::TriangleList,
|
||||
..Default::default()
|
||||
},
|
||||
depth_stencil: None,
|
||||
multisample: wgpu::MultisampleState::default(),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
});
|
||||
|
||||
let checker_viewport_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("background_checker_viewport_pipeline"),
|
||||
layout: Some(&checker_viewport_pipeline_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &checker_viewport_shader,
|
||||
entry_point: Some("vs_main"),
|
||||
compilation_options: Default::default(),
|
||||
buffers: &[],
|
||||
},
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &checker_viewport_shader,
|
||||
entry_point: Some("fs_main"),
|
||||
compilation_options: Default::default(),
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
format,
|
||||
blend: None,
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
}),
|
||||
primitive: wgpu::PrimitiveState {
|
||||
topology: wgpu::PrimitiveTopology::TriangleList,
|
||||
..Default::default()
|
||||
},
|
||||
depth_stencil: None,
|
||||
multisample: wgpu::MultisampleState::default(),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
});
|
||||
|
||||
let fullscreen_blend = wgpu::BlendState {
|
||||
color: wgpu::BlendComponent {
|
||||
src_factor: wgpu::BlendFactor::SrcAlpha,
|
||||
dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
|
||||
operation: wgpu::BlendOperation::Add,
|
||||
},
|
||||
alpha: wgpu::BlendComponent {
|
||||
src_factor: wgpu::BlendFactor::One,
|
||||
dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
|
||||
operation: wgpu::BlendOperation::Add,
|
||||
},
|
||||
};
|
||||
|
||||
let fullscreen_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("background_fullscreen_pipeline"),
|
||||
layout: Some(&fullscreen_pipeline_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &fullscreen_shader,
|
||||
entry_point: Some("vs_main"),
|
||||
compilation_options: Default::default(),
|
||||
buffers: &[],
|
||||
},
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &fullscreen_shader,
|
||||
entry_point: Some("fs_main"),
|
||||
compilation_options: Default::default(),
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
format,
|
||||
blend: Some(fullscreen_blend),
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
}),
|
||||
primitive: wgpu::PrimitiveState {
|
||||
topology: wgpu::PrimitiveTopology::TriangleList,
|
||||
..Default::default()
|
||||
},
|
||||
depth_stencil: None,
|
||||
multisample: wgpu::MultisampleState::default(),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
});
|
||||
|
||||
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
|
||||
label: Some("background_fullscreen_sampler"),
|
||||
mag_filter: wgpu::FilterMode::Linear,
|
||||
min_filter: wgpu::FilterMode::Linear,
|
||||
mipmap_filter: wgpu::MipmapFilterMode::Nearest,
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
Self {
|
||||
checker_rect_pipeline,
|
||||
checker_viewport_pipeline,
|
||||
fullscreen_pipeline,
|
||||
checker_bind_group_layout,
|
||||
fullscreen_bind_group_layout,
|
||||
sampler,
|
||||
}
|
||||
}
|
||||
|
||||
fn run<'a>(&'a self, executor: &'a WgpuExecutor, args: &'a Self::Args<'_>) -> Self::Out {
|
||||
let &CompositeBackgroundArgs {
|
||||
foreground,
|
||||
backgrounds,
|
||||
document_to_screen,
|
||||
zoom,
|
||||
} = args;
|
||||
|
||||
let foreground_size = foreground.size();
|
||||
let output = executor.request_texture(UVec2::new(foreground_size.width, foreground_size.height));
|
||||
|
||||
if zoom <= 0. {
|
||||
return output;
|
||||
}
|
||||
|
||||
let device = &executor.context().device;
|
||||
let queue = &executor.context().queue;
|
||||
|
||||
let checker_size_doc = 8. / zoom;
|
||||
let screen_to_document = document_to_screen.inverse();
|
||||
let viewport_size = output.size();
|
||||
let viewport_size = Vec2::new(viewport_size.width as f32, viewport_size.height as f32);
|
||||
|
||||
let output_view = output.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let foreground_view = foreground.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
|
||||
let checker_draws = if backgrounds.is_empty() {
|
||||
vec![(
|
||||
3,
|
||||
self.create_checker_bind_group(device, CompositeUniforms::fullscreen(viewport_size, screen_to_document, checker_size_doc)),
|
||||
)]
|
||||
} else {
|
||||
backgrounds
|
||||
.iter()
|
||||
.filter_map(|background| {
|
||||
let a = background.location.as_vec2();
|
||||
let b = (background.location + background.dimensions).as_vec2();
|
||||
|
||||
let min = a.min(b);
|
||||
let max = a.max(b);
|
||||
|
||||
if max.x <= min.x || max.y <= min.y {
|
||||
return None;
|
||||
}
|
||||
|
||||
let uniforms = CompositeUniforms::rect(min, max, document_to_screen, viewport_size, checker_size_doc);
|
||||
Some((6, self.create_checker_bind_group(device, uniforms)))
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
|
||||
let fullscreen_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("background_fullscreen_bind_group"),
|
||||
layout: &self.fullscreen_bind_group_layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: wgpu::BindingResource::Sampler(&self.sampler),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: wgpu::BindingResource::TextureView(&foreground_view),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("background_encoder") });
|
||||
|
||||
{
|
||||
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("background_pass"),
|
||||
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||
view: &output_view,
|
||||
resolve_target: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
depth_slice: None,
|
||||
})],
|
||||
depth_stencil_attachment: None,
|
||||
timestamp_writes: None,
|
||||
occlusion_query_set: None,
|
||||
multiview_mask: None,
|
||||
});
|
||||
|
||||
if backgrounds.is_empty() {
|
||||
pass.set_pipeline(&self.checker_viewport_pipeline);
|
||||
for (vertex_count, bind_group) in &checker_draws {
|
||||
pass.set_bind_group(0, bind_group, &[]);
|
||||
pass.draw(0..*vertex_count, 0..1);
|
||||
}
|
||||
} else {
|
||||
pass.set_pipeline(&self.checker_rect_pipeline);
|
||||
for (vertex_count, bind_group) in &checker_draws {
|
||||
pass.set_bind_group(0, bind_group, &[]);
|
||||
pass.draw(0..*vertex_count, 0..1);
|
||||
}
|
||||
}
|
||||
|
||||
pass.set_pipeline(&self.fullscreen_pipeline);
|
||||
pass.set_bind_group(0, &fullscreen_bind_group, &[]);
|
||||
pass.draw(0..3, 0..1);
|
||||
}
|
||||
|
||||
queue.submit(std::iter::once(encoder.finish()));
|
||||
|
||||
output
|
||||
}
|
||||
}
|
||||
|
||||
impl CompositeBackground {
|
||||
fn create_checker_bind_group(&self, device: &wgpu::Device, uniforms: CompositeUniforms) -> wgpu::BindGroup {
|
||||
let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("background_checker_uniforms"),
|
||||
contents: bytemuck::bytes_of(&uniforms),
|
||||
usage: wgpu::BufferUsages::UNIFORM,
|
||||
});
|
||||
|
||||
device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("background_checker_bind_group"),
|
||||
layout: &self.checker_bind_group_layout,
|
||||
entries: &[wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: buffer.as_entire_binding(),
|
||||
}],
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
|
||||
struct CompositeUniforms {
|
||||
transform_x: [f32; 2],
|
||||
transform_y: [f32; 2],
|
||||
transform_translation: [f32; 2],
|
||||
rect_min: [f32; 2],
|
||||
rect_max: [f32; 2],
|
||||
viewport_size: [f32; 2],
|
||||
pattern_origin: [f32; 2],
|
||||
checker_size: f32,
|
||||
_pad: f32,
|
||||
}
|
||||
|
||||
impl CompositeUniforms {
|
||||
fn fullscreen(viewport_size: Vec2, screen_to_document: Affine2, checker_size_doc: f32) -> Self {
|
||||
Self::new(screen_to_document, Vec2::ZERO, Vec2::ZERO, viewport_size, Vec2::ZERO, checker_size_doc)
|
||||
}
|
||||
|
||||
fn rect(rect_min: Vec2, rect_max: Vec2, document_to_screen: Affine2, viewport_size: Vec2, checker_size_doc: f32) -> Self {
|
||||
Self::new(document_to_screen, rect_min, rect_max, viewport_size, rect_min, checker_size_doc)
|
||||
}
|
||||
|
||||
fn new(transform: Affine2, rect_min: Vec2, rect_max: Vec2, viewport_size: Vec2, pattern_origin: Vec2, checker_size: f32) -> Self {
|
||||
Self {
|
||||
transform_x: transform.matrix2.x_axis.to_array(),
|
||||
transform_y: transform.matrix2.y_axis.to_array(),
|
||||
transform_translation: transform.translation.to_array(),
|
||||
rect_min: rect_min.to_array(),
|
||||
rect_max: rect_max.to_array(),
|
||||
viewport_size: viewport_size.to_array(),
|
||||
pattern_origin: pattern_origin.to_array(),
|
||||
checker_size,
|
||||
_pad: 0.,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
struct CompositeUniforms {
|
||||
transform_x: vec2<f32>,
|
||||
transform_y: vec2<f32>,
|
||||
transform_translation: vec2<f32>,
|
||||
rect_min: vec2<f32>,
|
||||
rect_max: vec2<f32>,
|
||||
viewport_size: vec2<f32>,
|
||||
pattern_origin: vec2<f32>,
|
||||
checker_size: f32,
|
||||
_pad: f32,
|
||||
};
|
||||
|
||||
@group(0) @binding(0)
|
||||
var<uniform> uniforms: CompositeUniforms;
|
||||
|
||||
struct VertexOutput {
|
||||
@builtin(position) position: vec4<f32>,
|
||||
@location(0) document_position: vec2<f32>,
|
||||
};
|
||||
|
||||
@vertex
|
||||
fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput {
|
||||
let document_corners = array<vec2<f32>, 6>(
|
||||
uniforms.rect_min,
|
||||
vec2<f32>(uniforms.rect_max.x, uniforms.rect_min.y),
|
||||
vec2<f32>(uniforms.rect_min.x, uniforms.rect_max.y),
|
||||
vec2<f32>(uniforms.rect_min.x, uniforms.rect_max.y),
|
||||
vec2<f32>(uniforms.rect_max.x, uniforms.rect_min.y),
|
||||
uniforms.rect_max,
|
||||
);
|
||||
let document_position = document_corners[vertex_index];
|
||||
|
||||
let transformed = uniforms.transform_x * document_position.x + uniforms.transform_y * document_position.y + uniforms.transform_translation;
|
||||
let normalized = transformed / uniforms.viewport_size;
|
||||
let clip = vec2<f32>(normalized.x * 2.0 - 1.0, 1.0 - normalized.y * 2.0);
|
||||
|
||||
var out: VertexOutput;
|
||||
out.position = vec4<f32>(clip, 0.0, 1.0);
|
||||
out.document_position = document_position;
|
||||
return out;
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
|
||||
let tile = floor((in.document_position - uniforms.pattern_origin) / uniforms.checker_size);
|
||||
let parity = i32(tile.x + tile.y) & 1;
|
||||
let luminance = select(1.0, 0.8, parity == 1);
|
||||
|
||||
let fw = fwidthFine(in.document_position);
|
||||
let coverage_max = 1.0 - smoothstep(uniforms.rect_max - fw, uniforms.rect_max, in.document_position);
|
||||
let coverage_min = smoothstep(uniforms.rect_min, uniforms.rect_min + fw, in.document_position);
|
||||
let coverage = coverage_max * coverage_min;
|
||||
let alpha = coverage.x * coverage.y;
|
||||
|
||||
return vec4<f32>(vec3<f32>(luminance), alpha);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
struct CompositeUniforms {
|
||||
transform_x: vec2<f32>,
|
||||
transform_y: vec2<f32>,
|
||||
transform_translation: vec2<f32>,
|
||||
rect_min: vec2<f32>,
|
||||
rect_max: vec2<f32>,
|
||||
viewport_size: vec2<f32>,
|
||||
pattern_origin: vec2<f32>,
|
||||
checker_size: f32,
|
||||
_pad: f32,
|
||||
};
|
||||
|
||||
@group(0) @binding(0)
|
||||
var<uniform> uniforms: CompositeUniforms;
|
||||
|
||||
struct VertexOutput {
|
||||
@builtin(position) position: vec4<f32>,
|
||||
@location(0) document_position: vec2<f32>,
|
||||
};
|
||||
|
||||
@vertex
|
||||
fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput {
|
||||
let positions = array<vec2<f32>, 3>(
|
||||
vec2<f32>(-1.0, -1.0),
|
||||
vec2<f32>(-1.0, 3.0),
|
||||
vec2<f32>( 3.0, -1.0),
|
||||
);
|
||||
let position = positions[vertex_index];
|
||||
|
||||
let screen_position = vec2<f32>((position.x + 1.0) * 0.5 * uniforms.viewport_size.x, (1.0 - position.y) * 0.5 * uniforms.viewport_size.y);
|
||||
let document_position = uniforms.transform_x * screen_position.x + uniforms.transform_y * screen_position.y + uniforms.transform_translation;
|
||||
|
||||
var out: VertexOutput;
|
||||
out.position = vec4<f32>(position, 0.0, 1.0);
|
||||
out.document_position = document_position;
|
||||
return out;
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
|
||||
let tile = floor((in.document_position - uniforms.pattern_origin) / uniforms.checker_size);
|
||||
let parity = i32(tile.x + tile.y) & 1;
|
||||
let luminance = vec3<f32>(select(1.0, 0.8, parity == 1));
|
||||
return vec4<f32>(luminance, 1.0);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
@group(0) @binding(0)
|
||||
var foreground_sampler: sampler;
|
||||
|
||||
@group(0) @binding(1)
|
||||
var foreground_texture: texture_2d<f32>;
|
||||
|
||||
struct VertexOutput {
|
||||
@builtin(position) position: vec4<f32>,
|
||||
@location(0) tex_coord: vec2<f32>,
|
||||
};
|
||||
|
||||
@vertex
|
||||
fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput {
|
||||
let positions = array<vec2<f32>, 3>(
|
||||
vec2<f32>(-1.0, -1.0),
|
||||
vec2<f32>(-1.0, 3.0),
|
||||
vec2<f32>( 3.0, -1.0),
|
||||
);
|
||||
|
||||
let tex_coords = array<vec2<f32>, 3>(
|
||||
vec2<f32>(0.0, 1.0),
|
||||
vec2<f32>(0.0, -1.0),
|
||||
vec2<f32>(2.0, 1.0),
|
||||
);
|
||||
|
||||
var vertex_out: VertexOutput;
|
||||
vertex_out.position = vec4<f32>(positions[vertex_index], 0.0, 1.0);
|
||||
vertex_out.tex_coord = tex_coords[vertex_index];
|
||||
return vertex_out;
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn fs_main(fragment_in: VertexOutput) -> @location(0) vec4<f32> {
|
||||
return textureSample(foreground_texture, foreground_sampler, fragment_in.tex_coord);
|
||||
}
|
||||
@@ -0,0 +1,494 @@
|
||||
//! Tile-based render caching for efficient viewport panning.
|
||||
|
||||
use core_types::gpoll::Interrupt;
|
||||
use core_types::list::Item;
|
||||
use core_types::math::bbox::AxisAlignedBbox;
|
||||
use core_types::transform::{Footprint, RenderQuality, Transform};
|
||||
use core_types::{Ctx, DeriveCtx, ExtractAll};
|
||||
use glam::{DAffine2, DVec2, IVec2, UVec2};
|
||||
use graph_craft::application_io::PlatformEditorApi;
|
||||
use graph_craft::document::value::{RenderOutput, RenderOutputType};
|
||||
use graphene_application_io::Texture;
|
||||
use rendering::{RenderOutputType as RenderOutputTypeRequest, RenderParams};
|
||||
use std::collections::HashSet;
|
||||
use std::hash::Hash;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
pub const TILE_SIZE: u32 = 256;
|
||||
pub const MAX_CACHE_MEMORY_BYTES: usize = 512 * 1024 * 1024;
|
||||
const BYTES_PER_PIXEL: usize = 4;
|
||||
|
||||
#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)]
|
||||
pub struct TileCoord {
|
||||
pub x: i32,
|
||||
pub y: i32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CachedRegion {
|
||||
pub texture: Texture,
|
||||
pub texture_size: UVec2,
|
||||
pub tiles: Vec<TileCoord>,
|
||||
pub metadata: rendering::RenderMetadata,
|
||||
last_access: u64,
|
||||
memory_size: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
|
||||
pub struct CacheKey {
|
||||
pub max_region_area: u32,
|
||||
pub render_mode_hash: u64,
|
||||
pub zoom: u64,
|
||||
pub rotation: u64,
|
||||
pub for_export: bool,
|
||||
pub for_mask: bool,
|
||||
pub thumbnail: bool,
|
||||
pub aligned_strokes: bool,
|
||||
pub override_paint_order: bool,
|
||||
pub animation_time_ms: i64,
|
||||
pub real_time_ms: i64,
|
||||
pub pointer: [u8; 16],
|
||||
}
|
||||
|
||||
impl CacheKey {
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
fn new(
|
||||
max_region_area: u32,
|
||||
render_mode_hash: u64,
|
||||
zoom: f64,
|
||||
rotation: f64,
|
||||
for_export: bool,
|
||||
for_mask: bool,
|
||||
thumbnail: bool,
|
||||
aligned_strokes: bool,
|
||||
override_paint_order: bool,
|
||||
animation_time: f64,
|
||||
real_time: f64,
|
||||
pointer: Option<DVec2>,
|
||||
) -> Self {
|
||||
let pointer_bytes = pointer
|
||||
.map(|p| {
|
||||
let mut bytes = [0u8; 16];
|
||||
bytes[..8].copy_from_slice(&p.x.to_le_bytes());
|
||||
bytes[8..].copy_from_slice(&p.y.to_le_bytes());
|
||||
bytes
|
||||
})
|
||||
.unwrap_or([0u8; 16]);
|
||||
const ROTATION_QUANTIZATION_DIGITS: i32 = 5;
|
||||
let quantization_amount = 10f64.powi(ROTATION_QUANTIZATION_DIGITS);
|
||||
let quantized_rotation = (rotation * quantization_amount).round() * quantization_amount.recip();
|
||||
Self {
|
||||
max_region_area,
|
||||
render_mode_hash,
|
||||
zoom: zoom.to_bits(),
|
||||
rotation: quantized_rotation.to_bits(),
|
||||
for_export,
|
||||
for_mask,
|
||||
thumbnail,
|
||||
aligned_strokes,
|
||||
override_paint_order,
|
||||
animation_time_ms: (animation_time * 1000.).round() as i64,
|
||||
real_time_ms: (real_time * 1000.).round() as i64,
|
||||
pointer: pointer_bytes,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Default, dyn_any::DynAny, Debug)]
|
||||
pub struct TileCache(Arc<Mutex<TileCacheImpl>>);
|
||||
|
||||
impl TileCache {
|
||||
pub fn query(&self, viewport_bounds: &AxisAlignedBbox, cache_key: &CacheKey, max_region_area: u32) -> CacheQuery {
|
||||
self.0.lock().unwrap().query(viewport_bounds, cache_key, max_region_area)
|
||||
}
|
||||
|
||||
pub fn store_regions(&self, regions: Vec<CachedRegion>) {
|
||||
self.0.lock().unwrap().store_regions(regions);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Debug)]
|
||||
struct TileCacheImpl {
|
||||
regions: Vec<CachedRegion>,
|
||||
timestamp: u64,
|
||||
total_memory: usize,
|
||||
cache_key: CacheKey,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RenderRegion {
|
||||
pub tiles: Vec<TileCoord>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct CacheQuery {
|
||||
pub cached_regions: Vec<CachedRegion>,
|
||||
pub missing_regions: Vec<RenderRegion>,
|
||||
}
|
||||
|
||||
fn bounds_to_tiles(bounds: &AxisAlignedBbox) -> Vec<TileCoord> {
|
||||
let tile_size = TILE_SIZE as f64;
|
||||
let tile_start_x = (bounds.start.x / tile_size).floor() as i32;
|
||||
let tile_start_y = (bounds.start.y / tile_size).floor() as i32;
|
||||
let tile_end_x = (bounds.end.x / tile_size).ceil() as i32;
|
||||
let tile_end_y = (bounds.end.y / tile_size).ceil() as i32;
|
||||
|
||||
let mut tiles = Vec::new();
|
||||
for y in tile_start_y..tile_end_y {
|
||||
for x in tile_start_x..tile_end_x {
|
||||
tiles.push(TileCoord { x, y });
|
||||
}
|
||||
}
|
||||
tiles
|
||||
}
|
||||
|
||||
fn tile_bounds(coord: &TileCoord) -> AxisAlignedBbox {
|
||||
let tile_size = TILE_SIZE as f64;
|
||||
let start = DVec2::new(coord.x as f64, coord.y as f64) * tile_size;
|
||||
AxisAlignedBbox {
|
||||
start,
|
||||
end: start + DVec2::splat(tile_size),
|
||||
}
|
||||
}
|
||||
|
||||
fn tiles_bounds(tiles: &[TileCoord]) -> AxisAlignedBbox {
|
||||
if tiles.is_empty() {
|
||||
return AxisAlignedBbox::ZERO;
|
||||
}
|
||||
let mut result = tile_bounds(&tiles[0]);
|
||||
for tile in &tiles[1..] {
|
||||
result = result.union(&tile_bounds(tile));
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
impl TileCacheImpl {
|
||||
fn query(&mut self, viewport_bounds: &AxisAlignedBbox, cache_key: &CacheKey, max_region_area: u32) -> CacheQuery {
|
||||
if &self.cache_key != cache_key {
|
||||
self.invalidate_all();
|
||||
self.cache_key = cache_key.clone();
|
||||
}
|
||||
|
||||
let required_tiles = bounds_to_tiles(viewport_bounds);
|
||||
let required_tile_set: HashSet<_> = required_tiles.iter().cloned().collect();
|
||||
let mut cached_regions = Vec::new();
|
||||
let mut covered_tiles = HashSet::new();
|
||||
|
||||
for region in &mut self.regions {
|
||||
let region_tiles: HashSet<_> = region.tiles.iter().cloned().collect();
|
||||
if region_tiles.iter().any(|t| required_tile_set.contains(t)) {
|
||||
region.last_access = self.timestamp;
|
||||
self.timestamp += 1;
|
||||
cached_regions.push(region.clone());
|
||||
covered_tiles.extend(region_tiles);
|
||||
}
|
||||
}
|
||||
|
||||
let missing_tiles: Vec<_> = required_tiles.into_iter().filter(|t| !covered_tiles.contains(t)).collect();
|
||||
let missing_regions = group_into_regions(&missing_tiles, max_region_area);
|
||||
CacheQuery { cached_regions, missing_regions }
|
||||
}
|
||||
|
||||
fn store_regions(&mut self, new_regions: Vec<CachedRegion>) {
|
||||
for mut region in new_regions {
|
||||
region.last_access = self.timestamp;
|
||||
self.timestamp += 1;
|
||||
self.total_memory += region.memory_size;
|
||||
self.regions.push(region);
|
||||
}
|
||||
self.evict_until_under_budget();
|
||||
}
|
||||
|
||||
fn evict_until_under_budget(&mut self) {
|
||||
while self.total_memory > MAX_CACHE_MEMORY_BYTES && !self.regions.is_empty() {
|
||||
if let Some((oldest_idx, _)) = self.regions.iter().enumerate().min_by_key(|(_, r)| r.last_access) {
|
||||
let removed = self.regions.remove(oldest_idx);
|
||||
self.total_memory = self.total_memory.saturating_sub(removed.memory_size);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn invalidate_all(&mut self) {
|
||||
self.regions.clear();
|
||||
self.total_memory = 0;
|
||||
}
|
||||
}
|
||||
|
||||
fn group_into_regions(tiles: &[TileCoord], max_region_area: u32) -> Vec<RenderRegion> {
|
||||
if tiles.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let tile_set: HashSet<_> = tiles.iter().cloned().collect();
|
||||
let mut visited = HashSet::new();
|
||||
let mut regions = Vec::new();
|
||||
|
||||
for &tile in tiles {
|
||||
if visited.contains(&tile) {
|
||||
continue;
|
||||
}
|
||||
let region_tiles = flood_fill(&tile, &tile_set, &mut visited);
|
||||
let region = RenderRegion { tiles: region_tiles };
|
||||
regions.extend(split_oversized_region(region, max_region_area));
|
||||
}
|
||||
regions
|
||||
}
|
||||
|
||||
/// Recursively subdivides a region until all sub-regions have area <= max_region_area.
|
||||
/// Uses axis-aligned splits on the longest dimension.
|
||||
fn split_oversized_region(region: RenderRegion, max_region_area: u32) -> Vec<RenderRegion> {
|
||||
let pixel_size = tiles_bounds(®ion.tiles).size();
|
||||
let area = (pixel_size.x * pixel_size.y) as u32;
|
||||
|
||||
// Base case: region is small enough
|
||||
if area <= max_region_area {
|
||||
return vec![region];
|
||||
}
|
||||
|
||||
// Determine split axis: choose the longer dimension
|
||||
let split_horizontally = pixel_size.x > pixel_size.y;
|
||||
|
||||
// Split tiles into two groups based on midpoint
|
||||
let mut group1 = Vec::new();
|
||||
let mut group2 = Vec::new();
|
||||
|
||||
if split_horizontally {
|
||||
let min_x = region.tiles.iter().map(|t| t.x).min().unwrap();
|
||||
let max_x = region.tiles.iter().map(|t| t.x).max().unwrap();
|
||||
let mid_x = min_x + (max_x - min_x) / 2;
|
||||
|
||||
for &tile in ®ion.tiles {
|
||||
if tile.x <= mid_x {
|
||||
group1.push(tile);
|
||||
} else {
|
||||
group2.push(tile);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let min_y = region.tiles.iter().map(|t| t.y).min().unwrap();
|
||||
let max_y = region.tiles.iter().map(|t| t.y).max().unwrap();
|
||||
let mid_y = min_y + (max_y - min_y) / 2;
|
||||
|
||||
for &tile in ®ion.tiles {
|
||||
if tile.y <= mid_y {
|
||||
group1.push(tile);
|
||||
} else {
|
||||
group2.push(tile);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if group1.is_empty() || group2.is_empty() {
|
||||
log::error!("Failed to split oversized region.");
|
||||
return vec![region];
|
||||
}
|
||||
|
||||
let mut result = Vec::new();
|
||||
for tiles in [group1, group2] {
|
||||
if !tiles.is_empty() {
|
||||
let sub_region = RenderRegion { tiles };
|
||||
result.extend(split_oversized_region(sub_region, max_region_area));
|
||||
}
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
fn flood_fill(start: &TileCoord, tile_set: &HashSet<TileCoord>, visited: &mut HashSet<TileCoord>) -> Vec<TileCoord> {
|
||||
let mut result = Vec::new();
|
||||
let mut stack = vec![*start];
|
||||
|
||||
while let Some(current) = stack.pop() {
|
||||
if visited.contains(¤t) || !tile_set.contains(¤t) {
|
||||
continue;
|
||||
}
|
||||
visited.insert(current);
|
||||
result.push(current);
|
||||
|
||||
for neighbor in [
|
||||
TileCoord { x: current.x - 1, y: current.y },
|
||||
TileCoord { x: current.x + 1, y: current.y },
|
||||
TileCoord { x: current.x, y: current.y - 1 },
|
||||
TileCoord { x: current.x, y: current.y + 1 },
|
||||
] {
|
||||
if tile_set.contains(&neighbor) && !visited.contains(&neighbor) {
|
||||
stack.push(neighbor);
|
||||
}
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
pub fn render_output_cache(
|
||||
ctx: impl Ctx + ExtractAll + DeriveCtx,
|
||||
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Item<Option<wgpu_executor::WgpuExecutorHandle>>,
|
||||
#[scope(crate::platform_application_io::editor_api::IDENTIFIER)] editor_api: Item<std::sync::Arc<PlatformEditorApi>>,
|
||||
data: impl Node<Context<'_>, Output = Item<RenderOutput>>,
|
||||
#[data] tile_cache: TileCache,
|
||||
) -> Result<Item<RenderOutput>, Interrupt> {
|
||||
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");
|
||||
return data.eval(&ctx.derived());
|
||||
};
|
||||
|
||||
// Fall back to direct render for non-Vello or zero-size viewports
|
||||
let physical_resolution = footprint.resolution;
|
||||
if !matches!(render_params.render_output_type, RenderOutputTypeRequest::Vello) || physical_resolution.x == 0 || physical_resolution.y == 0 {
|
||||
return data.eval(&ctx.derived());
|
||||
}
|
||||
|
||||
let zoom = footprint.scale_magnitudes().x;
|
||||
let rotation = footprint.decompose_rotation();
|
||||
|
||||
let device_origin_offset = footprint.transform.translation;
|
||||
let viewport_bounds_device = AxisAlignedBbox {
|
||||
start: -device_origin_offset,
|
||||
end: footprint.resolution.as_dvec2() - device_origin_offset,
|
||||
};
|
||||
|
||||
let max_region_area = editor_api.into_element().editor_preferences.max_render_region_area();
|
||||
|
||||
let cache_key = CacheKey::new(
|
||||
max_region_area,
|
||||
render_params.render_mode as u64,
|
||||
zoom,
|
||||
rotation,
|
||||
render_params.for_export,
|
||||
render_params.for_mask,
|
||||
render_params.thumbnail,
|
||||
render_params.aligned_strokes,
|
||||
render_params.override_paint_order,
|
||||
ctx.try_animation_time().unwrap_or(0.),
|
||||
ctx.try_real_time().unwrap_or(0.),
|
||||
ctx.try_pointer_position(),
|
||||
);
|
||||
|
||||
let cache_query = tile_cache.query(&viewport_bounds_device, &cache_key, max_region_area);
|
||||
|
||||
let mut new_regions = Vec::new();
|
||||
for missing_region in &cache_query.missing_regions {
|
||||
if missing_region.tiles.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let min_tile = missing_region.tiles.iter().fold(IVec2::new(i32::MAX, i32::MAX), |acc, t| acc.min(IVec2::new(t.x, t.y)));
|
||||
let max_tile = missing_region.tiles.iter().fold(IVec2::new(i32::MIN, i32::MIN), |acc, t| acc.max(IVec2::new(t.x, t.y)));
|
||||
|
||||
let tile_count = (max_tile - min_tile) + IVec2::ONE;
|
||||
let region_pixel_size = (tile_count * TILE_SIZE as i32).as_uvec2();
|
||||
|
||||
let tile_global_offset = min_tile.as_dvec2() * TILE_SIZE as f64 + device_origin_offset;
|
||||
let region_transform = DAffine2::from_translation(-tile_global_offset) * footprint.transform;
|
||||
let region_footprint = Footprint {
|
||||
transform: region_transform,
|
||||
resolution: region_pixel_size,
|
||||
quality: RenderQuality::Full,
|
||||
};
|
||||
|
||||
let mut result = data.eval(&ctx.with_footprint(®ion_footprint))?;
|
||||
|
||||
let RenderOutputType::Texture(texture) = result.data else {
|
||||
unreachable!("render_output_cache: expected texture output from Vello render");
|
||||
};
|
||||
|
||||
result.metadata.apply_transform(region_transform.inverse());
|
||||
|
||||
let memory_size = (region_pixel_size.x * region_pixel_size.y) as usize * BYTES_PER_PIXEL;
|
||||
|
||||
new_regions.push(CachedRegion {
|
||||
texture,
|
||||
texture_size: region_pixel_size,
|
||||
tiles: missing_region.tiles.clone(),
|
||||
metadata: result.metadata,
|
||||
last_access: 0,
|
||||
memory_size,
|
||||
});
|
||||
}
|
||||
|
||||
tile_cache.store_regions(new_regions.clone());
|
||||
|
||||
let all_regions: Vec<_> = cache_query.cached_regions.into_iter().chain(new_regions).collect();
|
||||
|
||||
// If no regions, fall back to direct render
|
||||
if all_regions.is_empty() {
|
||||
return data.eval(&ctx.derived());
|
||||
}
|
||||
|
||||
let executor = executor.into_element().expect("GPU executor not available");
|
||||
let output_texture = executor.request_texture(physical_resolution);
|
||||
|
||||
let combined_metadata = composite_cached_regions(&all_regions, &output_texture, &device_origin_offset, &footprint.transform, &executor);
|
||||
|
||||
Ok(Item::new_from_element(RenderOutput {
|
||||
data: RenderOutputType::Texture(output_texture),
|
||||
metadata: combined_metadata,
|
||||
}))
|
||||
}
|
||||
|
||||
fn composite_cached_regions(
|
||||
regions: &[CachedRegion],
|
||||
output_texture: &wgpu::Texture,
|
||||
device_origin_offset: &DVec2,
|
||||
viewport_transform: &DAffine2,
|
||||
exec: &wgpu_executor::WgpuExecutor,
|
||||
) -> rendering::RenderMetadata {
|
||||
let device = &exec.context().device;
|
||||
let queue = &exec.context().queue;
|
||||
let output_resolution = UVec2::new(output_texture.width(), output_texture.height());
|
||||
|
||||
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("composite") });
|
||||
let mut combined_metadata = rendering::RenderMetadata::default();
|
||||
|
||||
for region in regions {
|
||||
let min_tile = region.tiles.iter().fold(IVec2::new(i32::MAX, i32::MAX), |acc, t| acc.min(IVec2::new(t.x, t.y)));
|
||||
|
||||
// Convert global tile position to physical pixel offset in the output texture
|
||||
let offset_pixels = min_tile * TILE_SIZE as i32 + device_origin_offset.round().as_ivec2();
|
||||
|
||||
let (src_x, dst_x, width) = if offset_pixels.x >= 0 {
|
||||
(0, offset_pixels.x as u32, region.texture_size.x.min(output_resolution.x.saturating_sub(offset_pixels.x as u32)))
|
||||
} else {
|
||||
let skip = (-offset_pixels.x) as u32;
|
||||
(skip, 0, region.texture_size.x.saturating_sub(skip).min(output_resolution.x))
|
||||
};
|
||||
|
||||
let (src_y, dst_y, height) = if offset_pixels.y >= 0 {
|
||||
(0, offset_pixels.y as u32, region.texture_size.y.min(output_resolution.y.saturating_sub(offset_pixels.y as u32)))
|
||||
} else {
|
||||
let skip = (-offset_pixels.y) as u32;
|
||||
(skip, 0, region.texture_size.y.saturating_sub(skip).min(output_resolution.y))
|
||||
};
|
||||
|
||||
if width > 0 && height > 0 {
|
||||
encoder.copy_texture_to_texture(
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
texture: region.texture.as_ref(),
|
||||
mip_level: 0,
|
||||
origin: wgpu::Origin3d { x: src_x, y: src_y, z: 0 },
|
||||
aspect: wgpu::TextureAspect::All,
|
||||
},
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
texture: output_texture,
|
||||
mip_level: 0,
|
||||
origin: wgpu::Origin3d { x: dst_x, y: dst_y, z: 0 },
|
||||
aspect: wgpu::TextureAspect::All,
|
||||
},
|
||||
wgpu::Extent3d {
|
||||
width,
|
||||
height,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
let mut region_metadata = region.metadata.clone();
|
||||
region_metadata.apply_transform(*viewport_transform);
|
||||
combined_metadata.merge(®ion_metadata);
|
||||
}
|
||||
|
||||
queue.submit([encoder.finish()]);
|
||||
combined_metadata
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
use core_types::gpoll::Interrupt;
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::transform::{Footprint, Transform};
|
||||
use core_types::{Color, Context, Ctx, DeriveCtx, ExtractFootprint, ExtractIndex, ExtractVarArgs, InjectIndex, VarArgLink, VarArgSlots, WasmNotSend};
|
||||
use graph_craft::document::value::{RenderOutput, RenderOutputType};
|
||||
use graphene_application_io::{ExportFormat, RenderConfig};
|
||||
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 wgpu_executor::RenderContext;
|
||||
|
||||
#[derive(Clone, dyn_any::DynAny)]
|
||||
pub enum RenderIntermediateType {
|
||||
Vello(Arc<(vello::Scene, RenderContext)>),
|
||||
Svg(Arc<SvgRenderOutput>),
|
||||
}
|
||||
#[derive(Clone, dyn_any::DynAny)]
|
||||
pub struct RenderIntermediate {
|
||||
pub(crate) ty: RenderIntermediateType,
|
||||
pub(crate) metadata: RenderMetadata,
|
||||
}
|
||||
|
||||
fn intermediate_of<R: Render>(data: &R, render_params: &RenderParams) -> RenderIntermediate {
|
||||
let footprint = Footprint::default();
|
||||
let mut metadata = RenderMetadata::default();
|
||||
data.collect_metadata(&mut metadata, footprint, None);
|
||||
let intermediate = match &render_params.render_output_type {
|
||||
RenderOutputTypeRequest::Vello => {
|
||||
let mut scene = vello::Scene::new();
|
||||
|
||||
let mut context = wgpu_executor::RenderContext::default();
|
||||
data.render_to_vello(&mut scene, Default::default(), &mut context, render_params);
|
||||
|
||||
RenderIntermediate {
|
||||
ty: RenderIntermediateType::Vello(Arc::new((scene, context))),
|
||||
metadata,
|
||||
}
|
||||
}
|
||||
RenderOutputTypeRequest::Svg => {
|
||||
let mut render = SvgRender::new();
|
||||
|
||||
data.render_svg(&mut render, render_params);
|
||||
|
||||
RenderIntermediate {
|
||||
ty: RenderIntermediateType::Svg(Arc::new(render.into())),
|
||||
metadata,
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Item::new_from_element(intermediate)
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
fn render_intermediate<T: dyn_any::StaticTypeSized + 'static + Render + WasmNotSend + Send + Sync>(
|
||||
ctx: impl Ctx + ExtractVarArgs + DeriveCtx,
|
||||
#[implementations(
|
||||
Context -> List<Artboard>,
|
||||
Context -> List<Graphic>,
|
||||
Context -> List<Vector>,
|
||||
Context -> List<Raster<CPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<GradientStops>,
|
||||
Context -> List<String>,
|
||||
)]
|
||||
data: impl Node<Context<'_>, Output = T>,
|
||||
) -> Result<RenderIntermediate, Interrupt> {
|
||||
let data = data.eval(&ctx.derived())?;
|
||||
let render_params = ctx
|
||||
.vararg(0)
|
||||
.expect("Did not find var args")
|
||||
.downcast_ref::<RenderParams>()
|
||||
.expect("Downcasting render params yielded invalid type");
|
||||
|
||||
Ok(intermediate_of(&data, render_params))
|
||||
}
|
||||
|
||||
/// The leveled form of `render_intermediate`: the input's records materialize
|
||||
/// into a run, which renders directly.
|
||||
#[node_macro::node(category(""))]
|
||||
fn render_intermediate_leveled<T: Clone + Send + Sync + core_types::CacheHash + dyn_any::StaticTypeSized + 'static>(
|
||||
ctx: impl Ctx + ExtractVarArgs + ExtractIndex + InjectIndex + Copy,
|
||||
#[implementations(Artboard, Graphic, Vector, Raster<CPU>, Color, GradientStops, String)] data: IList<T>,
|
||||
) -> Result<RenderIntermediate, Interrupt>
|
||||
where
|
||||
for<'a> core_types::record::RunView<'a, T>: Render,
|
||||
{
|
||||
let item = data.as_group_item();
|
||||
let run = core_types::record::RunView::<T>::new(&item).expect("the run holds the row's element type");
|
||||
let render_params = ctx
|
||||
.vararg(0)
|
||||
.expect("Did not find var args")
|
||||
.downcast_ref::<RenderParams>()
|
||||
.expect("Downcasting render params yielded invalid type");
|
||||
|
||||
Ok(intermediate_of(&run, render_params))
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
fn render(
|
||||
ctx: impl Ctx + ExtractFootprint + ExtractVarArgs,
|
||||
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Item<Option<wgpu_executor::WgpuExecutorHandle>>,
|
||||
data: Item<RenderIntermediate>,
|
||||
) -> Item<RenderOutput> {
|
||||
let footprint = ctx.footprint();
|
||||
let render_params = ctx
|
||||
.vararg(0)
|
||||
.expect("Did not find var args")
|
||||
.downcast_ref::<RenderParams>()
|
||||
.expect("Downcasting render params yielded invalid type");
|
||||
let mut render_params = render_params.clone();
|
||||
render_params.footprint = *footprint;
|
||||
|
||||
let RenderIntermediate { ty, mut metadata } = data.into_element();
|
||||
metadata.apply_transform(footprint.transform);
|
||||
|
||||
let data = match (render_params.render_output_type, ty) {
|
||||
(RenderOutputTypeRequest::Svg, RenderIntermediateType::Svg(data)) => {
|
||||
let logical_transform = glam::DAffine2::from_scale(glam::DVec2::splat(1.0 / render_params.scale)) * footprint.transform;
|
||||
let logical_resolution = footprint.resolution.as_dvec2() / render_params.scale;
|
||||
|
||||
let mut render = SvgRender::from(data.as_ref());
|
||||
render.wrap_with_transform(logical_transform, Some(logical_resolution));
|
||||
|
||||
let output = SvgRenderOutput::from(render);
|
||||
assert!(output.svg_defs.is_empty());
|
||||
|
||||
RenderOutputType::Svg {
|
||||
svg: output.svg,
|
||||
image_data: output.image_data.into_iter().map(|(image, id)| (id, image.0)).collect(),
|
||||
}
|
||||
}
|
||||
(RenderOutputTypeRequest::Vello, RenderIntermediateType::Vello(data)) => {
|
||||
let (scene, context) = data.as_ref();
|
||||
|
||||
let footprint_transform_vello = vello::kurbo::Affine::new(footprint.transform.to_cols_array());
|
||||
|
||||
let mut transformed_scene = vello::Scene::new();
|
||||
transformed_scene.append(scene, Some(footprint_transform_vello));
|
||||
|
||||
// We now replace all transforms which are supposed to be infinite with a transform which covers the entire viewport.
|
||||
// See <https://xi.zulipchat.com/#narrow/channel/197075-vello/topic/Full.20screen.20color.2Fgradients/near/538435044> for more detail.
|
||||
//
|
||||
// `!is_finite()` rather than `== f32::INFINITY`: `scene.append` composes the child's `Affine::scale(INFINITY)` with
|
||||
// the viewport rotation, leaving `matrix[0] = cos(θ) * INFINITY`. In the (90°, 270°) tilt range cos is negative so
|
||||
// the result is `-INFINITY`, which the old equality check missed; Vello then rasterized a unit rect with non-finite
|
||||
// vertices, dropping the gradient and tanking performance. `!is_finite()` also covers NaN as a guard against future
|
||||
// code paths where `matrix[0]` could land on `0 * INFINITY`.
|
||||
let scaled_infinite_transform = vello::kurbo::Affine::scale_non_uniform(footprint.resolution.x as f64, footprint.resolution.y as f64);
|
||||
for transform in transformed_scene.encoding_mut().transforms.iter_mut() {
|
||||
if !transform.matrix[0].is_finite() {
|
||||
*transform = vello_encoding::Transform::from_kurbo(&scaled_infinite_transform);
|
||||
}
|
||||
}
|
||||
|
||||
let texture = executor
|
||||
.into_element()
|
||||
.expect("GPU executor not available")
|
||||
.render_vello_scene(&transformed_scene, footprint.resolution, context, None)
|
||||
.expect("Failed to render Vello scene");
|
||||
RenderOutputType::Texture(texture)
|
||||
}
|
||||
_ => unreachable!("Render node did not receive its requested data type"),
|
||||
};
|
||||
|
||||
Item::new_from_element(RenderOutput { data, metadata })
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
fn create_context(ctx: impl Ctx + ExtractVarArgs + DeriveCtx, data: impl Node<Context<'_>, Output = RenderOutput>) -> Result<RenderOutput, Interrupt> {
|
||||
let render_config = *ctx
|
||||
.vararg(0)
|
||||
.expect("Did not find var args")
|
||||
.downcast_ref::<RenderConfig>()
|
||||
.expect("Downcasting render config yielded invalid type");
|
||||
|
||||
let render_output_type = match render_config.export_format {
|
||||
ExportFormat::Svg => RenderOutputTypeRequest::Svg,
|
||||
ExportFormat::Raster => RenderOutputTypeRequest::Vello,
|
||||
};
|
||||
|
||||
let logical_viewport = render_config.viewport;
|
||||
let footprint = Footprint {
|
||||
transform: glam::DAffine2::from_scale(glam::DVec2::splat(render_config.scale)) * logical_viewport.transform,
|
||||
..logical_viewport
|
||||
};
|
||||
|
||||
let render_params = RenderParams {
|
||||
render_mode: render_config.render_mode,
|
||||
for_export: render_config.for_export,
|
||||
render_output_type,
|
||||
scale: render_config.scale,
|
||||
viewport_zoom: logical_viewport.scale_magnitudes().x,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let scope = ctx
|
||||
.scope()
|
||||
.with_real_time(Some(render_config.time.time))
|
||||
.with_animation_time(Some(render_config.time.animation_time.as_secs_f64()))
|
||||
.with_pointer_position(Some(render_config.pointer));
|
||||
let varargs = VarArgLink {
|
||||
args: VarArgSlots::Single(&render_params),
|
||||
outer: None,
|
||||
};
|
||||
let scoped = ctx.with_scope(&scope);
|
||||
let with_params = scoped.with_varargs(&varargs);
|
||||
let mut result = data.eval(&with_params.with_footprint(&footprint))?;
|
||||
|
||||
result.metadata.apply_transform(glam::DAffine2::from_scale(glam::DVec2::splat(1. / render_config.scale)));
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use core_types::arena::Arena;
|
||||
use core_types::context::{ContextImpl, EvalScope, VarArgsResult};
|
||||
use core_types::gpoll::GPoll;
|
||||
use core_types::node::Node;
|
||||
use core_types::{ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime};
|
||||
use graphene_application_io::TimingInformation;
|
||||
|
||||
fn probe(ctx: &ContextImpl) -> GPoll<RenderOutput> {
|
||||
let render_params = ctx.vararg(0).unwrap().downcast_ref::<RenderParams>().expect("the vararg chain must start with RenderParams");
|
||||
assert_eq!(render_params.scale, 2.0);
|
||||
assert!(matches!(ctx.vararg(1), Err(VarArgsResult::IndexOutOfBounds)), "the RenderConfig must not leak downstream");
|
||||
assert_eq!(ctx.footprint().transform, glam::DAffine2::from_scale(glam::DVec2::splat(2.0)) * Footprint::DEFAULT.transform);
|
||||
assert_eq!(ctx.try_real_time(), Some(1.5));
|
||||
assert_eq!(ctx.try_animation_time(), Some(2.0));
|
||||
assert_eq!(ctx.try_pointer_position(), Some(glam::DVec2::new(3.0, 4.0)));
|
||||
GPoll::Final(RenderOutput {
|
||||
data: RenderOutputType::Buffer {
|
||||
data: Vec::new(),
|
||||
width: 0,
|
||||
height: 0,
|
||||
},
|
||||
metadata: RenderMetadata::default(),
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_context_builds_the_render_context_from_the_root_vararg() {
|
||||
let arena = Arena::new(4096).unwrap();
|
||||
let generations = [];
|
||||
let scope = EvalScope::new(None, None, None, &generations, &arena);
|
||||
let root = ContextImpl::root(&scope);
|
||||
let render_config = RenderConfig {
|
||||
scale: 2.0,
|
||||
time: TimingInformation {
|
||||
time: 1.5,
|
||||
animation_time: std::time::Duration::from_secs(2),
|
||||
},
|
||||
pointer: glam::DVec2::new(3.0, 4.0),
|
||||
..Default::default()
|
||||
};
|
||||
let varargs = VarArgLink {
|
||||
args: VarArgSlots::Single(&render_config),
|
||||
outer: None,
|
||||
};
|
||||
let ctx = root.with_varargs(&varargs);
|
||||
|
||||
let probe = core_types::record::LiftedSource::<RenderOutput, _>::new(probe);
|
||||
let layout = Node::<ContextImpl>::layout(&probe).clone();
|
||||
let frames = core_types::record::test_frames(layout.frame_bytes().max(1 << 12));
|
||||
let mut graph = CreateContextNode::new(probe, &layout);
|
||||
// The executor resolves and installs the node's own layout at wiring;
|
||||
// without it the flip tail writes through the default empty layout.
|
||||
Node::<ContextImpl>::set_layout(
|
||||
&mut graph,
|
||||
core_types::record::RecordLayout {
|
||||
frame_bytes: layout.frame_bytes(),
|
||||
plan: Vec::new(),
|
||||
layout: layout.clone(),
|
||||
lane_invariant: u32::MAX,
|
||||
},
|
||||
);
|
||||
let GPoll::Final(result) = core_types::record::serve_input(&graph, &ctx, &frames) else {
|
||||
panic!("create_context must complete synchronously");
|
||||
};
|
||||
let output: &RenderOutput = unsafe { core_types::record::borrow_element(layout.rec(&result)) };
|
||||
assert_eq!(
|
||||
output.data,
|
||||
RenderOutputType::Buffer {
|
||||
data: Vec::new(),
|
||||
width: 0,
|
||||
height: 0
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
use core_types::gpoll::Interrupt;
|
||||
use core_types::list::Item;
|
||||
use core_types::transform::{Footprint, Transform};
|
||||
use core_types::{Ctx, DeriveCtx, ExtractAll};
|
||||
use glam::{DAffine2, DVec2, UVec2, Vec2};
|
||||
use graph_craft::document::value::{RenderOutput, RenderOutputType};
|
||||
use graphic_types::raster_types::Texture;
|
||||
use rendering::{RenderOutputType as RenderOutputTypeRequest, RenderParams};
|
||||
use vector_types::vector::style::RenderMode;
|
||||
use wgpu_executor::{WgpuExecutor, WgpuPipeline, WgpuPipelineCache};
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
pub fn render_pixel_preview(
|
||||
ctx: impl Ctx + ExtractAll + DeriveCtx,
|
||||
#[scope(pixel_preview_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>,
|
||||
data: impl Node<Context<'_>, Output = Item<RenderOutput>>,
|
||||
) -> Result<Item<RenderOutput>, Interrupt> {
|
||||
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");
|
||||
return data.eval(&ctx.derived());
|
||||
};
|
||||
let physical_scale = render_params.scale;
|
||||
|
||||
let footprint = *ctx.footprint();
|
||||
let viewport_zoom = footprint.scale_magnitudes().x;
|
||||
|
||||
if render_params.render_mode != RenderMode::PixelPreview || !matches!(render_params.render_output_type, RenderOutputTypeRequest::Vello) || viewport_zoom <= 1. {
|
||||
return data.eval(&ctx.derived());
|
||||
}
|
||||
|
||||
let physical_resolution = footprint.resolution;
|
||||
let logical_resolution = physical_resolution.as_dvec2() / physical_scale;
|
||||
|
||||
let logical_footprint = Footprint {
|
||||
transform: DAffine2::from_scale(DVec2::splat(1. / physical_scale)) * footprint.transform,
|
||||
resolution: logical_resolution.as_uvec2().max(UVec2::ONE),
|
||||
..footprint
|
||||
};
|
||||
|
||||
let bounds = logical_footprint.viewport_bounds_in_local_space();
|
||||
|
||||
let upstream_min = bounds.start.floor();
|
||||
let upstream_max = bounds.end.ceil();
|
||||
|
||||
let upstream_size = (upstream_max - upstream_min).max(DVec2::ONE);
|
||||
let upstream_resolution = upstream_size.as_uvec2().max(UVec2::ONE);
|
||||
|
||||
let upstream_footprint = Footprint {
|
||||
transform: DAffine2::from_translation(-upstream_min),
|
||||
resolution: upstream_resolution,
|
||||
quality: footprint.quality,
|
||||
};
|
||||
|
||||
let scoped = ctx.push_vararg(&render_params);
|
||||
let mut result = data.eval(&scoped.ctx().with_footprint(&upstream_footprint))?.into_element();
|
||||
|
||||
let RenderOutputType::Texture(ref source_texture) = result.data else {
|
||||
return Ok(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,
|
||||
size: physical_resolution,
|
||||
});
|
||||
|
||||
result.data = RenderOutputType::Texture(resampled);
|
||||
|
||||
result.metadata.apply_transform(footprint.transform * DAffine2::from_translation(upstream_min));
|
||||
|
||||
Ok(Item::new_from_element(result))
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), inject_scope)]
|
||||
fn pixel_preview_pipeline(
|
||||
_ctx: impl Ctx,
|
||||
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Item<Option<wgpu_executor::WgpuExecutorHandle>>,
|
||||
#[data] pipeline: WgpuPipelineCache,
|
||||
) -> Item<WgpuPipelineCache> {
|
||||
if let Some(executor) = executor.into_element() {
|
||||
executor.pipeline_init::<PixelPreview>(pipeline);
|
||||
}
|
||||
Item::new_from_element(pipeline.clone())
|
||||
}
|
||||
|
||||
pub struct PixelPreview {
|
||||
pipeline: wgpu::RenderPipeline,
|
||||
bind_group_layout: wgpu::BindGroupLayout,
|
||||
}
|
||||
|
||||
pub struct PixelPreviewArgs<'a> {
|
||||
source: &'a wgpu::Texture,
|
||||
transform: &'a DAffine2,
|
||||
size: UVec2,
|
||||
}
|
||||
|
||||
impl WgpuPipeline for PixelPreview {
|
||||
type Args<'a> = PixelPreviewArgs<'a>;
|
||||
type Out = Texture;
|
||||
|
||||
fn create(executor: &WgpuExecutor) -> Self {
|
||||
let device = &executor.context().device;
|
||||
let shader = device.create_shader_module(wgpu::include_wgsl!("render_pixel_preview.wgsl"));
|
||||
|
||||
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("resample_bind_group_layout"),
|
||||
entries: &[
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Texture {
|
||||
multisampled: false,
|
||||
view_dimension: wgpu::TextureViewDimension::D2,
|
||||
sample_type: wgpu::TextureSampleType::Float { filterable: false },
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("resample_pipeline_layout"),
|
||||
bind_group_layouts: &[Some(&bind_group_layout)],
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("resample_pipeline"),
|
||||
layout: Some(&pipeline_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &shader,
|
||||
entry_point: Some("vs_main"),
|
||||
buffers: &[],
|
||||
compilation_options: wgpu::PipelineCompilationOptions::default(),
|
||||
},
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &shader,
|
||||
entry_point: Some("fs_main"),
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
format: wgpu::TextureFormat::Rgba8Unorm,
|
||||
blend: None,
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
compilation_options: wgpu::PipelineCompilationOptions::default(),
|
||||
}),
|
||||
primitive: wgpu::PrimitiveState {
|
||||
topology: wgpu::PrimitiveTopology::TriangleList,
|
||||
..Default::default()
|
||||
},
|
||||
depth_stencil: None,
|
||||
multisample: wgpu::MultisampleState::default(),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
});
|
||||
|
||||
PixelPreview { pipeline, bind_group_layout }
|
||||
}
|
||||
|
||||
fn run<'a>(&'a self, executor: &'a WgpuExecutor, args: &'a Self::Args<'_>) -> Self::Out {
|
||||
let context = &executor.context();
|
||||
let &PixelPreviewArgs { source, transform, size } = args;
|
||||
|
||||
let output = executor.request_texture(size);
|
||||
|
||||
let source_view = source.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let output_view = output.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
|
||||
let params_buffer = context.device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("resample_params"),
|
||||
size: 32,
|
||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
let params_data = [transform.matrix2.x_axis.as_vec2(), transform.matrix2.y_axis.as_vec2(), transform.translation.as_vec2(), Vec2::ZERO];
|
||||
context.queue.write_buffer(¶ms_buffer, 0, bytemuck::cast_slice(¶ms_data));
|
||||
|
||||
let bind_group = context.device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("resample_bind_group"),
|
||||
layout: &self.bind_group_layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: wgpu::BindingResource::TextureView(&source_view),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: params_buffer.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
let mut encoder = context.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("resample_encoder") });
|
||||
|
||||
{
|
||||
let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("resample_pass"),
|
||||
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||
view: &output_view,
|
||||
resolve_target: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
depth_slice: None,
|
||||
})],
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
render_pass.set_pipeline(&self.pipeline);
|
||||
render_pass.set_bind_group(0, &bind_group, &[]);
|
||||
render_pass.draw(0..3, 0..1);
|
||||
}
|
||||
|
||||
context.queue.submit([encoder.finish()]);
|
||||
|
||||
output
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// =============
|
||||
// VERTEX SHADER
|
||||
// =============
|
||||
|
||||
struct VertexOutput {
|
||||
@builtin(position) clip_position: vec4<f32>,
|
||||
@location(0) tex_coords: vec2<f32>,
|
||||
}
|
||||
|
||||
@vertex
|
||||
fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput {
|
||||
var out: VertexOutput;
|
||||
let pos = array(
|
||||
vec2f(-1.0, -1.0),
|
||||
vec2f(3.0, -1.0),
|
||||
vec2f(-1.0, 3.0),
|
||||
);
|
||||
let xy = pos[vertex_index];
|
||||
out.clip_position = vec4f(xy, 0.0, 1.0);
|
||||
let coords = xy / 2. + 0.5;
|
||||
out.tex_coords = vec2f(coords.x, 1. - coords.y);
|
||||
return out;
|
||||
}
|
||||
|
||||
// ===============
|
||||
// FRAGMENT SHADER
|
||||
// ===============
|
||||
|
||||
@group(0) @binding(0)
|
||||
var t_source: texture_2d<f32>;
|
||||
|
||||
struct Params {
|
||||
matrix: mat2x2<f32>,
|
||||
translation: vec2<f32>,
|
||||
_pad: vec2<f32>,
|
||||
};
|
||||
|
||||
// We need to use a uniform buffer for the params because push constants are not supported on web
|
||||
@group(0) @binding(1)
|
||||
var<uniform> params: Params;
|
||||
|
||||
@fragment
|
||||
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
|
||||
let position = params.matrix * in.tex_coords + params.translation;
|
||||
let texel = vec2<i32>(floor(position));
|
||||
let texture_size = vec2<i32>(textureDimensions(t_source));
|
||||
if (texel.x >= 0 && texel.x < texture_size.x && texel.y >= 0 && texel.y < texture_size.y) {
|
||||
return textureLoad(t_source, texel, 0);
|
||||
}
|
||||
return vec4<f32>(0.0);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
pub use core_types::runtime::*;
|
||||
|
||||
use crate::platform_application_io::editor_api;
|
||||
use core_types::Ctx;
|
||||
use graph_craft::application_io::PlatformEditorApi;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[node_macro::node(category(""), inject_scope)]
|
||||
pub fn runtime(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: Arc<PlatformEditorApi>) -> RuntimeHandle {
|
||||
editor_api.runtime.clone()
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
use core_types::consts::{DEFAULT_FONT_SIZE, DEFAULT_LINE_HEIGHT};
|
||||
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 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"))]
|
||||
fn text(
|
||||
_: impl Ctx,
|
||||
_primary: (),
|
||||
/// The text content to be drawn.
|
||||
#[widget(ParsedWidgetOverride::Custom = "text_area")]
|
||||
#[default("Lorem ipsum")]
|
||||
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: Item<Resource>,
|
||||
/// The font size used to draw the text.
|
||||
#[unit(" px")]
|
||||
#[default(24.)]
|
||||
#[hard(1..)]
|
||||
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.
|
||||
#[unit("x")]
|
||||
#[hard(0..)]
|
||||
#[step(0.1)]
|
||||
#[default(1.2)]
|
||||
line_height: Item<f64>,
|
||||
/// Additional spacing, in pixels, added between each character.
|
||||
#[unit(" px")]
|
||||
#[step(0.1)]
|
||||
letter_spacing: Item<f64>,
|
||||
/// The angle of faux italic slant applied to each glyph.
|
||||
#[unit("°")]
|
||||
#[hard(-85..85)]
|
||||
letter_tilt: Item<f64>,
|
||||
/// Enables the maximum width constraint so lines can wrap.
|
||||
#[widget(ParsedWidgetOverride::Hidden)]
|
||||
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: Item<f64>,
|
||||
/// Whether the *Max Height* property is enabled so that lines beyond it are not drawn.
|
||||
#[widget(ParsedWidgetOverride::Hidden)]
|
||||
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: 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: 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() {
|
||||
item.set_attribute(ATTR_FONT, font);
|
||||
}
|
||||
if (size - DEFAULT_FONT_SIZE).abs() > f64::EPSILON {
|
||||
item.set_attribute(ATTR_FONT_SIZE, size);
|
||||
}
|
||||
if (line_height - DEFAULT_LINE_HEIGHT).abs() > f64::EPSILON {
|
||||
item.set_attribute(ATTR_LINE_HEIGHT, line_height);
|
||||
}
|
||||
if letter_spacing != 0. {
|
||||
item.set_attribute(ATTR_LETTER_SPACING, letter_spacing);
|
||||
}
|
||||
if letter_tilt != 0. {
|
||||
item.set_attribute(ATTR_LETTER_TILT, letter_tilt);
|
||||
}
|
||||
if has_max_width {
|
||||
item.set_attribute(ATTR_MAX_WIDTH, Some(max_width));
|
||||
}
|
||||
if has_max_height {
|
||||
item.set_attribute(ATTR_MAX_HEIGHT, Some(max_height));
|
||||
}
|
||||
if align != TextAlign::default() {
|
||||
item.set_attribute(ATTR_TEXT_ALIGN, align);
|
||||
}
|
||||
|
||||
item
|
||||
}
|
||||
|
||||
/// 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 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)
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "math-nodes"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
description = "Math operation nodes for Graphene"
|
||||
authors = ["Graphite Authors <contact@graphite.art>"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
[dependencies]
|
||||
core-types = { workspace = true }
|
||||
node-macro = { workspace = true }
|
||||
graphic-types = { workspace = true }
|
||||
vector-types = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
glam = { workspace = true }
|
||||
rand = { workspace = true }
|
||||
math-parser = { workspace = true }
|
||||
log = { workspace = true }
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "path-bool-nodes"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
description = "Path boolean operation nodes for Graphene"
|
||||
authors = ["Graphite Authors <contact@graphite.art>"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
[dependencies]
|
||||
# Local dependencies
|
||||
core-types = { workspace = true }
|
||||
graphic-types = { workspace = true }
|
||||
text-nodes = { workspace = true }
|
||||
node-macro = { workspace = true }
|
||||
glam = { workspace = true }
|
||||
linesweeper = { workspace = true }
|
||||
log = { workspace = true }
|
||||
smallvec = { workspace = true }
|
||||
vector-types = { workspace = true }
|
||||
@@ -0,0 +1,596 @@
|
||||
use core_types::attribute::{Attr, BlendMode as BlendModeAttr, ClippingMask, EditorLayerPath, Opacity, OpacityFill, Transform as TransformAttr};
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::uuid::NodeId;
|
||||
use core_types::{ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, BlendMode, Color, Ctx};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::graphic::{GraphicLevel, PaintColumns, PaintReach, bake_paint_transforms, is_paint_present, set_paint_attribute, set_paint_attribute_at};
|
||||
use graphic_types::markers::{EditorMergedLayers, Fill, Stroke};
|
||||
use graphic_types::raster_types::{CPU, GPU, Raster};
|
||||
use graphic_types::vector_types::GradientStops;
|
||||
use graphic_types::vector_types::gradient::{GradientSpreadMethod, GradientType};
|
||||
use graphic_types::vector_types::subpath::{ManipulatorGroup, Subpath};
|
||||
use graphic_types::vector_types::vector::PointId;
|
||||
use graphic_types::vector_types::vector::algorithms::merge_by_distance::MergeByDistanceExt;
|
||||
use graphic_types::vector_types::{ATTR_GRADIENT_TYPE, ATTR_SPREAD_METHOD};
|
||||
use graphic_types::{ATTR_FILL, ATTR_STROKE, Graphic, IntoGraphicList, Vector};
|
||||
use linesweeper::topology::Topology;
|
||||
use linesweeper::{BinaryOp, FillRule, binary_op};
|
||||
use smallvec::SmallVec;
|
||||
use vector_types::kurbo::{Affine, BezPath, CubicBez, Line, ParamCurve, PathSeg, Point, QuadBez};
|
||||
pub use vector_types::vector::misc::BooleanOperation;
|
||||
|
||||
// TODO: Fix boolean ops to work by removing .transform() and .one_instance_*() calls,
|
||||
// TODO: since before we used a Vec of single-item `List`s and now we use a single `List`
|
||||
// TODO: with multiple items while still assuming a single item for the boolean operations.
|
||||
|
||||
#[allow(clippy::type_complexity)]
|
||||
fn boolean_core<'e>(
|
||||
arena: &'e core_types::arena::Arena,
|
||||
flattened: List<Vector>,
|
||||
snapshot: List<Graphic<'static>>,
|
||||
operation: BooleanOperation,
|
||||
) -> Result<
|
||||
(
|
||||
Vector,
|
||||
Attr<'e, TransformAttr>,
|
||||
Attr<'e, Fill>,
|
||||
Attr<'e, Stroke>,
|
||||
Attr<'e, BlendModeAttr>,
|
||||
Attr<'e, Opacity>,
|
||||
Attr<'e, OpacityFill>,
|
||||
Attr<'e, ClippingMask>,
|
||||
Attr<'e, EditorLayerPath>,
|
||||
Attr<'e, EditorMergedLayers>,
|
||||
),
|
||||
core_types::gpoll::Interrupt,
|
||||
> {
|
||||
// The first index is the bottom of the stack
|
||||
let mut result_vector_list = boolean_operation_on_vector_list(&flattened, operation);
|
||||
|
||||
// Replace the transformation matrix with a mutation of the vector points themselves
|
||||
if result_vector_list.element_mut(0).is_some() {
|
||||
let transform: DAffine2 = result_vector_list.attribute_cloned_or_default(ATTR_TRANSFORM, 0);
|
||||
result_vector_list.set_attribute(ATTR_TRANSFORM, 0, DAffine2::IDENTITY);
|
||||
|
||||
let result_vector = result_vector_list.element_mut(0).unwrap();
|
||||
Vector::transform(result_vector, transform);
|
||||
result_vector.set_stroke_transform(DAffine2::IDENTITY);
|
||||
|
||||
// Clean up the boolean operation result by merging duplicated points
|
||||
let merge_transform: DAffine2 = result_vector_list.attribute_cloned_or_default(ATTR_TRANSFORM, 0);
|
||||
result_vector_list.element_mut(0).unwrap().merge_by_distance_spatial(merge_transform, 0.0001);
|
||||
}
|
||||
|
||||
let exhausted = || {
|
||||
core_types::gpoll::Interrupt::from(core_types::gpoll::GraphError {
|
||||
kind: core_types::gpoll::ErrorKind::ArenaExhausted,
|
||||
trace: Vec::new(),
|
||||
})
|
||||
};
|
||||
let park_paint = |paint: Option<List<Graphic<'static>>>| -> Result<Option<&'e List<Graphic>>, core_types::gpoll::Interrupt> {
|
||||
match paint {
|
||||
Some(list) => Ok(Some(arena.alloc_sized_keyed(list, 0).ok_or_else(exhausted)?.0)),
|
||||
None => Ok(None),
|
||||
}
|
||||
};
|
||||
|
||||
let element = result_vector_list.element(0).cloned().unwrap_or_default();
|
||||
use core_types::lane::LaneSource;
|
||||
let fill = park_paint(result_vector_list.attr::<Fill>(0).filter(|paint| is_paint_present(paint)).cloned())?;
|
||||
let stroke = park_paint(result_vector_list.attr::<Stroke>(0).filter(|paint| is_paint_present(paint)).cloned())?;
|
||||
let layer_path: Vec<NodeId> = result_vector_list.attribute::<Vec<NodeId>>(ATTR_EDITOR_LAYER_PATH, 0).cloned().unwrap_or_default();
|
||||
let layer_path = arena.alloc(layer_path).ok_or_else(exhausted)?.0;
|
||||
// Snapshot the input layers so the renderer can recurse into them for
|
||||
// editor click-target preservation.
|
||||
let merged_layers = arena.alloc_sized_keyed(snapshot, 0).ok_or_else(exhausted)?.0;
|
||||
|
||||
Ok((
|
||||
element,
|
||||
Attr(result_vector_list.attribute_cloned_or_default(ATTR_TRANSFORM, 0)),
|
||||
Attr(fill),
|
||||
Attr(stroke),
|
||||
Attr(result_vector_list.attribute_cloned_or_default(ATTR_BLEND_MODE, 0)),
|
||||
Attr(result_vector_list.attribute_cloned_or(ATTR_OPACITY, 0, 1.)),
|
||||
Attr(result_vector_list.attribute_cloned_or(ATTR_OPACITY_FILL, 0, 1.)),
|
||||
Attr(result_vector_list.attribute_cloned_or_default(ATTR_CLIPPING_MASK, 0)),
|
||||
Attr(layer_path.as_slice()),
|
||||
Attr(Some(merged_layers)),
|
||||
))
|
||||
}
|
||||
|
||||
/// Combines the geometric forms of one or more closed paths into a new vector path that results from cutting or joining the paths by the chosen method.
|
||||
#[node_macro::node(category("Vector: Modifier"), memoize)]
|
||||
fn boolean_operation<'e>(
|
||||
ctx: impl Ctx + ExtractArena<'e> + core_types::InjectIndex + Copy,
|
||||
/// The input of vector paths to perform the boolean operation on. Nested groups are automatically flattened.
|
||||
content: IList<Graphic<'static>>,
|
||||
/// Which boolean operation to perform on the paths.
|
||||
///
|
||||
/// Union combines all paths while cutting out overlapping areas (even the interiors of a single path).
|
||||
/// 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,
|
||||
) -> Result<
|
||||
(
|
||||
Vector,
|
||||
Attr<'e, TransformAttr>,
|
||||
Attr<'e, Fill>,
|
||||
Attr<'e, Stroke>,
|
||||
Attr<'e, BlendModeAttr>,
|
||||
Attr<'e, Opacity>,
|
||||
Attr<'e, OpacityFill>,
|
||||
Attr<'e, ClippingMask>,
|
||||
Attr<'e, EditorLayerPath>,
|
||||
Attr<'e, EditorMergedLayers>,
|
||||
),
|
||||
core_types::gpoll::Interrupt,
|
||||
> {
|
||||
let item = content.as_group_item();
|
||||
let flattened = flatten_vector_run(GraphicLevel::Run(&item), DAffine2::IDENTITY, PaintReach::NONE);
|
||||
let snapshot = graphic_types::graphic::run_to_list::<Graphic>(&item).expect("the run holds the row's element type").into_graphic_list();
|
||||
boolean_core(ctx.arena(), flattened, snapshot, operation)
|
||||
}
|
||||
|
||||
/// The boolean operation over a plain vector level, as [`boolean_operation`].
|
||||
#[node_macro::node(category(""))]
|
||||
fn boolean_operation_vector<'e>(
|
||||
ctx: impl Ctx + ExtractArena<'e> + core_types::InjectIndex + Copy,
|
||||
content: IList<Vector>,
|
||||
operation: BooleanOperation,
|
||||
) -> Result<
|
||||
(
|
||||
Vector,
|
||||
Attr<'e, TransformAttr>,
|
||||
Attr<'e, Fill>,
|
||||
Attr<'e, Stroke>,
|
||||
Attr<'e, BlendModeAttr>,
|
||||
Attr<'e, Opacity>,
|
||||
Attr<'e, OpacityFill>,
|
||||
Attr<'e, ClippingMask>,
|
||||
Attr<'e, EditorLayerPath>,
|
||||
Attr<'e, EditorMergedLayers>,
|
||||
),
|
||||
core_types::gpoll::Interrupt,
|
||||
> {
|
||||
let item = content.as_group_item();
|
||||
let flattened = graphic_types::graphic::run_to_list::<Vector>(&item).expect("the run holds vector lanes");
|
||||
let snapshot = graphic_types::graphic::run_to_list::<Vector>(&item).expect("the run holds the row's element type").into_graphic_list();
|
||||
boolean_core(ctx.arena(), flattened, snapshot, operation)
|
||||
}
|
||||
|
||||
pub use _boolean_operation_vector_mod::boolean_operation_vector_entries;
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
struct WindingNumber {
|
||||
elems: SmallVec<[i16; 8]>,
|
||||
}
|
||||
|
||||
impl linesweeper::topology::WindingNumber for WindingNumber {
|
||||
type Tag = (usize, usize);
|
||||
|
||||
fn single((tag, out_of): (usize, usize), positive: bool) -> Self {
|
||||
let mut elems = SmallVec::with_capacity(out_of);
|
||||
elems.resize(out_of, 0);
|
||||
elems[tag] = if positive { 1 } else { -1 };
|
||||
Self { elems }
|
||||
}
|
||||
|
||||
fn of_tag(&self, (tag, out_of): Self::Tag) -> Self {
|
||||
let mut elems = SmallVec::with_capacity(out_of);
|
||||
elems.resize(out_of, 0);
|
||||
if let (Some(slot), Some(&value)) = (elems.get_mut(tag), self.elems.get(tag)) {
|
||||
*slot = value;
|
||||
} else {
|
||||
log::warn!("WindingNumber::of_tag: tag {tag} out of bounds (out_of {out_of}, len {})", self.elems.len());
|
||||
}
|
||||
Self { elems }
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::AddAssign for WindingNumber {
|
||||
fn add_assign(&mut self, rhs: Self) {
|
||||
if rhs.elems.is_empty() {
|
||||
return;
|
||||
}
|
||||
if self.elems.is_empty() {
|
||||
self.elems = rhs.elems;
|
||||
} else {
|
||||
for (me, them) in self.elems.iter_mut().zip(&rhs.elems) {
|
||||
*me += *them;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::Add for WindingNumber {
|
||||
type Output = WindingNumber;
|
||||
|
||||
fn add(mut self, rhs: Self) -> Self::Output {
|
||||
self += rhs;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl WindingNumber {
|
||||
fn is_inside(&self, op: BooleanOperation) -> bool {
|
||||
let is_in = |w: &i16| *w != 0;
|
||||
let is_out = |w: &i16| *w == 0;
|
||||
match op {
|
||||
BooleanOperation::Union => self.elems.iter().any(is_in),
|
||||
BooleanOperation::SubtractFront => self.elems.first().is_some_and(is_in) && self.elems.iter().skip(1).all(is_out),
|
||||
BooleanOperation::SubtractBack => self.elems.last().is_some_and(is_in) && self.elems.iter().rev().skip(1).all(is_out),
|
||||
BooleanOperation::Intersect => !self.elems.is_empty() && self.elems.iter().all(is_in),
|
||||
BooleanOperation::Difference => self.elems.iter().any(is_in) && !self.elems.iter().all(is_in),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn boolean_operation_on_vector_list(vector: &List<Vector>, boolean_operation: BooleanOperation) -> List<Vector> {
|
||||
const EPSILON: f64 = 1e-5;
|
||||
let mut list = List::new();
|
||||
let mut paths = Vec::new();
|
||||
|
||||
let copy_from_index = if matches!(boolean_operation, BooleanOperation::SubtractFront) {
|
||||
if !vector.is_empty() { Some(0) } else { None }
|
||||
} else {
|
||||
if !vector.is_empty() { Some(vector.len() - 1) } else { None }
|
||||
};
|
||||
let mut row = if let Some(index) = copy_from_index {
|
||||
let mut attributes = vector.clone_item_attributes(index);
|
||||
let copy_from_transform: DAffine2 = vector.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
// The boolean op bakes input transforms into the output geometry, so the result item carries no transform of its own
|
||||
attributes.insert(ATTR_TRANSFORM, DAffine2::IDENTITY);
|
||||
|
||||
bake_paint_transforms(&mut attributes, copy_from_transform);
|
||||
|
||||
let copy_from = vector.element(index).unwrap();
|
||||
let element = Vector {
|
||||
stroke: copy_from.stroke.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
Item::from_parts(element, attributes)
|
||||
} else {
|
||||
Item::<Vector>::default()
|
||||
};
|
||||
|
||||
for index in 0..vector.len() {
|
||||
let element = vector.element(index).unwrap();
|
||||
paths.push(to_bez_path(element, vector.attribute_cloned_or_default(ATTR_TRANSFORM, index)));
|
||||
}
|
||||
|
||||
let top = match Topology::<WindingNumber>::from_paths(paths.iter().enumerate().map(|(idx, path)| (path, (idx, paths.len()))), EPSILON) {
|
||||
Ok(top) => top,
|
||||
Err(e) => {
|
||||
log::error!("Boolean operation failed while building topology: {e}");
|
||||
list.push(row);
|
||||
return list;
|
||||
}
|
||||
};
|
||||
let contours = top.contours(|winding| winding.is_inside(boolean_operation));
|
||||
for subpath in from_bez_paths(contours.contours().map(|c| &c.path)) {
|
||||
row.element_mut().append_subpath(subpath, false);
|
||||
}
|
||||
|
||||
list.push(row);
|
||||
list
|
||||
}
|
||||
|
||||
/// A raster stand-in row per lane: the image's unit rectangle under its
|
||||
/// transform, black-filled, keeping the layer routing and blending
|
||||
/// attributes.
|
||||
fn raster_stand_in_rows<S: core_types::lane::LaneSource>(image: &S, parent_transform: DAffine2) -> Vec<Item<Vector>> {
|
||||
(0..image.lane_count())
|
||||
.map(|i| {
|
||||
let row_transform: DAffine2 = image.attr::<TransformAttr>(i);
|
||||
let layer: Vec<NodeId> = image.attr::<EditorLayerPath>(i).to_vec();
|
||||
let blend_mode: BlendMode = image.attr::<BlendModeAttr>(i);
|
||||
let opacity: f64 = image.attr::<Opacity>(i);
|
||||
let fill: f64 = image.attr::<OpacityFill>(i);
|
||||
let clip: bool = image.attr::<ClippingMask>(i);
|
||||
|
||||
let mut subpath = Subpath::new_rectangle(DVec2::ZERO, DVec2::ONE);
|
||||
subpath.apply_transform(parent_transform * row_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);
|
||||
set_paint_attribute(item.attributes_mut(), ATTR_FILL, List::new_from_element(Color::BLACK));
|
||||
item
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A color row: an empty vector carrying the color as its fill paint over the
|
||||
/// lane's attributes.
|
||||
fn color_paint_row(color: Color, mut attributes: core_types::list::ItemAttributeValues) -> Item<Vector> {
|
||||
set_paint_attribute(&mut attributes, ATTR_FILL, List::new_from_element(color));
|
||||
|
||||
let mut element = Vector::default();
|
||||
element.set_stroke_transform(DAffine2::IDENTITY);
|
||||
|
||||
Item::from_parts(element, attributes)
|
||||
}
|
||||
|
||||
/// A gradient row: an empty vector carrying the stops as its fill paint, the
|
||||
/// gradient keys moved onto the paint.
|
||||
fn gradient_paint_row(stops: GradientStops, mut attributes: core_types::list::ItemAttributeValues) -> Item<Vector> {
|
||||
let mut gradient_paint = List::new_from_element(Graphic::Gradient(stops));
|
||||
if let Some(transform) = attributes.remove::<DAffine2>(ATTR_TRANSFORM) {
|
||||
gradient_paint.set_attribute(ATTR_TRANSFORM, 0, transform);
|
||||
}
|
||||
if let Some(gradient_type) = attributes.remove::<GradientType>(ATTR_GRADIENT_TYPE) {
|
||||
gradient_paint.set_attribute(ATTR_GRADIENT_TYPE, 0, gradient_type);
|
||||
}
|
||||
if let Some(spread_method) = attributes.remove::<GradientSpreadMethod>(ATTR_SPREAD_METHOD) {
|
||||
gradient_paint.set_attribute(ATTR_SPREAD_METHOD, 0, spread_method);
|
||||
}
|
||||
attributes.insert(ATTR_FILL, Some(gradient_paint));
|
||||
|
||||
let mut element = Vector::default();
|
||||
element.set_stroke_transform(DAffine2::IDENTITY);
|
||||
|
||||
Item::from_parts(element, attributes)
|
||||
}
|
||||
|
||||
/// A text lane's rows: the shaped glyph vectors under the composed transform.
|
||||
fn text_rows(text: &List<String>, parent_transform: DAffine2) -> Vec<Item<Vector>> {
|
||||
text_nodes::shape_text_list(text, false)
|
||||
.into_iter()
|
||||
.map(|mut sub_vector| {
|
||||
let current_transform: DAffine2 = sub_vector.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
*sub_vector.attribute_mut_or_insert_default(ATTR_TRANSFORM) = parent_transform * current_transform;
|
||||
sub_vector
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn push_rows(out: &mut List<Vector>, rows: Vec<Item<Vector>>) {
|
||||
for row in rows {
|
||||
out.push(row);
|
||||
}
|
||||
}
|
||||
|
||||
/// A de-tabled vector leaf as one row: the lane's attributes with the reach
|
||||
/// paint and the ancestor transform composed.
|
||||
fn push_leaf_vector_row(out: &mut List<Vector>, level: GraphicLevel<'_>, index: usize, vector: &Vector, ancestors: DAffine2, reach: PaintReach<'_>) {
|
||||
let out_index = out.len();
|
||||
out.push(Item::from_parts(vector.clone(), graphic_types::graphic::lane_attributes(level, index)));
|
||||
if reach.applies() {
|
||||
for (key, slot) in [(ATTR_FILL, reach.paint.fill), (ATTR_STROKE, reach.paint.stroke)] {
|
||||
if let Some(paint) = slot {
|
||||
set_paint_attribute_at(out, out_index, key, paint.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
let current: DAffine2 = out.attribute_cloned_or_default(ATTR_TRANSFORM, out_index);
|
||||
out.set_attribute(ATTR_TRANSFORM, out_index, ancestors * current);
|
||||
}
|
||||
|
||||
fn push_vector_rows(out: &mut List<Vector>, rows: &List<Vector>, composed: DAffine2, reach: PaintReach<'_>) {
|
||||
for row in 0..rows.len() {
|
||||
let Some(item) = rows.clone_item(row) else { continue };
|
||||
let index = out.len();
|
||||
out.push(item);
|
||||
if reach.applies() {
|
||||
for (key, slot) in [(ATTR_FILL, reach.paint.fill), (ATTR_STROKE, reach.paint.stroke)] {
|
||||
if let Some(paint) = slot {
|
||||
set_paint_attribute_at(out, index, key, paint.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
let current: DAffine2 = out.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
out.set_attribute(ATTR_TRANSFORM, index, composed * current);
|
||||
}
|
||||
}
|
||||
|
||||
fn push_union(out: &mut List<Vector>, flattened: List<Vector>) {
|
||||
for row in boolean_operation_on_vector_list(&flattened, BooleanOperation::Union).into_iter() {
|
||||
out.push(row);
|
||||
}
|
||||
}
|
||||
|
||||
/// The native flatten over a graphic level: the legacy flatten's arms over
|
||||
/// either level storage, with lane paint threaded by [`PaintReach`], leaf
|
||||
/// attributes read from their lanes, and native group runs walked directly.
|
||||
fn flatten_vector_run(level: GraphicLevel<'_>, transform: DAffine2, inherited: PaintReach<'_>) -> List<Vector> {
|
||||
let mut out = List::new();
|
||||
flatten_vector_run_into(&mut out, level, transform, inherited);
|
||||
out
|
||||
}
|
||||
|
||||
fn flatten_vector_run_into<'a>(out: &mut List<Vector>, level: GraphicLevel<'a>, transform: DAffine2, inherited: PaintReach<'a>) {
|
||||
use core_types::lane::{LaneSource, LeafLane};
|
||||
let columns = PaintColumns::new(&level);
|
||||
for index in 0..level.lane_count() {
|
||||
let Some(element) = level.element(index) else { continue };
|
||||
let reach = inherited.for_lane(&columns, index);
|
||||
let composed = transform * level.attr::<TransformAttr>(index);
|
||||
match element {
|
||||
Graphic::Vector(vector) => push_leaf_vector_row(out, level, index, vector, transform, reach),
|
||||
Graphic::Graphic(children) => push_union(out, flatten_vector_run(GraphicLevel::Legacy(children), composed, reach.nested())),
|
||||
Graphic::Group(group) => flatten_group(out, group, composed, reach),
|
||||
Graphic::RasterCPU(raster) => push_rows(out, raster_stand_in_rows(&LeafLane::new(&level, index, raster), transform)),
|
||||
Graphic::RasterGPU(raster) => push_rows(out, raster_stand_in_rows(&LeafLane::new(&level, index, raster), transform)),
|
||||
Graphic::Color(color) => push_rows(out, vec![color_paint_row(*color, graphic_types::graphic::lane_attributes(level, index))]),
|
||||
Graphic::Gradient(gradient) => push_rows(out, vec![gradient_paint_row(gradient.clone(), graphic_types::graphic::lane_attributes(level, index))]),
|
||||
Graphic::Text(text) => {
|
||||
let one = List::new_from_item(Item::from_parts(text.clone(), graphic_types::graphic::lane_attributes(level, index)));
|
||||
push_rows(out, text_rows(&one, composed));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A group flattens as its legacy lowering did: a vector run serves its rows,
|
||||
/// a graphic run unions like a nested list, and another typed run serves its
|
||||
/// stand-in rows.
|
||||
fn flatten_group(out: &mut List<Vector>, group: &core_types::record::Group, composed: DAffine2, reach: PaintReach<'_>) {
|
||||
let item = &group.content;
|
||||
if let Some(rows) = graphic_types::graphic::run_to_list::<Vector>(item) {
|
||||
push_vector_rows(out, &rows, composed, reach);
|
||||
} else if core_types::record::RunView::<Graphic>::new(item).is_some() {
|
||||
push_union(out, flatten_vector_run(GraphicLevel::Run(item), composed, reach.into_group_graphics()));
|
||||
} else if let Some(image) = graphic_types::graphic::run_to_list::<Raster<CPU>>(item) {
|
||||
push_rows(out, raster_stand_in_rows(&image, composed));
|
||||
} else if let Some(image) = graphic_types::graphic::run_to_list::<Raster<GPU>>(item) {
|
||||
push_rows(out, raster_stand_in_rows(&image, composed));
|
||||
} else if let Some(color) = graphic_types::graphic::run_to_list::<Color>(item) {
|
||||
push_rows(
|
||||
out,
|
||||
(0..color.len()).filter_map(|i| Some(color_paint_row(*color.element(i)?, color.clone_item_attributes(i)))).collect(),
|
||||
);
|
||||
} else if let Some(gradient) = graphic_types::graphic::run_to_list::<GradientStops>(item) {
|
||||
push_rows(
|
||||
out,
|
||||
(0..gradient.len())
|
||||
.filter_map(|i| Some(gradient_paint_row(gradient.element(i)?.clone(), gradient.clone_item_attributes(i))))
|
||||
.collect(),
|
||||
);
|
||||
} else if let Some(text) = graphic_types::graphic::run_to_list::<String>(item) {
|
||||
push_rows(out, text_rows(&text, composed));
|
||||
}
|
||||
}
|
||||
|
||||
// This quantization should potentially be removed since it's not conceptually necessary,
|
||||
// but without it, the oak leaf in the Changing Seasons demo artwork is funky because
|
||||
// quantization is needed for the top and bottom points to line up vertically.
|
||||
fn quantize_segment(seg: PathSeg) -> PathSeg {
|
||||
const QUANTIZE_EPS: f64 = 1e-8;
|
||||
fn q(p: Point) -> Point {
|
||||
Point::new((p.x / QUANTIZE_EPS).round() * QUANTIZE_EPS, (p.y / QUANTIZE_EPS).round() * QUANTIZE_EPS)
|
||||
}
|
||||
|
||||
match seg {
|
||||
PathSeg::Line(s) => PathSeg::Line(Line::new(q(s.p0), q(s.p1))),
|
||||
PathSeg::Quad(s) => PathSeg::Quad(QuadBez::new(q(s.p0), q(s.p1), q(s.p2))),
|
||||
PathSeg::Cubic(s) => PathSeg::Cubic(CubicBez::new(q(s.p0), q(s.p1), q(s.p2), q(s.p3))),
|
||||
}
|
||||
}
|
||||
|
||||
fn to_bez_path(vector: &Vector, transform: DAffine2) -> BezPath {
|
||||
let mut path = BezPath::new();
|
||||
for subpath in vector.stroke_bezier_paths() {
|
||||
push_subpath(&mut path, &subpath, transform);
|
||||
}
|
||||
path
|
||||
}
|
||||
|
||||
fn push_subpath(path: &mut BezPath, subpath: &Subpath<PointId>, transform: DAffine2) {
|
||||
let transform = Affine::new(transform.to_cols_array());
|
||||
let mut first = true;
|
||||
|
||||
for seg in subpath.iter_closed() {
|
||||
let quantized = quantize_segment(transform * seg);
|
||||
if first {
|
||||
first = false;
|
||||
path.move_to(quantized.start());
|
||||
}
|
||||
path.push(quantized.as_path_el());
|
||||
}
|
||||
path.close_path();
|
||||
}
|
||||
|
||||
fn from_bez_paths<'a>(paths: impl Iterator<Item = &'a BezPath>) -> Vec<Subpath<PointId>> {
|
||||
let mut all_subpaths = Vec::new();
|
||||
|
||||
for path in paths {
|
||||
let cubics: Vec<CubicBez> = path.segments().map(|segment| segment.to_cubic()).collect();
|
||||
let mut manipulators_list = Vec::new();
|
||||
let mut current_start = None;
|
||||
|
||||
for (index, cubic) in cubics.iter().enumerate() {
|
||||
let d = |p: Point| DVec2::new(p.x, p.y);
|
||||
let [start, handle1, handle2, end] = [d(cubic.p0), d(cubic.p1), d(cubic.p2), d(cubic.p3)];
|
||||
|
||||
if current_start.is_none() {
|
||||
// Use the correct in-handle (None) and out-handle for the start point
|
||||
manipulators_list.push(ManipulatorGroup::new(start, None, Some(handle1)));
|
||||
} else {
|
||||
// Update the out-handle of the previous point
|
||||
if let Some(last) = manipulators_list.last_mut() {
|
||||
last.out_handle = Some(handle1);
|
||||
}
|
||||
}
|
||||
|
||||
// Add the end point with the correct in-handle and out-handle (None)
|
||||
manipulators_list.push(ManipulatorGroup::new(end, Some(handle2), None));
|
||||
|
||||
current_start = Some(end);
|
||||
|
||||
// Check if this is the last segment
|
||||
if index == cubics.len() - 1 {
|
||||
all_subpaths.push(Subpath::new(manipulators_list, true));
|
||||
manipulators_list = Vec::new(); // Reset manipulators for the next path
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
all_subpaths
|
||||
}
|
||||
|
||||
pub fn boolean_intersect(a: &BezPath, b: &BezPath) -> Vec<BezPath> {
|
||||
match binary_op(a, b, FillRule::NonZero, BinaryOp::Intersection) {
|
||||
Ok(contours) => contours.contours().map(|c| c.path.clone()).collect(),
|
||||
Err(e) => {
|
||||
log::error!("Boolean Operation failed (a: {} segments, b: {} segments): {e}", a.segments().count(), b.segments().count());
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use core_types::record::Group;
|
||||
|
||||
fn square(corner: DVec2) -> Vector {
|
||||
Vector::from_subpath(Subpath::<PointId>::new_rectangle(corner, corner + DVec2::ONE))
|
||||
}
|
||||
|
||||
fn black_paint() -> List<Graphic<'static>> {
|
||||
List::new_from_element(Graphic::Color(Color::BLACK))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_native_flatten_reads_lanes_groups_and_reach() {
|
||||
let inner_vector = square(DVec2::ZERO);
|
||||
let arena = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
let mut builder = core_types::record::RunBuilder::new(&arena, core_types::record::element_write_hashed::<Vector>(), &[], 1).unwrap();
|
||||
builder.push(inner_vector.clone()).unwrap();
|
||||
let inner_item = builder.finish();
|
||||
|
||||
let mut top = List::new();
|
||||
top.push(Item::new_from_element(Graphic::Vector(square(DVec2::ZERO))));
|
||||
top.push(Item::new_from_element(Graphic::Color(Color::BLACK)));
|
||||
top.push(Item::new_from_element(Graphic::Group(Group { row: None, content: inner_item })));
|
||||
top.set_attribute(ATTR_TRANSFORM, 0, DAffine2::from_translation(DVec2::new(5., 5.)));
|
||||
set_paint_attribute_at(&mut top, 0, ATTR_FILL, black_paint());
|
||||
top.set_attribute(ATTR_OPACITY, 1, 0.5);
|
||||
top.set_attribute(ATTR_TRANSFORM, 2, DAffine2::from_scale(DVec2::splat(3.)));
|
||||
|
||||
let rows = flatten_vector_run(GraphicLevel::Legacy(&top), DAffine2::IDENTITY, PaintReach::NONE);
|
||||
assert_eq!(rows.len(), 3);
|
||||
|
||||
// Lane 0: the leaf row keeps its lane attributes, with the lane fill
|
||||
// present and the ancestor composition the identity.
|
||||
assert_eq!(rows.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM, 0), DAffine2::from_translation(DVec2::new(5., 5.)));
|
||||
assert!(graphic_types::graphic::paint_graphics::<Fill, _>(&rows, 0).is_some());
|
||||
|
||||
// Lane 1: the color stand-in carries the lane opacity and the color as
|
||||
// its fill.
|
||||
assert_eq!(rows.attribute_cloned_or::<f64>(ATTR_OPACITY, 1, 1.), 0.5);
|
||||
let fill = graphic_types::graphic::paint_graphics::<Fill, _>(&rows, 1).expect("the color row carries its fill");
|
||||
assert!(matches!(fill.element(0), Some(Graphic::Color(color)) if *color == Color::BLACK));
|
||||
|
||||
// Lane 2: the group's vector run serves its row under the lane
|
||||
// transform.
|
||||
assert_eq!(rows.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM, 2), DAffine2::from_scale(DVec2::splat(3.)));
|
||||
assert_eq!(rows.element(2).unwrap(), &inner_vector);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
[package]
|
||||
name = "raster-nodes"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
description = "Raster operation nodes for Graphene"
|
||||
authors = ["Graphite Authors <contact@graphite.art>"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
serde = ["dep:serde", "core-types?/serde", "raster-types?/serde", "vector-types?/serde"]
|
||||
shader-nodes = ["std", "dep:raster-nodes-shaders", "dep:wgpu-executor"]
|
||||
std = [
|
||||
"serde",
|
||||
"dep:core-types",
|
||||
"dep:dyn-any",
|
||||
"dep:graphene-resource",
|
||||
"dep:graphene-hash",
|
||||
"dep:raster-types",
|
||||
"dep:vector-types",
|
||||
"dep:image",
|
||||
"dep:ndarray",
|
||||
"dep:rand",
|
||||
"dep:rand_chacha",
|
||||
"dep:fastnoise-lite",
|
||||
"dep:kurbo",
|
||||
]
|
||||
wasm = [
|
||||
"core-types/wasm",
|
||||
"raster-types/wasm",
|
||||
"vector-types/wasm",
|
||||
"tsify",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[dependencies]
|
||||
# Local dependencies
|
||||
no-std-types = { workspace = true }
|
||||
node-macro = { workspace = true }
|
||||
|
||||
# Local std dependencies
|
||||
dyn-any = { workspace = true, optional = true }
|
||||
core-types = { workspace = true, optional = true }
|
||||
graphene-resource = { workspace = true, optional = true }
|
||||
graphene-hash = { workspace = true, optional = true }
|
||||
raster-types = { workspace = true, optional = true }
|
||||
vector-types = { workspace = true, optional = true }
|
||||
wgpu-executor = { workspace = true, optional = true }
|
||||
raster-nodes-shaders = { path = "./shaders", optional = true }
|
||||
|
||||
# Workspace dependencies
|
||||
bytemuck = { workspace = true }
|
||||
glam = { workspace = true }
|
||||
spirv-std = { workspace = true }
|
||||
num-traits = { workspace = true }
|
||||
num_enum = { workspace = true }
|
||||
|
||||
# Workspace std dependencies
|
||||
image = { workspace = true, optional = true }
|
||||
ndarray = { workspace = true, optional = true }
|
||||
rand = { workspace = true, optional = true }
|
||||
rand_chacha = { workspace = true, optional = true }
|
||||
fastnoise-lite = { workspace = true, optional = true }
|
||||
serde = { workspace = true, optional = true }
|
||||
kurbo = { workspace = true, optional = true }
|
||||
|
||||
# Workspace Wasm dependencies
|
||||
tsify = { workspace = true, optional = true }
|
||||
wasm-bindgen = { workspace = true, optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { workspace = true }
|
||||
futures = { workspace = true }
|
||||
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "raster-nodes-shaders"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
description = "graphene raster data format"
|
||||
authors = ["Graphite Authors <contact@graphite.art>"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
[dependencies]
|
||||
|
||||
[build-dependencies]
|
||||
cargo-gpu-install = { workspace = true }
|
||||
env_logger = { workspace = true }
|
||||
log = { workspace = true }
|
||||
@@ -0,0 +1,53 @@
|
||||
use cargo_gpu_install::install::{Install, InstalledBackend};
|
||||
use cargo_gpu_install::spirv_builder::SpirvMetadata;
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
env_logger::builder().filter_level(log::LevelFilter::Debug).init();
|
||||
|
||||
// Skip building the shaders if they are provided externally
|
||||
println!("cargo:rerun-if-env-changed=RASTER_NODES_SHADER_PATH");
|
||||
if !std::env::var("RASTER_NODES_SHADER_PATH").unwrap_or_default().is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Allows overriding the PATH to inject the rust-gpu rust toolchain when building the rest of the project with stable rustc.
|
||||
// Used in nix shell. Do not remove without checking with developers using nix.
|
||||
println!("cargo:rerun-if-env-changed=RUST_GPU_PATH_OVERRIDE");
|
||||
if let Ok(path_override) = std::env::var("RUST_GPU_PATH_OVERRIDE") {
|
||||
let current_path = std::env::var("PATH").unwrap_or_default();
|
||||
let new_path = format!("{path_override}:{current_path}");
|
||||
// SAFETY: Build script is single-threaded therefore this cannot lead to undefined behavior.
|
||||
unsafe {
|
||||
std::env::set_var("PATH", &new_path);
|
||||
}
|
||||
}
|
||||
|
||||
let shader_crate = PathBuf::from(concat!(env!("CARGO_MANIFEST_DIR"), "/entrypoint"));
|
||||
|
||||
println!("cargo:rerun-if-env-changed=RUSTC_CODEGEN_SPIRV_PATH");
|
||||
let rustc_codegen_spirv_path = std::env::var("RUSTC_CODEGEN_SPIRV_PATH").unwrap_or_default();
|
||||
let backend = if rustc_codegen_spirv_path.is_empty() {
|
||||
// install the toolchain and build the `rustc_codegen_spirv` codegen backend with it
|
||||
Install::from_shader_crate(shader_crate.clone()).run()?
|
||||
} else {
|
||||
// use the `RUSTC_CODEGEN_SPIRV` environment variable to find the codegen backend
|
||||
let mut backend = InstalledBackend::default();
|
||||
backend.rustc_codegen_spirv_location = PathBuf::from(rustc_codegen_spirv_path);
|
||||
backend.toolchain_channel = "nightly".to_string();
|
||||
backend
|
||||
};
|
||||
|
||||
// build the shader crate
|
||||
let mut builder = backend.to_spirv_builder(shader_crate, "spirv-unknown-naga-wgsl");
|
||||
builder.build_script.defaults = true;
|
||||
builder.spirv_metadata = SpirvMetadata::Full;
|
||||
let wgsl_result = builder.build()?;
|
||||
let path_to_spv = wgsl_result.module.unwrap_single();
|
||||
|
||||
// needs to be fixed upstream
|
||||
let path_to_wgsl = path_to_spv.with_extension("wgsl");
|
||||
|
||||
println!("cargo::rustc-env=RASTER_NODES_SHADER_PATH={}", path_to_wgsl.display());
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
[package]
|
||||
name = "raster-nodes-shaders-entrypoint"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
description = "graphene raster nodes shaders entrypoint"
|
||||
authors = ["Graphite Authors <contact@graphite.art>"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
[dependencies]
|
||||
raster-nodes = { path = "../..", default-features = false }
|
||||
@@ -0,0 +1,2 @@
|
||||
#![no_std]
|
||||
pub use raster_nodes::*;
|
||||
@@ -0,0 +1 @@
|
||||
pub const WGSL_SHADER: &str = include_str!(env!("RASTER_NODES_SHADER_PATH"));
|
||||
@@ -0,0 +1,32 @@
|
||||
use no_std_types::color::Color;
|
||||
|
||||
pub trait Adjust<P> {
|
||||
fn adjust(&mut self, map_fn: impl Fn(&P) -> P);
|
||||
}
|
||||
impl Adjust<Color> for Color {
|
||||
fn adjust(&mut self, map_fn: impl Fn(&Color) -> Color) {
|
||||
*self = map_fn(self);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
mod adjust_std {
|
||||
use super::*;
|
||||
use raster_types::{CPU, Raster};
|
||||
use vector_types::Gradient;
|
||||
|
||||
impl Adjust<Color> for Raster<CPU> {
|
||||
fn adjust(&mut self, map_fn: impl Fn(&Color) -> Color) {
|
||||
for color in self.data_mut().data.iter_mut() {
|
||||
*color = map_fn(color);
|
||||
}
|
||||
}
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,206 @@
|
||||
use crate::adjust::Adjust;
|
||||
#[cfg(feature = "std")]
|
||||
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::{Gradient, GradientStop};
|
||||
|
||||
pub trait Blend<P: Pixel> {
|
||||
fn blend(&self, under: &Self, blend_fn: impl Fn(P, P) -> P) -> Self;
|
||||
}
|
||||
impl Blend<Color> for Color {
|
||||
fn blend(&self, under: &Self, blend_fn: impl Fn(Color, Color) -> Color) -> Self {
|
||||
blend_fn(*self, *under)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
mod blend_std {
|
||||
use super::*;
|
||||
use core::cmp::Ordering;
|
||||
use raster_types::Image;
|
||||
use raster_types::Raster;
|
||||
|
||||
impl Blend<Color> for Raster<CPU> {
|
||||
fn blend(&self, under: &Self, blend_fn: impl Fn(Color, Color) -> Color) -> Self {
|
||||
let data = self.data.iter().zip(under.data.iter()).map(|(a, b)| blend_fn(*a, *b)).collect();
|
||||
|
||||
Raster::new_cpu(Image {
|
||||
data,
|
||||
width: self.width,
|
||||
height: self.height,
|
||||
base64_string: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
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);
|
||||
combined_stops.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal));
|
||||
let stops = combined_stops.into_iter().map(|position| {
|
||||
let over_color = self.evaluate(position);
|
||||
let under_color = under.evaluate(position);
|
||||
let color = blend_fn(over_color, under_color);
|
||||
GradientStop { position, midpoint: 0.5, color }
|
||||
});
|
||||
Gradient::new(stops)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn blend_colors(foreground: Color, background: Color, blend_mode: BlendMode, opacity: f32) -> Color {
|
||||
let target_color = match blend_mode {
|
||||
// Other utility blend modes (hidden from the normal list) - do not have alpha blend
|
||||
BlendMode::Erase => return background.alpha_subtract(foreground),
|
||||
BlendMode::Restore => return background.alpha_add(foreground),
|
||||
BlendMode::MultiplyAlpha => return background.alpha_multiply(foreground),
|
||||
blend_mode => apply_blend_mode(foreground, background, blend_mode),
|
||||
};
|
||||
|
||||
background.alpha_blend(target_color.apply_opacity(opacity))
|
||||
}
|
||||
|
||||
pub fn apply_blend_mode(foreground: Color, background: Color, blend_mode: BlendMode) -> Color {
|
||||
match blend_mode {
|
||||
// Normal group
|
||||
BlendMode::Normal => background.blend_rgb(foreground, Color::blend_normal),
|
||||
// Darken group
|
||||
BlendMode::Darken => background.blend_rgb(foreground, Color::blend_darken),
|
||||
BlendMode::Multiply => background.blend_rgb(foreground, Color::blend_multiply),
|
||||
BlendMode::ColorBurn => background.blend_rgb(foreground, Color::blend_color_burn),
|
||||
BlendMode::LinearBurn => background.blend_rgb(foreground, Color::blend_linear_burn),
|
||||
BlendMode::DarkerColor => background.blend_darker_color(foreground),
|
||||
// Lighten group
|
||||
BlendMode::Lighten => background.blend_rgb(foreground, Color::blend_lighten),
|
||||
BlendMode::Screen => background.blend_rgb(foreground, Color::blend_screen),
|
||||
BlendMode::ColorDodge => background.blend_rgb(foreground, Color::blend_color_dodge),
|
||||
BlendMode::LinearDodge => background.blend_rgb(foreground, Color::blend_linear_dodge),
|
||||
BlendMode::LighterColor => background.blend_lighter_color(foreground),
|
||||
// Contrast group
|
||||
BlendMode::Overlay => foreground.blend_rgb(background, Color::blend_hardlight),
|
||||
BlendMode::SoftLight => background.blend_rgb(foreground, Color::blend_softlight),
|
||||
BlendMode::HardLight => background.blend_rgb(foreground, Color::blend_hardlight),
|
||||
BlendMode::VividLight => background.blend_rgb(foreground, Color::blend_vivid_light),
|
||||
BlendMode::LinearLight => background.blend_rgb(foreground, Color::blend_linear_light),
|
||||
BlendMode::PinLight => background.blend_rgb(foreground, Color::blend_pin_light),
|
||||
BlendMode::HardMix => background.blend_rgb(foreground, Color::blend_hard_mix),
|
||||
// Inversion group
|
||||
BlendMode::Difference => background.blend_rgb(foreground, Color::blend_difference),
|
||||
BlendMode::Exclusion => background.blend_rgb(foreground, Color::blend_exclusion),
|
||||
BlendMode::Subtract => background.blend_rgb(foreground, Color::blend_subtract),
|
||||
BlendMode::Divide => background.blend_rgb(foreground, Color::blend_divide),
|
||||
// Component group
|
||||
BlendMode::Hue => background.blend_hue(foreground),
|
||||
BlendMode::Saturation => background.blend_saturation(foreground),
|
||||
BlendMode::Color => background.blend_color(foreground),
|
||||
BlendMode::Luminosity => background.blend_luminosity(foreground),
|
||||
// Other utility blend modes (hidden from the normal list) - do not have alpha blend
|
||||
_ => panic!("Used blend mode without alpha blend"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
#[node_macro::node(category("Raster"), cfg(feature = "std"))]
|
||||
fn mix<T: Blend<Color> + Clone + Send + Sync + core_types::CacheHash + 'static>(
|
||||
_: impl Ctx,
|
||||
#[implementations(
|
||||
Raster<CPU>,
|
||||
Color,
|
||||
Gradient,
|
||||
)]
|
||||
#[gpu_image]
|
||||
over: Item<T>,
|
||||
#[expose]
|
||||
#[implementations(
|
||||
Raster<CPU>,
|
||||
Color,
|
||||
Gradient,
|
||||
)]
|
||||
#[gpu_image]
|
||||
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> + Clone + Send + Sync + no_std_types::context::CacheHash + 'static>(
|
||||
_: impl Ctx,
|
||||
#[implementations(
|
||||
Raster<CPU>,
|
||||
Color,
|
||||
Gradient,
|
||||
)]
|
||||
#[gpu_image]
|
||||
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.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.
|
||||
let associated_pixel = Color::from_rgbaf32_unchecked(pixel.r() * pixel.a(), pixel.g() * pixel.a(), pixel.b() * pixel.a(), pixel.a());
|
||||
let overlay = apply_blend_mode(color, associated_pixel, blend_mode).map_rgb(|channel| channel * opacity);
|
||||
|
||||
Color::from_rgbaf32_unchecked(image.r() + overlay.r(), image.g() + overlay.g(), image.b() + overlay.b(), pixel.a())
|
||||
});
|
||||
image
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "std", test))]
|
||||
mod test {
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::color::Color;
|
||||
use core_types::list::Item;
|
||||
use raster_types::Image;
|
||||
use raster_types::Raster;
|
||||
|
||||
#[test]
|
||||
fn color_overlay_multiply() {
|
||||
let image_color = Color::from_rgbaf32_unchecked(0.7, 0.6, 0.5, 0.4);
|
||||
let image = Image::new(1, 1, image_color);
|
||||
|
||||
// Color { red: 0., green: 1., blue: 0., alpha: 1. }
|
||||
let overlay_color = Color::GREEN;
|
||||
|
||||
// 100% of the output should come from the multiplied value
|
||||
let opacity = 100.;
|
||||
|
||||
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()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
#[derive(Debug)]
|
||||
pub struct CubicSplines {
|
||||
pub x: [f32; 4],
|
||||
pub y: [f32; 4],
|
||||
}
|
||||
|
||||
impl CubicSplines {
|
||||
pub fn solve(&self) -> [f32; 4] {
|
||||
let (x, y) = (&self.x, &self.y);
|
||||
|
||||
// Build an augmented matrix to solve the system of equations using Gaussian elimination
|
||||
let mut augmented_matrix = [
|
||||
[
|
||||
2. / (x[1] - x[0]),
|
||||
1. / (x[1] - x[0]),
|
||||
0.,
|
||||
0.,
|
||||
// |
|
||||
3. * (y[1] - y[0]) / ((x[1] - x[0]) * (x[1] - x[0])),
|
||||
],
|
||||
[
|
||||
1. / (x[1] - x[0]),
|
||||
2. * (1. / (x[1] - x[0]) + 1. / (x[2] - x[1])),
|
||||
1. / (x[2] - x[1]),
|
||||
0.,
|
||||
// |
|
||||
3. * ((y[1] - y[0]) / ((x[1] - x[0]) * (x[1] - x[0])) + (y[2] - y[1]) / ((x[2] - x[1]) * (x[2] - x[1]))),
|
||||
],
|
||||
[
|
||||
0.,
|
||||
1. / (x[2] - x[1]),
|
||||
2. * (1. / (x[2] - x[1]) + 1. / (x[3] - x[2])),
|
||||
1. / (x[3] - x[2]),
|
||||
// |
|
||||
3. * ((y[2] - y[1]) / ((x[2] - x[1]) * (x[2] - x[1])) + (y[3] - y[2]) / ((x[3] - x[2]) * (x[3] - x[2]))),
|
||||
],
|
||||
[
|
||||
0.,
|
||||
0.,
|
||||
1. / (x[3] - x[2]),
|
||||
2. / (x[3] - x[2]),
|
||||
// |
|
||||
3. * (y[3] - y[2]) / ((x[3] - x[2]) * (x[3] - x[2])),
|
||||
],
|
||||
];
|
||||
|
||||
// Gaussian elimination: forward elimination
|
||||
for row in 0..4 {
|
||||
let pivot_row_index = (row..4)
|
||||
.max_by(|&a_row, &b_row| {
|
||||
augmented_matrix[a_row][row]
|
||||
.abs()
|
||||
.partial_cmp(&augmented_matrix[b_row][row].abs())
|
||||
.unwrap_or(core::cmp::Ordering::Equal)
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
// Swap the current row with the row that has the largest pivot element
|
||||
augmented_matrix.swap(row, pivot_row_index);
|
||||
|
||||
// Eliminate the current column in all rows below the current one
|
||||
for row_below_current in row + 1..4 {
|
||||
assert!(augmented_matrix[row][row].abs() > f32::EPSILON);
|
||||
|
||||
let scale_factor = augmented_matrix[row_below_current][row] / augmented_matrix[row][row];
|
||||
for col in row..5 {
|
||||
augmented_matrix[row_below_current][col] -= augmented_matrix[row][col] * scale_factor
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Gaussian elimination: back substitution
|
||||
let mut solutions = [0.; 4];
|
||||
for col in (0..4).rev() {
|
||||
assert!(augmented_matrix[col][col].abs() > f32::EPSILON);
|
||||
|
||||
solutions[col] = augmented_matrix[col][4] / augmented_matrix[col][col];
|
||||
|
||||
for row in (0..col).rev() {
|
||||
augmented_matrix[row][4] -= augmented_matrix[row][col] * solutions[col];
|
||||
augmented_matrix[row][col] = 0.;
|
||||
}
|
||||
}
|
||||
|
||||
solutions
|
||||
}
|
||||
|
||||
pub fn interpolate(&self, input: f32, solutions: &[f32]) -> f32 {
|
||||
if input <= self.x[0] {
|
||||
return self.y[0];
|
||||
}
|
||||
if input >= self.x[self.x.len() - 1] {
|
||||
return self.y[self.x.len() - 1];
|
||||
}
|
||||
|
||||
// Find the segment that the input falls between
|
||||
let mut segment = 1;
|
||||
while self.x[segment] < input {
|
||||
segment += 1;
|
||||
}
|
||||
let segment_start = segment - 1;
|
||||
let segment_end = segment;
|
||||
|
||||
// Calculate the output value using quadratic interpolation
|
||||
let input_value = self.x[segment_start];
|
||||
let input_value_prev = self.x[segment_end];
|
||||
let output_value = self.y[segment_start];
|
||||
let output_value_prev = self.y[segment_end];
|
||||
let solutions_value = solutions[segment_start];
|
||||
let solutions_value_prev = solutions[segment_end];
|
||||
|
||||
let output_delta = solutions_value_prev * (input_value - input_value_prev) - (output_value - output_value_prev);
|
||||
let solution_delta = (output_value - output_value_prev) - solutions_value * (input_value - input_value_prev);
|
||||
|
||||
let input_ratio = (input - input_value_prev) / (input_value - input_value_prev);
|
||||
let prev_output_ratio = (1. - input_ratio) * output_value_prev;
|
||||
let output_ratio = input_ratio * output_value;
|
||||
let quadratic_ratio = input_ratio * (1. - input_ratio) * (output_delta * (1. - input_ratio) + solution_delta * input_ratio);
|
||||
|
||||
let result = prev_output_ratio + output_ratio + quadratic_ratio;
|
||||
result.clamp(0., 1.)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
use core_types::context::Ctx;
|
||||
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};
|
||||
use raster_types::Image;
|
||||
use raster_types::{CPU, Raster};
|
||||
use std::cmp::{max, min};
|
||||
|
||||
#[node_macro::node(category("Raster: Filter"))]
|
||||
async fn dehaze(_: impl Ctx, image_frame: Item<Raster<CPU>>, strength: Item<Percentage>) -> Item<Raster<CPU>> {
|
||||
let strength = *strength.element();
|
||||
|
||||
let (image, attributes) = image_frame.into_parts();
|
||||
let (width, height) = (image.width, image.height);
|
||||
|
||||
// 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();
|
||||
|
||||
// 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.
|
||||
// The authors of the paper recommended using these values to get a reasonable balance of performance and quality.
|
||||
const PATCH_SIZE: u32 = 15;
|
||||
const TOP_PERCENT: f64 = 0.001;
|
||||
const RADIUS: u32 = 60;
|
||||
const EPSILON: f64 = 0.0001;
|
||||
const TX: f32 = 0.1;
|
||||
|
||||
// Dehazing algorithm based on "Single Image Haze Removal Using Dark Channel Prior"
|
||||
// Paper: <https://www.researchgate.net/publication/220182411_Single_Image_Haze_Removal_Using_Dark_Channel_Prior>
|
||||
// TODO: Make this algorithm work with negative strength values
|
||||
fn dehaze_image(image: DynamicImage, strength: f64) -> DynamicImage {
|
||||
// TODO: Break out this pair of steps into its own node, with a Memoize node which caches the pair of outputs, so the strength can be adjusted without recomputing these two steps.
|
||||
let dark_channel = compute_dark_channel(&image);
|
||||
let atmospheric_light = estimate_atmospheric_light(&image, &dark_channel);
|
||||
|
||||
let transmission_map = estimate_transmission_map(&image, &dark_channel, strength);
|
||||
let refined_transmission_map = refine_transmission_map(&image, &transmission_map);
|
||||
|
||||
recover(&image, &refined_transmission_map, atmospheric_light)
|
||||
}
|
||||
|
||||
fn compute_dark_channel(image: &DynamicImage) -> DynamicImage {
|
||||
let (width, height) = image.dimensions();
|
||||
let mut dark_channel = GrayImage::new(width, height);
|
||||
let half_patch = PATCH_SIZE / 2;
|
||||
|
||||
for y in 0..height {
|
||||
for x in 0..width {
|
||||
let pixel = image.get_pixel(x, y);
|
||||
let min_intensity = min(min(pixel[0], pixel[1]), pixel[2]);
|
||||
dark_channel.put_pixel(x, y, Luma([min_intensity]));
|
||||
}
|
||||
}
|
||||
|
||||
let mut eroded_channel = RgbaImage::new(width, height);
|
||||
|
||||
for y in 0..height {
|
||||
for x in 0..width {
|
||||
let mut local_min = u8::MAX;
|
||||
|
||||
for dy in 0..PATCH_SIZE {
|
||||
for dx in 0..PATCH_SIZE {
|
||||
let nx = x as i32 + dx as i32 - half_patch as i32;
|
||||
let ny = y as i32 + dy as i32 - half_patch as i32;
|
||||
|
||||
if nx >= 0 && nx < width as i32 && ny >= 0 && ny < height as i32 {
|
||||
let intensity = dark_channel.get_pixel(nx as u32, ny as u32)[0];
|
||||
if intensity < local_min {
|
||||
local_min = intensity;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let alpha = image.get_pixel(x, y)[3];
|
||||
eroded_channel.put_pixel(x, y, Rgba([local_min, local_min, local_min, alpha]));
|
||||
}
|
||||
}
|
||||
|
||||
DynamicImage::ImageRgba8(eroded_channel)
|
||||
}
|
||||
|
||||
fn estimate_atmospheric_light(hazy: &DynamicImage, dark_channel: &DynamicImage) -> Rgba<u8> {
|
||||
let (width, height) = hazy.dimensions();
|
||||
let dark = dark_channel.to_luma_alpha8();
|
||||
let total_pixels = (width * height) as usize;
|
||||
let num_pixels = ((TOP_PERCENT / 100.) * total_pixels as f64).ceil() as usize;
|
||||
|
||||
let mut intensities: Vec<(u32, u32, f64)> = Vec::with_capacity(total_pixels);
|
||||
|
||||
for y in 0..height {
|
||||
for x in 0..width {
|
||||
let pixel = dark.get_pixel(x, y);
|
||||
let intensity = pixel.0[0] as f64;
|
||||
intensities.push((x, y, intensity))
|
||||
}
|
||||
}
|
||||
|
||||
intensities.sort_by(|a, b| b.2.partial_cmp(&a.2).unwrap());
|
||||
|
||||
let top_intensities = &intensities[..num_pixels];
|
||||
|
||||
let mut atm_sum = [0., 0., 0.];
|
||||
for (x, y, _) in top_intensities {
|
||||
let pixel = hazy.get_pixel(*x, *y);
|
||||
atm_sum[0] += pixel[0] as f64;
|
||||
atm_sum[1] += pixel[1] as f64;
|
||||
atm_sum[2] += pixel[2] as f64;
|
||||
}
|
||||
|
||||
let num_pixels = num_pixels as f64;
|
||||
|
||||
Rgba([(atm_sum[0] / num_pixels) as u8, (atm_sum[1] / num_pixels) as u8, (atm_sum[2] / num_pixels) as u8, 255])
|
||||
}
|
||||
|
||||
fn estimate_transmission_map(image: &DynamicImage, dark_channel: &DynamicImage, omega: f64) -> DynamicImage {
|
||||
let (width, height) = image.dimensions();
|
||||
let mut transmission_map = RgbaImage::new(width, height);
|
||||
|
||||
for y in 0..height {
|
||||
for x in 0..width {
|
||||
let min_intensity = dark_channel.get_pixel(x, y).0[0] as f32 / 255.;
|
||||
let transmission_value = 1. - omega * min_intensity as f64;
|
||||
let alpha = image.get_pixel(x, y)[3];
|
||||
transmission_map.put_pixel(
|
||||
x,
|
||||
y,
|
||||
Rgba([(transmission_value * 255.) as u8, (transmission_value * 255.) as u8, (transmission_value * 255.) as u8, alpha]),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
DynamicImage::ImageRgba8(transmission_map)
|
||||
}
|
||||
|
||||
fn refine_transmission_map(img: &DynamicImage, transmission_map: &DynamicImage) -> DynamicImage {
|
||||
let gray_image = img.to_luma8();
|
||||
|
||||
let normalized_gray_image: GrayImage = ImageBuffer::from_fn(gray_image.width(), gray_image.height(), |x, y| {
|
||||
let pixel = gray_image.get_pixel(x, y);
|
||||
let normalized_value = (pixel[0] as f64 / 255.) * 255.;
|
||||
Luma([normalized_value as u8])
|
||||
});
|
||||
|
||||
let normalized_gray_image = DynamicImage::ImageLuma8(normalized_gray_image);
|
||||
|
||||
guided_filter(&normalized_gray_image, transmission_map, RADIUS, EPSILON)
|
||||
}
|
||||
|
||||
fn recover(im: &DynamicImage, t: &DynamicImage, a: Rgba<u8>) -> DynamicImage {
|
||||
let (width, height) = im.dimensions();
|
||||
let mut res = DynamicImage::new_rgba8(width, height);
|
||||
|
||||
let a = [a[0] as f32 / 255., a[1] as f32 / 255., a[2] as f32 / 255.];
|
||||
|
||||
for y in 0..height {
|
||||
for x in 0..width {
|
||||
let im_pixel = im.get_pixel(x, y).0;
|
||||
let t_pixel = t.get_pixel(x, y).0;
|
||||
let t_val = f32::max(t_pixel[0] as f32 / 255., TX);
|
||||
|
||||
let mut res_pixel = [0; 4];
|
||||
for ind in 0..3 {
|
||||
res_pixel[ind] = ((((im_pixel[ind] as f32 / 255. - a[ind]) / t_val) + a[ind]).clamp(0., 1.) * 255.) as u8;
|
||||
}
|
||||
res_pixel[3] = im_pixel[3];
|
||||
|
||||
res.put_pixel(x, y, Rgba(res_pixel));
|
||||
}
|
||||
}
|
||||
|
||||
res
|
||||
}
|
||||
|
||||
fn guided_filter(guidance_img: &DynamicImage, input_img: &DynamicImage, r: u32, epsilon: f64) -> DynamicImage {
|
||||
let (width, height) = guidance_img.dimensions();
|
||||
let radius = r as i32;
|
||||
|
||||
let guidance_nd = image_to_ndarray(guidance_img);
|
||||
let input_nd = image_to_ndarray(input_img);
|
||||
|
||||
let mean_guidance = box_filter(&guidance_nd, radius);
|
||||
let mean_input = box_filter(&input_nd, radius);
|
||||
let corr_guidance = box_filter(&(guidance_nd.clone() * guidance_nd.clone()), radius);
|
||||
let corr_guidance_input = box_filter(&(guidance_nd.clone() * input_nd.clone()), radius);
|
||||
|
||||
let var_guidance = &corr_guidance - &(mean_guidance.clone() * mean_guidance.clone());
|
||||
let cov_guidance_input = &corr_guidance_input - &(mean_guidance.clone() * mean_input.clone());
|
||||
|
||||
let a = &cov_guidance_input / &(var_guidance.clone() + epsilon);
|
||||
let b = mean_input - &(a.clone() * mean_guidance);
|
||||
|
||||
let mean_a = box_filter(&a, radius);
|
||||
let mean_b = box_filter(&b, radius);
|
||||
|
||||
let q = &mean_a * &guidance_nd + mean_b;
|
||||
|
||||
ndarray_to_image(&q, width, height)
|
||||
}
|
||||
|
||||
fn box_filter(img: &Array2<f64>, radius: i32) -> Array2<f64> {
|
||||
let (height, width) = img.dim();
|
||||
let mut result = Array2::zeros((height, width));
|
||||
let mut integral_image: ArrayBase<OwnedRepr<f64>, Dim<[usize; 2]>> = Array2::zeros((height + 1, width + 1));
|
||||
|
||||
// Compute integral image
|
||||
for y in 0..height {
|
||||
for x in 0..width {
|
||||
integral_image[(y + 1, x + 1)] = img[(y, x)] + integral_image[(y, x + 1)] + integral_image[(y + 1, x)] - integral_image[(y, x)];
|
||||
}
|
||||
}
|
||||
|
||||
for y in 0..height {
|
||||
for x in 0..width {
|
||||
let y1 = max(0, y as i32 - radius) as usize;
|
||||
let y2 = min(height as i32 - 1, y as i32 + radius) as usize;
|
||||
let x1 = max(0, x as i32 - radius) as usize;
|
||||
let x2 = min(width as i32 - 1, x as i32 + radius) as usize;
|
||||
|
||||
let area = (y2 - y1 + 1) as f64 * (x2 - x1 + 1) as f64;
|
||||
|
||||
result[(y, x)] = (integral_image[(y2 + 1, x2 + 1)] - integral_image[(y1, x2 + 1)] - integral_image[(y2 + 1, x1)] + integral_image[(y1, x1)]) / area;
|
||||
}
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
fn image_to_ndarray(img: &DynamicImage) -> Array2<f64> {
|
||||
let (width, height) = img.dimensions();
|
||||
let mut array = Array2::zeros((height as usize, width as usize));
|
||||
for (x, y, pixel) in img.pixels() {
|
||||
let luminance = pixel.0[0] as f64 / 255.;
|
||||
array[(y as usize, x as usize)] = luminance;
|
||||
}
|
||||
array
|
||||
}
|
||||
|
||||
fn ndarray_to_image(array: &Array2<f64>, width: u32, height: u32) -> DynamicImage {
|
||||
let mut img = DynamicImage::new_rgba8(width, height);
|
||||
for ((y, x), &value) in array.indexed_iter() {
|
||||
let clamped_value = (value * 255.).clamp(0., 255.) as u8;
|
||||
img.put_pixel(x as u32, y as u32, Rgba([clamped_value, clamped_value, clamped_value, 255]));
|
||||
}
|
||||
img
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
use bytemuck::{Pod, Zeroable};
|
||||
use core_types::color::{Alpha, Color, Pixel, RGB};
|
||||
use core_types::context::Ctx;
|
||||
use core_types::list::Item;
|
||||
use core_types::registry::types::PixelLength;
|
||||
use raster_types::Image;
|
||||
use raster_types::{Bitmap, BitmapMut};
|
||||
use raster_types::{CPU, Raster};
|
||||
|
||||
/// Working-buffer pixel for the blur algorithms' `gamma` mode: premultiplied sRGB-gamma `f32` channels.
|
||||
/// Only used internally so the working buffer's color space is reflected in the type instead of stuffed into `Color` (which is linear-light by invariant).
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Pod, Zeroable)]
|
||||
struct PremultipliedGammaPixel {
|
||||
r: f32,
|
||||
g: f32,
|
||||
b: f32,
|
||||
a: f32,
|
||||
}
|
||||
|
||||
impl Pixel for PremultipliedGammaPixel {}
|
||||
|
||||
impl RGB for PremultipliedGammaPixel {
|
||||
type ColorChannel = f32;
|
||||
fn red(&self) -> f32 {
|
||||
self.r
|
||||
}
|
||||
fn green(&self) -> f32 {
|
||||
self.g
|
||||
}
|
||||
fn blue(&self) -> f32 {
|
||||
self.b
|
||||
}
|
||||
}
|
||||
|
||||
impl Alpha for PremultipliedGammaPixel {
|
||||
type AlphaChannel = f32;
|
||||
const TRANSPARENT: Self = Self { r: 0., g: 0., b: 0., a: 0. };
|
||||
fn alpha(&self) -> f32 {
|
||||
self.a
|
||||
}
|
||||
fn multiplied_alpha(&self, mult: f32) -> Self {
|
||||
Self {
|
||||
r: self.r * mult,
|
||||
g: self.g * mult,
|
||||
b: self.b * mult,
|
||||
a: self.a * mult,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn premultiply_gamma(buffer: Image<Color>) -> Image<PremultipliedGammaPixel> {
|
||||
Image {
|
||||
width: buffer.width,
|
||||
height: buffer.height,
|
||||
data: buffer
|
||||
.data
|
||||
.into_iter()
|
||||
.map(|px| {
|
||||
let [r, g, b, a] = px.to_gamma_srgb_channels();
|
||||
PremultipliedGammaPixel { r: r * a, g: g * a, b: b * a, a }
|
||||
})
|
||||
.collect(),
|
||||
base64_string: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn unpremultiply_gamma_to_linear(buffer: Image<PremultipliedGammaPixel>) -> Image<Color> {
|
||||
Image {
|
||||
width: buffer.width,
|
||||
height: buffer.height,
|
||||
data: buffer
|
||||
.data
|
||||
.into_iter()
|
||||
.map(|px| {
|
||||
if px.a > 0. {
|
||||
let inv_a = 1. / px.a;
|
||||
Color::from_gamma_srgb_channels(px.r * inv_a, px.g * inv_a, px.b * inv_a, px.a)
|
||||
} else {
|
||||
Color::TRANSPARENT
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
base64_string: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Blurs the image with a Gaussian or box blur kernel filter.
|
||||
#[node_macro::node(category("Raster: Filter"))]
|
||||
fn blur(
|
||||
_: impl Ctx,
|
||||
/// The image to be blurred.
|
||||
image_frame: Item<Raster<CPU>>,
|
||||
/// The radius of the blur kernel.
|
||||
#[range]
|
||||
#[hard(0..)]
|
||||
#[soft(..100)]
|
||||
radius: Item<PixelLength>,
|
||||
/// Use a lower-quality box kernel instead of a circular Gaussian kernel. This is faster but produces boxy artifacts.
|
||||
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: Item<bool>,
|
||||
) -> Item<Raster<CPU>> {
|
||||
let (radius, box_blur, gamma) = (*radius.element(), *box_blur.element(), *gamma.element());
|
||||
|
||||
let (image, attributes) = image_frame.into_parts();
|
||||
|
||||
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.
|
||||
#[node_macro::node(category("Raster: Filter"))]
|
||||
fn median_filter(
|
||||
_: impl Ctx,
|
||||
/// The image to be filtered.
|
||||
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: Item<PixelLength>,
|
||||
) -> Item<Raster<CPU>> {
|
||||
let radius = *radius.element();
|
||||
|
||||
let (image, attributes) = image_frame.into_parts();
|
||||
|
||||
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
|
||||
fn gaussian_kernel(radius: f64) -> Vec<f64> {
|
||||
// Given radius, compute the size of the kernel that's approximately three times the radius
|
||||
let kernel_radius = (3. * radius).ceil() as usize;
|
||||
let kernel_size = 2 * kernel_radius + 1;
|
||||
let mut gaussian_kernel: Vec<f64> = vec![0.; kernel_size];
|
||||
|
||||
// Kernel values
|
||||
let two_radius_squared = 2. * radius * radius;
|
||||
let sum = gaussian_kernel
|
||||
.iter_mut()
|
||||
.enumerate()
|
||||
.map(|(i, value_at_index)| {
|
||||
let x = i as f64 - kernel_radius as f64;
|
||||
let exponent = -(x * x) / two_radius_squared;
|
||||
*value_at_index = exponent.exp();
|
||||
*value_at_index
|
||||
})
|
||||
.sum::<f64>();
|
||||
|
||||
// Normalize
|
||||
gaussian_kernel.iter_mut().for_each(|value_at_index| *value_at_index /= sum);
|
||||
|
||||
gaussian_kernel
|
||||
}
|
||||
|
||||
fn gaussian_blur_algorithm(buffer: Image<Color>, radius: f64, gamma: bool) -> Image<Color> {
|
||||
let kernel = gaussian_kernel(radius);
|
||||
if gamma {
|
||||
let working = premultiply_gamma(buffer);
|
||||
let blurred = gaussian_separable(working, &kernel, |r, g, b, a| PremultipliedGammaPixel { r, g, b, a });
|
||||
unpremultiply_gamma_to_linear(blurred)
|
||||
} else {
|
||||
let mut working = buffer;
|
||||
working.map_pixels(|px| px.apply_opacity(px.a()));
|
||||
let mut blurred = gaussian_separable(working, &kernel, Color::from_rgbaf32_unchecked);
|
||||
blurred.map_pixels(|px| px.to_unassociated_alpha());
|
||||
blurred
|
||||
}
|
||||
}
|
||||
|
||||
fn box_blur_algorithm(buffer: Image<Color>, radius: f64, gamma: bool) -> Image<Color> {
|
||||
if gamma {
|
||||
let working = premultiply_gamma(buffer);
|
||||
let blurred = box_separable(working, radius, |r, g, b, a| PremultipliedGammaPixel { r, g, b, a });
|
||||
unpremultiply_gamma_to_linear(blurred)
|
||||
} else {
|
||||
let mut working = buffer;
|
||||
working.map_pixels(|px| px.apply_opacity(px.a()));
|
||||
let mut blurred = box_separable(working, radius, Color::from_rgbaf32_unchecked);
|
||||
blurred.map_pixels(|px| px.to_unassociated_alpha());
|
||||
blurred
|
||||
}
|
||||
}
|
||||
|
||||
fn gaussian_separable<P, F>(buffer: Image<P>, kernel: &[f64], construct: F) -> Image<P>
|
||||
where
|
||||
P: Pixel + Copy + RGB<ColorChannel = f32> + Alpha<AlphaChannel = f32>,
|
||||
F: Fn(f32, f32, f32, f32) -> P,
|
||||
{
|
||||
let (width, height) = buffer.dimensions();
|
||||
let half_kernel = kernel.len() / 2;
|
||||
|
||||
let mut x_axis = Image::new(width, height, P::default());
|
||||
let mut y_axis = Image::new(width, height, P::default());
|
||||
|
||||
for pass in [false, true] {
|
||||
let (max, old_buffer, current_buffer) = match pass {
|
||||
false => (width, &buffer, &mut x_axis),
|
||||
true => (height, &x_axis, &mut y_axis),
|
||||
};
|
||||
let pass = pass as usize;
|
||||
|
||||
for y in 0..height {
|
||||
for x in 0..width {
|
||||
let (mut r_sum, mut g_sum, mut b_sum, mut a_sum, mut weight_sum) = (0., 0., 0., 0., 0.);
|
||||
|
||||
for (i, &weight) in kernel.iter().enumerate() {
|
||||
let p = [x, y][pass] as i32 + (i as i32 - half_kernel as i32);
|
||||
|
||||
if p >= 0
|
||||
&& p < max as i32 && let Some(px) = old_buffer.get_pixel([p as u32, x][pass], [y, p as u32][pass])
|
||||
{
|
||||
r_sum += px.r() as f64 * weight;
|
||||
g_sum += px.g() as f64 * weight;
|
||||
b_sum += px.b() as f64 * weight;
|
||||
a_sum += px.a() as f64 * weight;
|
||||
weight_sum += weight;
|
||||
}
|
||||
}
|
||||
|
||||
let (r, g, b, a) = if weight_sum > 0. {
|
||||
((r_sum / weight_sum) as f32, (g_sum / weight_sum) as f32, (b_sum / weight_sum) as f32, (a_sum / weight_sum) as f32)
|
||||
} else {
|
||||
let px = old_buffer.get_pixel(x, y).unwrap();
|
||||
(px.r(), px.g(), px.b(), px.a())
|
||||
};
|
||||
current_buffer.set_pixel(x, y, construct(r, g, b, a));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
y_axis
|
||||
}
|
||||
|
||||
fn box_separable<P, F>(buffer: Image<P>, radius: f64, construct: F) -> Image<P>
|
||||
where
|
||||
P: Pixel + Copy + RGB<ColorChannel = f32> + Alpha<AlphaChannel = f32>,
|
||||
F: Fn(f32, f32, f32, f32) -> P,
|
||||
{
|
||||
let (width, height) = buffer.dimensions();
|
||||
let mut x_axis = Image::new(width, height, P::default());
|
||||
let mut y_axis = Image::new(width, height, P::default());
|
||||
|
||||
for pass in [false, true] {
|
||||
let (max, old_buffer, current_buffer) = match pass {
|
||||
false => (width, &buffer, &mut x_axis),
|
||||
true => (height, &x_axis, &mut y_axis),
|
||||
};
|
||||
let pass = pass as usize;
|
||||
|
||||
for y in 0..height {
|
||||
for x in 0..width {
|
||||
let (mut r_sum, mut g_sum, mut b_sum, mut a_sum, mut weight_sum) = (0., 0., 0., 0., 0.);
|
||||
|
||||
let i = [x, y][pass];
|
||||
for d in (i as i32 - radius as i32).max(0)..=(i as i32 + radius as i32).min(max as i32 - 1) {
|
||||
if let Some(px) = old_buffer.get_pixel([d as u32, x][pass], [y, d as u32][pass]) {
|
||||
let weight = 1.;
|
||||
r_sum += px.r() as f64 * weight;
|
||||
g_sum += px.g() as f64 * weight;
|
||||
b_sum += px.b() as f64 * weight;
|
||||
a_sum += px.a() as f64 * weight;
|
||||
weight_sum += weight;
|
||||
}
|
||||
}
|
||||
|
||||
let (r, g, b, a) = ((r_sum / weight_sum) as f32, (g_sum / weight_sum) as f32, (b_sum / weight_sum) as f32, (a_sum / weight_sum) as f32);
|
||||
current_buffer.set_pixel(x, y, construct(r, g, b, a));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
y_axis
|
||||
}
|
||||
|
||||
fn median_filter_algorithm(original_buffer: Image<Color>, radius: u32) -> Image<Color> {
|
||||
let (width, height) = original_buffer.dimensions();
|
||||
let mut output = Image::new(width, height, Color::TRANSPARENT);
|
||||
|
||||
// Pre-allocate and reuse buffers outside the loops to avoid repeated allocations.
|
||||
let window_capacity = ((2 * radius + 1).pow(2)) as usize;
|
||||
let mut r_vals: Vec<f32> = Vec::with_capacity(window_capacity);
|
||||
let mut g_vals: Vec<f32> = Vec::with_capacity(window_capacity);
|
||||
let mut b_vals: Vec<f32> = Vec::with_capacity(window_capacity);
|
||||
let mut a_vals: Vec<f32> = Vec::with_capacity(window_capacity);
|
||||
|
||||
for y in 0..height {
|
||||
for x in 0..width {
|
||||
r_vals.clear();
|
||||
g_vals.clear();
|
||||
b_vals.clear();
|
||||
a_vals.clear();
|
||||
|
||||
// Use saturating_add to avoid potential overflow in extreme cases
|
||||
let y_max = y.saturating_add(radius).min(height - 1);
|
||||
let x_max = x.saturating_add(radius).min(width - 1);
|
||||
|
||||
for ny in y.saturating_sub(radius)..=y_max {
|
||||
for nx in x.saturating_sub(radius)..=x_max {
|
||||
if let Some(px) = original_buffer.get_pixel(nx, ny) {
|
||||
r_vals.push(px.r());
|
||||
g_vals.push(px.g());
|
||||
b_vals.push(px.b());
|
||||
a_vals.push(px.a());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let r = median_quickselect(&mut r_vals);
|
||||
let g = median_quickselect(&mut g_vals);
|
||||
let b = median_quickselect(&mut b_vals);
|
||||
let a = median_quickselect(&mut a_vals);
|
||||
|
||||
output.set_pixel(x, y, Color::from_rgbaf32_unchecked(r, g, b, a));
|
||||
}
|
||||
}
|
||||
|
||||
output
|
||||
}
|
||||
/// Finds the median of a slice using quickselect for O(n) average case performance.
|
||||
/// This is more efficient than sorting the entire slice which would be O(n log n).
|
||||
fn median_quickselect(values: &mut [f32]) -> f32 {
|
||||
let mid: usize = values.len() / 2;
|
||||
// nth_unstable is like quickselect: average O(n)
|
||||
// Use total_cmp for safe NaN handling instead of partial_cmp().unwrap()
|
||||
*values.select_nth_unstable_by(mid, |a, b| a.total_cmp(b)).1
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
use glam::{Vec2, Vec4};
|
||||
use spirv_std::spirv;
|
||||
|
||||
/// WebGPU NDC is like OpenGL: (-1..1, -1..1, 0..1)
|
||||
/// https://www.w3.org/TR/webgpu/#coordinate-systems
|
||||
///
|
||||
/// So to make a fullscreen triangle around a box at (-1..1):
|
||||
///
|
||||
/// ```text
|
||||
/// 3 +
|
||||
/// |\
|
||||
/// 2 | \
|
||||
/// | \
|
||||
/// 1 +-----+
|
||||
/// | |\
|
||||
/// 0 | 0 | \
|
||||
/// | | \
|
||||
/// -1 +-----+-----+
|
||||
/// -1 0 1 2 3
|
||||
/// ```
|
||||
const FULLSCREEN_VERTICES: [Vec2; 3] = [Vec2::new(-1., -1.), Vec2::new(-1., 3.), Vec2::new(3., -1.)];
|
||||
|
||||
#[spirv(vertex)]
|
||||
pub fn fullscreen_vertex(#[spirv(vertex_index)] vertex_index: u32, #[spirv(position)] gl_position: &mut Vec4) {
|
||||
// broken on edition 2024 branch
|
||||
// let vertex = unsafe { *FULLSCREEN_VERTICES.index_unchecked(vertex_index as usize) };
|
||||
let vertex = FULLSCREEN_VERTICES[vertex_index as usize];
|
||||
*gl_position = Vec4::from((vertex, 0., 1.));
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
//! Not immediately shader compatible due to needing [`Gradient`] as a param, which needs [`Vec`]
|
||||
|
||||
use crate::adjust::Adjust;
|
||||
use core_types::list::Item;
|
||||
use core_types::{Color, Ctx};
|
||||
use raster_types::{CPU, Raster};
|
||||
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> + Send>(
|
||||
_: impl Ctx,
|
||||
#[implementations(
|
||||
Raster<CPU>,
|
||||
Color,
|
||||
Gradient,
|
||||
)]
|
||||
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.element_mut().adjust(|color| {
|
||||
let intensity = color.luminance_rec_709();
|
||||
let intensity = if reverse { 1. - intensity } else { intensity };
|
||||
gradient.evaluate(intensity as f64)
|
||||
});
|
||||
|
||||
image
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
use core_types::color::Color;
|
||||
use core_types::context::{Ctx, ExtractIndex, InjectIndex};
|
||||
use core_types::gpoll::{GraphError, Interrupt};
|
||||
use raster_types::{CPU, Raster};
|
||||
|
||||
#[node_macro::node(category("Color"))]
|
||||
fn image_color_palette(
|
||||
ctx: impl Ctx + ExtractIndex + InjectIndex + Copy,
|
||||
image: IList<Raster<CPU>>,
|
||||
#[default(4)]
|
||||
#[hard(1..)]
|
||||
count: u32,
|
||||
) -> Result<IList<Color>, Interrupt> {
|
||||
const GRID: f32 = 3.;
|
||||
|
||||
let bins = GRID * GRID * GRID;
|
||||
|
||||
let mut histogram = vec![0; (bins + 1.) as usize];
|
||||
// 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 row in 0..image.len() {
|
||||
let element = image.element_ref(row);
|
||||
for pixel in 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;
|
||||
|
||||
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>>();
|
||||
|
||||
let palette: Vec<Color> = shorted
|
||||
.iter()
|
||||
.take(*count.element() as usize)
|
||||
.flat_map(|&i| {
|
||||
let list = &color_bins[i];
|
||||
|
||||
let [mut r, mut g, mut b, mut a] = [0.; 4];
|
||||
|
||||
for &[cr, cg, cb, ca] in list.iter() {
|
||||
r += cr;
|
||||
g += cg;
|
||||
b += cb;
|
||||
a += ca;
|
||||
}
|
||||
|
||||
let len = list.len() as f32;
|
||||
let [r, g, b, a] = [r / len, g / len, b / len, a / len];
|
||||
|
||||
// Reject NaN/out-of-range averages, then lift the gamma-space bin centroid to linear-light
|
||||
let in_gamut = a <= 1. && ![r, g, b, a].iter().any(|c| c.is_sign_negative() || !c.is_finite());
|
||||
in_gamut.then(|| Color::from_gamma_srgb_channels(r, g, b, a)).into_iter()
|
||||
})
|
||||
.collect();
|
||||
|
||||
palette.get(ctx.index() as usize).copied().ok_or_else(|| GraphError::past_end().into())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
use raster_types::Image;
|
||||
use raster_types::Raster;
|
||||
|
||||
#[test]
|
||||
fn test_image_color_palette() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = core_types::arena::Arena::new(1 << 22).unwrap();
|
||||
let generations = [];
|
||||
let scope = core_types::context::EvalScope::new(None, None, None, &generations, &arena);
|
||||
let ctx = core_types::context::ContextImpl::root(&scope);
|
||||
|
||||
let raster = Raster::new_cpu(Image {
|
||||
width: 100,
|
||||
height: 100,
|
||||
data: vec![Color::from_rgbaf32(0., 0., 0., 1.).unwrap(); 10000],
|
||||
base64_string: None,
|
||||
});
|
||||
let source = core_types::value::LeveledValueSource::new(vec![raster]);
|
||||
let core_types::record::LevelStatus::Batch(batch, _) = core_types::record::materialize_level(&source, &ctx, &arena, &frames) else {
|
||||
panic!("materialize failed")
|
||||
};
|
||||
let image = unsafe { core_types::node::List::<Raster<CPU>>::new(batch) };
|
||||
|
||||
// The root context addresses lane 0, the palette's first color
|
||||
let color = image_color_palette(&ctx, image, 1).unwrap();
|
||||
assert_eq!(color, Color::from_rgbaf32(0., 0., 0., 1.).unwrap());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
pub mod adjust;
|
||||
pub mod adjustments;
|
||||
pub mod blending_nodes;
|
||||
pub mod cubic_spline;
|
||||
pub mod fullscreen_vertex;
|
||||
|
||||
/// required by shader macro
|
||||
#[cfg(feature = "shader-nodes")]
|
||||
pub use raster_nodes_shaders::WGSL_SHADER;
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
pub mod dehaze;
|
||||
#[cfg(feature = "std")]
|
||||
pub mod filter;
|
||||
#[cfg(feature = "std")]
|
||||
pub mod gradient_map;
|
||||
#[cfg(feature = "std")]
|
||||
pub mod image_color_palette;
|
||||
#[cfg(feature = "std")]
|
||||
pub mod std_nodes;
|
||||
@@ -0,0 +1,588 @@
|
||||
use crate::adjustments::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, NoiseType};
|
||||
use core_types::attribute::{Attr, Attribute, BlendMode as BlendModeAttr, ClippingMask, EditorLayerPath, Opacity, OpacityFill, Transform as TransformAttr};
|
||||
use core_types::color::Color;
|
||||
use core_types::color::{Alpha, AlphaMut, Channel, LinearChannel, Luminance, RGBMut};
|
||||
use core_types::context::{Ctx, ExtractFootprint, ExtractIndex, InjectIndex};
|
||||
use core_types::extent::{LevelIn, ListIn, ValueIn};
|
||||
use core_types::gpoll::{Extent, GPoll, GraphError, Interrupt};
|
||||
use core_types::list::Item;
|
||||
use core_types::math::bbox::Bbox;
|
||||
use core_types::transform::Transform;
|
||||
use dyn_any::DynAny;
|
||||
use fastnoise_lite;
|
||||
use glam::{DAffine2, DVec2, Vec2};
|
||||
use graphene_resource::Resource;
|
||||
use rand::prelude::*;
|
||||
use rand_chacha::ChaCha8Rng;
|
||||
use raster_types::Image;
|
||||
use raster_types::{Bitmap, BitmapMut};
|
||||
use raster_types::{CPU, Raster};
|
||||
use std::fmt::Debug;
|
||||
|
||||
#[derive(Debug, DynAny)]
|
||||
pub enum Error {
|
||||
IO(std::io::Error),
|
||||
Image(::image::ImageError),
|
||||
}
|
||||
|
||||
impl From<std::io::Error> for Error {
|
||||
fn from(e: std::io::Error) -> Self {
|
||||
Error::IO(e)
|
||||
}
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Debug"))]
|
||||
pub fn sample_image(ctx: impl Ctx + ExtractFootprint, (image, lane_transform): (Raster<CPU>, Attr<TransformAttr>)) -> (Raster<CPU>, Attr<TransformAttr>) {
|
||||
let image_frame_transform: DAffine2 = *lane_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 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();
|
||||
|
||||
// A culled lane serves a zero-size raster, which renders as nothing.
|
||||
if size.x <= 0. || size.y <= 0. {
|
||||
return (Raster::new_cpu(Image::default()), Attr(image_frame_transform));
|
||||
}
|
||||
|
||||
let image_buffer = ::image::Rgba32FImage::from_raw(image.width, image.height, data).expect("Failed to convert internal image format into image-rs data type.");
|
||||
|
||||
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 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;
|
||||
|
||||
// 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 new_transform = image_frame_transform * DAffine2::from_translation(offset) * DAffine2::from_scale(size);
|
||||
|
||||
(Raster::new_cpu(image), Attr(new_transform))
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Raster: Channels"), extent(combine_channels_extent))]
|
||||
pub fn combine_channels<'e>(
|
||||
ctx: impl Ctx + ExtractArena<'e> + ExtractIndex + InjectIndex + Copy,
|
||||
_primary: (),
|
||||
#[expose] red: IList<Raster<CPU>>,
|
||||
#[expose] green: IList<Raster<CPU>>,
|
||||
#[expose] blue: IList<Raster<CPU>>,
|
||||
#[expose] alpha: IList<Raster<CPU>>,
|
||||
) -> Result<
|
||||
IList<(
|
||||
Raster<CPU>,
|
||||
Attr<'e, TransformAttr>,
|
||||
Attr<'e, BlendModeAttr>,
|
||||
Attr<'e, Opacity>,
|
||||
Attr<'e, OpacityFill>,
|
||||
Attr<'e, ClippingMask>,
|
||||
Attr<'e, EditorLayerPath>,
|
||||
)>,
|
||||
Interrupt,
|
||||
> {
|
||||
let lane = ctx.index() as usize;
|
||||
let max_len = red.len().max(green.len()).max(blue.len()).max(alpha.len());
|
||||
if lane >= max_len {
|
||||
return Err(GraphError::past_end().into());
|
||||
}
|
||||
|
||||
// Zero-size lanes and lanes past a shorter channel's end contribute nothing
|
||||
fn pick<'l>(list: &'l core_types::node::List<'_, Raster<CPU>>, lane: usize) -> Option<&'l Raster<CPU>> {
|
||||
(lane < list.len()).then(|| list.element_ref(lane)).filter(|i| i.width > 0 && i.height > 0)
|
||||
}
|
||||
let (red_el, green_el, blue_el, alpha_el) = (pick(&red, lane), pick(&green, lane), pick(&blue, lane), pick(&alpha, lane));
|
||||
|
||||
// This lane's transform and blending come from the first non-empty channel
|
||||
let attr_source = [(red_el.is_some(), &red), (green_el.is_some(), &green), (blue_el.is_some(), &blue), (alpha_el.is_some(), &alpha)]
|
||||
.into_iter()
|
||||
.find_map(|(present, list)| present.then_some(list.lane(lane)));
|
||||
|
||||
// The channels must have equal dimensions; an unusable lane serves a
|
||||
// zero-size raster, which renders as nothing (the legacy form dropped it)
|
||||
let channel_dimensions = [
|
||||
red_el.map(|r| (r.width, r.height)),
|
||||
green_el.map(|g| (g.width, g.height)),
|
||||
blue_el.map(|b| (b.width, b.height)),
|
||||
alpha_el.map(|a| (a.width, a.height)),
|
||||
];
|
||||
let mismatched = channel_dimensions
|
||||
.iter()
|
||||
.flatten()
|
||||
.any(|&(x, y)| channel_dimensions.iter().flatten().any(|&(other_x, other_y)| x != other_x || y != other_y));
|
||||
let (Some(source), Some(&(width, height)), false) = (attr_source, channel_dimensions.iter().flatten().next(), mismatched) else {
|
||||
return Ok((
|
||||
Raster::new_cpu(Image::default()),
|
||||
Attr(DAffine2::IDENTITY),
|
||||
Attr(<BlendModeAttr as Attribute>::default()),
|
||||
Attr(1.),
|
||||
Attr(1.),
|
||||
Attr(false),
|
||||
Attr(<EditorLayerPath as Attribute>::default()),
|
||||
));
|
||||
};
|
||||
|
||||
// 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_el.and_then(|r| r.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_el.and_then(|g| g.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_el.and_then(|b| b.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_el.and_then(|a| a.get_pixel(x, y)) {
|
||||
image_pixel.set_alpha(a.l().cast_linear_channel());
|
||||
} else {
|
||||
image_pixel.set_alpha(Channel::from_linear(1.));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The layer path re-parks into the arena so the borrow outlives the batch
|
||||
let layer_path: Vec<core_types::uuid::NodeId> = source.attr::<EditorLayerPath>().to_vec();
|
||||
let (layer_path, _) = ctx.arena().alloc(layer_path).ok_or(GraphError {
|
||||
kind: core_types::gpoll::ErrorKind::ArenaExhausted,
|
||||
trace: Vec::new(),
|
||||
})?;
|
||||
|
||||
Ok((
|
||||
Raster::new_cpu(image),
|
||||
Attr(source.attr::<TransformAttr>()),
|
||||
Attr(source.attr::<BlendModeAttr>()),
|
||||
Attr(source.attr::<Opacity>()),
|
||||
Attr(source.attr::<OpacityFill>()),
|
||||
Attr(source.attr::<ClippingMask>()),
|
||||
Attr(layer_path.as_slice()),
|
||||
))
|
||||
}
|
||||
|
||||
/// The combined level's count is the longest channel's; a lower-bound channel
|
||||
/// keeps the result a lower bound too, and consumers drain to past-end.
|
||||
fn combine_channels_extent(
|
||||
_primary: ValueIn<'_, ()>,
|
||||
red: ListIn<'_, Raster<CPU>>,
|
||||
green: ListIn<'_, Raster<CPU>>,
|
||||
blue: ListIn<'_, Raster<CPU>>,
|
||||
alpha: ListIn<'_, Raster<CPU>>,
|
||||
level: LevelIn,
|
||||
) -> GPoll<Extent> {
|
||||
match level.top() {
|
||||
true => red.total().zip(green.total()).zip(blue.total()).zip(alpha.total()).map(|(((red, green), blue), alpha)| {
|
||||
let totals = [red, green, blue, alpha];
|
||||
let bound = totals
|
||||
.iter()
|
||||
.map(|extent| match extent {
|
||||
Extent::Exactly(count) | Extent::AtLeast(count) => *count,
|
||||
Extent::Free => 0,
|
||||
})
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
match totals.iter().all(|extent| matches!(extent, Extent::Exactly(_))) {
|
||||
true => Extent::Exactly(bound),
|
||||
false => Extent::AtLeast(bound),
|
||||
}
|
||||
}),
|
||||
false => GPoll::Final(Extent::Exactly(1)),
|
||||
}
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Raster"))]
|
||||
pub fn mask(
|
||||
_: impl Ctx,
|
||||
/// The image to be masked.
|
||||
(mut image, lane_transform): (Raster<CPU>, Attr<TransformAttr>),
|
||||
/// The stencil to be used for masking.
|
||||
#[expose]
|
||||
stencil: IList<Raster<CPU>>,
|
||||
) -> (Raster<CPU>, Attr<TransformAttr>) {
|
||||
// TODO: Figure out what it means to support multiple stencil items?
|
||||
if stencil.is_empty() {
|
||||
// No stencil provided so we return the original image
|
||||
return (image, Attr(*lane_transform));
|
||||
}
|
||||
let stencil_element = stencil.element_ref(0);
|
||||
let stencil_transform: DAffine2 = stencil.lane(0).attr::<TransformAttr>();
|
||||
let stencil_size = DVec2::new(stencil_element.width as f64, stencil_element.height as f64);
|
||||
|
||||
let image_size = DVec2::new(image.width as f64, image.height as f64);
|
||||
let mask_size = stencil_transform.scale_magnitudes();
|
||||
|
||||
// A degenerate stencil serves a zero-size raster, which renders as
|
||||
// nothing (the legacy form dropped the lane)
|
||||
if mask_size == DVec2::ZERO {
|
||||
return (Raster::new_cpu(Image::default()), Attr(*lane_transform));
|
||||
}
|
||||
|
||||
// Transforms a point from the background image to the foreground image
|
||||
let transform_attribute: DAffine2 = *lane_transform;
|
||||
let bg_to_fg = transform_attribute * DAffine2::from_scale(1. / image_size);
|
||||
let stencil_transform_inverse = stencil_transform.inverse();
|
||||
|
||||
for y in 0..image.height {
|
||||
for x in 0..image.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 = image.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());
|
||||
}
|
||||
}
|
||||
|
||||
(image, Attr(transform_attribute))
|
||||
}
|
||||
|
||||
/// The per-lane extend, shared with the brush's plain callers.
|
||||
pub fn extend_image_to_bounds_core(image: Raster<CPU>, row_transform: DAffine2, bounds: DAffine2) -> (Raster<CPU>, DAffine2) {
|
||||
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 (image, row_transform);
|
||||
}
|
||||
|
||||
let (image_width, image_height) = (image.width, image.height);
|
||||
if image_width == 0 || image_height == 0 {
|
||||
return (empty_image_core(bounds, Color::TRANSPARENT), bounds);
|
||||
}
|
||||
let image_data = &image.data;
|
||||
|
||||
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 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;
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
// 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);
|
||||
|
||||
(Raster::new_cpu(new_image), new_texture_to_layer_space)
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
pub fn extend_image_to_bounds(_: impl Ctx, (image, transform): (Raster<CPU>, Attr<TransformAttr>), bounds: DAffine2) -> (Raster<CPU>, Attr<TransformAttr>) {
|
||||
let (image, transform) = extend_image_to_bounds_core(image, *transform, bounds);
|
||||
(image, Attr(transform))
|
||||
}
|
||||
|
||||
/// The blank texture a transform spans, shared with the brush's plain callers.
|
||||
pub fn empty_image_core(transform: DAffine2, color: Color) -> Raster<CPU> {
|
||||
let width = transform.transform_vector2(DVec2::new(1., 0.)).length() as u32;
|
||||
let height = transform.transform_vector2(DVec2::new(0., 1.)).length() as u32;
|
||||
|
||||
Raster::new_cpu(Image::new(width, height, color))
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Debug"))]
|
||||
pub fn empty_image(_: impl Ctx, transform: DAffine2, color: IList<Color>) -> (Raster<CPU>, Attr<TransformAttr>) {
|
||||
let color = match color.len() {
|
||||
0 => Color::WHITE,
|
||||
_ => color.get(0),
|
||||
};
|
||||
(empty_image_core(transform, color), Attr(transform))
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
pub fn image(_: impl Ctx, resource: Resource) -> Raster<CPU> {
|
||||
let image_data = resource.as_ref();
|
||||
|
||||
// A zero-size raster renders as nothing, matching the legacy empty list.
|
||||
let Some(image) = ::image::load_from_memory(image_data).ok() else {
|
||||
return Raster::new_cpu(Image::default());
|
||||
};
|
||||
let image = image.to_rgba32f();
|
||||
let image = Image {
|
||||
data: image
|
||||
.chunks(4)
|
||||
.map(|pixel| {
|
||||
let alpha = pixel[3];
|
||||
Color::from_gamma_srgb_channels(pixel[0] * alpha, pixel[1] * alpha, pixel[2] * alpha, alpha)
|
||||
})
|
||||
.collect(),
|
||||
width: image.width(),
|
||||
height: image.height(),
|
||||
..Default::default()
|
||||
};
|
||||
Raster::new_cpu(image)
|
||||
}
|
||||
|
||||
/// Generates customizable procedural noise patterns.
|
||||
#[node_macro::node(category("Raster: Pattern"))]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn noise_pattern(
|
||||
ctx: impl ExtractFootprint + Ctx,
|
||||
_primary: (),
|
||||
#[default(true)] clip: Item<bool>,
|
||||
seed: Item<u32>,
|
||||
#[widget(ParsedWidgetOverride::Custom = "noise_properties_scale")]
|
||||
#[default(10.)]
|
||||
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: Item<f64>,
|
||||
#[widget(ParsedWidgetOverride::Custom = "noise_properties_fractal_type")] fractal_type: Item<FractalType>,
|
||||
#[widget(ParsedWidgetOverride::Custom = "noise_properties_fractal_octaves")]
|
||||
#[default(3)]
|
||||
fractal_octaves: Item<u32>,
|
||||
#[widget(ParsedWidgetOverride::Custom = "noise_properties_fractal_lacunarity")]
|
||||
#[default(2.)]
|
||||
fractal_lacunarity: Item<f64>,
|
||||
#[widget(ParsedWidgetOverride::Custom = "noise_properties_fractal_gain")]
|
||||
#[default(0.5)]
|
||||
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: 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>> {
|
||||
let footprint = ctx.footprint();
|
||||
let viewport_bounds = footprint.viewport_bounds_in_local_space();
|
||||
|
||||
let mut size = viewport_bounds.size();
|
||||
let mut offset = viewport_bounds.start;
|
||||
if clip {
|
||||
// TODO: Remove "clip" entirely (and its arbitrary 100x100 clipping square) once we have proper resolution-aware layer clipping
|
||||
const CLIPPING_SQUARE_SIZE: f64 = 100.;
|
||||
let image_bounds = Bbox::from_transform(DAffine2::from_scale(DVec2::splat(CLIPPING_SQUARE_SIZE))).to_axis_aligned_bbox();
|
||||
let intersection = viewport_bounds.intersect(&image_bounds);
|
||||
|
||||
offset = (intersection.start - image_bounds.start).max(DVec2::ZERO);
|
||||
size = intersection.size();
|
||||
}
|
||||
|
||||
// A culled pattern serves a zero-size raster, which renders as nothing
|
||||
if size.x <= 0. || size.y <= 0. {
|
||||
return List::new();
|
||||
}
|
||||
|
||||
let transform = DAffine2::from_translation(offset) * DAffine2::from_scale(size);
|
||||
|
||||
let footprint_scale = footprint.scale();
|
||||
let width = (size.x * footprint_scale.x) as u32;
|
||||
let height = (size.y * footprint_scale.y) as u32;
|
||||
|
||||
// All
|
||||
let mut image = Image::new(width, height, Color::from_luminance(0.5));
|
||||
let mut noise = fastnoise_lite::FastNoiseLite::with_seed(seed as i32);
|
||||
noise.set_frequency(Some(1. / (scale as f32).max(f32::EPSILON)));
|
||||
|
||||
// Domain Warp
|
||||
let domain_warp_type = match domain_warp_type {
|
||||
DomainWarpType::None => None,
|
||||
DomainWarpType::OpenSimplex2 => Some(fastnoise_lite::DomainWarpType::OpenSimplex2),
|
||||
DomainWarpType::OpenSimplex2Reduced => Some(fastnoise_lite::DomainWarpType::OpenSimplex2Reduced),
|
||||
DomainWarpType::BasicGrid => Some(fastnoise_lite::DomainWarpType::BasicGrid),
|
||||
};
|
||||
let domain_warp_active = domain_warp_type.is_some();
|
||||
noise.set_domain_warp_type(domain_warp_type);
|
||||
noise.set_domain_warp_amp(Some(domain_warp_amplitude as f32));
|
||||
|
||||
// Fractal
|
||||
let noise_type = match noise_type {
|
||||
NoiseType::Perlin => fastnoise_lite::NoiseType::Perlin,
|
||||
NoiseType::OpenSimplex2 => fastnoise_lite::NoiseType::OpenSimplex2,
|
||||
NoiseType::OpenSimplex2S => fastnoise_lite::NoiseType::OpenSimplex2S,
|
||||
NoiseType::Cellular => fastnoise_lite::NoiseType::Cellular,
|
||||
NoiseType::ValueCubic => fastnoise_lite::NoiseType::ValueCubic,
|
||||
NoiseType::Value => fastnoise_lite::NoiseType::Value,
|
||||
NoiseType::WhiteNoise => {
|
||||
// TODO: Generate in layer space, not viewport space
|
||||
|
||||
let mut rng = ChaCha8Rng::seed_from_u64(seed as u64);
|
||||
|
||||
for y in 0..height {
|
||||
for x in 0..width {
|
||||
let pixel = image.get_pixel_mut(x, y).unwrap();
|
||||
let luminance = rng.random_range(0.0..1.) as f32;
|
||||
*pixel = Color::from_luminance(luminance);
|
||||
}
|
||||
}
|
||||
|
||||
return List::new_from_item(Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, transform));
|
||||
}
|
||||
};
|
||||
noise.set_noise_type(Some(noise_type));
|
||||
let fractal_type = match fractal_type {
|
||||
FractalType::None => fastnoise_lite::FractalType::None,
|
||||
FractalType::FBm => fastnoise_lite::FractalType::FBm,
|
||||
FractalType::Ridged => fastnoise_lite::FractalType::Ridged,
|
||||
FractalType::PingPong => fastnoise_lite::FractalType::PingPong,
|
||||
FractalType::DomainWarpProgressive => fastnoise_lite::FractalType::DomainWarpProgressive,
|
||||
FractalType::DomainWarpIndependent => fastnoise_lite::FractalType::DomainWarpIndependent,
|
||||
};
|
||||
noise.set_fractal_type(Some(fractal_type));
|
||||
noise.set_fractal_octaves(Some(fractal_octaves as i32));
|
||||
noise.set_fractal_lacunarity(Some(fractal_lacunarity as f32));
|
||||
noise.set_fractal_gain(Some(fractal_gain as f32));
|
||||
noise.set_fractal_weighted_strength(Some(fractal_weighted_strength as f32));
|
||||
noise.set_fractal_ping_pong_strength(Some(fractal_ping_pong_strength as f32));
|
||||
|
||||
// Cellular
|
||||
let cellular_distance_function = match cellular_distance_function {
|
||||
CellularDistanceFunction::Euclidean => fastnoise_lite::CellularDistanceFunction::Euclidean,
|
||||
CellularDistanceFunction::EuclideanSq => fastnoise_lite::CellularDistanceFunction::EuclideanSq,
|
||||
CellularDistanceFunction::Manhattan => fastnoise_lite::CellularDistanceFunction::Manhattan,
|
||||
CellularDistanceFunction::Hybrid => fastnoise_lite::CellularDistanceFunction::Hybrid,
|
||||
};
|
||||
let cellular_return_type = match cellular_return_type {
|
||||
CellularReturnType::CellValue => fastnoise_lite::CellularReturnType::CellValue,
|
||||
CellularReturnType::Nearest => fastnoise_lite::CellularReturnType::Distance,
|
||||
CellularReturnType::NextNearest => fastnoise_lite::CellularReturnType::Distance2,
|
||||
CellularReturnType::Average => fastnoise_lite::CellularReturnType::Distance2Add,
|
||||
CellularReturnType::Difference => fastnoise_lite::CellularReturnType::Distance2Sub,
|
||||
CellularReturnType::Product => fastnoise_lite::CellularReturnType::Distance2Mul,
|
||||
CellularReturnType::Division => fastnoise_lite::CellularReturnType::Distance2Div,
|
||||
};
|
||||
noise.set_cellular_distance_function(Some(cellular_distance_function));
|
||||
noise.set_cellular_return_type(Some(cellular_return_type));
|
||||
noise.set_cellular_jitter(Some(cellular_jitter as f32));
|
||||
|
||||
let coordinate_offset = offset.as_vec2();
|
||||
let scale = size.as_vec2() / Vec2::new(width as f32, height as f32);
|
||||
// Calculate the noise for every pixel
|
||||
for y in 0..height {
|
||||
for x in 0..width {
|
||||
let pixel = image.get_pixel_mut(x, y).unwrap();
|
||||
let pos = Vec2::new(x as f32, y as f32);
|
||||
let vec = pos * scale + coordinate_offset;
|
||||
|
||||
let (mut x, mut y) = (vec.x, vec.y);
|
||||
if domain_warp_active && domain_warp_amplitude > 0. {
|
||||
(x, y) = noise.domain_warp_2d(x, y);
|
||||
}
|
||||
|
||||
let luminance = (noise.get_noise_2d(x, y) + 1.) * 0.5;
|
||||
*pixel = Color::from_luminance(luminance);
|
||||
}
|
||||
}
|
||||
|
||||
List::new_from_item(Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, transform))
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Raster: Pattern"))]
|
||||
pub fn mandelbrot(ctx: impl Ctx + ExtractFootprint, _primary: ()) -> (Raster<CPU>, Attr<TransformAttr>) {
|
||||
let footprint = ctx.footprint();
|
||||
let viewport_bounds = footprint.viewport_bounds_in_local_space();
|
||||
|
||||
let image_bounds = Bbox::from_transform(DAffine2::IDENTITY).to_axis_aligned_bbox();
|
||||
let intersection = viewport_bounds.intersect(&image_bounds);
|
||||
let size = intersection.size();
|
||||
|
||||
let offset = (intersection.start - image_bounds.start).max(DVec2::ZERO);
|
||||
|
||||
// A culled pattern serves a zero-size raster, which renders as nothing
|
||||
if size.x <= 0. || size.y <= 0. {
|
||||
return (Raster::new_cpu(Image::default()), Attr(DAffine2::IDENTITY));
|
||||
}
|
||||
|
||||
let scale = footprint.scale();
|
||||
let width = (size.x * scale.x) as u32;
|
||||
let height = (size.y * scale.y) as u32;
|
||||
|
||||
let mut data = Vec::with_capacity(width as usize * height as usize);
|
||||
let max_iter = 255;
|
||||
|
||||
let scale = 3. * size.as_vec2() / Vec2::new(width as f32, height as f32);
|
||||
let coordinate_offset = offset.as_vec2() * 3. - Vec2::new(2., 1.5);
|
||||
for y in 0..height {
|
||||
for x in 0..width {
|
||||
let pos = Vec2::new(x as f32, y as f32);
|
||||
let c = pos * scale + coordinate_offset;
|
||||
|
||||
let iter = mandelbrot_impl(c, max_iter);
|
||||
data.push(map_color(iter, max_iter));
|
||||
}
|
||||
}
|
||||
|
||||
(
|
||||
Raster::new_cpu(Image {
|
||||
width,
|
||||
height,
|
||||
data,
|
||||
..Default::default()
|
||||
}),
|
||||
Attr(DAffine2::from_translation(offset) * DAffine2::from_scale(size)),
|
||||
)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn mandelbrot_impl(c: Vec2, max_iter: usize) -> usize {
|
||||
let mut z = Vec2::new(0., 0.);
|
||||
for i in 0..max_iter {
|
||||
z = Vec2::new(z.x * z.x - z.y * z.y, 2. * z.x * z.y) + c;
|
||||
if z.length_squared() > 4. {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
max_iter
|
||||
}
|
||||
|
||||
fn map_color(iter: usize, max_iter: usize) -> Color {
|
||||
let v = iter as f32 / max_iter as f32;
|
||||
Color::from_rgbaf32_unchecked(v, v, v, 1.)
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
[package]
|
||||
name = "repeat-nodes"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
description = "Repeat operation nodes for Graphene"
|
||||
authors = ["Graphite Authors <contact@graphite.art>"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
[features]
|
||||
default = ["serde"]
|
||||
|
||||
[dependencies]
|
||||
# Local dependencies
|
||||
core-types = { workspace = true }
|
||||
vector-types = { workspace = true }
|
||||
raster-types = { workspace = true }
|
||||
node-macro = { workspace = true }
|
||||
graphic-types = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
dyn-any = { workspace = true }
|
||||
glam = { workspace = true }
|
||||
log = { workspace = true }
|
||||
|
||||
# Optional workspace dependencies
|
||||
serde = { workspace = true, optional = true }
|
||||
@@ -0,0 +1,8 @@
|
||||
pub mod repeat_nodes;
|
||||
|
||||
// Re-export for convenience
|
||||
pub use core_types as gcore;
|
||||
pub use graphic_types;
|
||||
pub use raster_types;
|
||||
pub use repeat_nodes::*;
|
||||
pub use vector_types;
|
||||
@@ -0,0 +1,466 @@
|
||||
use core::f64::consts::TAU;
|
||||
use core_types::attribute::{Attr, Transform as TransformAttr};
|
||||
use core_types::context::IndexLink;
|
||||
use core_types::extent::{ExtentIn, LevelIn, ListIn, ValueIn};
|
||||
use core_types::gpoll::{Extent, GPoll, GraphError, Interrupt};
|
||||
use core_types::registry::types::{Angle, PixelSize};
|
||||
use core_types::{Ctx, DeriveCtx, ExtractIndex, InjectIndex};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::Vector;
|
||||
|
||||
/// Each copy evaluates the content within the copy's index pushed in,
|
||||
/// producing a level of `count` copies.
|
||||
// Someday this node can have the option to generate infinitely instead of a fixed count (basically `std::iter::repeat`).
|
||||
#[node_macro::node(category("Repeat"), extent(repeat_extent))]
|
||||
fn repeat<T>(
|
||||
ctx: impl Ctx + DeriveCtx + ExtractIndex,
|
||||
content: impl Node<Context<'_>, Output = T>,
|
||||
#[default(1)]
|
||||
#[hard(1..)]
|
||||
count: u32,
|
||||
reverse: bool,
|
||||
) -> Result<IList<T>, Interrupt> {
|
||||
let inner = content.inner_extent(ctx)?;
|
||||
let (copy, rest) = ctx.split_innermost(inner);
|
||||
if copy >= count as u64 {
|
||||
return Err(GraphError::past_end().into());
|
||||
}
|
||||
let copy = match reverse {
|
||||
true => count as u64 - 1 - copy,
|
||||
false => copy,
|
||||
};
|
||||
let mut frame = IndexLink { index: 0, outer: None };
|
||||
content.eval(&ctx.push_level(&mut frame, copy, rest))
|
||||
}
|
||||
|
||||
/// The pushed level's extent is the copy count; inner levels forward to the
|
||||
/// content, whose extent is taken uniform across copies (queried at copy 0).
|
||||
fn repeat_extent(content: ExtentIn<'_>, count: ValueIn<'_, u32>, _reverse: ValueIn<'_, bool>, level: LevelIn) -> GPoll<Extent> {
|
||||
match level.pushed() {
|
||||
true => count.get().map(|count| Extent::Exactly(count as usize)),
|
||||
false => content.at(level),
|
||||
}
|
||||
}
|
||||
|
||||
/// Each copy evaluates the content within the copy's index pushed in, the
|
||||
/// copy's step transform composed between the lane transform's translation
|
||||
/// and matrix parts.
|
||||
#[node_macro::node(category("Repeat"), extent(repeat_array_extent))]
|
||||
pub fn repeat_array<T>(
|
||||
ctx: impl Ctx + DeriveCtx + ExtractIndex,
|
||||
content: impl Node<Context<'_>, Output = (T, Attr<TransformAttr>)>,
|
||||
#[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: Item<PixelSize>,
|
||||
angle: Item<Angle>,
|
||||
#[default(5)]
|
||||
#[hard(1..)]
|
||||
count: u32,
|
||||
) -> Result<IList<(T, Attr<TransformAttr>)>, Interrupt> {
|
||||
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;
|
||||
|
||||
let inner = content.inner_extent(ctx)?;
|
||||
let (copy, rest) = ctx.split_innermost(inner);
|
||||
if copy >= count as u64 {
|
||||
return Err(GraphError::past_end().into());
|
||||
}
|
||||
let step_angle = copy as f64 * angle / total;
|
||||
let translation = copy as f64 * direction / total;
|
||||
let transform = DAffine2::from_angle(step_angle) * DAffine2::from_translation(translation);
|
||||
|
||||
let mut frame = IndexLink { index: 0, outer: None };
|
||||
let (element, local_transform) = content.eval(&ctx.push_level(&mut frame, copy, rest))?;
|
||||
let local_translation = DAffine2::from_translation(local_transform.translation);
|
||||
let local_matrix = DAffine2::from_mat2(local_transform.matrix2);
|
||||
Ok((element, Attr(local_translation * transform * local_matrix)))
|
||||
}
|
||||
|
||||
/// The pushed level's extent is the copy count; inner levels forward to the
|
||||
/// content, whose extent is taken uniform across copies (queried at copy 0).
|
||||
fn repeat_array_extent(content: ExtentIn<'_>, _direction: ValueIn<'_, DVec2>, _angle: ValueIn<'_, f64>, count: ValueIn<'_, u32>, level: LevelIn) -> GPoll<Extent> {
|
||||
match level.pushed() {
|
||||
true => count.get().map(|count| Extent::Exactly(count as usize)),
|
||||
false => content.at(level),
|
||||
}
|
||||
}
|
||||
|
||||
/// Each copy evaluates the content within the copy's index pushed in, rotated
|
||||
/// around the center by the copy's share of the turn.
|
||||
#[node_macro::node(category("Repeat"), extent(repeat_radial_extent))]
|
||||
fn repeat_radial<T>(
|
||||
ctx: impl Ctx + DeriveCtx + ExtractIndex,
|
||||
content: impl Node<Context<'_>, Output = (T, Attr<TransformAttr>)>,
|
||||
start_angle: Angle,
|
||||
#[unit(" px")]
|
||||
#[default(5)]
|
||||
radius: Item<f64>,
|
||||
#[default(5)]
|
||||
#[hard(1..)]
|
||||
count: u32,
|
||||
) -> Result<IList<(T, Attr<TransformAttr>)>, Interrupt> {
|
||||
let inner = content.inner_extent(ctx)?;
|
||||
let (copy, rest) = ctx.split_innermost(inner);
|
||||
if copy >= count as u64 {
|
||||
return Err(GraphError::past_end().into());
|
||||
}
|
||||
let mut frame = IndexLink { index: 0, outer: None };
|
||||
let (element, local) = content.eval(&ctx.push_level(&mut frame, copy, rest))?;
|
||||
|
||||
let angle = DAffine2::from_angle((TAU / count as f64) * copy as f64 + start_angle.to_radians());
|
||||
let translation = DAffine2::from_translation(radius * DVec2::Y);
|
||||
let step = angle * translation;
|
||||
let local_translation = DAffine2::from_translation(local.translation);
|
||||
let local_matrix = DAffine2::from_mat2(local.matrix2);
|
||||
Ok((element, Attr(local_translation * step * local_matrix)))
|
||||
}
|
||||
|
||||
/// The pushed level's extent is the copy count; inner levels forward to the
|
||||
/// content, whose extent is taken uniform across copies (queried at copy 0).
|
||||
fn repeat_radial_extent(content: ExtentIn<'_>, _start_angle: ValueIn<'_, Angle>, _radius: ValueIn<'_, f64>, count: ValueIn<'_, u32>, level: LevelIn) -> GPoll<Extent> {
|
||||
match level.pushed() {
|
||||
true => count.get().map(|count| Extent::Exactly(count as usize)),
|
||||
false => content.at(level),
|
||||
}
|
||||
}
|
||||
|
||||
/// The pushed level flattens every point of every points row, mirroring the
|
||||
/// legacy iteration order (rows in order, a row's points reversed when
|
||||
/// `reverse` is set); each copy evaluates the content with its point's
|
||||
/// transformed position pushed, then lands the content row's transform on
|
||||
/// that position.
|
||||
#[node_macro::node(category("Repeat"), name("Repeat on Points"), extent(repeat_on_points_extent))]
|
||||
fn repeat_on_points<T>(
|
||||
ctx: impl Ctx + DeriveCtx + ExtractIndex + InjectIndex + Copy,
|
||||
content: impl Node<Context<'_>, Output = (T, Attr<TransformAttr>)>,
|
||||
points: IList<Vector>,
|
||||
reverse: bool,
|
||||
) -> Result<IList<(T, Attr<TransformAttr>)>, Interrupt> {
|
||||
let inner = content.inner_extent(ctx)?;
|
||||
let (copy, rest) = ctx.split_innermost(inner);
|
||||
|
||||
let mut remaining = copy as usize;
|
||||
for row_index in 0..points.len() {
|
||||
let vector = points.element_ref(row_index);
|
||||
let positions = vector.point_domain.positions();
|
||||
if remaining >= positions.len() {
|
||||
remaining -= positions.len();
|
||||
continue;
|
||||
}
|
||||
let index = match reverse {
|
||||
true => positions.len() - 1 - remaining,
|
||||
false => remaining,
|
||||
};
|
||||
let transform: DAffine2 = points.lane(row_index).attr::<TransformAttr>();
|
||||
let transformed_point = transform.transform_point2(positions[index]);
|
||||
|
||||
let scoped = ctx.push_position(transformed_point);
|
||||
let mut frame = IndexLink { index: 0, outer: None };
|
||||
let (element, local) = content.eval(&scoped.ctx().push_level(&mut frame, copy, rest))?;
|
||||
let mut composed = *local;
|
||||
composed.translation = transformed_point;
|
||||
return Ok((element, Attr(composed)));
|
||||
}
|
||||
Err(GraphError::past_end().into())
|
||||
}
|
||||
|
||||
/// The pushed level's extent is the flattened point count across the points
|
||||
/// rows; inner levels forward to the content, uniform across copies.
|
||||
fn repeat_on_points_extent(content: ExtentIn<'_>, points: ListIn<'_, Vector>, _reverse: ValueIn<'_, bool>, level: LevelIn) -> GPoll<Extent> {
|
||||
match level.pushed() {
|
||||
true => points
|
||||
.get()
|
||||
.map(|points| Extent::Exactly((0..points.len()).map(|row| points.element_ref(row).point_domain.positions().len()).sum())),
|
||||
false => content.at(level),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
use core_types::SourceId;
|
||||
use core_types::arena::Arena;
|
||||
use core_types::context::{ContextImpl, EvalScope, ExtractArena};
|
||||
use core_types::node::Node;
|
||||
use core_types::record::{FieldWrite, FrameClaim, Layout, RecordSource, Served, capture, element_write};
|
||||
use core_types::value::ValueSource;
|
||||
use vector_types::subpath::Subpath;
|
||||
use vector_types::vector::misc::BoxCorners;
|
||||
|
||||
struct TransformSource {
|
||||
layout: Layout,
|
||||
element: f64,
|
||||
transform: DAffine2,
|
||||
}
|
||||
|
||||
impl<C: ExtractIndex> Node<C> for TransformSource {
|
||||
fn serve<'e, 'l>(&self, input: &C, slot: FrameClaim<'e, 'l>) -> GPoll<Served<'e>>
|
||||
where
|
||||
C: ExtractArena<ArenaRef = &'e Arena>,
|
||||
{
|
||||
let mut frame = slot;
|
||||
let arena = ExtractArena::arena(input);
|
||||
if frame.element(self.element, arena).is_none() {
|
||||
return GPoll::arena_exhausted();
|
||||
}
|
||||
write_attr_at::<TransformAttr>(&mut frame, &self.layout, self.transform);
|
||||
// SAFETY: the writes above complete the record of this layout.
|
||||
GPoll::Final(unsafe { frame.finish_served() })
|
||||
}
|
||||
|
||||
fn layout(&self) -> &Layout {
|
||||
&self.layout
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes a field at the layout's resolved offset, the wiring-proven pairing
|
||||
/// a generated node performs.
|
||||
fn write_field_at<T: Copy + 'static>(frame: &mut FrameClaim<'_, '_>, layout: &Layout, name: &str, level: u8, value: T) {
|
||||
let field = layout
|
||||
.fields
|
||||
.iter()
|
||||
.find(|field| field.name == name && field.level == level)
|
||||
.expect("the layout carries the written field");
|
||||
assert_eq!(field.type_id, std::any::TypeId::of::<T>(), "the field was declared at this value type");
|
||||
// SAFETY: the offset is this layout's own, at the field's declared type.
|
||||
unsafe { frame.attr_at(field.offset, value) };
|
||||
}
|
||||
|
||||
/// [`write_field_at`] for a census marker at level 0.
|
||||
fn write_attr_at<A: core_types::attribute::Attribute>(frame: &mut FrameClaim<'_, '_>, layout: &Layout, value: A::Value<'static>)
|
||||
where
|
||||
A::Value<'static>: Copy + 'static,
|
||||
{
|
||||
write_field_at(frame, layout, A::NAME, 0, value);
|
||||
}
|
||||
fn scope_fixture<'a>(generations: &'a [(SourceId, u64)], arena: &'a Arena) -> EvalScope<'a> {
|
||||
EvalScope::new(Some(0.5), None, None, generations, arena)
|
||||
}
|
||||
|
||||
struct VectorRows {
|
||||
layout: Layout,
|
||||
rows: Vec<(Vector, DAffine2)>,
|
||||
}
|
||||
|
||||
impl<C: ExtractIndex> Node<C> for VectorRows {
|
||||
fn serve<'e, 'l>(&self, input: &C, slot: FrameClaim<'e, 'l>) -> GPoll<Served<'e>>
|
||||
where
|
||||
C: ExtractArena<ArenaRef = &'e Arena>,
|
||||
{
|
||||
let (vector, transform) = &self.rows[input.innermost_index() as usize % self.rows.len()];
|
||||
let mut frame = slot;
|
||||
let arena = ExtractArena::arena(input);
|
||||
if frame.element(vector.clone(), arena).is_none() {
|
||||
return GPoll::arena_exhausted();
|
||||
}
|
||||
write_attr_at::<TransformAttr>(&mut frame, &self.layout, *transform);
|
||||
// SAFETY: the writes above complete the record of this layout.
|
||||
GPoll::Final(unsafe { frame.finish_served() })
|
||||
}
|
||||
|
||||
fn extent_at<'x>(&self, _input: &C, _level: u8, _frames: &core_types::record::Frames<'x>) -> GPoll<Extent>
|
||||
where
|
||||
C: ExtractArena<ArenaRef = &'x Arena>,
|
||||
{
|
||||
GPoll::Final(Extent::Exactly(self.rows.len()))
|
||||
}
|
||||
|
||||
fn layout(&self) -> &Layout {
|
||||
&self.layout
|
||||
}
|
||||
}
|
||||
|
||||
fn vector_rows_layout() -> Layout {
|
||||
Layout::default().with_writes(1, element_write::<Vector>(), &[FieldWrite::of::<TransformAttr>(0)])
|
||||
}
|
||||
|
||||
struct PositionProbe {
|
||||
layout: Layout,
|
||||
}
|
||||
|
||||
impl<C: ExtractIndex + core_types::context::ExtractPosition> Node<C> for PositionProbe {
|
||||
fn serve<'e, 'l>(&self, input: &C, slot: FrameClaim<'e, 'l>) -> GPoll<Served<'e>>
|
||||
where
|
||||
C: ExtractArena<ArenaRef = &'e Arena>,
|
||||
{
|
||||
let position = input.try_position().and_then(|mut positions| positions.next()).unwrap_or(DVec2::ZERO);
|
||||
let mut frame = slot;
|
||||
let arena = ExtractArena::arena(input);
|
||||
if frame.element(position.x, arena).is_none() {
|
||||
return GPoll::arena_exhausted();
|
||||
}
|
||||
write_attr_at::<TransformAttr>(&mut frame, &self.layout, DAffine2::IDENTITY);
|
||||
// SAFETY: the writes above complete the record of this layout.
|
||||
GPoll::Final(unsafe { frame.finish_served() })
|
||||
}
|
||||
|
||||
fn layout(&self) -> &Layout {
|
||||
&self.layout
|
||||
}
|
||||
}
|
||||
|
||||
fn transform_layout() -> Layout {
|
||||
Layout::default().with_writes(0, element_write::<f64>(), &[FieldWrite::of::<TransformAttr>(0)])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeat_array_composes_the_step_onto_each_copys_transform() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let layout = transform_layout();
|
||||
let content = TransformSource {
|
||||
layout: layout.clone(),
|
||||
element: 7.,
|
||||
transform: DAffine2::from_translation(DVec2::new(5., 5.)),
|
||||
};
|
||||
|
||||
let mut node = RepeatArrayNode::new(
|
||||
RecordSource::new(content, &layout, &layout),
|
||||
ValueSource::new(DVec2::new(10., 0.)),
|
||||
ValueSource::new(0.0f64),
|
||||
ValueSource::new(3u32),
|
||||
&layout,
|
||||
);
|
||||
Node::<ContextImpl>::set_layout(&mut node, repeat_array_layout_meta().resolve(&[Some(&layout)]));
|
||||
let leveled = Node::<ContextImpl>::layout(&node).clone();
|
||||
assert_eq!(leveled.depth, 1, "the IList return pushed one rank level above the content");
|
||||
assert_eq!(node.extent_at(&ctx, 0, &frames.reborrow()), GPoll::Final(Extent::Exactly(3)));
|
||||
|
||||
let head = ctx.index_head();
|
||||
for copy in 0..3u64 {
|
||||
let lane = ctx.promoted(&head, copy);
|
||||
let GPoll::Final(record) = capture(&node, &lane, &frames) else {
|
||||
panic!("expected a final record");
|
||||
};
|
||||
assert_eq!(record.element::<f64>(), 7.);
|
||||
// Zero angle, direction (10, 0), count 3: copy `j` steps j * (5, 0)
|
||||
// past the row's own (5, 5) translation.
|
||||
let composed: DAffine2 = record.attr::<TransformAttr>();
|
||||
assert_eq!(composed, DAffine2::from_translation(DVec2::new(5. + copy as f64 * 5., 5.)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeat_radial_rotates_each_copy_around_the_center() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let layout = transform_layout();
|
||||
let local = DAffine2::from_translation(DVec2::new(1., 0.));
|
||||
let content = TransformSource {
|
||||
layout: layout.clone(),
|
||||
element: 7.,
|
||||
transform: local,
|
||||
};
|
||||
|
||||
let mut node = RepeatRadialNode::new(
|
||||
RecordSource::new(content, &layout, &layout),
|
||||
ValueSource::new(90.0f64),
|
||||
ValueSource::new(2.0f64),
|
||||
ValueSource::new(4u32),
|
||||
&layout,
|
||||
);
|
||||
Node::<ContextImpl>::set_layout(&mut node, repeat_radial_layout_meta().resolve(&[Some(&layout)]));
|
||||
assert_eq!(node.extent_at(&ctx, 0, &frames.reborrow()), GPoll::Final(Extent::Exactly(4)));
|
||||
|
||||
let head = ctx.index_head();
|
||||
for copy in 0..4u64 {
|
||||
let lane = ctx.promoted(&head, copy);
|
||||
let GPoll::Final(record) = capture(&node, &lane, &frames) else {
|
||||
panic!("expected a final record");
|
||||
};
|
||||
assert_eq!(record.element::<f64>(), 7.);
|
||||
// The kernel's own formula, so the float operations match exactly.
|
||||
let step = DAffine2::from_angle((TAU / 4.) * copy as f64 + 90.0f64.to_radians()) * DAffine2::from_translation(2. * DVec2::Y);
|
||||
let expected = DAffine2::from_translation(local.translation) * step * DAffine2::from_mat2(local.matrix2);
|
||||
let composed: DAffine2 = record.attr::<TransformAttr>();
|
||||
assert_eq!(composed, expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeat_on_points_lands_each_copy_on_its_transformed_point() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(1 << 16).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let row0: Vec<DVec2> = vec![DVec2::new(40., 20.), DVec2::ONE];
|
||||
let row1: Vec<DVec2> = vec![DVec2::new(-42., 9.), DVec2::new(10., 345.), DVec2::new(3., 4.)];
|
||||
let row0_transform = DAffine2::from_translation(DVec2::new(100., 0.));
|
||||
let points = VectorRows {
|
||||
layout: vector_rows_layout(),
|
||||
rows: vec![
|
||||
(Vector::from_subpath(Subpath::from_anchors(row0.clone(), false)), row0_transform),
|
||||
(Vector::from_subpath(Subpath::from_anchors(row1.clone(), false)), DAffine2::IDENTITY),
|
||||
],
|
||||
};
|
||||
let content_layout = transform_layout();
|
||||
let content = PositionProbe { layout: content_layout.clone() };
|
||||
|
||||
let mut node = RepeatOnPointsNode::new(RecordSource::new(content, &content_layout, &content_layout), points, ValueSource::new(false), &content_layout);
|
||||
Node::<ContextImpl>::set_layout(&mut node, repeat_on_points_layout_meta().resolve(&[Some(&content_layout)]));
|
||||
let leveled = Node::<ContextImpl>::layout(&node).clone();
|
||||
assert_eq!(leveled.depth, 1);
|
||||
assert_eq!(
|
||||
node.extent_at(&ctx, 0, &frames.reborrow()),
|
||||
GPoll::Final(Extent::Exactly(5)),
|
||||
"the pushed level flattens both rows' points"
|
||||
);
|
||||
|
||||
let expected: Vec<DVec2> = row0.iter().map(|&point| row0_transform.transform_point2(point)).chain(row1.iter().copied()).collect();
|
||||
|
||||
let head = ctx.index_head();
|
||||
for (flat, &point) in expected.iter().enumerate() {
|
||||
let lane = ctx.promoted(&head, flat as u64);
|
||||
let GPoll::Final(record) = capture(&node, &lane, &frames) else {
|
||||
panic!("expected a final record");
|
||||
};
|
||||
// The content saw the pushed position, and the output transform lands on it.
|
||||
assert_eq!(record.element::<f64>(), point.x);
|
||||
let composed: DAffine2 = record.attr::<TransformAttr>();
|
||||
assert_eq!(composed.translation, point);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeat_on_points_reverse_flips_each_rows_points() {
|
||||
let frames = core_types::record::test_frames(1 << 16);
|
||||
let arena = Arena::new(1 << 16).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let positions: Vec<DVec2> = vec![DVec2::new(40., 20.), DVec2::ONE, DVec2::new(-42., 9.), DVec2::new(10., 345.)];
|
||||
let points = VectorRows {
|
||||
layout: vector_rows_layout(),
|
||||
rows: vec![(Vector::from_subpath(Subpath::from_anchors(positions.clone(), false)), DAffine2::IDENTITY)],
|
||||
};
|
||||
let content_layout = transform_layout();
|
||||
let content = PositionProbe { layout: content_layout.clone() };
|
||||
|
||||
let mut node = RepeatOnPointsNode::new(RecordSource::new(content, &content_layout, &content_layout), points, ValueSource::new(true), &content_layout);
|
||||
Node::<ContextImpl>::set_layout(&mut node, repeat_on_points_layout_meta().resolve(&[Some(&content_layout)]));
|
||||
|
||||
let mut expected = positions.clone();
|
||||
expected.reverse();
|
||||
let head = ctx.index_head();
|
||||
for (flat, &point) in expected.iter().enumerate() {
|
||||
let lane = ctx.promoted(&head, flat as u64);
|
||||
let GPoll::Final(record) = capture(&node, &lane, &frames) else {
|
||||
panic!("expected a final record");
|
||||
};
|
||||
let composed: DAffine2 = record.attr::<TransformAttr>();
|
||||
assert_eq!(composed.translation, point);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
[package]
|
||||
name = "text-nodes"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
description = "Text operation nodes for Graphene"
|
||||
authors = ["Graphite Authors <contact@graphite.art>"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
[features]
|
||||
default = ["serde"]
|
||||
serde = ["dep:serde", "core-types/serde", "vector-types/serde"]
|
||||
wasm = ["core-types/wasm", "tsify", "wasm-bindgen"]
|
||||
|
||||
[dependencies]
|
||||
# Local dependencies
|
||||
core-types = { workspace = true }
|
||||
graphene-hash = { workspace = true }
|
||||
graphene-resource = { workspace = true }
|
||||
raster-types = { workspace = true }
|
||||
vector-types = { workspace = true }
|
||||
node-macro = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
dyn-any = { workspace = true }
|
||||
glam = { workspace = true }
|
||||
parley = { workspace = true }
|
||||
skrifa = { workspace = true }
|
||||
log = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
convert_case = { workspace = true }
|
||||
titlecase = { workspace = true }
|
||||
fancy-regex = { workspace = true }
|
||||
unicode-segmentation = { workspace = true }
|
||||
|
||||
# Optional workspace dependencies
|
||||
serde = { workspace = true, optional = true }
|
||||
tsify = { workspace = true, optional = true }
|
||||
wasm-bindgen = { workspace = true, optional = true }
|
||||
@@ -0,0 +1,5 @@
|
||||
use graphene_resource::Resource;
|
||||
use std::sync::LazyLock;
|
||||
|
||||
const FALLBACK_FONT_BYTES: &[u8] = include_bytes!("source-sans-pro-regular.ttf");
|
||||
pub static FALLBACK_FONT_RESOURCE: LazyLock<Resource> = LazyLock::new(|| Resource::new(FALLBACK_FONT_BYTES));
|
||||
@@ -0,0 +1,71 @@
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use dyn_any::DynAny;
|
||||
|
||||
/// A font type (storing font family and font style)
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Debug, Clone, Eq, DynAny)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct Font {
|
||||
#[cfg_attr(feature = "serde", serde(rename = "fontFamily"))]
|
||||
pub font_family: String,
|
||||
#[cfg_attr(feature = "serde", serde(rename = "fontStyle", deserialize_with = "migrate_font_style"))]
|
||||
pub font_style: String,
|
||||
}
|
||||
|
||||
impl std::hash::Hash for Font {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
self.font_family.hash(state);
|
||||
self.font_style.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl CacheHash for Font {
|
||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
self.font_family.cache_hash(state);
|
||||
self.font_style.cache_hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for Font {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.font_family == other.font_family && self.font_style == other.font_style
|
||||
}
|
||||
}
|
||||
|
||||
impl Font {
|
||||
pub fn new(font_family: String, font_style: String) -> Self {
|
||||
Self { font_family, font_style }
|
||||
}
|
||||
|
||||
pub fn new_with_default_style(font_family: String) -> Self {
|
||||
Self::new(font_family, core_types::consts::DEFAULT_FONT_STYLE.into())
|
||||
}
|
||||
|
||||
pub fn named_weight(weight: u32) -> &'static str {
|
||||
// From https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight#common_weight_name_mapping
|
||||
match weight {
|
||||
100 => "Thin",
|
||||
200 => "Extra Light",
|
||||
300 => "Light",
|
||||
400 => "Regular",
|
||||
500 => "Medium",
|
||||
600 => "Semi Bold",
|
||||
700 => "Bold",
|
||||
800 => "Extra Bold",
|
||||
900 => "Black",
|
||||
950 => "Extra Black",
|
||||
_ => "Regular",
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Default for Font {
|
||||
fn default() -> Self {
|
||||
Self::new(core_types::consts::DEFAULT_FONT_FAMILY.into(), core_types::consts::DEFAULT_FONT_STYLE.into())
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this migration document upgrade code
|
||||
fn migrate_font_style<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<String, D::Error> {
|
||||
use serde::Deserialize;
|
||||
String::deserialize(deserializer).map(|name| if name == "Normal (400)" { "Regular (400)".to_string() } else { name })
|
||||
}
|
||||
@@ -0,0 +1,485 @@
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::{ATTR_TYPE, Ctx};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::unescape_string;
|
||||
|
||||
// ===========
|
||||
// Format JSON
|
||||
// ===========
|
||||
|
||||
/// Reformats a JSON string with control over indentation, line breaking, and spacing. Trailing commas are tolerated. Otherwise-invalid JSON input is returned unchanged.
|
||||
#[node_macro::node(name("Format JSON"), category("Text: JSON"))]
|
||||
fn format_json(
|
||||
_: impl Ctx,
|
||||
/// The JSON string to reformat.
|
||||
#[name("JSON")]
|
||||
json: Item<String>,
|
||||
/// Removes optional spaces within curly brackets and after colons and commas.
|
||||
compact: Item<bool>,
|
||||
/// Break arrays and objects across multiple lines when they exceed the line break length.
|
||||
#[default(true)]
|
||||
#[name("Multi-Line")]
|
||||
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: 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: 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: 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;
|
||||
|
||||
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.
|
||||
/// Respects string literals so commas inside strings are left untouched.
|
||||
fn strip_trailing_commas(json: &str) -> String {
|
||||
let mut output = String::with_capacity(json.len());
|
||||
let mut chars = json.chars().peekable();
|
||||
let mut in_string = false;
|
||||
|
||||
while let Some(c) = chars.next() {
|
||||
if in_string {
|
||||
output.push(c);
|
||||
|
||||
// Skip escaped characters inside strings
|
||||
if c == '\\'
|
||||
&& let Some(escaped) = chars.next()
|
||||
{
|
||||
output.push(escaped);
|
||||
} else if c == '"' {
|
||||
in_string = false;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
match c {
|
||||
'"' => {
|
||||
in_string = true;
|
||||
output.push(c);
|
||||
}
|
||||
',' => {
|
||||
// Skip any whitespace after the comma
|
||||
while chars.peek().is_some_and(|c| c.is_ascii_whitespace()) {
|
||||
chars.next();
|
||||
}
|
||||
|
||||
// Drop trailing commas (before `]` or `}`), but keep all others
|
||||
if !chars.peek().is_some_and(|&c| c == ']' || c == '}') {
|
||||
output.push(',');
|
||||
}
|
||||
}
|
||||
_ => output.push(c),
|
||||
}
|
||||
}
|
||||
|
||||
output
|
||||
}
|
||||
|
||||
/// Formats a JSON value as a single unbroken line.
|
||||
fn format_inline(value: &serde_json::Value, colon: &str, comma_space: &str, compact: bool) -> String {
|
||||
match value {
|
||||
serde_json::Value::Array(arr) => {
|
||||
let inner: Vec<String> = arr.iter().map(|v| format_inline(v, colon, comma_space, compact)).collect();
|
||||
format!("[{}]", inner.join(comma_space))
|
||||
}
|
||||
serde_json::Value::Object(obj) => {
|
||||
let inner: Vec<String> = obj
|
||||
.iter()
|
||||
.map(|(k, v)| format!("{}{}{}", serde_json::to_string(k).unwrap_or_default(), colon, format_inline(v, colon, comma_space, compact)))
|
||||
.collect();
|
||||
let joined = inner.join(comma_space);
|
||||
if compact || joined.is_empty() { format!("{{{joined}}}") } else { format!("{{ {joined} }}") }
|
||||
}
|
||||
other => serde_json::to_string(other).unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Formats a JSON value, optionally breaking containers across lines when they contain other containers or exceed the line break length limit.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn format_value(value: &serde_json::Value, depth: usize, indent: &str, colon: &str, comma_space: &str, compact: bool, break_nested: bool, line_width: usize) -> String {
|
||||
// Checks whether any direct child of a container is itself a container.
|
||||
let contains_containers = |value: &serde_json::Value| {
|
||||
// Checks whether a JSON value is a container (array or object).
|
||||
let is_container = |value: &serde_json::Value| matches!(value, serde_json::Value::Array(_) | serde_json::Value::Object(_));
|
||||
|
||||
match value {
|
||||
serde_json::Value::Array(arr) => arr.iter().any(is_container),
|
||||
serde_json::Value::Object(obj) => obj.values().any(is_container),
|
||||
_ => false,
|
||||
}
|
||||
};
|
||||
|
||||
match value {
|
||||
serde_json::Value::Array(arr) if !arr.is_empty() => {
|
||||
// Try inline if children are all leaves (or break_nested is off) and it fits
|
||||
if !break_nested || !contains_containers(value) {
|
||||
let inline = format_inline(value, colon, comma_space, compact);
|
||||
let current_indent_width = indent.len() * depth;
|
||||
if current_indent_width + inline.len() <= line_width {
|
||||
return inline;
|
||||
}
|
||||
}
|
||||
|
||||
// Break across lines
|
||||
let child_indent = indent.repeat(depth + 1);
|
||||
let closing_indent = indent.repeat(depth);
|
||||
let items: Vec<String> = arr
|
||||
.iter()
|
||||
.map(|v| format!("{child_indent}{}", format_value(v, depth + 1, indent, colon, comma_space, compact, break_nested, line_width)))
|
||||
.collect();
|
||||
format!("[\n{}\n{closing_indent}]", items.join(",\n"))
|
||||
}
|
||||
serde_json::Value::Object(obj) if !obj.is_empty() => {
|
||||
// Try inline if children are all leaves (or break_nested is off) and it fits
|
||||
if !break_nested || !contains_containers(value) {
|
||||
let inline = format_inline(value, colon, comma_space, compact);
|
||||
let current_indent_width = indent.len() * depth;
|
||||
if current_indent_width + inline.len() <= line_width {
|
||||
return inline;
|
||||
}
|
||||
}
|
||||
|
||||
// Break across lines
|
||||
let child_indent = indent.repeat(depth + 1);
|
||||
let closing_indent = indent.repeat(depth);
|
||||
let entries: Vec<String> = obj
|
||||
.iter()
|
||||
.map(|(k, v)| {
|
||||
let key = serde_json::to_string(k).unwrap_or_default();
|
||||
let val = format_value(v, depth + 1, indent, colon, comma_space, compact, break_nested, line_width);
|
||||
format!("{child_indent}{key}{colon}{val}")
|
||||
})
|
||||
.collect();
|
||||
format!("{{\n{}\n{closing_indent}}}", entries.join(",\n"))
|
||||
}
|
||||
other => serde_json::to_string(other).unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
|
||||
// ================
|
||||
// Query JSON (All)
|
||||
// ================
|
||||
|
||||
/// Extracts a single matched value from a JSON string using a path expression (see that parameter's description for its syntax). If no matches are found, an empty string is returned. If multiple values are matched, the first is returned. To read all matches, use the **Query JSON All** node.
|
||||
///
|
||||
/// This is useful in conjunction with the nodes:
|
||||
/// • **String to Number**: convert numeric query results to numbers.
|
||||
/// • **String Value** → **Equals**: convert "true", "false", or "null" query results to bools.
|
||||
#[node_macro::node(name("Query JSON"), category("Text: JSON"))]
|
||||
fn query_json(
|
||||
_: impl Ctx,
|
||||
/// The JSON string to extract a value from.
|
||||
#[name("JSON")]
|
||||
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.
|
||||
///
|
||||
/// Examples:
|
||||
/// Use `[2]` or `[-1]` to get the last value, and `[1]` or `[-2]` for the middle value, of `["a", "b", "c"]`.
|
||||
/// 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: 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: Item<bool>,
|
||||
) -> Item<String> {
|
||||
let mut json = json;
|
||||
let path = path.element().clone();
|
||||
let unquote_strings = *unquote_strings.element();
|
||||
|
||||
let cleaned = strip_trailing_commas(json.element());
|
||||
|
||||
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.
|
||||
///
|
||||
/// Each item carries a `type` attribute holding the matched value's JSON type (`"string"`, `"number"`, `"bool"`, `"null"`, `"object"`, or `"array"`).
|
||||
///
|
||||
/// This is useful in conjunction with the nodes:
|
||||
/// • **Index Elements**: access the `N`th query result.
|
||||
/// • **String to Number**: convert numeric query results to numbers.
|
||||
/// • **String Value** → **Equals**: convert "true", "false", or "null" query results to bools.
|
||||
#[node_macro::node(name("Query JSON All"), category("Text: JSON"))]
|
||||
fn query_json_all(
|
||||
_: impl Ctx,
|
||||
/// The JSON string to extract values from.
|
||||
#[name("JSON")]
|
||||
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.
|
||||
///
|
||||
/// Examples:
|
||||
/// Use `[2]` or `[-1]` to get the last value, and `[1]` or `[-2]` for the middle value, of `["a", "b", "c"]`.
|
||||
/// 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: 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: Item<bool>,
|
||||
) -> List<String> {
|
||||
let cleaned = strip_trailing_commas(json.element());
|
||||
let Ok(value): Result<Value, _> = serde_json::from_str(&cleaned) else { return List::new() };
|
||||
let Some(segments) = parse_json_path(path.element().trim()) else { return List::new() };
|
||||
|
||||
let mut results = Vec::new();
|
||||
resolve_all(&value, &segments, !*unquote_strings.element(), &mut results);
|
||||
|
||||
results.into_iter().map(|(text, ty)| Item::new_from_element(text).with_attribute(ATTR_TYPE, ty.to_string())).collect()
|
||||
}
|
||||
|
||||
/// A parsed segment of a JSON access path.
|
||||
enum JsonPathSegment {
|
||||
/// Access an object key, e.g. `.name` or `["my key"]`.
|
||||
Key(String),
|
||||
/// Access an array element by index, e.g. `[0]` or `[-1]`.
|
||||
Index(i32),
|
||||
/// Iterate all elements of an array or object values, e.g. `[]`.
|
||||
IterateAll,
|
||||
}
|
||||
|
||||
/// Parses a JSON access path like `users[0].name` or `.["my key"][].value` into segments.
|
||||
/// Returns `None` on syntax errors.
|
||||
fn parse_json_path(path: &str) -> Option<Vec<JsonPathSegment>> {
|
||||
let mut segments = Vec::new();
|
||||
let mut chars = path.chars().peekable();
|
||||
|
||||
// Skip optional leading dot
|
||||
if chars.peek() == Some(&'.') {
|
||||
chars.next();
|
||||
|
||||
if chars.peek() == Some(&'.') {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
|
||||
while chars.peek().is_some() {
|
||||
if chars.peek() == Some(&'[') {
|
||||
chars.next(); // consume '['
|
||||
|
||||
if chars.peek() == Some(&']') {
|
||||
// Empty brackets: iterate all
|
||||
chars.next();
|
||||
segments.push(JsonPathSegment::IterateAll);
|
||||
} else if matches!(chars.peek(), Some(&'"') | Some(&'\'')) {
|
||||
// Quoted key: ["my key"] or ['my key']
|
||||
let closing_quote = chars.next().unwrap(); // consume opening quote
|
||||
let mut key = String::new();
|
||||
while let Some(&c) = chars.peek() {
|
||||
if c == closing_quote {
|
||||
chars.next(); // consume closing quote
|
||||
break;
|
||||
}
|
||||
if c == '\\' {
|
||||
chars.next();
|
||||
match chars.next() {
|
||||
Some('"') => key.push('"'),
|
||||
Some('\'') => key.push('\''),
|
||||
Some('\\') => key.push('\\'),
|
||||
Some('/') => key.push('/'),
|
||||
Some('b') => key.push('\x08'),
|
||||
Some('f') => key.push('\x0C'),
|
||||
Some('n') => key.push('\n'),
|
||||
Some('r') => key.push('\r'),
|
||||
Some('t') => key.push('\t'),
|
||||
Some('u') => {
|
||||
// Decode a 4-hex-digit Unicode escape sequence, only consuming verified hex digits
|
||||
let mut hex_digits = [0_u8; 4];
|
||||
let mut count = 0;
|
||||
for digit in &mut hex_digits {
|
||||
match chars.peek() {
|
||||
Some(c) if c.is_ascii_hexdigit() => {
|
||||
*digit = chars.next().unwrap() as u8;
|
||||
count += 1;
|
||||
}
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
|
||||
let hex = &hex_digits[..count];
|
||||
if count == 4
|
||||
&& let Ok(hex_str) = core::str::from_utf8(hex)
|
||||
&& let Ok(code_point) = u32::from_str_radix(hex_str, 16)
|
||||
&& let Some(byte) = char::from_u32(code_point)
|
||||
{
|
||||
key.push(byte);
|
||||
} else {
|
||||
key.push('\\');
|
||||
key.push('u');
|
||||
for &byte in hex {
|
||||
key.push(byte as char);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(other) => {
|
||||
key.push('\\');
|
||||
key.push(other);
|
||||
}
|
||||
None => key.push('\\'),
|
||||
}
|
||||
} else {
|
||||
key.push(c);
|
||||
chars.next();
|
||||
}
|
||||
}
|
||||
// Require the closing ']'
|
||||
if chars.peek() == Some(&']') {
|
||||
chars.next();
|
||||
} else {
|
||||
return None;
|
||||
}
|
||||
segments.push(JsonPathSegment::Key(key));
|
||||
} else {
|
||||
// Numeric index: [0] or [-1]
|
||||
let mut num_str = String::new();
|
||||
while let Some(&c) = chars.peek() {
|
||||
if c == ']' {
|
||||
chars.next();
|
||||
break;
|
||||
}
|
||||
num_str.push(c);
|
||||
chars.next();
|
||||
}
|
||||
if let Ok(index) = num_str.trim().parse::<i32>() {
|
||||
segments.push(JsonPathSegment::Index(index));
|
||||
} else {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
} else if chars.peek() == Some(&'.') {
|
||||
// Dot separator before next key
|
||||
chars.next();
|
||||
|
||||
if chars.peek() == Some(&'.') || chars.peek().is_none() {
|
||||
return None;
|
||||
}
|
||||
} else {
|
||||
// Bare key: read until dot or bracket
|
||||
let mut key = String::new();
|
||||
while let Some(&c) = chars.peek() {
|
||||
if c == '.' || c == '[' {
|
||||
break;
|
||||
}
|
||||
key.push(c);
|
||||
chars.next();
|
||||
}
|
||||
if !key.is_empty() {
|
||||
segments.push(JsonPathSegment::Key(key));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some(segments)
|
||||
}
|
||||
|
||||
/// Converts a JSON value to its string representation.
|
||||
/// Strings are quoted by default to produce valid JSON syntax. When `quote_strings` is false, surrounding quotes are stripped.
|
||||
fn json_value_to_string(value: &serde_json::Value, quote_strings: bool) -> String {
|
||||
match value {
|
||||
serde_json::Value::String(s) if !quote_strings => s.clone(),
|
||||
other => other.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a short JSON-type name (`"string"`, `"number"`, `"bool"`, `"null"`, `"object"`, `"array"`) for a parsed value.
|
||||
fn json_value_type_name(value: &serde_json::Value) -> &'static str {
|
||||
match value {
|
||||
serde_json::Value::String(_) => "string",
|
||||
serde_json::Value::Number(_) => "number",
|
||||
serde_json::Value::Bool(_) => "bool",
|
||||
serde_json::Value::Null => "null",
|
||||
serde_json::Value::Object(_) => "object",
|
||||
serde_json::Value::Array(_) => "array",
|
||||
}
|
||||
}
|
||||
|
||||
/// Navigates a JSON value by one path segment, returning the resulting value (or `None` if the path is invalid).
|
||||
fn json_navigate<'a>(value: &'a serde_json::Value, segment: &JsonPathSegment) -> Option<&'a serde_json::Value> {
|
||||
match segment {
|
||||
JsonPathSegment::Key(key) => value.as_object().and_then(|obj| obj.get(key)),
|
||||
JsonPathSegment::Index(index) => {
|
||||
let arr = value.as_array()?;
|
||||
let resolved = if *index < 0 { arr.len().checked_sub(index.unsigned_abs() as usize)? } else { *index as usize };
|
||||
arr.get(resolved)
|
||||
}
|
||||
JsonPathSegment::IterateAll => None, // Handled by resolve_all
|
||||
}
|
||||
}
|
||||
|
||||
/// Recursively resolves a path against a JSON value, fanning out at each `[]` and collecting leaf results.
|
||||
fn resolve_all(value: &serde_json::Value, segments: &[JsonPathSegment], quote_strings: bool, results: &mut Vec<(String, &'static str)>) {
|
||||
// Find the next IterateAll in the remaining segments
|
||||
let Some(iterate_position) = segments.iter().position(|s| matches!(s, JsonPathSegment::IterateAll)) else {
|
||||
// No more [] segments, navigate the rest linearly
|
||||
let mut current = value;
|
||||
for segment in segments {
|
||||
let Some(next) = json_navigate(current, segment) else { return };
|
||||
current = next;
|
||||
}
|
||||
results.push((json_value_to_string(current, quote_strings), json_value_type_name(current)));
|
||||
return;
|
||||
};
|
||||
|
||||
// Navigate to the array/object before the []
|
||||
let mut current = value;
|
||||
for segment in &segments[..iterate_position] {
|
||||
let Some(next) = json_navigate(current, segment) else { return };
|
||||
current = next;
|
||||
}
|
||||
|
||||
// Fan out over elements and recurse with the remaining path
|
||||
let remaining = &segments[iterate_position + 1..];
|
||||
match current {
|
||||
serde_json::Value::Array(arr) => {
|
||||
for element in arr {
|
||||
resolve_all(element, remaining, quote_strings, results);
|
||||
}
|
||||
}
|
||||
serde_json::Value::Object(obj) => {
|
||||
for element in obj.values() {
|
||||
resolve_all(element, remaining, quote_strings, results);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,894 @@
|
||||
pub mod fallback;
|
||||
mod font;
|
||||
pub mod json;
|
||||
pub mod markers;
|
||||
mod path_builder;
|
||||
pub mod regex;
|
||||
mod text_context;
|
||||
mod to_path;
|
||||
|
||||
use convert_case::{Boundary, Converter, pattern};
|
||||
use core_types::gpoll::Interrupt;
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::registry::types::{SignedInteger, TextArea};
|
||||
use core_types::{Context, Ctx, DeriveCtx, ExtractVarArgs};
|
||||
use dyn_any::DynAny;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
|
||||
// Re-export for convenience
|
||||
pub use core_types as gcore;
|
||||
pub use fallback::FALLBACK_FONT_RESOURCE;
|
||||
pub use font::*;
|
||||
pub use markers::{ATTR_FONT, ATTR_TEXT_ALIGN};
|
||||
pub use text_context::{TextContext, for_each_styled_glyph_run};
|
||||
pub use to_path::*;
|
||||
pub use vector_types;
|
||||
|
||||
/// Alignment of lines of type within a text block.
|
||||
#[repr(C)]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[widget(Radio)]
|
||||
pub enum TextAlign {
|
||||
#[default]
|
||||
#[icon("TextAlignLeft")]
|
||||
#[cfg_attr(feature = "serde", serde(alias = "Left"))]
|
||||
AlignLeft,
|
||||
#[icon("TextAlignCenter")]
|
||||
#[cfg_attr(feature = "serde", serde(alias = "Center"))]
|
||||
AlignCenter,
|
||||
#[icon("TextAlignRight")]
|
||||
#[cfg_attr(feature = "serde", serde(alias = "Right"))]
|
||||
AlignRight,
|
||||
#[icon("TextJustifyLeft")]
|
||||
JustifyLeft,
|
||||
#[icon("TextJustifyCenter")]
|
||||
JustifyCenter,
|
||||
#[icon("TextJustifyRight")]
|
||||
JustifyRight,
|
||||
#[icon("TextJustifyAll")]
|
||||
JustifyAll,
|
||||
}
|
||||
|
||||
impl From<TextAlign> for parley::Alignment {
|
||||
fn from(val: TextAlign) -> Self {
|
||||
match val {
|
||||
TextAlign::AlignLeft => parley::Alignment::Left,
|
||||
TextAlign::AlignCenter => parley::Alignment::Center,
|
||||
TextAlign::AlignRight => parley::Alignment::Right,
|
||||
_ => parley::Alignment::Justify,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TextAlign {
|
||||
/// What `parley::Alignment` to apply as a post-correction to the last line of a paragraph, or `None` if parley's default already handles it.
|
||||
///
|
||||
/// `JustifyLeft` returns `None` because parley already left-aligns the last line of a `Justify` layout. The other justify modes need
|
||||
/// the last line shifted (`Center`/`Right`) or its inter-word spaces redistributed (`Justify` / `JustifyAll`).
|
||||
pub fn last_line_correction(self) -> Option<parley::Alignment> {
|
||||
match self {
|
||||
Self::JustifyCenter => Some(parley::Alignment::Center),
|
||||
Self::JustifyRight => Some(parley::Alignment::Right),
|
||||
Self::JustifyAll => Some(parley::Alignment::Justify),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// CSS `(text-align, text-align-last)` values approximating this alignment for the `contenteditable` text overlay.
|
||||
pub fn css(self) -> (&'static str, &'static str) {
|
||||
match self {
|
||||
Self::AlignLeft => ("left", "auto"),
|
||||
Self::AlignCenter => ("center", "auto"),
|
||||
Self::AlignRight => ("right", "auto"),
|
||||
Self::JustifyLeft => ("justify", "auto"),
|
||||
Self::JustifyCenter => ("justify", "center"),
|
||||
Self::JustifyRight => ("justify", "right"),
|
||||
Self::JustifyAll => ("justify", "justify"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Clone, Copy, Debug)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct TypesettingConfig {
|
||||
pub font_size: f64,
|
||||
pub line_height_ratio: f64,
|
||||
pub letter_spacing: f64,
|
||||
pub letter_tilt: f64,
|
||||
pub max_width: Option<f64>,
|
||||
pub max_height: Option<f64>,
|
||||
pub align: TextAlign,
|
||||
}
|
||||
|
||||
impl Default for TypesettingConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
font_size: 24.,
|
||||
line_height_ratio: 1.2,
|
||||
letter_spacing: 0.,
|
||||
letter_tilt: 0.,
|
||||
max_width: None,
|
||||
max_height: None,
|
||||
align: TextAlign::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts escape sequence representations (`\n`, `\r`, `\t`, `\0`, `\\`) into their corresponding control characters.
|
||||
/// Unrecognized escape sequences (e.g. `\x`) are preserved as-is.
|
||||
fn unescape_string(input: String) -> String {
|
||||
let mut result = String::with_capacity(input.len());
|
||||
let mut chars = input.chars();
|
||||
|
||||
while let Some(c) = chars.next() {
|
||||
if c == '\\' {
|
||||
match chars.next() {
|
||||
Some('n') => result.push('\n'),
|
||||
Some('r') => result.push('\r'),
|
||||
Some('t') => result.push('\t'),
|
||||
Some('0') => result.push('\0'),
|
||||
Some('\\') => result.push('\\'),
|
||||
Some(unrecognized) => result.extend(['\\', unrecognized]),
|
||||
None => result.push('\\'),
|
||||
}
|
||||
} else {
|
||||
result.push(c);
|
||||
}
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
/// Converts control characters (newline, carriage return, tab, null, backslash) back into their escape sequence representations.
|
||||
fn escape_string(input: String) -> String {
|
||||
let mut result = String::with_capacity(input.len());
|
||||
|
||||
for c in input.chars() {
|
||||
match c {
|
||||
'\n' => result.push_str("\\n"),
|
||||
'\r' => result.push_str("\\r"),
|
||||
'\t' => result.push_str("\\t"),
|
||||
'\0' => result.push_str("\\0"),
|
||||
'\\' => result.push_str("\\\\"),
|
||||
other => result.push(other),
|
||||
}
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, dyn_any::DynAny, node_macro::ChoiceType, serde::Serialize, serde::Deserialize)]
|
||||
#[widget(Dropdown)]
|
||||
pub enum StringCapitalization {
|
||||
/// "on the origin of species" — Converts all letters to lower case.
|
||||
#[default]
|
||||
#[label("lower case")]
|
||||
LowerCase,
|
||||
/// "ON THE ORIGIN OF SPECIES" — Converts all letters to upper case.
|
||||
#[label("UPPER CASE")]
|
||||
UpperCase,
|
||||
/// "On The Origin Of Species" — Converts the first letter of every word to upper case.
|
||||
#[label("Capital Case")]
|
||||
CapitalCase,
|
||||
/// "On the Origin of Species" — Converts the first letter of significant words to upper case.
|
||||
#[label("Headline Case")]
|
||||
HeadlineCase,
|
||||
/// "On the origin of species" — Converts the first letter of every word to lower case, except the initial word which is made upper case.
|
||||
#[label("Sentence case")]
|
||||
SentenceCase,
|
||||
/// "on The Origin Of Species" — Converts the first letter of every word to upper case, except the initial word which is made lower case.
|
||||
#[label("camel Case")]
|
||||
CamelCase,
|
||||
}
|
||||
|
||||
/// Constructs a string value which may be set to any plain text.
|
||||
#[node_macro::node(category("Value"))]
|
||||
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: Item<String>) -> Item<String> {
|
||||
value
|
||||
}
|
||||
|
||||
/// Joins two strings together.
|
||||
#[node_macro::node(category("Text"))]
|
||||
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: 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: 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)
|
||||
} else {
|
||||
(start as usize).min(total_graphemes)
|
||||
};
|
||||
let end = if end <= 0. {
|
||||
total_graphemes.saturating_sub(end.abs() as usize)
|
||||
} else {
|
||||
(end as usize).min(total_graphemes)
|
||||
};
|
||||
|
||||
let result = if start >= end {
|
||||
String::new()
|
||||
} else {
|
||||
string.element().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.
|
||||
#[node_macro::node(category("Text"))]
|
||||
fn string_truncate(
|
||||
_: impl Ctx,
|
||||
/// The string to truncate.
|
||||
string: Item<String>,
|
||||
/// The maximum number of characters allowed, including the suffix if one is appended.
|
||||
#[default(80)]
|
||||
length: Item<u32>,
|
||||
/// A suffix appended to indicate truncation occurred, unless empty. Its length counts towards the character budget.
|
||||
#[default("…")]
|
||||
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.element().graphemes(true).take(max_length).collect();
|
||||
let keep = max_length - suffix.graphemes(true).count();
|
||||
|
||||
let mut truncated: String = string.element().graphemes(true).take(keep).collect();
|
||||
truncated.push_str(&suffix);
|
||||
|
||||
*string.element_mut() = truncated;
|
||||
string
|
||||
}
|
||||
|
||||
/// Formats a number as a string with control over decimal places, decimal separator, and thousands grouping.
|
||||
#[node_macro::node(category("Text"), properties("format_number_properties"))]
|
||||
fn format_number(
|
||||
_: impl Ctx,
|
||||
/// The number to format as a string.
|
||||
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: Item<u32>,
|
||||
/// The character(s) used as the decimal point.
|
||||
#[default(".")]
|
||||
decimal_separator: Item<String>,
|
||||
/// Always show the exact number of decimal places, even if they are trailing zeros.
|
||||
#[default(true)]
|
||||
fixed_decimals: Item<bool>,
|
||||
/// Whether to group digits with a thousands separator.
|
||||
use_thousands_separator: Item<bool>,
|
||||
/// The character(s) inserted between digit groups.
|
||||
#[default(",")]
|
||||
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: 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.
|
||||
let requested_places = decimal_places as usize;
|
||||
let max_places = {
|
||||
let whole_digits = if number == 0. { 1 } else { (number.abs().log10().floor() as usize).saturating_add(1) };
|
||||
let upper_bound = 17_usize.saturating_sub(whole_digits);
|
||||
let mut meaningful = upper_bound;
|
||||
for p in 0..=upper_bound {
|
||||
let s = format!("{number:.p$}");
|
||||
if s.parse::<f64>() == Ok(number) {
|
||||
meaningful = p;
|
||||
break;
|
||||
}
|
||||
}
|
||||
meaningful
|
||||
};
|
||||
let places = requested_places.min(max_places);
|
||||
let formatted = format!("{number:.places$}");
|
||||
|
||||
// If the user requested more decimal places than the float can represent, pad with zeros
|
||||
let extra_zeros = requested_places.saturating_sub(places);
|
||||
|
||||
// Split into sign, whole, and decimal parts
|
||||
let (sign, unsigned) = if let Some(rest) = formatted.strip_prefix('-') { ("-", rest) } else { ("", formatted.as_str()) };
|
||||
|
||||
let (whole_string, decimal_string) = match unsigned.split_once('.') {
|
||||
Some((w, d)) => {
|
||||
let padded = if extra_zeros > 0 { format!("{d}{:0>width$}", "", width = extra_zeros) } else { d.to_string() };
|
||||
(w.to_string(), Some(padded))
|
||||
}
|
||||
None => (unsigned.to_string(), None),
|
||||
};
|
||||
|
||||
// Apply thousands grouping to the whole number part
|
||||
let grouped_whole = if use_thousands_separator && !thousands_separator.is_empty() {
|
||||
let skip = start_at_10000 && whole_string.len() <= 4;
|
||||
if skip {
|
||||
whole_string.clone()
|
||||
} else {
|
||||
let mut result = String::new();
|
||||
for (i, ch) in whole_string.chars().rev().enumerate() {
|
||||
if i > 0 && i % 3 == 0 {
|
||||
result.push_str(&thousands_separator.chars().rev().collect::<String>());
|
||||
}
|
||||
result.push(ch);
|
||||
}
|
||||
result.chars().rev().collect()
|
||||
}
|
||||
} else {
|
||||
whole_string
|
||||
};
|
||||
|
||||
// Build the final string
|
||||
let result = match decimal_string {
|
||||
None if fixed_decimals && requested_places > 0 => {
|
||||
let zeros = "0".repeat(requested_places);
|
||||
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}")
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
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"), 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: Item<String>,
|
||||
/// The value of the result if the string cannot be parsed as a valid number.
|
||||
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.
|
||||
#[node_macro::node(category("Text"))]
|
||||
fn string_trim(
|
||||
_: impl Ctx,
|
||||
/// The string that may contain leading and trailing whitespace that should be removed.
|
||||
string: Item<String>,
|
||||
/// Whether the start of the string should have its whitespace removed.
|
||||
#[default(true)]
|
||||
start: Item<bool>,
|
||||
/// Whether the end of the string should have its whitespace removed.
|
||||
#[default(true)]
|
||||
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.
|
||||
///
|
||||
/// Unescape: `\n` (newline), `\r` (carriage return), `\t` (tab), `\0` (null), and `\\` (backslash) are converted into the actual special characters.
|
||||
/// Escape: the actual special characters are converted back into their escape sequence representations.
|
||||
#[node_macro::node(category("Text"))]
|
||||
fn string_escape(
|
||||
_: impl Ctx,
|
||||
/// The string that contains either literal escape sequences or control characters to be converted to the opposite representation.
|
||||
string: Item<String>,
|
||||
/// Convert the control characters back into their escape sequence representations.
|
||||
#[default(true)]
|
||||
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".)
|
||||
#[node_macro::node(category("Text"))]
|
||||
fn string_reverse(
|
||||
_: impl Ctx,
|
||||
/// The string to be reversed.
|
||||
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.
|
||||
#[node_macro::node(category("Text"))]
|
||||
fn string_repeat(
|
||||
_: impl Ctx,
|
||||
/// The string to be repeated.
|
||||
string: Item<String>,
|
||||
/// The number of times the string should appear in the output.
|
||||
#[default(2)]
|
||||
#[hard(1..)]
|
||||
count: Item<u32>,
|
||||
/// The string placed between each repetition.
|
||||
#[default("\\n")]
|
||||
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: 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.element() as usize;
|
||||
|
||||
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.element());
|
||||
}
|
||||
|
||||
*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.
|
||||
#[node_macro::node(category("Text"))]
|
||||
fn string_pad(
|
||||
_: impl Ctx,
|
||||
/// The string to be padded to a target length.
|
||||
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: Item<u32>,
|
||||
/// The repeated substring used to fill the remaining space. A multi-charcter substring may end partway through its final repetition.
|
||||
#[default("#")]
|
||||
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: Item<String>,
|
||||
/// Pad at the end of the string instead of the start.
|
||||
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;
|
||||
}
|
||||
|
||||
// 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.element().rfind(&*up_to) } else { string.element().find(&*up_to) }
|
||||
{
|
||||
let (before, after) = string.element().split_at(position);
|
||||
|
||||
if from_end {
|
||||
// Pad the portion after the substring
|
||||
let after_substring = &after[up_to.len()..];
|
||||
let current_length = after_substring.graphemes(true).count();
|
||||
if current_length >= target_length {
|
||||
return string;
|
||||
}
|
||||
let pad_length = target_length - current_length;
|
||||
let padding: String = padding.graphemes(true).cycle().take(pad_length).collect();
|
||||
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();
|
||||
if current_length >= target_length {
|
||||
return string;
|
||||
}
|
||||
let pad_length = target_length - current_length;
|
||||
let padding: String = padding.graphemes(true).cycle().take(pad_length).collect();
|
||||
let result = format!("{padding}{before}{after}");
|
||||
|
||||
*string.element_mut() = result;
|
||||
return string;
|
||||
}
|
||||
}
|
||||
|
||||
let current_length = string.element().graphemes(true).count();
|
||||
if current_length >= target_length {
|
||||
return string;
|
||||
}
|
||||
|
||||
let pad_length = target_length - current_length;
|
||||
let padding: String = padding.graphemes(true).cycle().take(pad_length).collect();
|
||||
|
||||
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.
|
||||
#[node_macro::node(category("Text"))]
|
||||
fn string_contains(
|
||||
_: impl Ctx,
|
||||
/// The string to search within.
|
||||
string: Item<String>,
|
||||
/// The substring to search for.
|
||||
substring: Item<String>,
|
||||
/// Only match if the substring appears at the start of the string.
|
||||
at_start: Item<bool>,
|
||||
/// Only match if the substring appears at the end of the string.
|
||||
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.
|
||||
#[node_macro::node(category("Text"))]
|
||||
fn string_find_index(
|
||||
_: impl Ctx,
|
||||
/// The string to search within.
|
||||
string: Item<String>,
|
||||
/// The substring to search for.
|
||||
substring: Item<String>,
|
||||
/// Find the start index of the last occurrence instead of the first.
|
||||
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() {
|
||||
let result = if from_end { string.graphemes(true).count() as f64 } else { 0. };
|
||||
return Item::from_parts(result, attributes);
|
||||
}
|
||||
|
||||
let result = if from_end {
|
||||
// Search backwards by finding all byte-level matches and taking the last one
|
||||
string
|
||||
.rmatch_indices(substring)
|
||||
.next()
|
||||
.map_or(-1., |(byte_index, _)| string[..byte_index].graphemes(true).count() as f64)
|
||||
} else {
|
||||
string
|
||||
.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.
|
||||
#[node_macro::node(category("Text"))]
|
||||
fn string_occurrences(
|
||||
_: impl Ctx,
|
||||
/// The string to search within.
|
||||
string: Item<String>,
|
||||
/// The substring to count occurrences of.
|
||||
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: Item<bool>,
|
||||
) -> Item<f64> {
|
||||
let (string, attributes) = string.into_parts();
|
||||
let substring = substring.element().as_str();
|
||||
|
||||
if substring.is_empty() {
|
||||
return Item::from_parts(0., attributes);
|
||||
}
|
||||
|
||||
// NON-OVERLAPPING: Simple linear scan.
|
||||
// O(n), where n = string length
|
||||
if !*overlapping.element() {
|
||||
return Item::from_parts(string.matches(substring).count() as f64, attributes);
|
||||
}
|
||||
|
||||
// OVERLAPPING: KMP (Knuth-Morris-Pratt) algorithm.
|
||||
// O(n + m), where n = string length, m = substring length
|
||||
|
||||
let pattern: Vec<char> = substring.chars().collect();
|
||||
let text: Vec<char> = string.chars().collect();
|
||||
|
||||
// Build the KMP failure function:
|
||||
// For each position in the pattern, the length of the longest proper prefix that is also a suffix.
|
||||
// This lets us skip ahead on mismatches instead of restarting from scratch.
|
||||
let mut failure = vec![0_usize; pattern.len()];
|
||||
let mut k = 0;
|
||||
for i in 1..pattern.len() {
|
||||
while k > 0 && pattern[k] != pattern[i] {
|
||||
k = failure[k - 1];
|
||||
}
|
||||
|
||||
if pattern[k] == pattern[i] {
|
||||
k += 1;
|
||||
}
|
||||
|
||||
failure[i] = k;
|
||||
}
|
||||
|
||||
// Scan the text, advancing the pattern cursor without ever backtracking in the text
|
||||
let mut count: usize = 0;
|
||||
let mut pattern_cursor = 0;
|
||||
for &text_char in &text {
|
||||
while pattern_cursor > 0 && pattern[pattern_cursor] != text_char {
|
||||
pattern_cursor = failure[pattern_cursor - 1];
|
||||
}
|
||||
|
||||
if pattern[pattern_cursor] == text_char {
|
||||
pattern_cursor += 1;
|
||||
}
|
||||
|
||||
if pattern_cursor == pattern.len() {
|
||||
count += 1;
|
||||
|
||||
// Reset using failure function to allow overlapping matches
|
||||
pattern_cursor = failure[pattern_cursor - 1];
|
||||
}
|
||||
}
|
||||
|
||||
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.
|
||||
#[node_macro::node(category("Text"), properties("string_capitalization_properties"))]
|
||||
fn string_capitalization(
|
||||
_: impl Ctx,
|
||||
/// The string to have its letter capitalization converted.
|
||||
string: Item<String>,
|
||||
/// The capitalization style to apply.
|
||||
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: Item<bool>,
|
||||
/// The string placed between each word.
|
||||
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
|
||||
let result = if use_joiner {
|
||||
match capitalization {
|
||||
// Simple case mappings that preserve the string's existing structure
|
||||
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(&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(&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(&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 => input.to_lowercase(),
|
||||
StringCapitalization::UpperCase => input.to_uppercase(),
|
||||
StringCapitalization::CapitalCase => {
|
||||
let mut capitalize_next = true;
|
||||
input.chars().fold(String::with_capacity(input.len()), |mut result, c| {
|
||||
if c.is_whitespace() || c == '_' || c == '-' {
|
||||
capitalize_next = true;
|
||||
result.push(c);
|
||||
} else if capitalize_next {
|
||||
capitalize_next = false;
|
||||
result.extend(c.to_uppercase());
|
||||
} else {
|
||||
result.push(c);
|
||||
}
|
||||
result
|
||||
})
|
||||
}
|
||||
StringCapitalization::HeadlineCase => titlecase::titlecase(&input),
|
||||
StringCapitalization::SentenceCase => {
|
||||
let mut chars = input.chars();
|
||||
match chars.next() {
|
||||
Some(first) => first.to_uppercase().to_string() + &chars.as_str().to_lowercase(),
|
||||
None => String::new(),
|
||||
}
|
||||
}
|
||||
StringCapitalization::CamelCase => {
|
||||
let mut capitalize_next = false;
|
||||
input.chars().fold(String::with_capacity(input.len()), |mut result, c| {
|
||||
if c.is_whitespace() || c == '_' || c == '-' {
|
||||
capitalize_next = true;
|
||||
result.push(c);
|
||||
} else if capitalize_next {
|
||||
capitalize_next = false;
|
||||
result.extend(c.to_uppercase());
|
||||
} else {
|
||||
result.extend(c.to_lowercase());
|
||||
}
|
||||
result
|
||||
})
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
*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: 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.
|
||||
///
|
||||
/// For example, splitting "a, b, c" with delimiter ", " produces `["a", "b", "c"]`.
|
||||
#[node_macro::node(category("Text"))]
|
||||
fn string_split(
|
||||
_: impl Ctx,
|
||||
/// The string to split into substrings.
|
||||
string: Item<String>,
|
||||
/// The character(s) that separate the substrings. These are not included in the outputs.
|
||||
#[default("\\n")]
|
||||
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: Item<bool>,
|
||||
) -> List<String> {
|
||||
let delimiter = delimiter.element().clone();
|
||||
let delimiter = if *delimiter_escaping.element() { unescape_string(delimiter) } else { delimiter };
|
||||
|
||||
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.
|
||||
///
|
||||
/// For example, joining `["a", "b", "c"]` with separator ", " produces "a, b, c".
|
||||
#[node_macro::node(category("Text"))]
|
||||
fn string_join(
|
||||
_: impl Ctx,
|
||||
/// The list of strings to join together.
|
||||
strings: List<String>,
|
||||
/// The text placed between each pair of strings.
|
||||
#[default(", ")]
|
||||
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: 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 };
|
||||
|
||||
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.
|
||||
#[node_macro::node(category("Text"))]
|
||||
fn map_string(
|
||||
ctx: impl Ctx + DeriveCtx,
|
||||
strings: List<String>,
|
||||
#[expose]
|
||||
#[implementations(Context -> Item<String>)]
|
||||
mapped: impl Node<Context<'_>, Output = Item<String>>,
|
||||
) -> Result<List<String>, Interrupt> {
|
||||
let spilled = ctx.index_head();
|
||||
let mut result = List::new();
|
||||
|
||||
for (i, row) in strings.into_iter().enumerate() {
|
||||
let scoped = ctx.push_vararg(&row);
|
||||
let mapped_string = mapped.eval(&scoped.ctx().promoted(&spilled, i as u64))?;
|
||||
|
||||
result.push(mapped_string);
|
||||
}
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Reads the current string from within a **Map String** node's loop.
|
||||
#[node_macro::node(category("Context"))]
|
||||
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::<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: 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)
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
//! Attribute markers whose value types live in this crate, with their name
|
||||
//! constants for the string-keyed legacy readers and writers.
|
||||
|
||||
use core_types::attribute::Attribute;
|
||||
|
||||
core_types::attribute! {
|
||||
/// Text item's font, as a resource of the loaded font file.
|
||||
pub Font("font"): &graphene_resource::Resource;
|
||||
/// Text item's horizontal alignment of lines within the block.
|
||||
pub TextAlign("text_align"): crate::TextAlign;
|
||||
}
|
||||
|
||||
pub const ATTR_FONT: &str = Font::NAME;
|
||||
pub const ATTR_TEXT_ALIGN: &str = TextAlign::NAME;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use core_types::attribute::info;
|
||||
use std::any::TypeId;
|
||||
|
||||
#[test]
|
||||
fn the_census_carries_this_crates_names() {
|
||||
assert_eq!(info("font").unwrap().value_type, TypeId::of::<&'static graphene_resource::Resource>());
|
||||
assert_eq!(info("text_align").unwrap().value_type, TypeId::of::<crate::TextAlign>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_font_default_is_the_empty_resource() {
|
||||
assert!(<Font as Attribute>::default().is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::{ATTR_EDITOR_TEXT_FRAME, ATTR_TRANSFORM};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use parley::GlyphRun;
|
||||
use skrifa::GlyphId;
|
||||
use skrifa::instance::{LocationRef, NormalizedCoord, Size};
|
||||
use skrifa::outline::{DrawSettings, OutlinePen};
|
||||
use skrifa::raw::FontRef as ReadFontsRef;
|
||||
use skrifa::{MetadataProvider, OutlineGlyph};
|
||||
use vector_types::ATTR_EDITOR_CLICK_TARGET;
|
||||
use vector_types::subpath::{ManipulatorGroup, Subpath};
|
||||
use vector_types::vector::{PointId, Vector};
|
||||
|
||||
pub struct PathBuilder {
|
||||
current_subpath: Subpath<PointId>,
|
||||
origin: DVec2,
|
||||
glyph_subpaths: Vec<Subpath<PointId>>,
|
||||
pub vector_list: List<Vector>,
|
||||
/// Per-glyph AABBs collected in single-item mode, published as `ATTR_EDITOR_CLICK_TARGET` in `finalize()`.
|
||||
merged_click_target_bboxes: Vec<[DVec2; 2]>,
|
||||
/// Per-glyph baselines, parallel to `merged_click_target_bboxes`. Groups glyphs by line for the widening pass.
|
||||
merged_click_target_baselines: Vec<f64>,
|
||||
/// Per-glyph AABBs in glyph-local space (multi-item mode), widened in `finalize()` to fill gaps.
|
||||
per_glyph_bboxes: Vec<Option<[DVec2; 2]>>,
|
||||
/// Text frame size, stamped per item as `ATTR_EDITOR_TEXT_FRAME` relative to each item's origin.
|
||||
text_frame_size: DVec2,
|
||||
/// First glyph's baseline offset (pre-height-filter). Used for the empty placeholder item so
|
||||
/// `local_transforms` stays stable when all glyphs are clipped during a resize drag.
|
||||
first_glyph_offset: DVec2,
|
||||
scale: f64,
|
||||
id: PointId,
|
||||
}
|
||||
|
||||
impl PathBuilder {
|
||||
pub fn new(per_glyph_items: bool, scale: f64, text_frame_size: DVec2, first_glyph_offset: DVec2) -> Self {
|
||||
Self {
|
||||
current_subpath: Subpath::new(Vec::new(), false),
|
||||
glyph_subpaths: Vec::new(),
|
||||
vector_list: if per_glyph_items { List::new() } else { List::new_from_element(Vector::default()) },
|
||||
merged_click_target_bboxes: Vec::new(),
|
||||
merged_click_target_baselines: Vec::new(),
|
||||
per_glyph_bboxes: Vec::new(),
|
||||
text_frame_size,
|
||||
first_glyph_offset,
|
||||
scale,
|
||||
id: PointId::ZERO,
|
||||
origin: DVec2::default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn point(&self, x: f32, y: f32) -> DVec2 {
|
||||
DVec2::new(self.origin.x + x as f64, self.origin.y - y as f64) * self.scale
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn draw_glyph(
|
||||
&mut self,
|
||||
glyph: &OutlineGlyph<'_>,
|
||||
size: f32,
|
||||
normalized_coords: &[NormalizedCoord],
|
||||
glyph_offset: DVec2,
|
||||
style_skew: Option<DAffine2>,
|
||||
skew: DAffine2,
|
||||
per_glyph_items: bool,
|
||||
) -> bool {
|
||||
let location_ref = LocationRef::new(normalized_coords);
|
||||
let settings = DrawSettings::unhinted(Size::new(size), location_ref);
|
||||
glyph.draw(settings, self).unwrap();
|
||||
let has_geometry = !self.glyph_subpaths.is_empty();
|
||||
|
||||
// Apply transforms in correct order: style-based skew first, then user-requested skew
|
||||
// This ensures font synthesis (italic) is applied before user transformations
|
||||
for glyph_subpath in &mut self.glyph_subpaths {
|
||||
if let Some(style_skew) = style_skew {
|
||||
glyph_subpath.apply_transform(style_skew);
|
||||
}
|
||||
|
||||
glyph_subpath.apply_transform(skew);
|
||||
}
|
||||
|
||||
let glyph_bbox = subpaths_bounding_box(&self.glyph_subpaths);
|
||||
|
||||
if per_glyph_items {
|
||||
// Frame in item-local space: top-left at `-glyph_offset` so the item transform cancels it
|
||||
// back to the layer-local frame origin, regardless of which glyph survived
|
||||
let frame_in_item_local = DAffine2::from_scale_angle_translation(self.text_frame_size, 0., -glyph_offset);
|
||||
|
||||
let item = Item::new_from_element(Vector::from_subpaths(core::mem::take(&mut self.glyph_subpaths), false))
|
||||
.with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(glyph_offset))
|
||||
.with_attribute(ATTR_EDITOR_TEXT_FRAME, frame_in_item_local);
|
||||
self.vector_list.push(item);
|
||||
|
||||
// Defer click target creation to `finalize()` where adjacent AABBs get widened
|
||||
self.per_glyph_bboxes.push(glyph_bbox);
|
||||
} else {
|
||||
for subpath in self.glyph_subpaths.drain(..) {
|
||||
// Unwrapping here is ok because `self.vector_list` is initialized with a single `List<Vector>` item
|
||||
self.vector_list.element_mut(0).unwrap().append_subpath(subpath, false);
|
||||
}
|
||||
if let Some(bbox) = glyph_bbox {
|
||||
self.merged_click_target_bboxes.push(bbox);
|
||||
self.merged_click_target_baselines.push(glyph_offset.y);
|
||||
}
|
||||
}
|
||||
|
||||
has_geometry
|
||||
}
|
||||
|
||||
pub fn render_glyph_run(&mut self, glyph_run: &GlyphRun<'_, ()>, letter_tilt: f64, per_glyph_items: bool, x_offset: f32, space_extra: f32) {
|
||||
let mut run_x = glyph_run.offset() + x_offset;
|
||||
let run_y = glyph_run.baseline();
|
||||
|
||||
let run = glyph_run.run();
|
||||
|
||||
// User-requested letter tilt applied around baseline to avoid vertical displacement
|
||||
// Translation ensures rotation point is at the baseline, not origin
|
||||
let skew = if per_glyph_items {
|
||||
DAffine2::from_cols_array(&[1., 0., -letter_tilt.to_radians().tan(), 1., 0., 0.])
|
||||
} else {
|
||||
DAffine2::from_translation(DVec2::new(0., run_y as f64))
|
||||
* DAffine2::from_cols_array(&[1., 0., -letter_tilt.to_radians().tan(), 1., 0., 0.])
|
||||
* DAffine2::from_translation(DVec2::new(0., -run_y as f64))
|
||||
};
|
||||
|
||||
let synthesis = run.synthesis();
|
||||
|
||||
// Font synthesis (e.g., synthetic italic) applied separately from user transforms
|
||||
// This preserves the distinction between font styling and user transformations
|
||||
let style_skew = synthesis.skew().map(|angle| {
|
||||
if per_glyph_items {
|
||||
DAffine2::from_cols_array(&[1., 0., -angle.to_radians().tan() as f64, 1., 0., 0.])
|
||||
} else {
|
||||
DAffine2::from_translation(DVec2::new(0., run_y as f64))
|
||||
* DAffine2::from_cols_array(&[1., 0., -angle.to_radians().tan() as f64, 1., 0., 0.])
|
||||
* DAffine2::from_translation(DVec2::new(0., -run_y as f64))
|
||||
}
|
||||
});
|
||||
|
||||
let font = run.font();
|
||||
let font_size = run.font_size();
|
||||
|
||||
let normalized_coords = run.normalized_coords().iter().map(|coord| NormalizedCoord::from_bits(*coord)).collect::<Vec<_>>();
|
||||
|
||||
// TODO: This can be cached for better performance
|
||||
let font_collection_ref = font.data.as_ref();
|
||||
let font_ref = ReadFontsRef::from_index(font_collection_ref, font.index).unwrap();
|
||||
let outlines = font_ref.outline_glyphs();
|
||||
|
||||
for glyph in glyph_run.glyphs() {
|
||||
let glyph_offset = DVec2::new((run_x + glyph.x) as f64, (run_y - glyph.y) as f64);
|
||||
run_x += glyph.advance;
|
||||
|
||||
let glyph_id = GlyphId::from(glyph.id);
|
||||
if let Some(glyph_outline) = outlines.get(glyph_id) {
|
||||
if !per_glyph_items {
|
||||
self.origin = glyph_offset;
|
||||
}
|
||||
let drew_geometry = self.draw_glyph(&glyph_outline, font_size, &normalized_coords, glyph_offset, style_skew, skew, per_glyph_items);
|
||||
|
||||
if !drew_geometry && space_extra != 0. && glyph.advance > 0. {
|
||||
run_x += space_extra;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn finalize(mut self) -> List<Vector> {
|
||||
// Empty list = all glyphs clipped by height. Create a placeholder with the same item-0
|
||||
// transform a populated list would have so `local_transforms` stays stable mid-drag.
|
||||
// TODO: Remove this hack and move the attribute up to the parent return value when <https://github.com/GraphiteEditor/Graphite/issues/3779> is done.
|
||||
if self.vector_list.is_empty() {
|
||||
let frame_in_item_local = DAffine2::from_scale_angle_translation(self.text_frame_size, 0., -self.first_glyph_offset);
|
||||
let item = Item::new_from_element(Vector::default())
|
||||
.with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(self.first_glyph_offset))
|
||||
.with_attribute(ATTR_EDITOR_TEXT_FRAME, frame_in_item_local);
|
||||
self.vector_list.push(item);
|
||||
}
|
||||
|
||||
// Widen per-glyph AABBs to close horizontal gaps, then publish as click targets
|
||||
if !self.per_glyph_bboxes.is_empty() {
|
||||
// Project glyph-local AABBs into layer-local for the widening pass
|
||||
let entries: Vec<(usize, DVec2, [DVec2; 2])> = self
|
||||
.per_glyph_bboxes
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, bbox)| {
|
||||
let bbox = (*bbox)?;
|
||||
let offset = self.vector_list.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM, index).translation;
|
||||
Some((index, offset, [bbox[0] + offset, bbox[1] + offset]))
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut layer_bboxes: Vec<[DVec2; 2]> = entries.iter().map(|entry| entry.2).collect();
|
||||
let baselines: Vec<f64> = entries.iter().map(|entry| entry.1.y).collect();
|
||||
widen_horizontal_gaps(&mut layer_bboxes, &baselines);
|
||||
|
||||
// Project back to glyph-local and stamp as click targets
|
||||
for (entry, widened) in entries.iter().zip(layer_bboxes.iter()) {
|
||||
let glyph_local = [widened[0] - entry.1, widened[1] - entry.1];
|
||||
let rect = Subpath::new_rectangle(glyph_local[0], glyph_local[1]);
|
||||
self.vector_list.set_attribute(ATTR_EDITOR_CLICK_TARGET, entry.0, Some(Vector::from_subpaths([rect], false)));
|
||||
}
|
||||
}
|
||||
|
||||
// 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);
|
||||
|
||||
let widened_subpaths: Vec<_> = bboxes.iter().map(|[min, max]| Subpath::new_rectangle(*min, *max)).collect();
|
||||
self.vector_list.set_attribute(ATTR_EDITOR_CLICK_TARGET, 0, Some(Vector::from_subpaths(widened_subpaths, false)));
|
||||
}
|
||||
|
||||
// Fill in text frame for items that don't have one yet (single-item mode, where item 0 = identity)
|
||||
let frame = DAffine2::from_scale(self.text_frame_size);
|
||||
for index in 0..self.vector_list.len() {
|
||||
if self.vector_list.attribute::<DAffine2>(ATTR_EDITOR_TEXT_FRAME, index).is_none() {
|
||||
self.vector_list.set_attribute(ATTR_EDITOR_TEXT_FRAME, index, frame);
|
||||
}
|
||||
}
|
||||
|
||||
self.vector_list
|
||||
}
|
||||
}
|
||||
|
||||
/// Widen AABBs horizontally so same-line neighbors fill inter-glyph gaps.
|
||||
/// The shorter glyph (higher min.y) widens toward its taller neighbor; equal heights split the gap.
|
||||
/// Assumes input is in reading order. Linear runtime.
|
||||
fn widen_horizontal_gaps(bboxes: &mut [[DVec2; 2]], baselines: &[f64]) {
|
||||
for i in 0..bboxes.len().saturating_sub(1) {
|
||||
// Skip cross-line pairs (loose epsilon since baselines come from layout floats)
|
||||
if (baselines[i] - baselines[i + 1]).abs() > 1e-4 {
|
||||
continue;
|
||||
}
|
||||
|
||||
let gap = bboxes[i + 1][0].x - bboxes[i][1].x;
|
||||
if gap <= 0. {
|
||||
continue;
|
||||
}
|
||||
|
||||
let left_top = bboxes[i][0].y;
|
||||
let right_top = bboxes[i + 1][0].y;
|
||||
|
||||
if left_top > right_top {
|
||||
bboxes[i][1].x += gap;
|
||||
} else if right_top > left_top {
|
||||
bboxes[i + 1][0].x -= gap;
|
||||
} else {
|
||||
let half = gap / 2.;
|
||||
bboxes[i][1].x += half;
|
||||
bboxes[i + 1][0].x -= half;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn subpaths_bounding_box(subpaths: &[Subpath<PointId>]) -> Option<[DVec2; 2]> {
|
||||
subpaths
|
||||
.iter()
|
||||
.filter_map(|subpath| subpath.bounding_box())
|
||||
.reduce(|[a_min, a_max], [b_min, b_max]| [a_min.min(b_min), a_max.max(b_max)])
|
||||
}
|
||||
|
||||
impl OutlinePen for PathBuilder {
|
||||
fn move_to(&mut self, x: f32, y: f32) {
|
||||
if !self.current_subpath.is_empty() {
|
||||
self.glyph_subpaths.push(std::mem::replace(&mut self.current_subpath, Subpath::new(Vec::new(), false)));
|
||||
}
|
||||
self.current_subpath.push_manipulator_group(ManipulatorGroup::new_anchor_with_id(self.point(x, y), self.id.next_id()));
|
||||
}
|
||||
|
||||
fn line_to(&mut self, x: f32, y: f32) {
|
||||
self.current_subpath.push_manipulator_group(ManipulatorGroup::new_anchor_with_id(self.point(x, y), self.id.next_id()));
|
||||
}
|
||||
|
||||
fn quad_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32) {
|
||||
let [handle, anchor] = [self.point(x1, y1), self.point(x2, y2)];
|
||||
self.current_subpath.last_manipulator_group_mut().unwrap().out_handle = Some(handle);
|
||||
self.current_subpath.push_manipulator_group(ManipulatorGroup::new_with_id(anchor, None, None, self.id.next_id()));
|
||||
}
|
||||
|
||||
fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x3: f32, y3: f32) {
|
||||
let [handle1, handle2, anchor] = [self.point(x1, y1), self.point(x2, y2), self.point(x3, y3)];
|
||||
self.current_subpath.last_manipulator_group_mut().unwrap().out_handle = Some(handle1);
|
||||
self.current_subpath
|
||||
.push_manipulator_group(ManipulatorGroup::new_with_id(anchor, Some(handle2), None, self.id.next_id()));
|
||||
}
|
||||
|
||||
fn close(&mut self) {
|
||||
self.current_subpath.set_closed(true);
|
||||
self.glyph_subpaths.push(std::mem::replace(&mut self.current_subpath, Subpath::new(Vec::new(), false)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::registry::types::SignedInteger;
|
||||
use core_types::{ATTR_END, ATTR_NAME, ATTR_START, Ctx};
|
||||
|
||||
/// Checks whether the string contains a match for the given regular expression pattern. Optionally restricts the match to only the start and/or end of the string.
|
||||
#[node_macro::node(category("Text: Regex"))]
|
||||
fn regex_contains(
|
||||
_: impl Ctx,
|
||||
/// The string to search within.
|
||||
string: Item<String>,
|
||||
/// The regular expression pattern to search for.
|
||||
pattern: Item<String>,
|
||||
/// Match letters regardless of case.
|
||||
case_insensitive: Item<bool>,
|
||||
/// Make `^` and `$` match the start and end of each line, not just the whole string.
|
||||
multiline: Item<bool>,
|
||||
/// Only match if the pattern appears at the start of the string.
|
||||
at_start: Item<bool>,
|
||||
/// Only match if the pattern appears at the end of the string.
|
||||
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)",
|
||||
(false, true) => "(?m)",
|
||||
(true, true) => "(?im)",
|
||||
};
|
||||
let anchored_pattern = match (at_start, at_end) {
|
||||
(true, true) => format!("{flags}\\A(?:{pattern})\\z"),
|
||||
(true, false) => format!("{flags}\\A(?:{pattern})"),
|
||||
(false, true) => format!("{flags}(?:{pattern})\\z"),
|
||||
(false, false) => format!("{flags}{pattern}"),
|
||||
};
|
||||
|
||||
let Ok(regex) = fancy_regex::Regex::new(&anchored_pattern) else {
|
||||
log::error!("Invalid regex pattern: {pattern}");
|
||||
return Item::from_parts(false, attributes);
|
||||
};
|
||||
|
||||
Item::from_parts(regex.is_match(&string).unwrap_or(false), attributes)
|
||||
}
|
||||
|
||||
/// 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: Item<String>,
|
||||
/// The regular expression pattern to search for.
|
||||
pattern: Item<String>,
|
||||
/// The replacement string. Use `$0` for the whole match and `$1`, `$2`, etc. for capture groups.
|
||||
replacement: Item<String>,
|
||||
/// Replace all matches. When disabled, only the first match is replaced.
|
||||
#[default(true)]
|
||||
replace_all: Item<bool>,
|
||||
/// Match letters regardless of case.
|
||||
case_insensitive: Item<bool>,
|
||||
/// Make `^` and `$` match the start and end of each line, not just the whole 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)",
|
||||
(false, true) => "(?m)",
|
||||
(true, true) => "(?im)",
|
||||
};
|
||||
let full_pattern = format!("{flags}{pattern}");
|
||||
|
||||
let Ok(regex) = fancy_regex::Regex::new(&full_pattern) else {
|
||||
log::warn!("Invalid regex pattern: {pattern}");
|
||||
return string;
|
||||
};
|
||||
|
||||
let result = if replace_all {
|
||||
regex.replace_all(string.element(), replacement.as_str()).into_owned()
|
||||
} else {
|
||||
regex.replace(string.element(), replacement.as_str()).into_owned()
|
||||
};
|
||||
|
||||
*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).
|
||||
///
|
||||
/// The match index selects which non-overlapping occurrence to return (0 for the first match). Returns an empty list if no match is found at the given index.
|
||||
///
|
||||
/// Each item carries `start` and `end` byte-offset attributes pointing into the original string, plus a `name` attribute holding
|
||||
/// the capture group's name (empty for unnamed groups, and for index 0 which is the whole match).
|
||||
#[node_macro::node(category(""))]
|
||||
fn regex_find(
|
||||
_: impl Ctx,
|
||||
/// The string to search within.
|
||||
string: Item<String>,
|
||||
/// The regular expression pattern to search for.
|
||||
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: Item<SignedInteger>,
|
||||
/// Match letters regardless of case.
|
||||
case_insensitive: Item<bool>,
|
||||
/// Make `^` and `$` match the start and end of each line, not just the whole string.
|
||||
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();
|
||||
}
|
||||
|
||||
let flags = match (case_insensitive, multiline) {
|
||||
(false, false) => "",
|
||||
(true, false) => "(?i)",
|
||||
(false, true) => "(?m)",
|
||||
(true, true) => "(?im)",
|
||||
};
|
||||
let full_pattern = format!("{flags}{pattern}");
|
||||
|
||||
let Ok(regex) = fancy_regex::Regex::new(&full_pattern) else {
|
||||
log::error!("Invalid regex pattern: {pattern}");
|
||||
return List::new();
|
||||
};
|
||||
|
||||
// Capture group names indexed positionally; index 0 (the whole match) is always None.
|
||||
let capture_names: Vec<Option<String>> = regex.capture_names().map(|name| name.map(str::to_string)).collect();
|
||||
|
||||
// Collect all matches since we need to support negative indexing
|
||||
let matches: Vec<_> = regex.captures_iter(string).filter_map(|c| c.ok()).collect();
|
||||
|
||||
let match_index = match_index as i32;
|
||||
let resolved_index = if match_index < 0 {
|
||||
let from_end = (-match_index) as usize;
|
||||
if from_end > matches.len() {
|
||||
return List::new();
|
||||
}
|
||||
matches.len() - from_end
|
||||
} else {
|
||||
match_index as usize
|
||||
};
|
||||
|
||||
let Some(captures) = matches.get(resolved_index) else {
|
||||
return List::new();
|
||||
};
|
||||
|
||||
// Index 0 is the whole match, 1+ are capture groups
|
||||
(0..captures.len())
|
||||
.map(|i| {
|
||||
let captured = captures.get(i);
|
||||
let text = captured.map_or(String::new(), |m| m.as_str().to_string());
|
||||
let start = captured.map_or(0_u64, |m| m.start() as u64);
|
||||
let end = captured.map_or(0_u64, |m| m.end() as u64);
|
||||
let name = capture_names.get(i).cloned().flatten().unwrap_or_default();
|
||||
Item::new_from_element(text)
|
||||
.with_attribute(ATTR_START, start)
|
||||
.with_attribute(ATTR_END, end)
|
||||
.with_attribute(ATTR_NAME, name)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Finds all non-overlapping matches of a regular expression pattern in the string, returning a list of the matched substrings.
|
||||
///
|
||||
/// Each item carries `start` and `end` byte-offset attributes pointing into the original string.
|
||||
#[node_macro::node(category("Text: Regex"))]
|
||||
fn regex_find_all(
|
||||
_: impl Ctx,
|
||||
/// The string to search within.
|
||||
string: Item<String>,
|
||||
/// The regular expression pattern to search for.
|
||||
pattern: Item<String>,
|
||||
/// Match letters regardless of case.
|
||||
case_insensitive: Item<bool>,
|
||||
/// Make `^` and `$` match the start and end of each line, not just the whole string.
|
||||
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();
|
||||
}
|
||||
|
||||
let flags = match (case_insensitive, multiline) {
|
||||
(false, false) => "",
|
||||
(true, false) => "(?i)",
|
||||
(false, true) => "(?m)",
|
||||
(true, true) => "(?im)",
|
||||
};
|
||||
let full_pattern = format!("{flags}{pattern}");
|
||||
|
||||
let Ok(regex) = fancy_regex::Regex::new(&full_pattern) else {
|
||||
log::error!("Invalid regex pattern: {pattern}");
|
||||
return List::new();
|
||||
};
|
||||
|
||||
regex
|
||||
.find_iter(string)
|
||||
.filter_map(|m| m.ok())
|
||||
.map(|m| {
|
||||
Item::new_from_element(m.as_str().to_string())
|
||||
.with_attribute(ATTR_START, m.start() as u64)
|
||||
.with_attribute(ATTR_END, m.end() as u64)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Splits a string into a list of substrings pulled from between separator characters as matched by a regular expression.
|
||||
///
|
||||
/// For example, splitting "Three, two, one... LIFTOFF" with pattern `\W+` (non-word characters) produces `["Three", "two", "one", "LIFTOFF"]`.
|
||||
#[node_macro::node(category("Text: Regex"))]
|
||||
fn regex_split(
|
||||
_: impl Ctx,
|
||||
/// The string to split into substrings.
|
||||
string: Item<String>,
|
||||
/// The regular expression pattern to split on. Matches are consumed and not included in the output.
|
||||
pattern: Item<String>,
|
||||
/// Match letters regardless of case.
|
||||
case_insensitive: Item<bool>,
|
||||
/// Make `^` and `$` match the start and end of each line, not just the whole string.
|
||||
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_item(string);
|
||||
}
|
||||
|
||||
let flags = match (case_insensitive, multiline) {
|
||||
(false, false) => "",
|
||||
(true, false) => "(?i)",
|
||||
(false, true) => "(?m)",
|
||||
(true, true) => "(?im)",
|
||||
};
|
||||
let full_pattern = format!("{flags}{pattern}");
|
||||
|
||||
let Ok(regex) = fancy_regex::Regex::new(&full_pattern) else {
|
||||
log::error!("Invalid regex pattern: {pattern}");
|
||||
return List::new_from_item(string);
|
||||
};
|
||||
|
||||
regex.split(string.element()).filter_map(|s| s.ok()).map(|s| s.to_string()).map(Item::new_from_element).collect()
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,189 @@
|
||||
use super::TypesettingConfig;
|
||||
use super::path_builder::PathBuilder;
|
||||
use core::cell::RefCell;
|
||||
use core_types::list::List;
|
||||
use glam::DVec2;
|
||||
use graphene_resource::{Resource, ResourceHash};
|
||||
use parley::fontique::{Blob, FamilyId, FontInfo};
|
||||
use parley::{AlignmentOptions, FontContext, GlyphRun, Layout, LayoutContext, LineHeight, PositionedLayoutItem, StyleProperty};
|
||||
use std::collections::HashMap;
|
||||
use vector_types::Vector;
|
||||
|
||||
thread_local! {
|
||||
static THREAD_TEXT: RefCell<TextContext> = RefCell::new(TextContext::default());
|
||||
}
|
||||
|
||||
/// Iterates the glyph runs of a laid-out text in reading order, computing each line's last-line alignment correction
|
||||
/// (`x_offset` and per-space `space_extra`) and skipping runs clipped by `max_height`. Shared by the vector shaper and the
|
||||
/// SVG/Vello text renderers so the alignment logic lives in one place.
|
||||
pub fn for_each_styled_glyph_run(layout: &Layout<()>, text: &str, typesetting: TypesettingConfig, mut visit: impl FnMut(&GlyphRun<'_, ()>, f32, f32)) {
|
||||
let alignment_width = typesetting.max_width.map(|w| w as f32).unwrap_or_else(|| layout.full_width());
|
||||
let last_line_correction = typesetting.align.last_line_correction();
|
||||
|
||||
for line in layout.lines() {
|
||||
let range = line.text_range();
|
||||
// Parley always includes a hard-break `\n` as the last byte of the preceding line's range, so the line is at the end of
|
||||
// a paragraph if it's the very last line of the buffer or its text ends with `\n`.
|
||||
let is_last_para_line = range.end == text.len() || text.get(range.clone()).is_some_and(|s| s.ends_with('\n'));
|
||||
|
||||
let mut x_offset = 0.;
|
||||
let mut space_extra = 0.;
|
||||
|
||||
if is_last_para_line && let Some(correction) = last_line_correction {
|
||||
let metrics = line.metrics();
|
||||
let content_advance = metrics.advance - metrics.trailing_whitespace;
|
||||
let free_space = alignment_width - content_advance;
|
||||
|
||||
match correction {
|
||||
parley::Alignment::Center => x_offset = free_space * 0.5,
|
||||
parley::Alignment::Right => x_offset = free_space,
|
||||
parley::Alignment::Justify => {
|
||||
// Exclude trailing-whitespace clusters from the divisor so the redistribution stretches only the internal spaces.
|
||||
// Parley's `trailing_whitespace` is in advance units, not bytes, so we re-derive the byte boundary here to filter cluster ranges.
|
||||
let line_text = text.get(range.clone()).unwrap_or("");
|
||||
let trailing_len = line_text.len() - line_text.trim_end().len();
|
||||
let visible_end_index = range.end - trailing_len;
|
||||
|
||||
let space_count: usize = line
|
||||
.runs()
|
||||
.map(|run| run.clusters().filter(|c| c.is_space_or_nbsp() && c.text_range().start < visible_end_index).count())
|
||||
.sum();
|
||||
if space_count > 0 {
|
||||
space_extra = free_space / space_count as f32;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
for item in line.items() {
|
||||
if let PositionedLayoutItem::GlyphRun(glyph_run) = item
|
||||
&& typesetting.max_height.filter(|&max_height| glyph_run.baseline() > max_height as f32).is_none()
|
||||
{
|
||||
visit(&glyph_run, x_offset, space_extra);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Unified thread-local text processing context that combines font and layout management
|
||||
/// for efficient text rendering operations.
|
||||
#[derive(Default)]
|
||||
pub struct TextContext {
|
||||
font_context: FontContext,
|
||||
layout_context: LayoutContext<()>,
|
||||
font_info_cache: HashMap<ResourceHash, (FamilyId, FontInfo)>,
|
||||
}
|
||||
|
||||
impl TextContext {
|
||||
/// Access the thread-local TextContext instance for text processing operations
|
||||
pub fn with_thread_local<F, R>(f: F) -> R
|
||||
where
|
||||
F: FnOnce(&mut TextContext) -> R,
|
||||
{
|
||||
THREAD_TEXT.with_borrow_mut(f)
|
||||
}
|
||||
|
||||
/// Get or cache font information for the given font resource.
|
||||
fn get_font_info(&mut self, font: &Resource) -> Option<(String, FontInfo)> {
|
||||
let hash = font.hash();
|
||||
if let Some((family_id, font_info)) = self.font_info_cache.get(&hash)
|
||||
&& let Some(family_name) = self.font_context.collection.family_name(*family_id)
|
||||
{
|
||||
return Some((family_name.to_string(), font_info.clone()));
|
||||
}
|
||||
|
||||
let families = self.font_context.collection.register_fonts(Blob::new(font.into()), None);
|
||||
|
||||
families.first().and_then(|(family_id, fonts_info)| {
|
||||
fonts_info.first().and_then(|font_info| {
|
||||
self.font_context.collection.family_name(*family_id).map(|family_name| {
|
||||
self.font_info_cache.insert(hash, (*family_id, font_info.clone()));
|
||||
(family_name.to_string(), font_info.clone())
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Create a text layout from the given font resource and typesetting configuration.
|
||||
pub fn layout_text(&mut self, text: &str, font: &Resource, typesetting: TypesettingConfig) -> Option<Layout<()>> {
|
||||
let (font_family, font_info) = self.get_font_info(font)?;
|
||||
|
||||
const DISPLAY_SCALE: f32 = 1.;
|
||||
let mut builder = self.layout_context.ranged_builder(&mut self.font_context, text, DISPLAY_SCALE, false);
|
||||
|
||||
builder.push_default(StyleProperty::FontSize(typesetting.font_size as f32));
|
||||
builder.push_default(StyleProperty::LetterSpacing(typesetting.letter_spacing as f32));
|
||||
builder.push_default(StyleProperty::FontFamily(parley::FontFamily::Single(parley::FontFamilyName::Named(std::borrow::Cow::Owned(
|
||||
font_family,
|
||||
)))));
|
||||
builder.push_default(StyleProperty::FontWeight(font_info.weight()));
|
||||
builder.push_default(StyleProperty::FontStyle(font_info.style()));
|
||||
builder.push_default(StyleProperty::FontWidth(font_info.width()));
|
||||
builder.push_default(LineHeight::FontSizeRelative(typesetting.line_height_ratio as f32));
|
||||
|
||||
let mut layout: Layout<()> = builder.build(text);
|
||||
|
||||
layout.break_all_lines(typesetting.max_width.map(|mw| mw as f32));
|
||||
layout.align(typesetting.align.into(), AlignmentOptions::default());
|
||||
|
||||
Some(layout)
|
||||
}
|
||||
|
||||
/// Convert text to vector paths using the specified font and typesetting configuration
|
||||
pub fn to_path(&mut self, text: &str, font: &Resource, typesetting: TypesettingConfig, per_glyph_items: bool) -> List<Vector> {
|
||||
let Some(layout) = self.layout_text(text, font, typesetting) else {
|
||||
return List::new_from_element(Vector::default());
|
||||
};
|
||||
|
||||
let text_frame_size = DVec2::new(
|
||||
typesetting.max_width.unwrap_or_else(|| layout.full_width() as f64),
|
||||
typesetting.max_height.unwrap_or_else(|| layout.height() as f64),
|
||||
);
|
||||
|
||||
// First glyph offset (pre-height-filter) so the empty placeholder item in `per_glyph_items`
|
||||
// mode keeps the same item 0's transform, preventing `local_transforms` from jumping mid-drag
|
||||
let first_glyph_offset = layout
|
||||
.lines()
|
||||
.flat_map(|line| line.items())
|
||||
.find_map(|item| match item {
|
||||
PositionedLayoutItem::GlyphRun(run) => run.glyphs().next().map(|glyph| DVec2::new((run.offset() + glyph.x) as f64, (run.baseline() - glyph.y) as f64)),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
let mut path_builder = PathBuilder::new(per_glyph_items, layout.scale() as f64, text_frame_size, first_glyph_offset);
|
||||
|
||||
for_each_styled_glyph_run(&layout, text, typesetting, |glyph_run, x_offset, space_extra| {
|
||||
path_builder.render_glyph_run(glyph_run, typesetting.letter_tilt, per_glyph_items, x_offset, space_extra);
|
||||
});
|
||||
|
||||
path_builder.finalize()
|
||||
}
|
||||
|
||||
/// Calculate the bounding box of text using the specified font and typesetting configuration
|
||||
pub fn bounding_box(&mut self, text: &str, font: &Resource, typesetting: TypesettingConfig, for_clipping_test: bool) -> DVec2 {
|
||||
let Some(layout) = self.layout_text(text, font, typesetting) else {
|
||||
return DVec2::ZERO;
|
||||
};
|
||||
|
||||
let layout_width = layout.full_width() as f64;
|
||||
let layout_height = layout.height() as f64;
|
||||
|
||||
if for_clipping_test {
|
||||
return DVec2::new(layout_width, layout_height);
|
||||
}
|
||||
|
||||
let width = typesetting.max_width.unwrap_or(layout_width);
|
||||
let height = typesetting.max_height.unwrap_or(layout_height);
|
||||
|
||||
DVec2::new(width, height)
|
||||
}
|
||||
|
||||
/// Check if text lines are being clipped due to height constraints
|
||||
pub fn lines_clipping(&mut self, text: &str, font: &Resource, typesetting: TypesettingConfig) -> bool {
|
||||
let Some(max_height) = typesetting.max_height else { return false };
|
||||
let bounds = self.bounding_box(text, font, typesetting, true);
|
||||
max_height < bounds.y
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
use super::TypesettingConfig;
|
||||
use super::text_context::TextContext;
|
||||
use crate::markers::{ATTR_FONT, ATTR_TEXT_ALIGN};
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::list::{Item, List, NodeIdPath};
|
||||
use core_types::{
|
||||
ATTR_BLEND_MODE, ATTR_EDITOR_LAYER_PATH, ATTR_FONT_SIZE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM,
|
||||
};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphene_resource::Resource;
|
||||
use vector_types::Vector;
|
||||
|
||||
pub fn to_path(text: &str, font: &Resource, typesetting: TypesettingConfig, per_glyph_items: bool) -> List<Vector> {
|
||||
TextContext::with_thread_local(|ctx| ctx.to_path(text, font, typesetting, per_glyph_items))
|
||||
}
|
||||
|
||||
pub fn bounding_box(text: &str, font: &Resource, typesetting: TypesettingConfig, for_clipping_test: bool) -> DVec2 {
|
||||
TextContext::with_thread_local(|ctx| ctx.bounding_box(text, font, typesetting, for_clipping_test))
|
||||
}
|
||||
|
||||
pub fn lines_clipping(text: &str, font: &Resource, typesetting: TypesettingConfig) -> bool {
|
||||
TextContext::with_thread_local(|ctx| ctx.lines_clipping(text, font, typesetting))
|
||||
}
|
||||
|
||||
/// 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(item) = strings.clone_item(index) else { continue };
|
||||
for produced in shape_text_item(&item, separate_glyphs).into_iter() {
|
||||
result.push(produced);
|
||||
}
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
[package]
|
||||
name = "transform-nodes"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
description = "Transform operation nodes for Graphene"
|
||||
authors = ["Graphite Authors <contact@graphite.art>"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
[features]
|
||||
default = ["serde"]
|
||||
|
||||
[dependencies]
|
||||
# Local dependencies
|
||||
core-types = { workspace = true }
|
||||
vector-types = { workspace = true }
|
||||
graphic-types = { workspace = true }
|
||||
node-macro = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
glam = { workspace = true }
|
||||
rand = { workspace = true }
|
||||
|
||||
# Optional workspace dependencies
|
||||
serde = { workspace = true, optional = true }
|
||||
@@ -0,0 +1,7 @@
|
||||
pub mod transform_nodes;
|
||||
|
||||
// Re-export for convenience
|
||||
pub use core_types as gcore;
|
||||
pub use graphic_types;
|
||||
pub use transform_nodes::*;
|
||||
pub use vector_types;
|
||||
@@ -0,0 +1,148 @@
|
||||
use core::f64;
|
||||
use core_types::attribute::{Attr, Transform as TransformAttr};
|
||||
use core_types::color::Color;
|
||||
use core_types::extent::{ExtentIn, LevelIn, ValueIn};
|
||||
use core_types::gpoll::{Extent, GPoll, Interrupt};
|
||||
use core_types::transform::{ApplyTransform, ScaleType, Transform};
|
||||
use core_types::{CacheHash, Context, Ctx, DeriveCtx, InjectFootprint, ModifyFootprint};
|
||||
use glam::{DAffine2, DMat2, DVec2};
|
||||
use graphic_types::raster_types::{CPU, GPU, Raster};
|
||||
use graphic_types::{Artboard, Graphic, Vector};
|
||||
use vector_types::Gradient;
|
||||
|
||||
/// Applies the specified transform to each lane of the input, composing onto the lane's transform attribute.
|
||||
#[node_macro::node(category("Math: Transform"), extent(transform_extent))]
|
||||
fn transform<T>(
|
||||
ctx: impl Ctx + DeriveCtx + ModifyFootprint,
|
||||
content: impl Node<Context<'_>, Output = (T, Attr<TransformAttr>)>,
|
||||
#[widget(ParsedWidgetOverride::Custom = "transform_translation")] translation: DVec2,
|
||||
#[widget(ParsedWidgetOverride::Custom = "transform_rotation")] rotation: f64,
|
||||
#[widget(ParsedWidgetOverride::Custom = "transform_scale")]
|
||||
#[default(1., 1.)]
|
||||
scale: DVec2,
|
||||
#[widget(ParsedWidgetOverride::Custom = "transform_skew")] skew: DVec2,
|
||||
) -> Result<(T, Attr<TransformAttr>), Interrupt> {
|
||||
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 transformed = ctx.modify_footprint(|footprint| footprint.apply_transform(&matrix));
|
||||
let (element, transform) = content.eval(&transformed.ctx())?;
|
||||
|
||||
Ok((element, Attr(matrix * *transform)))
|
||||
}
|
||||
|
||||
fn transform_extent(content: ExtentIn<'_>, _translation: ValueIn<'_, DVec2>, _rotation: ValueIn<'_, f64>, _scale: ValueIn<'_, DVec2>, _skew: ValueIn<'_, DVec2>, level: LevelIn) -> GPoll<Extent> {
|
||||
content.at(level)
|
||||
}
|
||||
|
||||
/// The transform applied to a plain transform or point value. Registered under the same identifier
|
||||
/// as the leveled `transform`, serving its value-typed rows.
|
||||
#[node_macro::node(category(""))]
|
||||
fn transform_value<T: ApplyTransform + 'static>(
|
||||
ctx: impl Ctx + DeriveCtx + ModifyFootprint,
|
||||
#[implementations(Context -> DAffine2, Context -> DVec2)] content: impl Node<Context<'_>, Output = T>,
|
||||
#[widget(ParsedWidgetOverride::Custom = "transform_translation")] translation: DVec2,
|
||||
#[widget(ParsedWidgetOverride::Custom = "transform_rotation")] rotation: f64,
|
||||
#[widget(ParsedWidgetOverride::Custom = "transform_scale")]
|
||||
#[default(1., 1.)]
|
||||
scale: DVec2,
|
||||
#[widget(ParsedWidgetOverride::Custom = "transform_skew")] skew: DVec2,
|
||||
) -> Result<T, Interrupt> {
|
||||
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 transformed = ctx.modify_footprint(|footprint| footprint.apply_transform(&matrix));
|
||||
let mut transform_target = content.eval(&transformed.ctx())?;
|
||||
|
||||
transform_target.left_apply_transform(&matrix);
|
||||
|
||||
Ok(transform_target)
|
||||
}
|
||||
|
||||
pub use _transform_value_mod::transform_value_entries;
|
||||
|
||||
/// 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.
|
||||
/// Shear is represented jointly by rotation and scale, so resetting both will also remove any shear.
|
||||
#[node_macro::node(category("Math: Transform"))]
|
||||
fn reset_transform<T>(_: impl Ctx, (element, transform): (T, Attr<TransformAttr>), #[default(true)] reset_translation: bool, reset_rotation: bool, reset_scale: bool) -> (T, Attr<TransformAttr>) {
|
||||
let mut row_transform = *transform;
|
||||
if reset_translation {
|
||||
row_transform.translation = DVec2::ZERO;
|
||||
}
|
||||
|
||||
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) => {}
|
||||
}
|
||||
(element, Attr(row_transform))
|
||||
}
|
||||
|
||||
/// Overwrites the transform of each lane of the input with the specified transform.
|
||||
#[node_macro::node(category("Math: Transform"))]
|
||||
fn replace_transform<T>(_: impl Ctx + InjectFootprint, (element, _content_transform): (T, Attr<TransformAttr>), transform: DAffine2) -> (T, Attr<TransformAttr>) {
|
||||
(element, Attr(transform))
|
||||
}
|
||||
|
||||
// TODO: Figure out how this node should behave once #2982 is implemented.
|
||||
/// Obtains the transform of the first lane of the input, if present.
|
||||
#[node_macro::node(category("Math: Transform"), path(core_types::vector))]
|
||||
fn extract_transform<T: Clone + Send + Sync + CacheHash + 'static>(_: impl Ctx, #[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, GradientStops)] content: IList<T>) -> DAffine2 {
|
||||
match content.len() {
|
||||
0 => DAffine2::default(),
|
||||
_ => content.lane(0).attr::<TransformAttr>(),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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: 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: 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: 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: 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: Item<DAffine2>) -> Item<f64> {
|
||||
Item::new_from_element(transform.into_element().decompose_skew().atan().to_degrees())
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
[package]
|
||||
name = "vector-nodes"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
description = "Vector operation nodes for Graphene"
|
||||
authors = ["Graphite Authors <contact@graphite.art>"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
[features]
|
||||
default = ["serde"]
|
||||
serde = ["dep:serde", "core-types/serde", "vector-types/serde", "graphic-types/serde"]
|
||||
wasm = ["core-types/wasm", "tsify", "wasm-bindgen"]
|
||||
|
||||
[dependencies]
|
||||
# Local dependencies
|
||||
core-types = { workspace = true }
|
||||
graphene-hash = { workspace = true }
|
||||
vector-types = { workspace = true }
|
||||
graphic-types = { workspace = true }
|
||||
node-macro = { workspace = true }
|
||||
repeat-nodes = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
dyn-any = { workspace = true }
|
||||
glam = { workspace = true }
|
||||
kurbo = { workspace = true }
|
||||
rand = { workspace = true }
|
||||
rustc-hash = { workspace = true }
|
||||
log = { workspace = true }
|
||||
qrcodegen = { workspace = true }
|
||||
|
||||
# Optional workspace dependencies
|
||||
serde = { workspace = true, optional = true }
|
||||
tsify = { workspace = true, optional = true }
|
||||
wasm-bindgen = { workspace = true, optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
graphene-core = { workspace = true }
|
||||
tokio = { workspace = true, features = ["macros", "rt"] }
|
||||
futures = { workspace = true }
|
||||
@@ -0,0 +1,450 @@
|
||||
use core_types::list::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::{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(
|
||||
_: impl Ctx,
|
||||
_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))))
|
||||
}
|
||||
|
||||
/// Generates an arc shape forming a portion of a circle which may be open, closed, or a pie slice.
|
||||
#[node_macro::node(category("Vector: Shape"))]
|
||||
fn arc(
|
||||
_: impl Ctx,
|
||||
_primary: (),
|
||||
#[unit(" px")]
|
||||
#[default(50.)]
|
||||
radius: f64,
|
||||
start_angle: 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(
|
||||
radius,
|
||||
start_angle / 360. * std::f64::consts::TAU,
|
||||
sweep_angle / 360. * std::f64::consts::TAU,
|
||||
match arc_type {
|
||||
ArcType::Open => subpath::ArcType::Open,
|
||||
ArcType::Closed => subpath::ArcType::Closed,
|
||||
ArcType::PieSlice => subpath::ArcType::PieSlice,
|
||||
},
|
||||
)))
|
||||
}
|
||||
|
||||
/// Generates a spiral shape that winds from an inner to an outer radius.
|
||||
#[node_macro::node(category("Vector: Shape"), properties("spiral_properties"))]
|
||||
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(
|
||||
inner_radius,
|
||||
outer_radius,
|
||||
turns,
|
||||
start_angle.to_radians(),
|
||||
angular_resolution.to_radians(),
|
||||
spiral_type,
|
||||
)))
|
||||
}
|
||||
|
||||
/// Generates an ellipse shape (an oval or stretched circle) with the chosen radii.
|
||||
#[node_macro::node(category("Vector: Shape"))]
|
||||
fn ellipse(
|
||||
_: impl Ctx,
|
||||
_primary: (),
|
||||
#[unit(" px")]
|
||||
#[default(50)]
|
||||
radius_x: f64,
|
||||
#[unit(" px")]
|
||||
#[default(25)]
|
||||
radius_y: f64,
|
||||
) -> List<Vector> {
|
||||
let radius = DVec2::new(radius_x, radius_y);
|
||||
let corner1 = -radius;
|
||||
let corner2 = radius;
|
||||
|
||||
let mut ellipse = Vector::from_subpath(subpath::Subpath::new_ellipse(corner1, corner2));
|
||||
|
||||
let len = ellipse.segment_domain.ids().len();
|
||||
for i in 0..len {
|
||||
ellipse
|
||||
.colinear_manipulators
|
||||
.push([HandleId::end(ellipse.segment_domain.ids()[i]), HandleId::primary(ellipse.segment_domain.ids()[(i + 1) % len])]);
|
||||
}
|
||||
|
||||
List::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>(
|
||||
_: impl Ctx,
|
||||
_primary: (),
|
||||
#[unit(" px")]
|
||||
#[default(100)]
|
||||
width: 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)
|
||||
}
|
||||
|
||||
/// Generates an regular polygon shape like a triangle, square, pentagon, hexagon, heptagon, octagon, or any higher n-gon.
|
||||
#[node_macro::node(category("Vector: Shape"))]
|
||||
fn regular_polygon<T: AsU64>(
|
||||
_: impl Ctx,
|
||||
_primary: (),
|
||||
#[default(6)]
|
||||
#[hard(3..)]
|
||||
#[implementations(u32, u64, f64)]
|
||||
sides: 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)))
|
||||
}
|
||||
|
||||
/// Generates an n-pointed star shape with inner and outer points at chosen radii from the center.
|
||||
#[node_macro::node(category("Vector: Shape"))]
|
||||
fn star<T: AsU64>(
|
||||
_: impl Ctx,
|
||||
_primary: (),
|
||||
#[default(5)]
|
||||
#[hard(2..)]
|
||||
#[implementations(u32, u64, f64)]
|
||||
sides: T,
|
||||
#[unit(" px")]
|
||||
#[default(50)]
|
||||
radius_1: 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.;
|
||||
|
||||
List::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))]
|
||||
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[widget(Radio)]
|
||||
pub enum QRCodeErrorCorrectionLevel {
|
||||
/// Allows recovery from up to 7% data loss.
|
||||
#[default]
|
||||
Low,
|
||||
/// Allows recovery from up to 15% data loss.
|
||||
Medium,
|
||||
/// Allows recovery from up to 25% data loss.
|
||||
Quartile,
|
||||
/// Allows recovery from up to 30% data loss.
|
||||
High,
|
||||
}
|
||||
|
||||
/// Generates a QR code from the input text.
|
||||
#[node_macro::node(category("Vector: Shape"), name("QR Code"))]
|
||||
fn qr_code(
|
||||
_: impl Ctx,
|
||||
_primary: (),
|
||||
#[widget(ParsedWidgetOverride::Custom = "text_area")]
|
||||
#[default("https://graphite.art")]
|
||||
text: String,
|
||||
#[widget(ParsedWidgetOverride::Hidden)] has_size: bool,
|
||||
#[unit(" px")]
|
||||
#[hard(1..)]
|
||||
#[widget(ParsedWidgetOverride::Custom = "optional_f64")]
|
||||
size: f64,
|
||||
error_correction: QRCodeErrorCorrectionLevel,
|
||||
#[default(false)] individual_squares: bool,
|
||||
) -> List<Vector> {
|
||||
let ecc = match error_correction {
|
||||
QRCodeErrorCorrectionLevel::Low => qrcodegen::QrCodeEcc::Low,
|
||||
QRCodeErrorCorrectionLevel::Medium => qrcodegen::QrCodeEcc::Medium,
|
||||
QRCodeErrorCorrectionLevel::Quartile => qrcodegen::QrCodeEcc::Quartile,
|
||||
QRCodeErrorCorrectionLevel::High => qrcodegen::QrCodeEcc::High,
|
||||
};
|
||||
|
||||
let Ok(qr_code) = qrcodegen::QrCode::encode_text(&text, ecc) else { return List::default() };
|
||||
|
||||
let mut vector = match individual_squares {
|
||||
true => {
|
||||
let mut vector = Vector::default();
|
||||
|
||||
let dimension = qr_code.size() as usize;
|
||||
for y in 0..dimension {
|
||||
for x in 0..dimension {
|
||||
if qr_code.get_module(x as i32, y as i32) {
|
||||
let corner1 = DVec2::new(x as f64, y as f64);
|
||||
let corner2 = corner1 + DVec2::splat(1.);
|
||||
vector.append_subpath(
|
||||
subpath::Subpath::from_anchors([corner1, DVec2::new(corner2.x, corner1.y), corner2, DVec2::new(corner1.x, corner2.y)], true),
|
||||
false,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
vector
|
||||
}
|
||||
false => crate::merge_qr_squares::merge_qr_squares(&qr_code),
|
||||
};
|
||||
|
||||
if has_size {
|
||||
vector.transform(glam::DAffine2::from_scale(DVec2::splat(size / qr_code.size() as f64)));
|
||||
}
|
||||
|
||||
List::new_from_element(vector)
|
||||
}
|
||||
|
||||
/// Generates an arrow from the origin to the chosen coordinate.
|
||||
#[node_macro::node(category("Vector: Shape"))]
|
||||
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)))
|
||||
}
|
||||
|
||||
#[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)))
|
||||
}
|
||||
|
||||
trait GridSpacing {
|
||||
fn as_dvec2(&self) -> DVec2;
|
||||
}
|
||||
impl GridSpacing for f64 {
|
||||
fn as_dvec2(&self) -> DVec2 {
|
||||
DVec2::splat(*self)
|
||||
}
|
||||
}
|
||||
impl GridSpacing for DVec2 {
|
||||
fn as_dvec2(&self) -> DVec2 {
|
||||
*self
|
||||
}
|
||||
}
|
||||
|
||||
/// Generates a rectangular or isometric grid with the chosen number of columns and rows. Line segments connect the points, forming a vector mesh.
|
||||
#[node_macro::node(category("Vector: Shape"), properties("grid_properties"))]
|
||||
fn grid<T: GridSpacing>(
|
||||
_: impl Ctx,
|
||||
_primary: (),
|
||||
grid_type: 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();
|
||||
let (angle_a, angle_b) = angles.into();
|
||||
|
||||
let mut vector = Vector::default();
|
||||
let mut segment_id = SegmentId::ZERO;
|
||||
let mut point_id = PointId::ZERO;
|
||||
|
||||
match grid_type {
|
||||
GridType::Rectangular => {
|
||||
// Create rectangular grid points and connect them with line segments
|
||||
for y in 0..rows {
|
||||
for x in 0..columns {
|
||||
// Add current point to the grid
|
||||
let current_index = vector.point_domain.ids().len();
|
||||
vector.point_domain.push(point_id.next_id(), DVec2::new(x_spacing * x as f64, y_spacing * y as f64));
|
||||
|
||||
// Helper function to connect points with line segments
|
||||
let mut push_segment = |to_index: Option<usize>| {
|
||||
if let Some(other_index) = to_index {
|
||||
vector
|
||||
.segment_domain
|
||||
.push(segment_id.next_id(), other_index, current_index, subpath::BezierHandles::Linear, StrokeId::ZERO);
|
||||
}
|
||||
};
|
||||
|
||||
// Connect to the point to the left (horizontal connection)
|
||||
push_segment((x > 0).then(|| current_index - 1));
|
||||
|
||||
// Connect to the point above (vertical connection)
|
||||
push_segment(current_index.checked_sub(columns as usize));
|
||||
}
|
||||
}
|
||||
}
|
||||
GridType::Isometric => {
|
||||
// Calculate isometric grid spacing based on angles
|
||||
let tan_a = angle_a.to_radians().tan();
|
||||
let tan_b = angle_b.to_radians().tan();
|
||||
let spacing = DVec2::new(y_spacing / (tan_a + tan_b), y_spacing);
|
||||
|
||||
// Create isometric grid points and connect them with line segments
|
||||
for y in 0..rows {
|
||||
for x in 0..columns {
|
||||
// Add current point to the grid with offset for odd columns
|
||||
let current_index = vector.point_domain.ids().len();
|
||||
|
||||
let a_angles_eaten = x.div_ceil(2) as f64;
|
||||
let b_angles_eaten = (x / 2) as f64;
|
||||
|
||||
let offset_y_fraction = b_angles_eaten * tan_b - a_angles_eaten * tan_a;
|
||||
|
||||
let position = DVec2::new(spacing.x * x as f64, spacing.y * y as f64 + offset_y_fraction * spacing.x);
|
||||
vector.point_domain.push(point_id.next_id(), position);
|
||||
|
||||
// Helper function to connect points with line segments
|
||||
let mut push_segment = |to_index: Option<usize>| {
|
||||
if let Some(other_index) = to_index {
|
||||
vector
|
||||
.segment_domain
|
||||
.push(segment_id.next_id(), other_index, current_index, subpath::BezierHandles::Linear, StrokeId::ZERO);
|
||||
}
|
||||
};
|
||||
|
||||
// Connect to the point to the left
|
||||
push_segment((x > 0).then(|| current_index - 1));
|
||||
|
||||
// Connect to the point directly above
|
||||
push_segment(current_index.checked_sub(columns as usize));
|
||||
|
||||
// Additional diagonal connections for odd columns (creates hexagonal pattern)
|
||||
if x % 2 == 1 {
|
||||
// Connect to the point diagonally up-right (if not at right edge)
|
||||
push_segment(current_index.checked_sub(columns as usize - 1).filter(|_| x + 1 < columns));
|
||||
|
||||
// Connect to the point diagonally up-left
|
||||
push_segment(current_index.checked_sub(columns as usize + 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
List::new_from_element(vector)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[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());
|
||||
|
||||
// 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() {
|
||||
assert_eq!(bezier.handles, subpath::BezierHandles::Linear);
|
||||
assert!(
|
||||
((bezier.start - bezier.end).length() - 10.).abs() < 1e-5,
|
||||
"Length of {} should be 10",
|
||||
(bezier.start - bezier.end).length()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[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() {
|
||||
assert_eq!(bezier.handles, subpath::BezierHandles::Linear);
|
||||
let vector = bezier.start - bezier.end;
|
||||
let angle = (vector.angle_to(DVec2::X).to_degrees() + 180.) % 180.;
|
||||
assert!([90., 150., 40.].into_iter().any(|target| (target - angle).abs() < 1e-10), "unexpected angle of {angle}")
|
||||
}
|
||||
}
|
||||
|
||||
#[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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
pub mod generator_nodes;
|
||||
pub mod merge_qr_squares;
|
||||
pub mod vector_modification_nodes;
|
||||
mod vector_nodes;
|
||||
|
||||
#[macro_use]
|
||||
extern crate log;
|
||||
|
||||
// Re-export for convenience
|
||||
pub use core_types as gcore;
|
||||
pub use generator_nodes::*;
|
||||
pub use graphic_types;
|
||||
pub use vector_modification_nodes::*;
|
||||
pub use vector_nodes::*;
|
||||
pub use vector_types;
|
||||
@@ -0,0 +1,124 @@
|
||||
use glam::DVec2;
|
||||
use graphic_types::Vector;
|
||||
use std::collections::VecDeque;
|
||||
use vector_types::subpath;
|
||||
|
||||
pub fn merge_qr_squares(qr_code: &qrcodegen::QrCode) -> Vector {
|
||||
let mut vector = Vector::default();
|
||||
|
||||
let size = qr_code.size() as usize;
|
||||
|
||||
// 0 = empty
|
||||
// 1 = filled, unvisited
|
||||
// 2 = filled, current island
|
||||
let mut remaining = vec![vec![0u8; size]; size];
|
||||
|
||||
#[allow(clippy::needless_range_loop)]
|
||||
for y in 0..size {
|
||||
#[allow(clippy::needless_range_loop)]
|
||||
for x in 0..size {
|
||||
if qr_code.get_module(x as i32, y as i32) {
|
||||
remaining[y][x] = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for y in 0..size {
|
||||
for x in 0..size {
|
||||
if remaining[y][x] != 1 {
|
||||
continue;
|
||||
}
|
||||
|
||||
// fill island
|
||||
let mut island = Vec::new();
|
||||
let mut queue = VecDeque::new();
|
||||
queue.push_back((x, y));
|
||||
remaining[y][x] = 2;
|
||||
|
||||
while let Some((ix, iy)) = queue.pop_front() {
|
||||
island.push((ix, iy));
|
||||
|
||||
for (dx, dy) in [(0, 1), (0, -1), (1, 0), (-1, 0)] {
|
||||
let nx = ix as i32 + dx;
|
||||
let ny = iy as i32 + dy;
|
||||
|
||||
if nx >= 0 && nx < size as i32 && ny >= 0 && ny < size as i32 && remaining[ny as usize][nx as usize] == 1 {
|
||||
remaining[ny as usize][nx as usize] = 2;
|
||||
queue.push_back((nx as usize, ny as usize));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// boundary detection
|
||||
let mut outbound = vec![vec![0u8; size + 1]; size + 1];
|
||||
|
||||
for &(ix, iy) in &island {
|
||||
if iy == 0 || remaining[iy - 1][ix] != 2 {
|
||||
outbound[iy][ix] |= 1 << 0;
|
||||
}
|
||||
if ix == size - 1 || remaining[iy][ix + 1] != 2 {
|
||||
outbound[iy][ix + 1] |= 1 << 1;
|
||||
}
|
||||
if iy == size - 1 || remaining[iy + 1][ix] != 2 {
|
||||
outbound[iy + 1][ix + 1] |= 1 << 2;
|
||||
}
|
||||
if ix == 0 || remaining[iy][ix - 1] != 2 {
|
||||
outbound[iy + 1][ix] |= 1 << 3;
|
||||
}
|
||||
}
|
||||
|
||||
// tracing loops
|
||||
for vy in 0..=size {
|
||||
for vx in 0..=size {
|
||||
while outbound[vy][vx] != 0 {
|
||||
let mut dir = outbound[vy][vx].trailing_zeros() as usize;
|
||||
let start = (vx, vy);
|
||||
let mut current = start;
|
||||
let mut points = Vec::new();
|
||||
|
||||
loop {
|
||||
points.push(DVec2::new(current.0 as f64, current.1 as f64));
|
||||
outbound[current.1][current.0] &= !(1 << dir);
|
||||
|
||||
current = match dir {
|
||||
0 => (current.0 + 1, current.1),
|
||||
1 => (current.0, current.1 + 1),
|
||||
2 => (current.0 - 1, current.1),
|
||||
3 => (current.0, current.1 - 1),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
if current == start {
|
||||
break;
|
||||
}
|
||||
dir = outbound[current.1][current.0].trailing_zeros() as usize;
|
||||
}
|
||||
|
||||
if points.len() > 2 {
|
||||
let mut simplified = Vec::new();
|
||||
for i in 0..points.len() {
|
||||
let prev = points[(i + points.len() - 1) % points.len()];
|
||||
let curr = points[i];
|
||||
let next = points[(i + 1) % points.len()];
|
||||
if (curr - prev).perp_dot(next - curr).abs() > 1e-6 {
|
||||
simplified.push(curr);
|
||||
}
|
||||
}
|
||||
|
||||
if !simplified.is_empty() {
|
||||
vector.append_subpath(subpath::Subpath::from_anchors(simplified, true), false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// marking island as processed
|
||||
for &(ix, iy) in &island {
|
||||
remaining[iy][ix] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
vector
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
use core_types::list::List;
|
||||
use core_types::uuid::NodeId;
|
||||
use core_types::{ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_TRANSFORM, Ctx};
|
||||
use glam::DAffine2;
|
||||
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;
|
||||
|
||||
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);
|
||||
|
||||
// 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 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 });
|
||||
|
||||
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.
|
||||
#[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;
|
||||
}
|
||||
|
||||
vector
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user