Compare commits

...
30 changed files with 839 additions and 115 deletions

No files matched your search

@@ -11,6 +11,7 @@ use graphene_std::animation::RealTimeMode;
use graphene_std::blending::BlendMode;
use graphene_std::color::SRGBA8;
use graphene_std::core_types::misc::format_f64;
use graphene_std::generator::Generator;
use graphene_std::gradient::Gradient;
use graphene_std::list::{INTERNAL_ATTRIBUTE_PREFIX, Item, List, NodeIdPath};
use graphene_std::math::float_noise::round_away_float_noise;
@@ -377,6 +378,7 @@ macro_rules! inspectable_types {
List<Raster<GPU>>,
List<Color>,
List<Gradient>,
List<Generator>,
List<String>,
List<f64>,
List<i64>,
@@ -433,6 +435,7 @@ macro_rules! inspectable_types {
Item<Raster<GPU>>,
Item<Color>,
Item<Gradient>,
Item<Generator>,
Item<String>,
Item<f64>,
Item<i64>,
@@ -880,6 +883,7 @@ impl TableItemLayout for Graphic {
Self::RasterGPU(item) => item.identifier(),
Self::Color(item) => item.identifier(),
Self::Gradient(item) => item.identifier(),
Self::Generator(item) => item.identifier(),
Self::Text(item) => item.identifier(),
Self::NoneList(list) => list.identifier(),
Self::GraphicList(list) => list.identifier(),
@@ -888,6 +892,7 @@ impl TableItemLayout for Graphic {
Self::RasterGPUList(list) => list.identifier(),
Self::ColorList(list) => list.identifier(),
Self::GradientList(list) => list.identifier(),
Self::GeneratorList(list) => list.identifier(),
Self::TextList(list) => list.identifier(),
Self::StrokeList(list) => list.identifier(),
}
@@ -905,6 +910,7 @@ impl TableItemLayout for Graphic {
Self::RasterGPU(item) => item.layout_with_breadcrumb(data),
Self::Color(item) => item.layout_with_breadcrumb(data),
Self::Gradient(item) => item.layout_with_breadcrumb(data),
Self::Generator(item) => item.layout_with_breadcrumb(data),
Self::Text(item) => item.layout_with_breadcrumb(data),
Self::NoneList(list) => list.layout_with_breadcrumb(data),
Self::GraphicList(list) => list.layout_with_breadcrumb(data),
@@ -913,6 +919,7 @@ impl TableItemLayout for Graphic {
Self::RasterGPUList(list) => list.layout_with_breadcrumb(data),
Self::ColorList(list) => list.layout_with_breadcrumb(data),
Self::GradientList(list) => list.layout_with_breadcrumb(data),
Self::GeneratorList(list) => list.layout_with_breadcrumb(data),
Self::TextList(list) => list.layout_with_breadcrumb(data),
Self::StrokeList(list) => list.layout_with_breadcrumb(data),
}
@@ -1245,6 +1252,7 @@ impl_table_item_layout_for_choice_enum!(
BevelDirection,
BevelStyle,
EffectKind,
Generator,
GlowSource,
GradientForm,
GradientSpread,
@@ -1392,9 +1400,11 @@ macro_rules! known_item_types {
List<Raster<GPU>>,
List<Color>,
List<Gradient>,
List<Generator>,
List<String>,
List<f64>,
Gradient,
Generator,
Color,
NodeId,
DAffine2,
@@ -34,6 +34,8 @@ impl FrontendGraphDataType {
"Gradient" => Self::Gradient,
"String" => Self::Typography,
"f64" | "i64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
// A generator draws pixels like an image, at whatever resolution is needed
"Generator" => Self::Raster,
raster if raster.starts_with("Raster") => Self::Raster,
_ => Self::General,
}
@@ -8,6 +8,7 @@ use graphene_animation::AnimationCurve;
use graphene_std::animation::RealTimeMode;
use graphene_std::any::DynAnyNode;
use graphene_std::brush::Stroke;
use graphene_std::generator::Generator;
use graphene_std::gradient::Gradient;
use graphene_std::list::{AttributeValueDyn, Bundle, Item, List, ListDyn, NodeIdPath};
#[cfg(feature = "gpu")]
@@ -46,6 +47,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Raster<GPU>>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Color>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Gradient>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Generator>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Artboard>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Graphic>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Vector>]),
@@ -56,6 +58,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<wgpu_executor::WgpuPipelineCache>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Color>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Gradient>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Generator>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<DashPattern>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<BoxCorners>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<TransferCurve>]),
@@ -104,6 +107,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Raster<CPU>>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Color>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Gradient>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Generator>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<String>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<NodeIdPath>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<f64>]),
@@ -124,6 +128,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Raster<GPU>>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Color>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Gradient>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Generator>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<DashPattern>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<BoxCorners>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<TransferCurve>]),
@@ -370,6 +375,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
Graphic,
Color,
Gradient,
Generator,
String,
f64,
DVec2,
@@ -422,6 +428,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
Raster<CPU>,
Color,
Gradient,
Generator,
f64,
i64,
bool,
@@ -462,6 +469,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
String,
Color,
Gradient,
Generator,
Artboard,
));
#[cfg(feature = "gpu")]
@@ -515,6 +523,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
// This is what lets a paint list zip element-wise against the content it paints.
node_types.extend(embed_adapter_row!(from_element: Color, element: Graphic));
node_types.extend(embed_adapter_row!(from_element: Gradient, element: Graphic));
node_types.extend(embed_adapter_row!(from_element: Generator, element: Graphic));
node_types.extend(embed_adapter_row!(from_element: String, element: Graphic));
node_types.extend(embed_adapter_row!(from_element: Vector, element: Graphic));
node_types.extend(embed_adapter_row!(from_element: Raster<CPU>, element: Graphic));
@@ -572,6 +581,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
attribute_value_node!(List<String>),
attribute_value_node!(List<Color>),
attribute_value_node!(List<Gradient>),
attribute_value_node!(List<Generator>),
attribute_value_node!(List<Vector>),
attribute_value_node!(List<Raster<CPU>>),
#[cfg(feature = "gpu")]
@@ -599,6 +609,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
transform_list_node!(element: Raster<GPU>),
transform_list_node!(element: Color),
transform_list_node!(element: Gradient),
transform_list_node!(element: Generator),
];
node_types.extend(transform_list_rows);
let mut map: HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeConstructor>> = HashMap::new();
@@ -1,7 +1,8 @@
//! Color adjustments as plain data holding their nodes' settings in the nodes' own units, decoded from effect rows, carried out by the kernels of the `raster-kernels` crate.
use crate::Graphic;
use crate::effects::{EffectKind, ParameterVisitor};
use crate::effects::EffectKind;
use crate::parameters::ParameterVisitor;
use core_types::Color;
use core_types::blending::BlendMode;
use core_types::color::SRGBA8;
@@ -4,6 +4,7 @@
use crate::Graphic;
use crate::adjustment::Adjustment;
use crate::parameters::{ParameterVisitor, ReadParameters, WriteParameters};
use core_types::ATTR_TRANSFORM;
use core_types::Color;
use core_types::blending::BlendMode;
@@ -193,7 +194,7 @@ impl Effect {
/// Decodes the parameters into an [`EffectOperation`], falling back to the default for any absent attribute.
pub fn operation(&self) -> EffectOperation {
let mut operation = EffectOperation::placeholder(self.kind());
operation.visit_parameters(&mut ReadParameters(&self.0));
operation.visit_parameters(&mut ReadParameters(&|key| self.0.attributes().get_any(key)));
// A solid paint mixes the same into every pixel, so the renderers carry it out with the other adjustments
match operation {
@@ -546,35 +547,6 @@ impl EffectOperation {
}
}
/// What a value needs to ride an attribute.
pub(crate) trait ParameterValue: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static {}
impl<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static> ParameterValue for T {}
/// Handles each parameter of an operation, given the attribute key it rides and its implicit default.
pub(crate) trait ParameterVisitor {
fn parameter<T: ParameterValue>(&mut self, key: &str, value: &mut T, default: T);
}
/// Stamps each parameter that differs from its default onto a row.
struct WriteParameters<'a>(&'a mut Item<EffectKind>);
impl ParameterVisitor for WriteParameters<'_> {
fn parameter<T: ParameterValue>(&mut self, key: &str, value: &mut T, default: T) {
if *value != default {
self.0.set_attribute(key, value.clone());
}
}
}
/// Reads each parameter from a row, or its default where the row lacks it.
struct ReadParameters<'a>(&'a Item<EffectKind>);
impl ParameterVisitor for ReadParameters<'_> {
fn parameter<T: ParameterValue>(&mut self, key: &str, value: &mut T, default: T) {
*value = self.0.attribute::<T>(key).cloned().unwrap_or(default);
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -1,6 +1,12 @@
//! Procedural patterns described by their settings, rendered at whatever resolution is needed of whatever part is seen by the kernels of the `raster-kernels` crate.
use crate::parameters::{ParameterVisitor, ReadParameters, StampParameters};
use core_types::bounds::{BoundingBox, RenderBoundingBox};
use core_types::graphene_hash::CacheHash;
use core_types::list::Item;
use dyn_any::DynAny;
use glam::DAffine2;
use std::any::Any;
/// Style of noise pattern.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
@@ -90,7 +96,7 @@ pub enum DomainWarpType {
}
/// The settings of a noise pattern, whose lengths are measured in the document units of the space it's sampled in.
#[derive(Debug, Clone, PartialEq, CacheHash)]
#[derive(Debug, Clone, Default, PartialEq, CacheHash)]
pub struct NoiseSettings {
pub seed: i64,
pub scale: f64,
@@ -115,3 +121,82 @@ pub enum GeneratorPattern {
/// The Mandelbrot set, with the unit square spanning -2 to 1 along the real axis and -1.5 to 1.5 along the imaginary axis.
Mandelbrot,
}
/// A procedural pattern filling the whole plane, which renderers draw at whatever resolution they need across whatever part they see.
/// The item's transform places the pattern's own space, and a noise pattern's settings ride the item as attributes named after the Noise Pattern node's parameters.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny)]
pub enum Generator {
#[default]
Noise,
/// The Mandelbrot set, with the unit square spanning -2 to 1 along the real axis and -1.5 to 1.5 along the imaginary axis.
Mandelbrot,
}
impl std::fmt::Display for Generator {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Noise => "Noise",
Self::Mandelbrot => "Mandelbrot",
})
}
}
impl BoundingBox for Generator {
fn bounding_box(&self, transform: DAffine2, _include_stroke: bool) -> RenderBoundingBox {
match transform.matrix2.determinant() == 0. {
true => RenderBoundingBox::None,
false => RenderBoundingBox::Infinite,
}
}
fn thumbnail_bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
self.bounding_box(transform, include_stroke)
}
}
impl NoiseSettings {
/// Stamps every setting onto the generator's item, whatever its value, so which attributes the item carries doesn't depend on them.
pub fn stamp(&self, item: &mut Item<Generator>) {
self.clone().visit_parameters(&mut StampParameters(item));
}
/// Visits each setting with the attribute it rides, named after the Noise Pattern node's parameter, and its default, which is the node's.
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor) {
visitor.parameter("seed", &mut self.seed, 0);
visitor.parameter("scale", &mut self.scale, 10.);
visitor.parameter("noise_type", &mut self.noise_type, NoiseType::default());
visitor.parameter("domain_warp_type", &mut self.domain_warp_type, DomainWarpType::default());
visitor.parameter("domain_warp_amplitude", &mut self.domain_warp_amplitude, 100.);
visitor.parameter("fractal_type", &mut self.fractal_type, FractalType::default());
visitor.parameter("fractal_octaves", &mut self.fractal_octaves, 3);
visitor.parameter("fractal_lacunarity", &mut self.fractal_lacunarity, 2.);
visitor.parameter("fractal_gain", &mut self.fractal_gain, 0.5);
visitor.parameter("fractal_weighted_strength", &mut self.fractal_weighted_strength, 0.);
visitor.parameter("fractal_ping_pong_strength", &mut self.fractal_ping_pong_strength, 2.);
visitor.parameter("cellular_distance_function", &mut self.cellular_distance_function, CellularDistanceFunction::default());
visitor.parameter("cellular_return_type", &mut self.cellular_return_type, CellularReturnType::default());
visitor.parameter("cellular_jitter", &mut self.cellular_jitter, 1.);
}
}
impl GeneratorPattern {
/// The pattern a generator draws, reading a noise pattern's settings with `attribute`, which looks one of the item's attributes up by key.
/// Each setting the item lacks takes its default.
pub fn decode<'a>(generator: Generator, attribute: &'a dyn Fn(&str) -> Option<&'a dyn Any>) -> Self {
match generator {
Generator::Noise => {
let mut settings = NoiseSettings::default();
settings.visit_parameters(&mut ReadParameters(attribute));
Self::Noise(settings)
}
Generator::Mandelbrot => Self::Mandelbrot,
}
}
/// The pattern a generator item draws.
pub fn of_item(item: &Item<Generator>) -> Self {
Self::decode(*item.element(), &|key| item.attributes().get_any(key))
}
}
@@ -1,4 +1,5 @@
use crate::appearance::{Appearance, Cover, Coverage};
use crate::generator::Generator;
use brush_types::Stroke;
use core_types::bounds::{BoundingBox, RenderBoundingBox};
use core_types::graphene_hash::CacheHash;
@@ -26,6 +27,7 @@ pub enum Graphic {
RasterGPU(Item<Raster<GPU>>),
Color(Item<Color>),
Gradient(Item<Gradient>),
Generator(Item<Generator>),
Text(Item<String>),
NoneList(List<none::None>),
GraphicList(List<Graphic>),
@@ -34,6 +36,7 @@ pub enum Graphic {
RasterGPUList(List<Raster<GPU>>),
ColorList(List<Color>),
GradientList(List<Gradient>),
GeneratorList(List<Generator>),
TextList(List<String>),
StrokeList(List<Stroke>),
}
@@ -137,6 +140,23 @@ impl From<List<Gradient>> for Graphic {
}
}
// Generator
impl From<Generator> for Graphic {
fn from(generator: Generator) -> Self {
Graphic::Generator(Item::new_from_element(generator))
}
}
impl From<Item<Generator>> for Graphic {
fn from(generator: Item<Generator>) -> Self {
Graphic::Generator(generator)
}
}
impl From<List<Generator>> for Graphic {
fn from(generator: List<Generator>) -> Self {
Graphic::GeneratorList(generator)
}
}
// Stroke
impl From<Stroke> for Graphic {
fn from(stroke: Stroke) -> Self {
@@ -312,12 +332,14 @@ pub fn bake_paint_transforms(attributes: &mut ItemAttributeValues, transform: DA
Graphic::RasterCPU(item) => bake_item_transform(item, transform),
Graphic::RasterGPU(item) => bake_item_transform(item, transform),
Graphic::Gradient(item) => bake_item_transform(item, transform),
Graphic::Generator(item) => bake_item_transform(item, transform),
Graphic::Text(item) => bake_item_transform(item, transform),
Graphic::GraphicList(list) => bake_list_transform(list, transform),
Graphic::VectorList(list) => bake_list_transform(list, transform),
Graphic::RasterCPUList(list) => bake_list_transform(list, transform),
Graphic::RasterGPUList(list) => bake_list_transform(list, transform),
Graphic::GradientList(list) => bake_list_transform(list, transform),
Graphic::GeneratorList(list) => bake_list_transform(list, transform),
Graphic::TextList(list) => bake_list_transform(list, transform),
Graphic::StrokeList(list) => bake_list_transform(list, transform),
// A color has no spatial extent, so there is no placement for a transform to move
@@ -390,6 +412,16 @@ impl TryFromGraphic for Gradient {
}
}
impl TryFromGraphic for Generator {
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
match graphic {
Graphic::Generator(item) => Some(List::new_from_item(item)),
Graphic::GeneratorList(list) => Some(list),
_ => None,
}
}
}
impl TryFromGraphic for String {
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
match graphic {
@@ -457,6 +489,12 @@ impl IntoGraphicList for List<Gradient> {
}
}
impl IntoGraphicList for List<Generator> {
fn into_graphic_list(self) -> List<Graphic> {
List::new_from_element(Graphic::GeneratorList(self))
}
}
impl IntoGraphicList for List<Stroke> {
fn into_graphic_list(self) -> List<Graphic> {
let layer_path: NodeIdPath = self.attribute_cloned_or_default(ATTR_EDITOR_LAYER_PATH, 0);
@@ -570,6 +608,7 @@ impl Graphic {
Graphic::RasterGPU(item) => item_clipped(item),
Graphic::Color(item) => item_clipped(item),
Graphic::Gradient(item) => item_clipped(item),
Graphic::Generator(item) => item_clipped(item),
Graphic::Text(item) => item_clipped(item),
Graphic::NoneList(list) => all_clipped(list),
Graphic::VectorList(list) => all_clipped(list),
@@ -578,6 +617,7 @@ impl Graphic {
Graphic::RasterGPUList(list) => all_clipped(list),
Graphic::ColorList(list) => all_clipped(list),
Graphic::GradientList(list) => all_clipped(list),
Graphic::GeneratorList(list) => all_clipped(list),
Graphic::TextList(list) => all_clipped(list),
Graphic::StrokeList(list) => all_clipped(list),
}
@@ -616,6 +656,7 @@ impl Graphic {
}
Graphic::RasterCPU(_) | Graphic::RasterCPUList(_) => false,
Graphic::RasterGPU(_) | Graphic::RasterGPUList(_) => false,
Graphic::Generator(_) | Graphic::GeneratorList(_) => false,
Graphic::Color(item) => item_opacity_is_full(item) && item.element().is_opaque(),
Graphic::ColorList(list) => !list.is_empty() && every_item_has_full_opacity(list) && list.iter_element_values().all(|color| color.is_opaque()),
// A `Clear` spread cuts off to transparency past the ends, leaving the rest of the region unpainted
@@ -662,9 +703,11 @@ impl Graphic {
// Their content is never inspected, so zeroed opacity is the only invisibility these can report
Graphic::RasterCPU(item) => item_opacity_is_zero(item),
Graphic::RasterGPU(item) => item_opacity_is_zero(item),
Graphic::Generator(item) => item_opacity_is_zero(item),
Graphic::Text(item) => item_opacity_is_zero(item),
Graphic::RasterCPUList(list) => every_item_has_zero_opacity(list),
Graphic::RasterGPUList(list) => every_item_has_zero_opacity(list),
Graphic::GeneratorList(list) => every_item_has_zero_opacity(list),
Graphic::TextList(list) => every_item_has_zero_opacity(list),
Graphic::StrokeList(list) => every_item_has_zero_opacity(list),
}
@@ -680,11 +723,12 @@ impl Graphic {
match self {
// A leaf always holds exactly one element, so only the none-typed content is truly empty
Graphic::None(_) | Graphic::NoneList(_) => true,
Graphic::Graphic(_) | Graphic::Vector(_) | Graphic::RasterCPU(_) | Graphic::RasterGPU(_) | Graphic::Color(_) | Graphic::Gradient(_) | Graphic::Text(_) => false,
Graphic::Graphic(_) | Graphic::Vector(_) | Graphic::RasterCPU(_) | Graphic::RasterGPU(_) | Graphic::Color(_) | Graphic::Gradient(_) | Graphic::Generator(_) | Graphic::Text(_) => false,
Graphic::GraphicList(list) => list.is_empty(),
Graphic::VectorList(list) => list.is_empty(),
Graphic::ColorList(list) => list.is_empty(),
Graphic::GradientList(list) => list.is_empty(),
Graphic::GeneratorList(list) => list.is_empty(),
Graphic::RasterCPUList(list) => list.is_empty(),
Graphic::RasterGPUList(list) => list.is_empty(),
Graphic::TextList(list) => list.is_empty(),
@@ -841,6 +885,7 @@ impl BoundingBox for Graphic {
Graphic::RasterGPU(item) => item.bounding_box(transform, include_stroke),
Graphic::Color(item) => item.bounding_box(transform, include_stroke),
Graphic::Gradient(item) => item.bounding_box(transform, include_stroke),
Graphic::Generator(item) => item.bounding_box(transform, include_stroke),
Graphic::Text(item) => item.bounding_box(transform, include_stroke),
Graphic::VectorList(list) => vector_list_bounding_box(list, transform, include_stroke),
Graphic::RasterCPUList(list) => list.bounding_box(transform, include_stroke),
@@ -848,6 +893,7 @@ impl BoundingBox for Graphic {
Graphic::GraphicList(list) => list.bounding_box(transform, include_stroke),
Graphic::ColorList(list) => list.bounding_box(transform, include_stroke),
Graphic::GradientList(list) => list.bounding_box(transform, include_stroke),
Graphic::GeneratorList(list) => list.bounding_box(transform, include_stroke),
Graphic::TextList(list) => list.bounding_box(transform, include_stroke),
Graphic::StrokeList(list) => list.bounding_box(transform, include_stroke),
}
@@ -862,6 +908,7 @@ impl BoundingBox for Graphic {
Graphic::RasterGPU(item) => item.thumbnail_bounding_box(transform, include_stroke),
Graphic::Color(item) => item.thumbnail_bounding_box(transform, include_stroke),
Graphic::Gradient(item) => item.thumbnail_bounding_box(transform, include_stroke),
Graphic::Generator(item) => item.thumbnail_bounding_box(transform, include_stroke),
Graphic::Text(item) => item.thumbnail_bounding_box(transform, include_stroke),
Graphic::VectorList(vector) => vector_list_bounding_box(vector, transform, include_stroke),
Graphic::RasterCPUList(raster) => raster.thumbnail_bounding_box(transform, include_stroke),
@@ -869,6 +916,7 @@ impl BoundingBox for Graphic {
Graphic::GraphicList(list) => list.thumbnail_bounding_box(transform, include_stroke),
Graphic::ColorList(color) => color.thumbnail_bounding_box(transform, include_stroke),
Graphic::GradientList(gradient) => gradient.thumbnail_bounding_box(transform, include_stroke),
Graphic::GeneratorList(generator) => generator.thumbnail_bounding_box(transform, include_stroke),
Graphic::TextList(list) => list.thumbnail_bounding_box(transform, include_stroke),
Graphic::StrokeList(list) => list.thumbnail_bounding_box(transform, include_stroke),
}
@@ -4,6 +4,7 @@ pub mod artboard;
pub mod effects;
pub mod generator;
pub mod graphic;
pub(crate) mod parameters;
// Re-export all transitive dependencies so downstream crates only need to depend on graphic-types
pub use core_types;
@@ -15,6 +16,7 @@ pub use adjustment::Adjustment;
pub use appearance::{Appearance, Cover, CoverPlacement, Coverage, FillAndStroke, stamp_coverage};
pub use artboard::Artboard;
pub use effects::{BevelDirection, BevelStyle, Effect, EffectKind, EffectOperation, Effects, GlowSource, fitted_paint, stamp_effect};
pub use generator::Generator;
pub use graphic::{Graphic, IntoGraphicList, TryFromGraphic, Vector};
pub mod migrations {
@@ -0,0 +1,44 @@
//! Parameters riding an item as attributes, each read as its default when absent, which one listing per operation both writes and reads.
use core_types::graphene_hash::CacheHash;
use core_types::list::Item;
use std::any::Any;
use std::fmt::Debug;
/// What a value needs to ride an attribute.
pub(crate) trait ParameterValue: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static {}
impl<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static> ParameterValue for T {}
/// Handles each parameter of an operation, given the attribute key it rides and its default.
pub(crate) trait ParameterVisitor {
fn parameter<T: ParameterValue>(&mut self, key: &str, value: &mut T, default: T);
}
/// Stamps each parameter that differs from its default onto an item, for rows whose attributes are part of their value.
pub(crate) struct WriteParameters<'a, T>(pub &'a mut Item<T>);
impl<T> ParameterVisitor for WriteParameters<'_, T> {
fn parameter<U: ParameterValue>(&mut self, key: &str, value: &mut U, default: U) {
if *value != default {
self.0.set_attribute(key, value.clone());
}
}
}
/// Stamps every parameter onto an item, for an item on a wire, whose attributes mustn't come and go with their values.
pub(crate) struct StampParameters<'a, T>(pub &'a mut Item<T>);
impl<T> ParameterVisitor for StampParameters<'_, T> {
fn parameter<U: ParameterValue>(&mut self, key: &str, value: &mut U, _default: U) {
self.0.set_attribute(key, value.clone());
}
}
/// Reads each parameter from the attribute that the lookup finds by key, or its default where there's none.
pub(crate) struct ReadParameters<'a>(pub &'a dyn Fn(&str) -> Option<&'a dyn Any>);
impl ParameterVisitor for ReadParameters<'_> {
fn parameter<T: ParameterValue>(&mut self, key: &str, value: &mut T, default: T) {
*value = (self.0)(key).and_then(|value| value.downcast_ref::<T>()).cloned().unwrap_or(default);
}
}
@@ -269,10 +269,12 @@ impl RenderExt for Graphic {
| Graphic::Vector(_)
| Graphic::RasterCPU(_)
| Graphic::RasterGPU(_)
| Graphic::Generator(_)
| Graphic::Text(_)
| Graphic::VectorList(_)
| Graphic::RasterCPUList(_)
| Graphic::RasterGPUList(_)
| Graphic::GeneratorList(_)
| Graphic::GraphicList(_)
| Graphic::GradientList(_)
| Graphic::TextList(_)
+91 -2
View File
@@ -24,6 +24,7 @@ use core_types::{
use dyn_any::DynAny;
use glam::{DAffine2, DMat2, DVec2};
use graphene_resource::Resource;
use graphic_types::generator::GeneratorPattern;
use graphic_types::raster_types::{CPU, GPU, Raster, Storage, Texture};
use graphic_types::vector_types::gradient::{Gradient, GradientForm, wrapped_dial};
use graphic_types::vector_types::vector::click_target::{ClickTarget, FreePoint, TargetPath};
@@ -32,7 +33,7 @@ use graphic_types::vector_types::vector::style::{RenderMode, StrokeAlign, Stroke
use graphic_types::vector_types::vector::{
GeometryCache, Path, PlacedContours, contour_bezpaths, contours_bounding_box, contours_stroke_inclusive_bounding_box, edit_item_geometry, edit_list_row_geometry, no_paths,
};
use graphic_types::{Adjustment, Appearance, Artboard, BevelStyle, Cover, Coverage, EffectOperation, Effects, FillAndStroke, Graphic, Vector, fitted_paint};
use graphic_types::{Adjustment, Appearance, Artboard, BevelStyle, Cover, Coverage, EffectOperation, Effects, FillAndStroke, Generator, Graphic, Vector, fitted_paint};
use kurbo::{Affine, BezPath, Cap, Join, PathEl, Shape};
use num_traits::Zero;
use raster_kernels::adjustments::{adjust_color, adjusted_raster, leading_adjustments, preserves_alpha};
@@ -76,6 +77,13 @@ impl<'a, T> ItemRef<'a, T> {
}
}
pub(crate) fn attribute_any(self, key: &str) -> Option<&'a dyn std::any::Any> {
match self {
ItemRef::ListItem(list, index) => list.attribute_any(key, index),
ItemRef::Item(item) => item.attributes().get_any(key),
}
}
pub(crate) fn attribute_cloned_or<A: Clone + 'static>(self, key: &str, fallback: A) -> A {
match self {
ItemRef::ListItem(list, index) => list.attribute_cloned_or(key, index, fallback),
@@ -386,6 +394,7 @@ fn nested_effects_reach(graphic: &Graphic) -> f64 {
Graphic::RasterGPU(item) => item_reach(item),
Graphic::Color(item) => item_reach(item),
Graphic::Gradient(item) => item_reach(item),
Graphic::Generator(item) => item_reach(item),
Graphic::Text(item) => item_reach(item),
Graphic::GraphicList(list) => list_reach(list, nested_effects_reach),
Graphic::VectorList(list) => list_reach(list, |_| 0.),
@@ -393,6 +402,7 @@ fn nested_effects_reach(graphic: &Graphic) -> f64 {
Graphic::RasterGPUList(list) => list_reach(list, |_| 0.),
Graphic::ColorList(list) => list_reach(list, |_| 0.),
Graphic::GradientList(list) => list_reach(list, |_| 0.),
Graphic::GeneratorList(list) => list_reach(list, |_| 0.),
Graphic::TextList(list) => list_reach(list, |_| 0.),
}
}
@@ -1873,6 +1883,7 @@ impl Render for Graphic {
Graphic::RasterGPU(item) => render_raster_gpu_item_svg(ItemRef::Item(item), render, render_params),
Graphic::Color(item) => render_color_item_svg(ItemRef::Item(item), render, render_params),
Graphic::Gradient(item) => render_gradient_item_svg(ItemRef::Item(item), render, render_params),
Graphic::Generator(_) => (),
Graphic::Text(item) => render_text_item_svg(ItemRef::Item(item), render, render_params),
Graphic::GraphicList(list) => list.render_svg(render, render_params),
Graphic::VectorList(list) => list.render_svg(render, render_params),
@@ -1880,6 +1891,7 @@ impl Render for Graphic {
Graphic::RasterGPUList(list) => list.render_svg(render, render_params),
Graphic::ColorList(list) => list.render_svg(render, render_params),
Graphic::GradientList(list) => list.render_svg(render, render_params),
Graphic::GeneratorList(list) => list.render_svg(render, render_params),
Graphic::TextList(list) => list.render_svg(render, render_params),
Graphic::StrokeList(_) => (),
}
@@ -1901,6 +1913,7 @@ impl Render for Graphic {
Graphic::RasterGPU(item) => render_raster_gpu_item_to_vello(ItemRef::Item(item), scene, transform, render_params),
Graphic::Color(item) => render_color_item_to_vello(ItemRef::Item(item), scene, transform, render_params),
Graphic::Gradient(item) => render_gradient_item_to_vello(ItemRef::Item(item), scene, transform, render_params),
Graphic::Generator(item) => render_generator_item_to_vello(ItemRef::Item(item), scene, transform, render_params),
Graphic::Text(item) => render_text_item_to_vello(ItemRef::Item(item), scene, transform, render_params),
Graphic::GraphicList(list) => list.render_to_vello(scene, transform, render_params),
Graphic::VectorList(list) => list.render_to_vello(scene, transform, render_params),
@@ -1908,6 +1921,7 @@ impl Render for Graphic {
Graphic::RasterGPUList(list) => list.render_to_vello(scene, transform, render_params),
Graphic::ColorList(list) => list.render_to_vello(scene, transform, render_params),
Graphic::GradientList(list) => list.render_to_vello(scene, transform, render_params),
Graphic::GeneratorList(list) => list.render_to_vello(scene, transform, render_params),
Graphic::TextList(list) => list.render_to_vello(scene, transform, render_params),
Graphic::StrokeList(_) => (),
}
@@ -1929,10 +1943,12 @@ impl Render for Graphic {
| Graphic::RasterCPU(_)
| Graphic::Color(_)
| Graphic::Gradient(_)
| Graphic::Generator(_)
| Graphic::Text(_)
| Graphic::RasterCPUList(_)
| Graphic::ColorList(_)
| Graphic::GradientList(_)
| Graphic::GeneratorList(_)
| Graphic::TextList(_)
| Graphic::StrokeList(_) => {}
}
@@ -1969,6 +1985,7 @@ impl Render for Graphic {
Graphic::RasterGPU(item) => first_item_inserts(metadata, item.attribute_cloned_or_default(ATTR_TRANSFORM)),
Graphic::Color(item) => first_item_inserts(metadata, item.attribute_cloned_or_default(ATTR_TRANSFORM)),
Graphic::Gradient(item) => first_item_inserts(metadata, item.attribute_cloned_or_default(ATTR_TRANSFORM)),
Graphic::Generator(item) => first_item_inserts(metadata, item.attribute_cloned_or_default(ATTR_TRANSFORM)),
Graphic::Text(item) => first_item_inserts(metadata, item.attribute_cloned_or_default(ATTR_TRANSFORM)),
Graphic::RasterCPUList(list) => {
metadata.upstream_footprints.insert(element_id, footprint);
@@ -2002,6 +2019,14 @@ impl Render for Graphic {
metadata.local_transforms.insert(element_id, list.attribute_cloned_or_default(ATTR_TRANSFORM, 0));
}
}
Graphic::GeneratorList(list) => {
metadata.upstream_footprints.insert(element_id, footprint);
// TODO: Find a way to handle more than the first item
if !list.is_empty() {
metadata.local_transforms.insert(element_id, list.attribute_cloned_or_default(ATTR_TRANSFORM, 0));
}
}
Graphic::TextList(list) => {
metadata.upstream_footprints.insert(element_id, footprint);
@@ -2029,6 +2054,7 @@ impl Render for Graphic {
Graphic::RasterGPU(item) => collect_raster_metadata(Some(ItemRef::Item(item)), metadata, footprint, element_id),
Graphic::Color(_) => (),
Graphic::Gradient(item) => collect_gradient_items_metadata(std::iter::once(ItemRef::Item(item)), metadata, element_id),
Graphic::Generator(_) => (),
Graphic::Text(item) => collect_text_items_metadata(std::iter::once(ItemRef::Item(item)), metadata, footprint, element_id),
Graphic::GraphicList(list) => list.collect_metadata(metadata, footprint, element_id, inherited_appearance),
Graphic::VectorList(list) => list.collect_metadata(metadata, footprint, element_id, inherited_appearance),
@@ -2036,6 +2062,7 @@ impl Render for Graphic {
Graphic::RasterGPUList(list) => list.collect_metadata(metadata, footprint, element_id, inherited_appearance),
Graphic::ColorList(list) => list.collect_metadata(metadata, footprint, element_id, inherited_appearance),
Graphic::GradientList(list) => list.collect_metadata(metadata, footprint, element_id, inherited_appearance),
Graphic::GeneratorList(list) => list.collect_metadata(metadata, footprint, element_id, inherited_appearance),
Graphic::TextList(list) => list.collect_metadata(metadata, footprint, element_id, inherited_appearance),
Graphic::StrokeList(list) => list.collect_metadata(metadata, footprint, element_id, inherited_appearance),
}
@@ -2050,6 +2077,7 @@ impl Render for Graphic {
Graphic::RasterGPU(item) => add_unit_square_click_target(item.attribute_cloned_or_default(ATTR_TRANSFORM), click_targets),
Graphic::Color(_) => (),
Graphic::Gradient(item) => add_gradient_item_click_targets(ItemRef::Item(item), click_targets),
Graphic::Generator(_) => (),
Graphic::Text(item) => add_text_item_click_targets(ItemRef::Item(item), click_targets),
Graphic::GraphicList(list) => list.add_upstream_click_targets(click_targets, inherited_appearance),
Graphic::VectorList(list) => list.add_upstream_click_targets(click_targets, inherited_appearance),
@@ -2057,6 +2085,7 @@ impl Render for Graphic {
Graphic::RasterGPUList(list) => list.add_upstream_click_targets(click_targets, inherited_appearance),
Graphic::ColorList(list) => list.add_upstream_click_targets(click_targets, inherited_appearance),
Graphic::GradientList(list) => list.add_upstream_click_targets(click_targets, inherited_appearance),
Graphic::GeneratorList(list) => list.add_upstream_click_targets(click_targets, inherited_appearance),
Graphic::TextList(list) => list.add_upstream_click_targets(click_targets, inherited_appearance),
Graphic::StrokeList(list) => list.add_upstream_click_targets(click_targets, inherited_appearance),
}
@@ -2071,6 +2100,7 @@ impl Render for Graphic {
Graphic::RasterGPU(item) => add_unit_square_click_target(item.attribute_cloned_or_default(ATTR_TRANSFORM), outlines),
Graphic::Color(_) => (),
Graphic::Gradient(item) => add_gradient_item_outline_targets(ItemRef::Item(item), outlines),
Graphic::Generator(_) => (),
Graphic::Text(item) => add_text_item_click_targets(ItemRef::Item(item), outlines),
Graphic::GraphicList(list) => list.add_upstream_outline_targets(outlines, inherited_appearance),
Graphic::VectorList(list) => list.add_upstream_outline_targets(outlines, inherited_appearance),
@@ -2078,6 +2108,7 @@ impl Render for Graphic {
Graphic::RasterGPUList(list) => list.add_upstream_outline_targets(outlines, inherited_appearance),
Graphic::ColorList(list) => list.add_upstream_outline_targets(outlines, inherited_appearance),
Graphic::GradientList(list) => list.add_upstream_outline_targets(outlines, inherited_appearance),
Graphic::GeneratorList(list) => list.add_upstream_outline_targets(outlines, inherited_appearance),
Graphic::TextList(list) => list.add_upstream_outline_targets(outlines, inherited_appearance),
Graphic::StrokeList(list) => list.add_upstream_outline_targets(outlines, inherited_appearance),
}
@@ -2787,10 +2818,12 @@ fn render_vector_item_to_vello(
| Graphic::Vector(_)
| Graphic::RasterCPU(_)
| Graphic::RasterGPU(_)
| Graphic::Generator(_)
| Graphic::Text(_)
| Graphic::VectorList(_)
| Graphic::RasterCPUList(_)
| Graphic::RasterGPUList(_)
| Graphic::GeneratorList(_)
| Graphic::GraphicList(_)
| Graphic::TextList(_)
| Graphic::StrokeList(_) => {
@@ -2877,10 +2910,12 @@ fn render_vector_item_to_vello(
| Graphic::Vector(_)
| Graphic::RasterCPU(_)
| Graphic::RasterGPU(_)
| Graphic::Generator(_)
| Graphic::Text(_)
| Graphic::VectorList(_)
| Graphic::RasterCPUList(_)
| Graphic::RasterGPUList(_)
| Graphic::GeneratorList(_)
| Graphic::GraphicList(_)
| Graphic::TextList(_)
| Graphic::StrokeList(_) => {
@@ -3477,6 +3512,56 @@ fn render_raster_cpu_item_to_vello(item: ItemRef<'_, Raster<CPU>>, scene: &mut V
/// The most pixels an image may have for its adjustments to be carried out on a texture of it, past which an effects group carries them out at the render's resolution.
const MAX_ADJUSTED_TEXTURE_PIXELS: u64 = 4096 * 4096;
/// Draws one item of generator content into the Vello scene, which renders its pattern for each render at the resolution it needs.
fn render_generator_item_to_vello(item: ItemRef<'_, Generator>, scene: &mut VelloSceneBuilder, transform: DAffine2, render_params: &RenderParams) {
let Some(&generator) = item.element() else { return };
// Outline mode shows only geometry, and a generator filling the plane has none
if let RenderMode::Outline = render_params.render_mode {
return;
}
let blend_mode_attr: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE);
let compositing = item.compositing(render_params);
let local_to_scene = transform * item.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM);
let bounds = generator.bounding_box(local_to_scene, false);
if bounds == RenderBoundingBox::None {
return;
}
// Opacity and blend modes composite through a layer covering the whole render
let mut layer = false;
if compositing.opacity < 1. || blend_mode_attr != BlendMode::default() {
let blending = peniko::BlendMode::new(blend_mode_attr.to_peniko(), peniko::Compose::SrcOver);
scene.push_viewport_layer(blending, compositing.opacity);
layer = true;
}
let pattern = GeneratorPattern::decode(generator, &|key| item.attribute_any(key));
compositing.draw_with_effects(
scene,
transform,
render_params,
|| bounds,
|scene| scene.draw_generator(&pattern, kurbo::Affine::new(local_to_scene.to_cols_array())),
);
if layer {
scene.pop_layer();
}
}
impl Render for List<Generator> {
// A generator's pattern is rendered by GPU kernels, which SVG output has no GPU to run, so it draws nothing as a GPU raster does
fn render_svg(&self, _render: &mut SvgRender, _render_params: &RenderParams) {}
fn render_to_vello(&self, scene: &mut VelloSceneBuilder, transform: DAffine2, render_params: &RenderParams) {
for index in 0..self.len() {
render_generator_item_to_vello(ItemRef::ListItem(self, index), scene, transform, render_params);
}
}
}
/// The metadata a raster contributes under an `element_id`: a unit-square click target,
/// plus the first item's transform and any merged-layers snapshot when a first item exists.
fn collect_raster_metadata<T>(first_row: Option<ItemRef<'_, T>>, metadata: &mut RenderMetadata, footprint: Footprint, element_id: Option<NodeId>) {
@@ -4768,7 +4853,7 @@ mod tests {
#[test]
fn solid_vector_paints_take_their_adjustments_into_their_colors() {
use crate::vello_scene_builder::{EffectsRenderer, VelloSceneBuilder};
use crate::vello_scene_builder::{EffectsRenderer, GeneratorTile, VelloSceneBuilder};
use graphic_types::{Effect, EffectOperation, stamp_effect};
use kurbo::Shape;
@@ -4811,6 +4896,10 @@ mod tests {
fn adjust_raster(&mut self, _: &Raster<CPU>, _: &[Adjustment]) -> Option<graphic_types::raster_types::Texture> {
None
}
fn prepare_generator_tile(&mut self, _: &GeneratorPattern, _: GeneratorTile) -> bool {
false
}
}
let mut effects_renderer = NoEffectsGroups;
let mut scene = VelloSceneBuilder::new(16, 16, kurbo::Affine::IDENTITY, 4096).with_effects_renderer(&mut effects_renderer);
@@ -1,4 +1,6 @@
use glam::{DMat2, UVec2};
use glam::{DMat2, DVec2, UVec2};
use graphene_hash::CacheHash;
use graphic_types::generator::GeneratorPattern;
use graphic_types::raster_types::{CPU, Raster, Texture};
use graphic_types::{Adjustment, Effects};
use kurbo::{Affine, BezPath, PathEl, Point, Rect, Shape, Stroke};
@@ -13,6 +15,16 @@ const SHAPE_TOLERANCE: f64 = 0.1;
/// The texture size an effects group's area rounds up to a multiple of, so a group moving across renders keeps reusing the same pooled textures.
const EFFECTS_SIZE_CLASS: u32 = 64;
/// The pixels across and down a generator's tile covers, besides the samples bordering it that let neighboring tiles overlap seamlessly.
const GENERATOR_TILE_PIXELS: u32 = 256;
/// The samples bordering each side of a generator's tile, and how many of them its neighbor's drawing overlaps.
const GENERATOR_TILE_BORDER: u32 = 2;
const GENERATOR_TILE_OVERLAP: u32 = 1;
/// The most tiles one generator draws in a render, past which larger tiles render at a lower resolution, as for a view skewed far along one axis.
const MAX_GENERATOR_TILES_PER_DRAW: f64 = 256.;
/// Builds a Vello GPU scene of a fixed size, recording the images it draws so the renderer can supply their textures at render time.
pub struct VelloSceneBuilder<'a> {
scene: vello_gpu::Scene,
@@ -50,6 +62,9 @@ pub trait EffectsRenderer: Send {
/// A straight-alpha texture of the size of the CPU `raster`, with `adjustments` carried out on its pixels, kept for as long as they're drawn that way.
/// `None` if they can't be carried out.
fn adjust_raster(&mut self, raster: &Raster<CPU>, adjustments: &[Adjustment]) -> Option<Texture>;
/// Makes `tile` of `pattern` ready to be drawn as an image, rendering it unless it's been kept from an earlier render. `false` if it can't be rendered.
fn prepare_generator_tile(&mut self, pattern: &GeneratorPattern, tile: GeneratorTile) -> bool;
}
/// What a fill or stroke paints with.
@@ -100,6 +115,8 @@ pub enum SceneImage {
Raster(Raster<CPU>),
/// Straight-alpha pixels in a GPU texture, whose copy for sampling gets mipmaps if it's drawn `minified`.
Texture { texture: Texture, minified: bool },
/// One tile of a generator's pattern, which the renderer made and kept when it was drawn.
GeneratorTile(GeneratorTile),
}
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
@@ -107,6 +124,36 @@ enum ImageKey {
Blob(u64),
Raster(u64),
Texture(Texture, bool),
GeneratorTile(GeneratorTile),
}
/// One tile of a generator's pattern, from a grid in the pattern's space whose tiles span a power of two of units.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct GeneratorTile {
/// Identifies the pattern by the hash of its settings.
pub pattern: u64,
/// The tiles span `2^-level` units, so a tile is about the same number of pixels in view at any zoom.
pub level: i32,
pub column: i64,
pub row: i64,
}
impl GeneratorTile {
/// The samples across and down the tile and its border.
pub const SAMPLES: u32 = GENERATOR_TILE_PIXELS + 2 * GENERATOR_TILE_BORDER;
/// The area of the pattern's space the tile and its border's samples cover, from its minimum to its maximum corner.
pub fn area(&self) -> [DVec2; 2] {
let (corner, texel) = self.corner_and_texel();
[corner, corner + DVec2::splat(Self::SAMPLES as f64 * texel)]
}
/// The corner of the tile's samples, including its border, in the pattern's space, and the span of one sample.
fn corner_and_texel(&self) -> (DVec2, f64) {
let span = 2_f64.powi(-self.level);
let texel = span / GENERATOR_TILE_PIXELS as f64;
(DVec2::new(self.column as f64, self.row as f64) * span - GENERATOR_TILE_BORDER as f64 * texel, texel)
}
}
#[derive(Debug)]
@@ -287,6 +334,76 @@ impl<'a> VelloSceneBuilder<'a> {
self.effects_renderer.as_deref_mut().filter(|renderer| renderer.renders_effects())?.adjust_raster(raster, adjustments)
}
/// Draws a generator's pattern, whose own space `transform` places, across the part of the scene it covers as tiles the renderer makes the first time each is seen.
/// The tiles span a power of two of the pattern's units, so a pan reuses them, as does a zoom until the scale nears the next power.
pub fn draw_generator(&mut self, pattern: &GeneratorPattern, transform: Affine) {
if !self.effects_renderer.as_ref().is_some_and(|renderer| renderer.renders_effects()) {
return;
}
let local_to_device = self.view * transform;
let [a, b, c, d, _, _] = local_to_device.as_coeffs();
let determinant = a * d - b * c;
if !determinant.is_normal() {
return;
}
// The part of the pattern's space in view
let viewport = Rect::new(0., 0., self.width() as f64, self.height() as f64);
let visible = local_to_device.inverse().transform_rect_bbox(viewport);
if visible.width() <= 0. || visible.height() <= 0. {
return;
}
// The tile size nearest to a tile's pixels in view, grown if the view would otherwise need too many
let pixels_per_unit = determinant.abs().sqrt();
let tile_span = |level: i32| 2_f64.powi(-level);
let tile_range = |start: f64, end: f64, span: f64| (start / span).floor() as i64..(end / span).ceil() as i64;
let tile_count = |level: i32| {
let span = tile_span(level);
(tile_range(visible.x0, visible.x1, span).count() * tile_range(visible.y0, visible.y1, span).count()) as f64
};
let mut level = (pixels_per_unit / GENERATOR_TILE_PIXELS as f64).log2().round() as i32;
while tile_count(level) > MAX_GENERATOR_TILES_PER_DRAW {
level -= 1;
}
let span = tile_span(level);
let mut hasher = std::hash::DefaultHasher::new();
pattern.cache_hash(&mut hasher);
let pattern_hash = std::hash::Hasher::finish(&hasher);
let (border, overlap) = (GENERATOR_TILE_BORDER as f64, GENERATOR_TILE_OVERLAP as f64);
for row in tile_range(visible.y0, visible.y1, span) {
for column in tile_range(visible.x0, visible.x1, span) {
let tile = GeneratorTile {
pattern: pattern_hash,
level,
column,
row,
};
if !self.effects_renderer.as_deref_mut().is_some_and(|renderer| renderer.prepare_generator_tile(pattern, tile)) {
continue;
}
let id = *self.image_ids.entry(ImageKey::GeneratorTile(tile)).or_insert_with(|| {
self.images.push(SceneImage::GeneratorTile(tile));
TextureId(self.images.len() as u64 - 1)
});
// Drawn across the tile and part of its border, overlapping its neighbors' identical samples so no seam shows between them
let (corner, texel) = tile.corner_and_texel();
self.scene.set_transform(local_to_device * Affine::translate((corner.x, corner.y)) * Affine::scale(texel));
self.scene.set_paint(PaintType::Image(Image {
image: ImageSource::external_texture(id, TextureRegion::Full, true),
sampler: peniko::ImageSampler::new(),
}));
self.scene.set_paint_transform(Affine::IDENTITY);
let (start, end) = (border - overlap, border + GENERATOR_TILE_PIXELS as f64 + overlap);
self.scene.fill_rect(&Rect::new(start, start, end, end));
}
}
}
/// Draws the content `draw` draws with `effects` carried out on it, within `bounds` in the space of the drawn content (or everywhere for `None`), drawing again for each part of a split render.
/// `draw_paint` draws each paint overlay's paint by its index among them, and `fill` fades the content but not the shadows and glows cast from it.
pub fn draw_effects(&mut self, effects: &Effects, fill: f32, bounds: Option<Rect>, draw_paint: &mut dyn FnMut(usize, &mut VelloSceneBuilder), draw: &mut dyn FnMut(&mut VelloSceneBuilder)) {
@@ -373,6 +490,7 @@ impl<'a> VelloSceneBuilder<'a> {
SceneImage::Pixels(data) => (data.width, data.height),
SceneImage::Raster(raster) => (raster.width, raster.height),
SceneImage::Texture { texture, .. } => (texture.width(), texture.height()),
SceneImage::GeneratorTile(_) => (GeneratorTile::SAMPLES, GeneratorTile::SAMPLES),
};
if width == 0 || height == 0 {
return None;
@@ -382,6 +500,7 @@ impl<'a> VelloSceneBuilder<'a> {
SceneImage::Pixels(data) => ImageKey::Blob(data.data.id()),
SceneImage::Raster(raster) => ImageKey::Raster(raster.buffer_id()),
SceneImage::Texture { texture, minified } => ImageKey::Texture(texture.clone(), *minified),
SceneImage::GeneratorTile(tile) => ImageKey::GeneratorTile(*tile),
};
let id = *self.image_ids.entry(key).or_insert_with(|| {
self.images.push(image);
@@ -1,14 +1,15 @@
use crate::WgpuPipelineCache;
use crate::raster_effects::apply_effects;
use crate::raster_kernel::adjust_raster;
use crate::raster_kernel::{adjust_raster, render_generator};
use core_types::NodeError;
use core_types::graphene_hash::CacheHash;
use core_types::ops::Convert;
use core_types::transform::Footprint;
use glam::{DMat2, UVec2};
use graphic_types::generator::GeneratorPattern;
use graphic_types::{Adjustment, Effects, Graphic};
use raster_types::{CPU, GPU, Raster, Texture, WeakCPU};
use rendering::vello_scene_builder::{EffectsRenderer, SceneImage, VelloSceneBuilder, image_downscale_factor, image_texture_size};
use rendering::vello_scene_builder::{EffectsRenderer, GeneratorTile, SceneImage, VelloSceneBuilder, image_downscale_factor, image_texture_size};
use std::collections::HashMap;
use std::sync::{Mutex, PoisonError};
use vello_gpu::kurbo::Affine;
@@ -25,6 +26,9 @@ const TEXTURE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
/// How many renders a GPU texture's premultiplied copy survives without being drawn before it is freed.
const UNUSED_IMAGE_RENDER_LIMIT: u64 = 60;
/// The most tiles of generators kept between renders, past which the least recently drawn are freed.
const MAX_CACHED_GENERATOR_TILES: usize = 256;
/// How many times a render with too much content for Vello GPU is halved, reaching areas 1/4096 the size of the original.
const MAX_SPLIT_DEPTH: u32 = 12;
@@ -351,6 +355,59 @@ impl EffectsRenderer for RenderContext<'_> {
}
}
}
fn prepare_generator_tile(&mut self, pattern: &GeneratorPattern, tile: GeneratorTile) -> bool {
let key = ImageKey::GeneratorTile(tile);
let render_count = self.canvas.images.render_count;
if let Some(image_texture) = self.canvas.images.textures.get_mut(&key) {
image_texture.last_used = render_count;
return true;
}
let size = UVec2::splat(GeneratorTile::SAMPLES);
let rendered = render_generator(pattern, tile.area(), size, self.kernels);
let source = match rendered.as_ref().map(|raster| raster.texture()) {
Ok(Some(source)) => source,
Ok(None) => return false,
Err(error) => {
log::error!("Failed to render a generator's tile: {error}");
return false;
}
};
// Unlike a raster's texture, which the texture cache may hand back with new contents, the tile's pixels stay as they are, so its copy for sampling is made once
let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("vello_gpu_generator_tile"),
});
let texture = premultiplied_image_texture(self.device, source, true);
self.renderer.alpha_conversion.premultiply_with_mipmaps(self.device, &mut encoder, source, &texture);
self.queue.lock().submit([encoder.finish()]);
self.canvas.images.textures.insert(
key,
ImageTexture {
texture,
last_used: render_count,
raster: None,
},
);
true
}
}
/// A texture to hold the premultiplied copy of `source` that Vello GPU samples, with mipmaps if it's drawn `minified`.
fn premultiplied_image_texture(device: &wgpu::Device, source: &wgpu::Texture, minified: bool) -> wgpu::Texture {
let level_count = if minified { source.width().max(source.height()).ilog2() + 1 } else { 1 };
device.create_texture(&wgpu::TextureDescriptor {
label: Some("vello_gpu_premultiplied_image"),
size: source.size(),
mip_level_count: level_count,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: TEXTURE_FORMAT,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT,
view_formats: &[],
})
}
/// Leaves `target` transparent.
@@ -360,12 +417,13 @@ fn clear(device: &wgpu::Device, queue: &Queue, target: &wgpu::Texture) {
queue.submit([encoder.finish()]);
}
/// Identifies the pixels behind an image texture: a blob of CPU pixels, or a GPU texture.
/// Identifies the pixels behind an image texture: a blob of CPU pixels, a GPU texture, or a tile of a generator's pattern.
#[derive(Clone, PartialEq, Eq, Hash)]
enum ImageKey {
Blob(u64),
Raster(u64),
Texture(wgpu::Texture, bool),
GeneratorTile(GeneratorTile),
}
/// A premultiplied copy of an image's pixels that Vello GPU samples as an external texture.
@@ -399,6 +457,7 @@ impl ImageTextures {
SceneImage::Pixels(data) => ImageKey::Blob(data.data.id()),
SceneImage::Raster(raster) => ImageKey::Raster(raster.buffer_id()),
SceneImage::Texture { texture, minified } => ImageKey::Texture((**texture).clone(), *minified),
SceneImage::GeneratorTile(tile) => ImageKey::GeneratorTile(*tile),
};
if !self.textures.contains_key(&key) {
@@ -415,23 +474,13 @@ impl ImageTextures {
let (pixels, width, height) = raster.to_flat_u8();
upload_pixels(device, queue, &pixels, width, height, peniko::ImageAlphaType::Alpha, max_texture_size)?
}
SceneImage::Texture { texture, minified } => {
let level_count = if *minified { texture.width().max(texture.height()).ilog2() + 1 } else { 1 };
device.create_texture(&wgpu::TextureDescriptor {
label: Some("vello_gpu_premultiplied_image"),
size: texture.size(),
mip_level_count: level_count,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: TEXTURE_FORMAT,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT,
view_formats: &[],
})
}
SceneImage::Texture { texture, minified } => premultiplied_image_texture(device, texture, *minified),
// Kept since it was drawn, so there's nothing to supply if it couldn't be made
SceneImage::GeneratorTile(_) => return None,
};
let raster = match image {
SceneImage::Raster(raster) => Some(raster.downgrade()),
SceneImage::Pixels(_) | SceneImage::Texture { .. } => None,
SceneImage::Pixels(_) | SceneImage::Texture { .. } | SceneImage::GeneratorTile(_) => None,
};
self.textures.insert(key.clone(), ImageTexture { texture, last_used: 0, raster });
}
@@ -441,22 +490,7 @@ impl ImageTextures {
let view = image_texture.texture.create_view(&wgpu::TextureViewDescriptor::default());
if let SceneImage::Texture { texture: source, .. } = image {
let level_view = |level: u32| {
image_texture.texture.create_view(&wgpu::TextureViewDescriptor {
base_mip_level: level,
mip_level_count: Some(1),
..Default::default()
})
};
let source_view = source.create_view(&wgpu::TextureViewDescriptor::default());
let loads_linear_light = source.format().is_srgb() || matches!(source.format(), crate::RASTER_FORMAT | crate::FALLBACK_RASTER_FORMAT);
alpha_conversion.premultiply(device, encoder, &source_view, loads_linear_light, &level_view(0));
// Each mipmap level halves the one before it, so a minified image averages its pixels rather than skipping over them
for level in 1..image_texture.texture.mip_level_count() {
alpha_conversion.halve(device, encoder, &level_view(level - 1), &level_view(level));
}
alpha_conversion.premultiply_with_mipmaps(device, encoder, source, &image_texture.texture);
}
Some(view)
@@ -470,9 +504,21 @@ impl ImageTextures {
// CPU pixels get a new blob ID at every render, so a blob this render didn't draw is unlikely to return
ImageKey::Blob(_) => unused_renders == 0,
ImageKey::Raster(_) => unused_renders == 0 || (unused_renders < UNUSED_IMAGE_RENDER_LIMIT && image_texture.raster.as_ref().is_some_and(WeakCPU::is_alive)),
ImageKey::Texture(..) => unused_renders < UNUSED_IMAGE_RENDER_LIMIT,
ImageKey::Texture(..) | ImageKey::GeneratorTile(_) => unused_renders < UNUSED_IMAGE_RENDER_LIMIT,
}
});
// Panning and zooming across a generator leaves tiles behind faster than they go unused for long, so the least recent beyond a limit are freed too
let mut tile_ages: Vec<u64> = (self.textures.iter())
.filter(|(key, _)| matches!(key, ImageKey::GeneratorTile(_)))
.map(|(_, image_texture)| image_texture.last_used)
.collect();
if tile_ages.len() > MAX_CACHED_GENERATOR_TILES {
let excess = tile_ages.len() - MAX_CACHED_GENERATOR_TILES;
let (_, &mut oldest_kept, _) = tile_ages.select_nth_unstable(excess);
self.textures
.retain(|key, image_texture| !matches!(key, ImageKey::GeneratorTile(_)) || image_texture.last_used >= oldest_kept);
}
}
}
@@ -837,6 +883,26 @@ impl AlphaConversion {
self.run(device, encoder, &self.premultiply_pipeline, parameters, source, target);
}
/// Fills `target` and each of its mipmap levels with the premultiplied pixels of the straight-alpha `source`.
fn premultiply_with_mipmaps(&self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, source: &wgpu::Texture, target: &wgpu::Texture) {
let level_view = |level: u32| {
target.create_view(&wgpu::TextureViewDescriptor {
base_mip_level: level,
mip_level_count: Some(1),
..Default::default()
})
};
let source_view = source.create_view(&wgpu::TextureViewDescriptor::default());
let loads_linear_light = source.format().is_srgb() || matches!(source.format(), crate::RASTER_FORMAT | crate::FALLBACK_RASTER_FORMAT);
self.premultiply(device, encoder, &source_view, loads_linear_light, &level_view(0));
// Each mipmap level halves the one before it, so a minified image averages its pixels rather than skipping over them
for level in 1..target.mip_level_count() {
self.halve(device, encoder, &level_view(level - 1), &level_view(level));
}
}
fn halve(&self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, source: &wgpu::TextureView, target: &wgpu::TextureView) {
self.run(device, encoder, &self.halve_pipeline, &self.linear_source_parameters, source, target);
}
@@ -1054,6 +1054,17 @@ fn effects_groups_carry_out_adjustments_like_their_kernels_map_colors() {
let mut worst = 0;
for (index, color) in colors.iter().enumerate() {
// A half-float raster rounds a color's gamma channels by up to about 0.0004, which can carry a luminance this close to a Threshold level across it
let [r, g, b, _] = color.to_gamma_srgb_channels();
let luminance = (4915. * r + 9667. * g + 1802. * b) / 16384.;
let near_level = |level: f64| (luminance as f64 - level / 100.).abs() < 0.001;
if run
.iter()
.any(|adjustment| matches!(adjustment, Adjustment::Threshold { min_luminance, max_luminance } if near_level(*min_luminance) || near_level(*max_luminance)))
{
continue;
}
let mapped = run.iter().fold(*color, |color, adjustment| adjust_color(adjustment, color));
let cpu = mapped.to_gamma_srgb_channels().map(|channel| (channel * 255.).round() as i32);
for channel in 0..3 {
@@ -1263,3 +1274,97 @@ fn images_reveal_the_colors_of_transparent_pixels_when_adjusted() {
}
}
}
/// A noise pattern with features a few units across.
fn noise_pattern() -> graphic_types::generator::GeneratorPattern {
use graphic_types::generator::*;
GeneratorPattern::Noise(NoiseSettings {
seed: 11,
scale: 6.,
noise_type: NoiseType::OpenSimplex2,
domain_warp_type: DomainWarpType::None,
domain_warp_amplitude: 0.,
fractal_type: FractalType::FBm,
fractal_octaves: 3,
fractal_lacunarity: 2.,
fractal_gain: 0.5,
fractal_weighted_strength: 0.,
fractal_ping_pong_strength: 2.,
cellular_distance_function: CellularDistanceFunction::Euclidean,
cellular_return_type: CellularReturnType::Nearest,
cellular_jitter: 1.,
})
}
#[test]
fn generators_draw_their_pattern_at_the_resolution_in_view() {
use crate::raster_kernel::render_generator;
use core_types::ops::ConvertAsync;
use core_types::transform::Footprint;
use graphic_types::raster_types::{CPU, Raster};
// Each unit of the pattern drawn across two pixels, so its tiles sample the pattern at every pixel's center
let size = UVec2::new(80, 80);
let pattern = noise_pattern();
let Some(pixels) = render(size, |scene| scene.draw_generator(&pattern, Affine::translate((8., 8.)) * Affine::scale(2.))) else {
return;
};
let executor = executor().unwrap();
let _turn = take_turn();
let kernel = render_generator(&pattern, [glam::DVec2::ZERO, glam::DVec2::splat(32.)], UVec2::splat(64), &executor.render_kernels()).unwrap();
let kernel: Raster<CPU> = futures::executor::block_on(kernel.convert(Footprint::DEFAULT, executor.clone()));
let (expected, _, _) = kernel.to_flat_u8();
let mut worst = 0;
for y in 0..64 {
for x in 0..64 {
let drawn = pixel(&pixels, size, x + 8, y + 8);
let sampled = &expected[((y * 64 + x) * 4) as usize..][..4];
worst = (0..3).map(|channel| drawn[channel].abs_diff(sampled[channel])).fold(worst, u8::max);
}
}
assert!(worst <= 2, "the drawn pattern differs from the kernel's own samples by up to {worst} levels");
// The pattern fills the plane, past the area compared
assert_eq!(pixel(&pixels, size, 2, 2)[3], 255);
assert_eq!(pixel(&pixels, size, 76, 76)[3], 255);
}
#[test]
fn generator_tiles_are_reused_across_a_pan() {
let Some(executor) = executor() else { return };
let _turn = take_turn();
let tiles = |canvas: &crate::VelloCanvas| {
canvas
.images
.textures
.values()
.map(|image_texture| image_texture.texture.clone())
.collect::<std::collections::HashSet<_>>()
};
// A pattern drawn two pixels to a unit, in tiles of 256 pixels, panned by part of a tile
let mut canvas = crate::VelloCanvas::default();
let pattern = noise_pattern();
let size = UVec2::splat(512);
let target = executor.request_texture(size);
let render = |canvas: &mut crate::VelloCanvas, offset: f64| {
let mut draw = |scene: &mut VelloSceneBuilder| scene.draw_generator(&pattern, Affine::translate((offset, 0.)) * Affine::scale(2.));
let context = executor.context();
(executor.inner.vello_renderer)
.render(canvas, &context.device, &context.queue, &executor.render_kernels(), &mut draw, Affine::IDENTITY, size, &target)
.unwrap();
};
render(&mut canvas, 0.);
let first = tiles(&canvas);
assert!(!first.is_empty(), "the view should draw tiles");
render(&mut canvas, 0.);
assert_eq!(tiles(&canvas), first, "drawing the same view again renders no tiles");
render(&mut canvas, -100.);
let panned = tiles(&canvas);
assert!(panned.is_superset(&first), "panning keeps the tiles it has rendered");
assert!(panned.len() < first.len() * 2, "panning renders only the tiles newly in view, not all {} again", first.len());
}
+4 -4
View File
@@ -1,8 +1,8 @@
use core_types::list::Item;
use core_types::{ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_OPACITY, ATTR_OPACITY_FILL, BlendMode, Color, Ctx};
use graphic_types::Graphic;
use graphic_types::Vector;
use graphic_types::raster_types::{CPU, GPU, Raster};
use graphic_types::{Generator, Graphic};
use vector_types::Gradient;
/// Applies the blend mode to the input graphics. Setting this allows for customizing how overlapping content is composited together.
@@ -10,7 +10,7 @@ use vector_types::Gradient;
fn blend_mode<T>(
_: impl Ctx,
/// The content that will be composited when rendering.
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String)]
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String, Generator)]
content: Item<T>,
/// The choice of equation that controls how brightness and color blends between overlapping pixels.
blend_mode: Item<BlendMode>,
@@ -29,7 +29,7 @@ fn blend_mode<T>(
fn opacity<T>(
_: impl Ctx,
/// The content that will be composited when rendering.
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String)]
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String, Generator)]
content: Item<T>,
/// Whether the *Opacity* property is enabled, multiplying the existing opacity by the chosen percentage.
#[widget(ParsedWidgetOverride::Hidden)]
@@ -76,7 +76,7 @@ fn opacity<T>(
fn clipping_mask<T>(
_: impl Ctx,
/// The content that will be composited when rendering.
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String)]
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String, Generator)]
content: Item<T>,
/// Whether the content inherits the alpha of the content beneath it.
clip: Item<bool>,
+5
View File
@@ -3,6 +3,7 @@ use core_types::transform::Footprint;
use core_types::{CacheHash, CloneVarArgs, Color, Context, Ctx, ExtractAll, ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime, Interrupt, OwnedContextImpl};
use glam::{DAffine2, DVec2};
use graphene_animation::AnimationCurve;
use graphic_types::Generator;
use graphic_types::vector_types::Gradient;
use graphic_types::{Artboard, Graphic, Vector};
use raster_types::{CPU, GPU, Raster};
@@ -89,6 +90,7 @@ fn step_real_time<T>(
Context -> Item<Raster<GPU>>,
Context -> Item<Color>,
Context -> Item<Gradient>,
Context -> Item<Generator>,
Context -> Item<Artboard>,
Context -> List<String>,
Context -> List<f64>,
@@ -99,6 +101,7 @@ fn step_real_time<T>(
Context -> List<Raster<GPU>>,
Context -> List<Color>,
Context -> List<Gradient>,
Context -> List<Generator>,
Context -> List<Artboard>,
)]
value: impl Node<Context<'static>, Output = T>,
@@ -135,6 +138,7 @@ fn step_animation_time<T>(
Context -> Item<Raster<GPU>>,
Context -> Item<Color>,
Context -> Item<Gradient>,
Context -> Item<Generator>,
Context -> Item<Artboard>,
Context -> List<String>,
Context -> List<f64>,
@@ -145,6 +149,7 @@ fn step_animation_time<T>(
Context -> List<Raster<GPU>>,
Context -> List<Color>,
Context -> List<Gradient>,
Context -> List<Generator>,
Context -> List<Artboard>,
)]
value: impl Node<Context<'static>, Output = T>,
@@ -5,6 +5,7 @@ use core_types::transform::Footprint;
use core_types::{Color, Interrupt, OwnedContextImpl};
use glam::{DAffine2, DVec2};
use graphene_animation::AnimationCurve;
use graphic_types::Generator;
use graphic_types::vector_types::Gradient;
use graphic_types::{Artboard, Graphic, Vector};
use raster_types::{CPU, GPU, Raster};
@@ -30,6 +31,7 @@ fn context_modification<T>(
Context -> Item<Color>,
Context -> Item<Artboard>,
Context -> Item<Gradient>,
Context -> Item<Generator>,
Context -> Item<NodeIdPath>,
Context -> Item<AttributeValueDyn>,
Context -> Item<AnimationCurve>,
@@ -43,6 +45,7 @@ fn context_modification<T>(
Context -> List<Color>,
Context -> List<Artboard>,
Context -> List<Gradient>,
Context -> List<Generator>,
Context -> List<AnimationCurve>,
Context -> ListDyn,
)]
+2
View File
@@ -2,6 +2,7 @@ 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, Interrupt, OwnedContextImpl};
use glam::{DAffine2, DVec2};
use graphic_types::Generator;
use graphic_types::graphic::{Graphic, IntoGraphicList};
use graphic_types::{Artboard, Vector};
use raster_types::{CPU, GPU, Raster};
@@ -20,6 +21,7 @@ fn create_artboard<T: IntoGraphicList>(
Context -> List<Raster<GPU>>,
Context -> List<Color>,
Context -> List<Gradient>,
Context -> List<Generator>,
Context -> Item<DAffine2>, // TODO: Remove this
)]
content: impl Node<Context<'static>, Output = T>,
+16 -3
View File
@@ -7,7 +7,7 @@ use core_types::{
};
use glam::{DAffine2, DVec2};
use graphic_types::graphic::{Graphic, IntoGraphicList, is_lone_anonymous_leaf};
use graphic_types::{Artboard, Vector};
use graphic_types::{Artboard, Generator, Vector};
use rand::SeedableRng;
use rand::seq::SliceRandom;
use raster_types::{CPU, GPU, Raster};
@@ -34,6 +34,7 @@ fn remove_at_index<T: graphic_types::graphic::OmitIndex + Clone + Default>(
List<Raster<GPU>>,
List<Color>,
List<Gradient>,
List<Generator>,
List<Artboard>,
)]
list: T,
@@ -68,6 +69,7 @@ fn item_at_index<T: Clone + Default + Send + Sync + 'static>(
List<Raster<GPU>>,
List<Color>,
List<Gradient>,
List<Generator>,
List<Artboard>,
)]
list: List<T>,
@@ -106,6 +108,7 @@ fn filter<T: Send + Sync + Clone + 'static>(
List<Raster<GPU>>,
List<Color>,
List<Gradient>,
List<Generator>,
List<Artboard>,
)]
list: List<T>,
@@ -139,6 +142,7 @@ fn reverse<T: Send + Sync + Clone + 'static>(
List<Raster<GPU>>,
List<Color>,
List<Gradient>,
List<Generator>,
List<Artboard>,
)]
list: List<T>,
@@ -164,6 +168,7 @@ fn shift<T: Send + Sync + Clone + 'static>(
List<Raster<GPU>>,
List<Color>,
List<Gradient>,
List<Generator>,
List<Artboard>,
)]
list: List<T>,
@@ -209,6 +214,7 @@ fn shuffle<T: Send + Sync + Clone + 'static>(
List<Raster<GPU>>,
List<Color>,
List<Gradient>,
List<Generator>,
List<Artboard>,
)]
list: List<T>,
@@ -281,6 +287,7 @@ fn slice<T: Send + Sync + Clone + 'static>(
List<Raster<GPU>>,
List<Color>,
List<Gradient>,
List<Generator>,
List<Artboard>,
)]
list: List<T>,
@@ -416,6 +423,7 @@ fn map<Item: AnyHash + Send + Sync + CacheHash + Clone>(
List<Raster<GPU>>,
List<Color>,
List<Gradient>,
List<Generator>,
List<Artboard>,
)]
content: List<Item>,
@@ -432,6 +440,7 @@ fn map<Item: AnyHash + Send + Sync + CacheHash + Clone>(
Context -> List<Raster<GPU>>,
Context -> List<Color>,
Context -> List<Gradient>,
Context -> List<Generator>,
Context -> List<Artboard>,
)]
mapped: impl Node<Context<'static>, Output = List<Item>>,
@@ -602,6 +611,7 @@ fn write_attribute<T: AnyHash + Clone + Send + Sync + CacheHash>(
List<Raster<GPU>>,
List<Color>,
List<Gradient>,
List<Generator>,
List<Artboard>,
List<BlendMode>,
List<GradientForm>,
@@ -915,6 +925,7 @@ fn extend<T: Send + Clone>(
List<Raster<GPU>>,
List<Color>,
List<Gradient>,
List<Generator>,
List<Artboard>,
List<Stroke>,
)]
@@ -934,6 +945,7 @@ fn extend<T: Send + Clone>(
List<Raster<GPU>>,
List<Color>,
List<Gradient>,
List<Generator>,
List<Artboard>,
List<Stroke>,
)]
@@ -951,9 +963,9 @@ fn extend<T: Send + Clone>(
#[node_macro::node(category(""))]
fn legacy_layer_extend<T: Send + Clone>(
_: impl Ctx,
#[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<String>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<Gradient>)] base: List<T>,
#[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<String>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<Gradient>, List<Generator>)] base: List<T>,
#[expose]
#[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<String>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<Gradient>)]
#[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<String>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<Gradient>, List<Generator>)]
new: List<T>,
nested_node_path: Item<NodeIdPath>,
) -> List<T> {
@@ -985,6 +997,7 @@ fn into_group<T: Into<Graphic>>(
List<Raster<GPU>>,
List<Color>,
List<Gradient>,
List<Generator>,
List<String>,
List<DVec2>,
Item<DAffine2>, // TODO: Remove this
+4
View File
@@ -60,6 +60,10 @@ pub mod gradient {
pub use vector_types::{Gradient, GradientStop};
}
pub mod generator {
pub use graphic_types::generator::*;
}
pub mod transform {
pub use core_types::transform::*;
pub use vector_types::ReferencePoint;
+2
View File
@@ -5,6 +5,7 @@ use core_types::{CloneVarArgs, ExtractAll, ExtractVarArgs};
use core_types::{Color, Context, Ctx, ExtractFootprint, Interrupt, NodeError, OwnedContextImpl, WasmNotSend};
use graph_craft::document::value::{RenderOutput, RenderOutputType};
use graphene_application_io::{ExportFormat, RenderConfig};
use graphic_types::Generator;
use graphic_types::raster_types::{CPU, GPU, Raster, Texture};
use graphic_types::{Artboard, Graphic, Vector};
use rendering::vello_scene_builder::VelloSceneBuilder;
@@ -34,6 +35,7 @@ fn render_intermediate<T: 'static + Render + WasmNotSend + Send + Sync>(
Context -> List<Raster<GPU>>,
Context -> List<Color>,
Context -> List<Gradient>,
Context -> List<Generator>,
Context -> List<String>,
)]
data: impl Node<Context<'static>, Output = T>,
+3 -1
View File
@@ -5,7 +5,7 @@ use core_types::{Color, Ctx, OwnedContextImpl, num_traits};
use core_types::{Context, Interrupt};
use glam::{DAffine2, DMat2, DVec2};
use graphic_types::raster_types::{CPU, GPU, Raster};
use graphic_types::{Artboard, Graphic, Vector};
use graphic_types::{Artboard, Generator, Graphic, Vector};
use math_parser::ast;
use math_parser::context::{EvalContext, NothingMap, ValueProvider};
use math_parser::executer::EvalError;
@@ -1613,6 +1613,7 @@ fn switch<T: Send>(
Context -> Item<Raster<GPU>>,
Context -> Item<Color>,
Context -> Item<Gradient>,
Context -> Item<Generator>,
Context -> Item<Artboard>,
Context -> Item<Bundle<String>>,
Context -> Item<Bundle<bool>>,
@@ -1643,6 +1644,7 @@ fn switch<T: Send>(
Context -> Item<Raster<GPU>>,
Context -> Item<Color>,
Context -> Item<Gradient>,
Context -> Item<Generator>,
Context -> Item<Artboard>,
Context -> Item<Bundle<String>>,
Context -> Item<Bundle<bool>>,
+3 -3
View File
@@ -281,9 +281,9 @@ fn flatten_vector(graphic_list: &List<Graphic>) -> Result<List<Vector>, BooleanO
boolean_operation_on_vector_list(&flattened, BooleanOperation::Union)?.into_iter().collect::<Vec<_>>()
}
}
// Rasters, colors, and gradients bound no region, so they contribute no operand
Graphic::None(_) | Graphic::NoneList(_) | Graphic::RasterCPU(_) | Graphic::RasterGPU(_) | Graphic::Color(_) | Graphic::Gradient(_) => Vec::new(),
Graphic::RasterCPUList(_) | Graphic::RasterGPUList(_) | Graphic::ColorList(_) | Graphic::GradientList(_) => Vec::new(),
// Rasters, colors, gradients, and generators bound no region, so they contribute no operand
Graphic::None(_) | Graphic::NoneList(_) | Graphic::RasterCPU(_) | Graphic::RasterGPU(_) | Graphic::Color(_) | Graphic::Gradient(_) | Graphic::Generator(_) => Vec::new(),
Graphic::RasterCPUList(_) | Graphic::RasterGPUList(_) | Graphic::ColorList(_) | Graphic::GradientList(_) | Graphic::GeneratorList(_) => Vec::new(),
// Strokes have no vector outline representation; a brush node renders them to rasters
Graphic::StrokeList(_) => Vec::new(),
// Normalized to GraphicList above
+20 -20
View File
@@ -17,7 +17,7 @@ use graphic_types::adjustment::{
};
pub use graphic_types::adjustment::{DesaturateMethod, RelativeAbsolute, SelectiveColorChoice};
pub use graphic_types::generator::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, NoiseType};
use graphic_types::{Graphic, Vector};
use graphic_types::{Generator, Graphic, Vector};
use num_enum::{FromPrimitive, IntoPrimitive};
use raster_kernels::color_lookup_table::parse_cached;
use raster_types::{CPU, GPU, Raster};
@@ -32,7 +32,7 @@ fn adjust<T: ApplyEffect>(item: Item<T>, adjustment: Adjustment, pipeline: Item<
#[node_macro::node(category("Raster: Adjustment"), icon("NodeDesaturate"))]
fn desaturate<T: ApplyEffect>(
_: impl Ctx,
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] input: Item<T>,
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] input: Item<T>,
method: Item<DesaturateMethod>,
#[scope(raster_kernel_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>,
) -> Result<Item<T>, Interrupt> {
@@ -42,7 +42,7 @@ fn desaturate<T: ApplyEffect>(
#[node_macro::node(category("Raster: Adjustment"), icon("NodeGammaCorrection"))]
fn gamma_correction<T: ApplyEffect>(
_: impl Ctx,
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] input: Item<T>,
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] input: Item<T>,
#[default(2.2)]
#[range]
#[hard(0.0001..)]
@@ -116,7 +116,7 @@ impl MapColor for ExtractChannel {
#[node_macro::node(category("Raster: Adjustment"), icon("NodeMakeOpaque"))]
fn make_opaque<T: ApplyEffect>(
_: impl Ctx,
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] input: Item<T>,
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] input: Item<T>,
#[scope(raster_kernel_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>,
) -> Result<Item<T>, Interrupt> {
adjust(input, Adjustment::MakeOpaque, pipeline)
@@ -133,7 +133,7 @@ fn make_opaque<T: ApplyEffect>(
#[node_macro::node(name("Brightness/Contrast"), category("Raster: Adjustment"), icon("NodeBrightnessContrast"), inspector("brightness_contrast_inspector"))]
fn brightness_contrast<T: ApplyEffect>(
_: impl Ctx,
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] input: Item<T>,
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] input: Item<T>,
#[unit("%")]
#[range]
#[hard(-150..150)]
@@ -186,7 +186,7 @@ pub enum AdjustmentChannel {
#[node_macro::node(category("Raster: Adjustment"), icon("NodeLevels"), inspector("levels_inspector"))]
fn levels<T: ApplyEffect>(
_: impl Ctx,
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] image: Item<T>,
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] image: Item<T>,
#[unit("%")]
#[range]
#[hard(0..100)]
@@ -359,7 +359,7 @@ fn levels<T: ApplyEffect>(
#[node_macro::node(category("Raster: Adjustment"), icon("NodeCurves"), inspector("transfer_curves_inspector"))]
fn curves<T: ApplyEffect>(
_: impl Ctx,
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] image: Item<T>,
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] image: Item<T>,
curve: Item<TransferCurve>,
#[name("(Red) Curve")] red_curve: Item<TransferCurve>,
#[name("(Green) Curve")] green_curve: Item<TransferCurve>,
@@ -407,7 +407,7 @@ fn points_to_transfer_curve(
#[node_macro::node(name("Black & White"), category("Raster: Adjustment"), icon("NodeBlackAndWhite"), inspector("black_and_white_inspector"))]
fn black_and_white<T: ApplyEffect>(
_: impl Ctx,
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] image: Item<T>,
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] image: Item<T>,
use_tint: Item<bool>,
#[default("#e1d3b3")] tint: Item<Color>,
#[unit("%")]
@@ -481,7 +481,7 @@ pub enum HueSaturationRange {
#[node_macro::node(name("Hue/Saturation"), category("Raster: Adjustment"), icon("NodeHueSaturation"), inspector("hue_saturation_inspector"))]
fn hue_saturation<T: ApplyEffect>(
_: impl Ctx,
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] input: Item<T>,
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] input: Item<T>,
#[unit("°")]
#[range]
#[soft(-180..180)]
@@ -818,7 +818,7 @@ fn hue_saturation<T: ApplyEffect>(
#[node_macro::node(category("Raster: Adjustment"), icon("NodeInvert"))]
fn invert<T: ApplyEffect>(
_: impl Ctx,
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] input: Item<T>,
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] input: Item<T>,
#[scope(raster_kernel_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>,
) -> Result<Item<T>, Interrupt> {
adjust(input, Adjustment::Invert, pipeline)
@@ -829,7 +829,7 @@ fn invert<T: ApplyEffect>(
#[node_macro::node(category("Raster: Adjustment"), icon("NodeThreshold"), inspector("threshold_inspector"))]
fn threshold<T: ApplyEffect>(
_: impl Ctx,
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] image: Item<T>,
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] image: Item<T>,
#[unit("%")]
#[range]
#[hard(0..100)]
@@ -868,7 +868,7 @@ fn threshold<T: ApplyEffect>(
#[node_macro::node(category("Raster: Adjustment"), icon("NodeGradientMap"))]
fn gradient_map<T: ApplyEffect>(
_: impl Ctx,
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] image: Item<T>,
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] image: Item<T>,
#[default(Color::BLACK, Color::WHITE)] gradient: Item<Gradient>,
reverse: Item<bool>,
#[scope(raster_kernel_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>,
@@ -889,7 +889,7 @@ fn gradient_map<T: ApplyEffect>(
#[node_macro::node(category("Raster: Adjustment"), icon("NodeVibrance"), inspector("vibrance_inspector"))]
fn vibrance<T: ApplyEffect>(
_: impl Ctx,
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] image: Item<T>,
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] image: Item<T>,
#[unit("%")]
#[range]
#[hard(-100..100)]
@@ -943,7 +943,7 @@ pub enum RedGreenBlueAlpha {
#[node_macro::node(category("Raster: Adjustment"), icon("NodeChannelMixer"), inspector("channel_mixer_inspector"))]
fn channel_mixer<T: ApplyEffect>(
_: impl Ctx,
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] image: Item<T>,
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] image: Item<T>,
monochrome: Item<bool>,
@@ -1077,7 +1077,7 @@ fn channel_mixer<T: ApplyEffect>(
#[node_macro::node(category("Raster: Adjustment"), icon("NodeSelectiveColor"), inspector("selective_color_inspector"))]
fn selective_color<T: ApplyEffect>(
_: impl Ctx,
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] image: Item<T>,
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] image: Item<T>,
mode: Item<RelativeAbsolute>,
@@ -1300,7 +1300,7 @@ fn selective_color<T: ApplyEffect>(
#[node_macro::node(category("Raster: Adjustment"), icon("NodePosterize"))]
fn posterize<T: ApplyEffect>(
_: impl Ctx,
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] input: Item<T>,
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] input: Item<T>,
#[default(4)]
#[hard(2..)]
levels: Item<i64>,
@@ -1318,7 +1318,7 @@ fn posterize<T: ApplyEffect>(
#[node_macro::node(category("Raster: Adjustment"), icon("NodeExposure"), inspector("exposure_inspector"))]
fn exposure<T: ApplyEffect>(
_: impl Ctx,
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] input: Item<T>,
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] input: Item<T>,
#[range]
#[soft(-20..20)]
exposure: Item<f64>,
@@ -1364,7 +1364,7 @@ pub enum TonalRange {
#[node_macro::node(category("Raster: Adjustment"), icon("NodeColorBalance"), inspector("color_balance_inspector"))]
fn color_balance<T: ApplyEffect>(
_: impl Ctx,
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] image: Item<T>,
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] image: Item<T>,
#[name("(Shadows) Cyan-Red")]
#[unit("%")]
@@ -1441,7 +1441,7 @@ fn color_balance<T: ApplyEffect>(
#[node_macro::node(category("Raster: Adjustment"), icon("NodePhotoFilter"))]
fn photo_filter<T: ApplyEffect>(
_: impl Ctx,
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] image: Item<T>,
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] image: Item<T>,
#[default("#ec8a00")] color: Item<Color>,
#[unit("%")]
#[range]
@@ -1472,7 +1472,7 @@ fn photo_filter<T: ApplyEffect>(
fn color_lookup<T: ApplyEffect>(
_: impl Ctx,
/// The image whose colors are remapped by the LUT (lookup table).
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)]
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)]
image: Item<T>,
/// A LUT (lookup table) file in the `.cube`, `.3dl`, `.look`, `.csp`, or `.icc` (*abstract* or *device link* ICC profile) format.
#[name("LUT File")]
+11 -10
View File
@@ -4,7 +4,7 @@ use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_
use core_types::{ATTR_OPACITY_FILL, CacheHash, Color, Ctx, Interrupt, NodeError};
use glam::DVec2;
use graphic_types::raster_types::{CPU, GPU, Raster};
use graphic_types::{Adjustment, BevelDirection, BevelStyle, Effect, EffectOperation, Effects, GlowSource, Graphic, Vector, stamp_effect};
use graphic_types::{Adjustment, BevelDirection, BevelStyle, Effect, EffectOperation, Effects, Generator, GlowSource, Graphic, Vector, stamp_effect};
use raster_kernels::adjustments::{adjust_color, adjust_gradient, preserves_alpha};
use std::hash::{DefaultHasher, Hasher};
use std::sync::{Arc, Mutex, PoisonError};
@@ -33,6 +33,7 @@ impl ApplyEffect for Graphic {}
impl ApplyEffect for Vector {}
impl ApplyEffect for Raster<CPU> {}
impl ApplyEffect for String {}
impl ApplyEffect for Generator {}
/// A color has no pixels for an effect to read, so an adjustment is carried out on the color itself with its kernel's mapping.
impl ApplyEffect for Color {
@@ -85,7 +86,7 @@ fn apply_effect<T: ApplyEffect>(content: Item<T>, operation: EffectOperation, pi
fn blur<T: ApplyEffect>(
_: impl Ctx,
/// The content to blur.
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String)]
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String, Generator)]
content: Item<T>,
/// How far the blur spreads each point of the content.
#[unit(" px")]
@@ -115,7 +116,7 @@ fn blur<T: ApplyEffect>(
fn drop_shadow<T: ApplyEffect>(
_: impl Ctx,
/// The content casting the shadow.
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String)]
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String, Generator)]
content: Item<T>,
/// The shadow's color, with its opacity.
#[default("#00000080")]
@@ -154,7 +155,7 @@ fn drop_shadow<T: ApplyEffect>(
fn inner_shadow<T: ApplyEffect>(
_: impl Ctx,
/// The content the shadow falls inside.
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String)]
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String, Generator)]
content: Item<T>,
/// The shadow's color, with its opacity.
#[default("#00000080")]
@@ -193,7 +194,7 @@ fn inner_shadow<T: ApplyEffect>(
fn outer_glow<T: ApplyEffect>(
_: impl Ctx,
/// The content to glow around.
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String)]
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String, Generator)]
content: Item<T>,
/// The glow's color, with its opacity.
#[default("#ffffbebf")]
@@ -227,7 +228,7 @@ fn outer_glow<T: ApplyEffect>(
fn inner_glow<T: ApplyEffect>(
_: impl Ctx,
/// The content to glow within.
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String)]
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String, Generator)]
content: Item<T>,
/// The glow's color, with its opacity.
#[default("#ffffbebf")]
@@ -264,7 +265,7 @@ fn inner_glow<T: ApplyEffect>(
fn satin<T: ApplyEffect>(
_: impl Ctx,
/// The content to shade.
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String)]
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String, Generator)]
content: Item<T>,
/// The shading's color, with its opacity.
#[default("#00000080")]
@@ -302,7 +303,7 @@ fn satin<T: ApplyEffect>(
fn outline<T: ApplyEffect>(
_: impl Ctx,
/// The content to outline.
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String)]
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String, Generator)]
content: Item<T>,
/// The outline's color, with its opacity.
#[default(Color::BLACK)]
@@ -335,7 +336,7 @@ fn outline<T: ApplyEffect>(
fn bevel_and_emboss<T: ApplyEffect>(
_: impl Ctx,
/// The content to raise.
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String)]
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String, Generator)]
content: Item<T>,
/// Where the slope lies: inside the edge, outside it, across it, or across it with the edge pressed in.
style: Item<BevelStyle>,
@@ -403,7 +404,7 @@ fn bevel_and_emboss<T: ApplyEffect>(
fn paint_overlay<T: ApplyEffect>(
_: impl Ctx,
/// The content to paint over.
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String)]
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String, Generator)]
content: Item<T>,
/// The color, gradient, image, or other graphic to paint with. A gradient or image without its own placement stretches across the content.
#[default(Color::BLACK)]
+65 -1
View File
@@ -9,7 +9,7 @@ use core_types::transform::Transform;
use core_types::{Interrupt, NodeError};
use glam::{DAffine2, DVec2, UVec2};
use graphene_resource::Resource;
use graphic_types::generator::{GeneratorPattern, NoiseSettings};
use graphic_types::generator::{Generator, GeneratorPattern, NoiseSettings};
use raster_types::{CPU, GPU, Raster, Storage};
use raster_types::{Image, ImageError};
use wgpu_executor::WgpuPipelineCache;
@@ -309,6 +309,70 @@ fn noise_pattern(
Ok(Item::new_from_element(raster.with_coverage(logical_transform.inverse() * transform)).with_attribute(ATTR_TRANSFORM, logical_transform))
}
/// Generates a procedural noise pattern which fills the plane, drawn at the resolution the render needs.
#[node_macro::node(category("Raster"), icon("NodeNoisePattern"))]
#[allow(clippy::too_many_arguments)]
fn noise_pattern_generator(
_: impl Ctx,
_primary: (),
#[hard(0..)] seed: Item<i64>,
#[widget(ParsedWidgetOverride::Custom = "noise_inspector_scale")]
#[default(10.)]
scale: Item<f64>,
#[widget(ParsedWidgetOverride::Custom = "noise_inspector_noise_type")] noise_type: Item<NoiseType>,
#[widget(ParsedWidgetOverride::Custom = "noise_inspector_domain_warp_type")] domain_warp_type: Item<DomainWarpType>,
#[widget(ParsedWidgetOverride::Custom = "noise_inspector_domain_warp_amplitude")]
#[default(100.)]
domain_warp_amplitude: Item<f64>,
#[widget(ParsedWidgetOverride::Custom = "noise_inspector_fractal_type")] fractal_type: Item<FractalType>,
#[widget(ParsedWidgetOverride::Custom = "noise_inspector_fractal_octaves")]
#[default(3)]
#[hard(1..10)]
fractal_octaves: Item<i64>,
#[widget(ParsedWidgetOverride::Custom = "noise_inspector_fractal_lacunarity")]
#[default(2.)]
fractal_lacunarity: Item<f64>,
#[widget(ParsedWidgetOverride::Custom = "noise_inspector_fractal_gain")]
#[default(0.5)]
fractal_gain: Item<f64>,
#[widget(ParsedWidgetOverride::Custom = "noise_inspector_fractal_weighted_strength")] fractal_weighted_strength: Item<f64>,
#[widget(ParsedWidgetOverride::Custom = "noise_inspector_ping_pong_strength")]
#[default(2.)]
fractal_ping_pong_strength: Item<f64>,
#[widget(ParsedWidgetOverride::Custom = "noise_inspector_cellular_distance_function")] cellular_distance_function: Item<CellularDistanceFunction>,
#[widget(ParsedWidgetOverride::Custom = "noise_inspector_cellular_return_type")] cellular_return_type: Item<CellularReturnType>,
#[widget(ParsedWidgetOverride::Custom = "noise_inspector_cellular_jitter")]
#[default(1.)]
cellular_jitter: Item<f64>,
) -> Item<Generator> {
let settings = NoiseSettings {
seed: seed.into_element(),
scale: scale.into_element(),
noise_type: noise_type.into_element(),
domain_warp_type: domain_warp_type.into_element(),
domain_warp_amplitude: domain_warp_amplitude.into_element(),
fractal_type: fractal_type.into_element(),
fractal_octaves: fractal_octaves.into_element(),
fractal_lacunarity: fractal_lacunarity.into_element(),
fractal_gain: fractal_gain.into_element(),
fractal_weighted_strength: fractal_weighted_strength.into_element(),
fractal_ping_pong_strength: fractal_ping_pong_strength.into_element(),
cellular_distance_function: cellular_distance_function.into_element(),
cellular_return_type: cellular_return_type.into_element(),
cellular_jitter: cellular_jitter.into_element(),
};
let mut generator = Item::new_from_element(Generator::Noise);
settings.stamp(&mut generator);
generator
}
/// Generates the Mandelbrot set which fills the plane, drawn at the resolution the render needs.
#[node_macro::node(category("Raster"), icon("NodeMandelbrot"))]
fn mandelbrot_generator(_: impl Ctx, _primary: ()) -> Item<Generator> {
Item::new_from_element(Generator::Mandelbrot)
}
#[node_macro::node(category("Raster"), icon("NodeMandelbrot"))]
fn mandelbrot(ctx: impl ExtractFootprint + Send, #[scope(raster_kernel_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>) -> Result<Item<Raster<GPU>>, Interrupt> {
let footprint = ctx.footprint();
@@ -4,6 +4,7 @@ use core_types::list::{Item, List};
use core_types::transform::Footprint;
use core_types::{ATTR_TRANSFORM, CloneVarArgs, Color, Ctx, ExtractAll, InjectVarArgs, Interrupt, LazyInput, Node, OwnedContextImpl};
use glam::{DAffine2, DVec2};
use graphic_types::Generator;
use graphic_types::{Artboard, Graphic, Vector};
use raster_types::{CPU, GPU, Raster};
use vector_types::Gradient;
@@ -57,6 +58,7 @@ fn repeat<T: Send + Clone + 'static>(
Context -> List<Raster<GPU>>,
Context -> List<Color>,
Context -> List<Gradient>,
Context -> List<Generator>,
Context -> List<Artboard>,
)]
content: impl Node<Context<'static>, Output = List<T>>,
@@ -102,6 +104,7 @@ fn repeat_array<T: Send + Clone + 'static>(
Context -> List<Raster<GPU>>,
Context -> List<Color>,
Context -> List<Gradient>,
Context -> List<Generator>,
Context -> List<Artboard>,
)]
content: impl Node<Context<'static>, Output = List<T>>,
@@ -164,6 +167,7 @@ fn repeat_radial<T: Send + Clone + 'static>(
Context -> List<Raster<GPU>>,
Context -> List<Color>,
Context -> List<Gradient>,
Context -> List<Generator>,
Context -> List<Artboard>,
)]
content: impl Node<Context<'static>, Output = List<T>>,
@@ -224,6 +228,7 @@ fn repeat_on_points<T: Send + Clone + 'static>(
Context -> List<Raster<GPU>>,
Context -> List<Color>,
Context -> List<Gradient>,
Context -> List<Generator>,
Context -> List<Artboard>,
)]
content: impl Node<Context<'static>, Output = List<T>>,
@@ -5,7 +5,7 @@ use core_types::transform::{ApplyTransform, ScaleType, Transform};
use core_types::{ATTR_TRANSFORM, CloneVarArgs, Context, Ctx, ExtractAll, Interrupt, LazyInput, ModifyFootprint, Node, OwnedContextImpl};
use glam::{DAffine2, DMat2, DVec2};
use graphic_types::raster_types::{CPU, GPU, Raster};
use graphic_types::{Artboard, Graphic, Vector};
use graphic_types::{Artboard, Generator, Graphic, Vector};
use vector_types::Gradient;
/// Applies the specified transform to the input content.
@@ -22,6 +22,7 @@ fn transform<T: Send + 'static>(
Context -> Item<Raster<GPU>>,
Context -> Item<Color>,
Context -> Item<Gradient>,
Context -> Item<Generator>,
)]
content: impl Node<Context<'static>, Output = Item<T>>,
#[widget(ParsedWidgetOverride::Custom = "transform_translation")] translation: Item<DVec2>,
@@ -182,7 +183,7 @@ fn replaced_transform_context<T, N: Node<Context<'static>, Output = Item<T>>>(
/// Obtains the transform of the input content.
#[node_macro::node(category("Transform"), icon("NodeExtractTransform"), path(core_types::vector))]
fn extract_transform<T: Send>(_: impl Ctx, #[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String, Artboard)] content: Item<T>) -> Item<DAffine2> {
fn extract_transform<T: Send>(_: impl Ctx, #[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, Generator, String, Artboard)] content: Item<T>) -> Item<DAffine2> {
Item::new_from_element(content.attribute_cloned_or_default(ATTR_TRANSFORM))
}
+2 -1
View File
@@ -17,7 +17,7 @@ use glam::{DAffine2, DMat2, DVec2};
use graphic_types::Vector;
use graphic_types::graphic::{bake_paint_transforms, is_paint_present};
use graphic_types::raster_types::{CPU, GPU, Raster};
use graphic_types::{Appearance, Cover, CoverPlacement, Coverage, Graphic, IntoGraphicList, stamp_coverage};
use graphic_types::{Appearance, Cover, CoverPlacement, Coverage, Generator, Graphic, IntoGraphicList, stamp_coverage};
use kurbo::simplify::{SimplifyOptions, simplify_bezpath};
use kurbo::{Affine, BezPath, DEFAULT_ACCURACY, Line, ParamCurve, ParamCurveArclen, PathEl, PathSeg, Shape};
use rand::{Rng, SeedableRng};
@@ -557,6 +557,7 @@ fn copy_to_points<I: Send + Clone>(
Context -> List<Raster<GPU>>,
Context -> List<Color>,
Context -> List<Gradient>,
Context -> List<Generator>,
)]
content: impl Node<Context<'static>, Output = List<I>>,
/// Minimum range of randomized sizes given to each placed copy.
+65
View File
@@ -984,4 +984,69 @@ mod tests {
assert!(compile(median_filter::IDENTIFIER).is_empty(), "a node that isn't footprint invariant shouldn't warn");
}
#[test]
fn generator_nodes_compile_on_their_own_and_dont_reach_gpu_only_inputs() {
use graph_craft::application_io::PlatformEditorApi;
use graph_craft::document::value::TaggedValue;
use graph_craft::graphene_compiler::Compiler;
use graph_craft::proto::TypingContext;
use graphene_std::raster_nodes::filter::median_filter;
use graphene_std::raster_nodes::raster_kernel::raster_kernel_pipeline;
use graphene_std::raster_nodes::std_nodes::{mandelbrot_generator, noise_pattern_generator};
use graphene_std::runtime::{AsyncRuntime, Spawn, Task};
use interpreted_executor::util::wrap_network_in_scope;
use std::sync::Arc;
struct NoSpawner;
impl Spawn for NoSpawner {
fn spawn(&self, _: Task) {}
}
// Each generator's settings at their type's default, after the empty primary input
let generator_node = |identifier: &ProtoNodeIdentifier| {
let setting_types: Vec<Type> = {
let registry = core_types::registry::NODE_REGISTRY.lock().unwrap();
let (_, io) = registry[identifier].iter().next().unwrap();
io.inputs.iter().skip(1).map(|input| input.nested_type().clone()).collect()
};
let settings = setting_types.into_iter().map(|setting| NodeInput::value(TaggedValue::TypeDefault(setting), false));
DocumentNode {
inputs: std::iter::once(NodeInput::value(TaggedValue::None, false)).chain(settings).collect(),
implementation: DocumentNodeImplementation::ProtoNode(identifier.clone()),
..Default::default()
}
};
let compile = |nodes: Vec<(NodeId, DocumentNode)>, export: NodeId| {
let network = NodeNetwork {
exports: vec![NodeInput::node(export, 0)],
nodes: nodes.into_iter().collect(),
..Default::default()
};
let runtime = AsyncRuntime::new(Arc::new(NoSpawner), Arc::new(std::time::Instant::now()));
let mut network = wrap_network_in_scope(network, Arc::new(PlatformEditorApi::default()), runtime.handle());
Preprocessor::new().preprocess(&mut network, &|_| None).unwrap();
Compiler {}.compile_single(network).unwrap()
};
for identifier in [mandelbrot_generator::IDENTIFIER, noise_pattern_generator::IDENTIFIER] {
let compiled = compile(vec![(NodeId(0), generator_node(&identifier))], NodeId(0));
let mut typing_context = TypingContext::new(&interpreted_executor::node_registry::NODE_REGISTRY);
typing_context.update(&compiled.network).expect("a generator should compile on its own");
assert!(compiled.warnings.is_empty(), "{identifier:?} shouldn't warn: {:?}", compiled.warnings);
let median = DocumentNode {
inputs: vec![
NodeInput::node(NodeId(0), 0),
NodeInput::value(TaggedValue::Number(10.), false),
NodeInput::scope(raster_kernel_pipeline::IDENTIFIER),
],
implementation: DocumentNodeImplementation::ProtoNode(median_filter::IDENTIFIER),
..Default::default()
};
let compiled = compile(vec![(NodeId(0), generator_node(&identifier)), (NodeId(1), median)], NodeId(1));
let mut typing_context = TypingContext::new(&interpreted_executor::node_registry::NODE_REGISTRY);
assert!(typing_context.update(&compiled.network).is_err(), "{identifier:?} shouldn't reach a GPU-only input");
}
}
}