mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-05 19:12:08 -10:00
Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3f5ed7909d | ||
|
|
2cb2dd31fc | ||
|
|
86e6a9f08f | ||
|
|
dee8681459 | ||
|
|
239df7af7c | ||
|
|
86b16c3558 | ||
|
|
506c413cd0 | ||
|
|
dd996adbcb | ||
|
|
a1bb538b9d | ||
|
|
acd7726dee | ||
|
|
e30bf2e987 | ||
|
|
c8e8fbf8d1 | ||
|
|
9517b006fa | ||
|
|
cfb45f2d54 | ||
|
|
e27119b58b |
No files matched your search
@@ -150,20 +150,14 @@ jobs:
|
||||
run: cargo run build web${{ inputs.debug && ' debug' || '' }}
|
||||
|
||||
- name: 📤 Publish to Cloudflare Pages
|
||||
if: inputs.merge_queue == false
|
||||
if: inputs.merge_queue == false && !github.event.pull_request.head.repo.fork
|
||||
id: cloudflare
|
||||
continue-on-error: ${{ github.event_name != 'push' }}
|
||||
env:
|
||||
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
||||
# Passed through the environment so a branch name can't inject shell syntax
|
||||
HEAD_BRANCH: ${{ inputs.checkout_ref || github.head_ref || github.ref_name }}
|
||||
run: |
|
||||
if [ -z "$CLOUDFLARE_API_TOKEN" ]; then
|
||||
echo "No Cloudflare API token available (fork PR), skipping deploy."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [ "${{ github.event_name }}" = "push" ]; then
|
||||
DEPLOY_BRANCH="master"
|
||||
else
|
||||
|
||||
@@ -51,6 +51,8 @@ jobs:
|
||||
with:
|
||||
# Cache on Cargo.lock file
|
||||
cache-on-failure: true
|
||||
# Saved only by master pushes, since a PR's saved cache is readable only by that PR yet counts toward the repo's size limit
|
||||
save-if: ${{ github.event_name == 'push' }}
|
||||
|
||||
- name: Install gungraun-runner and valgrind
|
||||
uses: gungraun/setup-gungraun@62591572561bb2f4ed2ae300b8a8bea99ea8ddaf # v1.1.3
|
||||
|
||||
Generated
+1
@@ -6021,6 +6021,7 @@ dependencies = [
|
||||
"graphene-resource",
|
||||
"graphic-types",
|
||||
"kurbo",
|
||||
"linesweeper",
|
||||
"log",
|
||||
"num-traits",
|
||||
"parley",
|
||||
|
||||
@@ -878,6 +878,22 @@ pub struct SliderMarker {
|
||||
/// Whether this marker follows its neighbors instead of bounding them, so they may drag past its drawn position.
|
||||
#[serde(rename = "betweenNeighbors")]
|
||||
between_neighbors: bool,
|
||||
/// How this marker and the next may pass each other.
|
||||
#[serde(rename = "overlapNext")]
|
||||
overlap_next: MarkerOverlap,
|
||||
}
|
||||
|
||||
/// How a slider marker and the next may pass each other, as split handles whose ranges may overlap.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum MarkerOverlap {
|
||||
/// Neither may pass the other.
|
||||
#[default]
|
||||
Never,
|
||||
/// Each may pass the other but not the marker beyond it, so split handles' inner halves can overlap while the handles can't pass each other.
|
||||
NextOnly,
|
||||
/// The markers up to this one and those after it don't bound each other, so split handles can pass each other entirely.
|
||||
Freely,
|
||||
}
|
||||
|
||||
impl SliderMarker {
|
||||
@@ -890,6 +906,7 @@ impl SliderMarker {
|
||||
paired_with_next: false,
|
||||
dashed_to_next: false,
|
||||
between_neighbors: false,
|
||||
overlap_next: MarkerOverlap::Never,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -907,6 +924,11 @@ impl SliderMarker {
|
||||
self.dashed_to_next = true;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn overlap_next(mut self, overlap: MarkerOverlap) -> Self {
|
||||
self.overlap_next = overlap;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
|
||||
@@ -35,8 +35,8 @@ use graphene_std::vector::style::{
|
||||
};
|
||||
use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector};
|
||||
use graphene_std::{
|
||||
Appearance, Artboard, BevelDirection, BevelStyle, BevelTechnique, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource, GlowTechnique, Graphic,
|
||||
MaskMode, MinimumMaximumMode, NoiseDistribution,
|
||||
Appearance, Artboard, BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource,
|
||||
GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution,
|
||||
};
|
||||
use graphene_std::{DisplaceMode, RadialBlurMethod, WaveType};
|
||||
use kurbo::BezPath;
|
||||
@@ -1277,6 +1277,7 @@ impl_table_item_layout_for_choice_enum!(
|
||||
WarpStyle,
|
||||
WaveType,
|
||||
DisplaceMode,
|
||||
BlendIfChannel,
|
||||
EffectKind,
|
||||
Generator,
|
||||
GlowSource,
|
||||
@@ -1472,6 +1473,7 @@ macro_rules! known_item_types {
|
||||
WarpStyle,
|
||||
WaveType,
|
||||
DisplaceMode,
|
||||
BlendIfChannel,
|
||||
DashPattern,
|
||||
BoxCorners,
|
||||
TransferCurve,
|
||||
|
||||
@@ -5,16 +5,19 @@ use super::node_inspector::{self, ParameterWidgetsInfo, SliderRange};
|
||||
use super::utility_types::{FrontendNodeType, InputTypeConstraint};
|
||||
use crate::messages::frontend::IconName;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{NodeNetworkInterface, NodeTemplate, NodeTemplateImplementation};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{
|
||||
InputMetadata, NodeNetworkInterface, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, Vec2InputSettings, WidgetOverride,
|
||||
};
|
||||
use crate::messages::portfolio::ingest::utility_types::TypeFilter;
|
||||
use crate::messages::prelude::{DocumentId, FontsMessage, FontsMessageHandler, Message, ResourceMessageHandler, Responses};
|
||||
use crate::node_graph_executor::NodeGraphExecutor;
|
||||
use glam::DVec2;
|
||||
use graph_craft::ProtoNodeIdentifier;
|
||||
use graph_craft::concrete;
|
||||
use graph_craft::document::value::*;
|
||||
use graph_craft::document::*;
|
||||
use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, NoiseType};
|
||||
use graph_craft::{concrete, list};
|
||||
use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, Color, DomainWarpType, FractalType, NoiseType};
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::*;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
|
||||
@@ -37,11 +40,6 @@ impl NodeInspectorContext<'_> {
|
||||
let input_inspector_row = self.network_interface.persistent_input_metadata(node_id, index, self.selection_network_path)?;
|
||||
let widget_override = input_inspector_row.widget_override.clone()?;
|
||||
|
||||
// Older documents store number and Vec2 widget settings this way, but they come from the definition's parameter
|
||||
if matches!(widget_override.as_str(), "number" | "vec2") {
|
||||
return None;
|
||||
}
|
||||
|
||||
let Some(widget_override_lambda) = INPUT_OVERRIDES.get(&widget_override) else {
|
||||
log::error!("Could not get widget override '{widget_override}' lambda in call_widget_override");
|
||||
return None;
|
||||
@@ -53,11 +51,11 @@ impl NodeInspectorContext<'_> {
|
||||
}
|
||||
|
||||
/// Input position of the location parameter on the "Artboard" layer template, which follows the two layer-shaped inputs (stack and content) and maps through to the inner Create Artboard proto node.
|
||||
pub const ARTBOARD_LOCATION_INPUT_INDEX: usize = graphene_std::subgraphs::artboard::LocationInput::INDEX;
|
||||
pub const ARTBOARD_LOCATION_INPUT_INDEX: usize = 2;
|
||||
/// Input position of the dimensions parameter on the "Artboard" layer template, which follows the two layer-shaped inputs (stack and content) and maps through to the inner Create Artboard proto node.
|
||||
pub const ARTBOARD_DIMENSIONS_INPUT_INDEX: usize = graphene_std::subgraphs::artboard::DimensionsInput::INDEX;
|
||||
pub const ARTBOARD_DIMENSIONS_INPUT_INDEX: usize = 3;
|
||||
/// Input position of the control path parameter on the "Blend" network node template.
|
||||
pub const BLEND_PATH_INPUT_INDEX: usize = graphene_std::subgraphs::blend::PathInput::INDEX;
|
||||
pub const BLEND_PATH_INPUT_INDEX: usize = 4;
|
||||
|
||||
/// The key used to access definitions for a network node or proto node.
|
||||
/// For proto nodes, this is their [`ProtoNodeIdentifier`].
|
||||
@@ -109,7 +107,8 @@ pub struct DocumentNodeDefinition {
|
||||
/// Used to create the [`DefinitionIdentifier::Network`] identifier.
|
||||
pub identifier: &'static str,
|
||||
|
||||
/// The definition's position in its lineage, from `version(N)` on its `#[node]` or `#[graph]`. Instances store it next to their reference.
|
||||
/// The definition's position in its lineage. Bump it, with a `network` migration, when a change would load existing instances wrongly.
|
||||
/// Instances store it next to their reference. Proto-node definitions take theirs from the node macro.
|
||||
pub version: u32,
|
||||
|
||||
/// The default [`NodeTemplate`] this definition instantiates.
|
||||
@@ -137,9 +136,529 @@ static DOCUMENT_NODE_TYPES: once_cell::sync::Lazy<HashMap<DefinitionIdentifier,
|
||||
|
||||
/// Defines the "signature" or "header file"-like metadata for the document nodes, but not the implementation (which is defined in the node registry).
|
||||
/// The [`DocumentNode`] is the instance while these [`DocumentNodeDefinition`]s are the "classes" or "blueprints" from which the instances are built.
|
||||
/// A proto node within a definition takes its input and output metadata from the node macro in NODE_METADATA, and its display name too unless the definition gives one.
|
||||
/// Only the position can be set for protonodes within a definition. The rest of the metadata comes from the node macro in NODE_METADATA
|
||||
fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
|
||||
document_node_derive::derive_definitions()
|
||||
let custom = vec![
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Merge",
|
||||
version: 1,
|
||||
category: "Graphic",
|
||||
icon: Some("NodeMerge"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(2), 0)],
|
||||
nodes: [
|
||||
// Primary (bottom) input type coercion
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::import(generic!(T), 0)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::as_graphic::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -2)),
|
||||
..Default::default()
|
||||
},
|
||||
// Secondary (left) input type coercion
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::import(generic!(T), 1)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::into_group::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -1)),
|
||||
..Default::default()
|
||||
},
|
||||
NodeTemplate {
|
||||
call_argument: generic!(T),
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::node(NodeId(1), 0)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::extend::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -2)),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![NodeInput::type_default(list!(Graphic), true), NodeInput::type_default(list!(Graphic), true)],
|
||||
input_metadata: vec![
|
||||
("Base", "The stack of layers below this one, which the content is placed above.").into(),
|
||||
("Content", "The artwork this layer adds to the stack as a single item.").into(),
|
||||
],
|
||||
output_names: vec!["Out".to_string()],
|
||||
output_descriptions: vec!["The stack of layers with this layer's content placed on top.".to_string()],
|
||||
node_type_metadata: NodeTypePersistentMetadata::layer(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("Merges the provided content as a new item in the layer's compositing stack."),
|
||||
inspector: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Artboard",
|
||||
version: 1,
|
||||
category: "Graphic",
|
||||
icon: Some("NodeArtboard"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [
|
||||
NodeTemplate {
|
||||
call_argument: generic!(T),
|
||||
implementation: NodeTemplateImplementation::ProtoNode(artboard::create_artboard::IDENTIFIER),
|
||||
inputs: vec![
|
||||
NodeInput::import(Type::Fn(concrete!(Context).into(), generic!(T).into()), 1),
|
||||
NodeInput::import(item!(TaggedValue), 2),
|
||||
NodeInput::import(item!(TaggedValue), 3),
|
||||
NodeInput::import(item!(TaggedValue), 4),
|
||||
NodeInput::import(item!(TaggedValue), 5),
|
||||
],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -3)),
|
||||
..Default::default()
|
||||
},
|
||||
NodeTemplate {
|
||||
inputs: vec![
|
||||
NodeInput::import(graphene_std::Type::Fn(Box::new(concrete!(Context)), Box::new(list!(Artboard))), 0),
|
||||
NodeInput::node(NodeId(0), 0),
|
||||
],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::extend::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -4)),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![
|
||||
NodeInput::type_default(list!(Artboard), true),
|
||||
NodeInput::type_default(list!(Graphic), true),
|
||||
NodeInput::value(TaggedValue::DVec2(DVec2::ZERO), false),
|
||||
NodeInput::value(TaggedValue::DVec2(DVec2::new(1920., 1080.)), false),
|
||||
NodeInput::value(TaggedValue::Color(Color::WHITE), false),
|
||||
NodeInput::value(TaggedValue::Bool(true), false),
|
||||
],
|
||||
input_metadata: vec![
|
||||
("Base", "The stack of artboards below this one, which this artboard is placed above.").into(),
|
||||
("Content", "Graphics to include within the artboard.").into(),
|
||||
InputMetadata::with_name_description_override(
|
||||
"Location",
|
||||
"Coordinate of the top-left corner of the artboard within the document.",
|
||||
WidgetOverride::Vec2(Vec2InputSettings {
|
||||
x: "X".to_string(),
|
||||
y: "Y".to_string(),
|
||||
unit: " px".to_string(),
|
||||
is_integer: true,
|
||||
..Default::default()
|
||||
}),
|
||||
),
|
||||
InputMetadata::with_name_description_override(
|
||||
"Dimensions",
|
||||
"Width and height of the artboard within the document.",
|
||||
WidgetOverride::Vec2(Vec2InputSettings {
|
||||
x: "W".to_string(),
|
||||
y: "H".to_string(),
|
||||
unit: " px".to_string(),
|
||||
is_integer: true,
|
||||
..Default::default()
|
||||
}),
|
||||
),
|
||||
InputMetadata::with_name_description_override("Background", "Color of the artboard background.", WidgetOverride::Custom("artboard_background".to_string())),
|
||||
("Clip", "Whether to cut off the contained content that extends outside the artboard, or keep it visible.").into(),
|
||||
],
|
||||
output_names: vec!["Out".to_string()],
|
||||
output_descriptions: vec!["The stack of artboards with this artboard placed on top.".to_string()],
|
||||
node_type_metadata: NodeTypePersistentMetadata::layer(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("Creates a new Artboard which can be used as a working surface."),
|
||||
inspector: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Blend",
|
||||
version: 1,
|
||||
category: "Vector: Deform",
|
||||
icon: Some("NodeBlend"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(16), 0)],
|
||||
nodes: [
|
||||
// 0: Separate Paths (split the vector into its individual paths)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::separate_paths::IDENTIFIER),
|
||||
inputs: vec![NodeInput::import(generic!(T), 4)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// 1: Count (number of subpaths)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::count::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 2)),
|
||||
..Default::default()
|
||||
},
|
||||
// 2: Max (clamp subpath count to at least 1 for empty path case)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(1), 0), NodeInput::value(TaggedValue::Number(1.), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(9, 2)),
|
||||
..Default::default()
|
||||
},
|
||||
// 3: As Number (the integer count enters the network's decimal math)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER),
|
||||
inputs: vec![NodeInput::import(item!(i64), 1)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 13)),
|
||||
..Default::default()
|
||||
},
|
||||
// 4: Multiply (total_instances = count × subpath_count)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::multiply::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(17), 0), NodeInput::node(NodeId(2), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 1)),
|
||||
..Default::default()
|
||||
},
|
||||
// 5: Subtract (count - 1, open subpath denominator)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::subtract::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(17), 0), NodeInput::value(TaggedValue::Number(1.), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 14)),
|
||||
..Default::default()
|
||||
},
|
||||
// 6: Read Index (current repetition index)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(context::read_index::IDENTIFIER),
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::Integer(0), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 7)),
|
||||
..Default::default()
|
||||
},
|
||||
// 7: Divide (index / count)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::divide::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(6), 0), NodeInput::node(NodeId(17), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 10)),
|
||||
..Default::default()
|
||||
},
|
||||
// 8: Floor (floor(index / count) = subpath index)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::floor::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(7), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 4)),
|
||||
..Default::default()
|
||||
},
|
||||
// 9: Modulo (index % count = local index within subpath)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::modulo::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(6), 0), NodeInput::node(NodeId(17), 0), NodeInput::value(TaggedValue::Bool(true), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 7)),
|
||||
..Default::default()
|
||||
},
|
||||
// 10: Path Is Closed (check if current subpath is closed)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::path_is_closed::IDENTIFIER),
|
||||
inputs: vec![NodeInput::import(generic!(T), 4), NodeInput::node(NodeId(8), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 2)),
|
||||
..Default::default()
|
||||
},
|
||||
// 11: Switch (closed → count, open → max(count - 1, 1) as denominator)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::switch::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(10), 0), NodeInput::node(NodeId(17), 0), NodeInput::node(NodeId(18), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 12)),
|
||||
..Default::default()
|
||||
},
|
||||
// 12: Divide (local_index / denominator = within-subpath fraction)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::divide::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(9), 0), NodeInput::node(NodeId(11), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 7)),
|
||||
..Default::default()
|
||||
},
|
||||
// 13: Multiply (fraction × 0.9999999999 to avoid overflowing to the next subpath)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::multiply::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(12), 0), NodeInput::value(TaggedValue::Number(0.9999999999), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 7)),
|
||||
..Default::default()
|
||||
},
|
||||
// 14: Add (subpath_index + clamped fraction = progression)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::add::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(8), 0), NodeInput::node(NodeId(13), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(37, 4)),
|
||||
..Default::default()
|
||||
},
|
||||
// 15: Morph (content, progression, reverse, distribution, path)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::morph::IDENTIFIER),
|
||||
inputs: vec![
|
||||
NodeInput::import(generic!(T), 0),
|
||||
NodeInput::node(NodeId(14), 0),
|
||||
NodeInput::value(TaggedValue::Bool(false), false),
|
||||
NodeInput::import(item!(vector::misc::InterpolationDistribution), 3),
|
||||
NodeInput::import(item!(Vector), 4),
|
||||
],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(44, 3)),
|
||||
..Default::default()
|
||||
},
|
||||
// 16: Repeat
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(repeat_nodes::repeat::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(15), 0), NodeInput::node(NodeId(4), 0), NodeInput::import(generic!(T), 2)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(51, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// 17: Max (clamp count to at least 1)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(3), 0), NodeInput::value(TaggedValue::Number(1.), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(9, 13)),
|
||||
..Default::default()
|
||||
},
|
||||
// 18: Max (clamp open-path denominator to at least 1 to avoid division by zero when count = 1)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(5), 0), NodeInput::value(TaggedValue::Number(1.), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 14)),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![
|
||||
NodeInput::type_default(list!(Vector), true),
|
||||
NodeInput::value(TaggedValue::Integer(10), false),
|
||||
NodeInput::value(TaggedValue::Bool(Default::default()), false),
|
||||
NodeInput::value(TaggedValue::InterpolationDistribution(Default::default()), false),
|
||||
NodeInput::type_default(item!(Vector), false),
|
||||
],
|
||||
input_metadata: vec![
|
||||
("Content", "The vector objects to create intermediate shapes between.").into(),
|
||||
(
|
||||
"Count",
|
||||
"The number of shapes spanning from the first object to the last, repeated for each subpath of the control path.",
|
||||
)
|
||||
.into(),
|
||||
("Reverse", "Flip the stacking order of the shapes, so the ones nearest the first object are on top.").into(),
|
||||
("Distribution", "What changes evenly from one shape to the next, which sets how the intermediate shapes are spaced.").into(),
|
||||
(
|
||||
"Path",
|
||||
"An optional control path with one anchor point per object. Curved segments shape the trajectory of the blend instead of traveling straight.",
|
||||
)
|
||||
.into(),
|
||||
],
|
||||
output_names: vec!["Out".to_string()],
|
||||
output_descriptions: vec!["The blended shapes, from the first object to the last.".to_string()],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("Creates a series of intermediate shapes that gradually transition between vector objects, optionally along a control path."),
|
||||
inspector: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Origins to Polyline",
|
||||
version: 1,
|
||||
category: "Vector: Path",
|
||||
icon: Some("NodeOriginsToPolyline"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(7), 0)],
|
||||
nodes: [
|
||||
// 0: Read Vector
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(context::read_vector::IDENTIFIER),
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 1)),
|
||||
..Default::default()
|
||||
},
|
||||
// 1: Extract Transform
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(transform_nodes::extract_transform::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 1)),
|
||||
..Default::default()
|
||||
},
|
||||
// 2: Decompose Translation
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(transform_nodes::decompose_translation::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(1), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(14, 1)),
|
||||
..Default::default()
|
||||
},
|
||||
// 3: As Vector (auto-converts the decomposed translation into a single-anchor List<Vector>)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::as_vector::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(2), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(21, 1)),
|
||||
..Default::default()
|
||||
},
|
||||
// 4: Flatten Vector
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic_nodes::graphic::flatten_vector::IDENTIFIER),
|
||||
inputs: vec![NodeInput::import(generic!(T), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(21, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// 5: Map
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::map::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(4), 0), NodeInput::node(NodeId(3), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(28, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// 6: Combine Paths
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::combine_paths::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(5), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(35, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// 7: Points to Polyline
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::points_to_polyline::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(6), 0), NodeInput::value(TaggedValue::Bool(false), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(42, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![NodeInput::type_default(list!(Vector), true)],
|
||||
input_metadata: vec![("Vector", "The vector objects to connect in order by their origins.").into()],
|
||||
output_names: vec!["Vector".to_string()],
|
||||
output_descriptions: vec!["An open polyline with an anchor point at the origin of each object.".to_string()],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("Connects the origins of vector objects in order with an open polyline, such as to make a control path for the **Blend** and **Morph** nodes."),
|
||||
inspector: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Load Image",
|
||||
version: 1,
|
||||
category: "Data: I/O",
|
||||
icon: Some("NodeLoadImage"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::import(item!(String), 1)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(platform_application_io::load_resource::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(platform_application_io::bytes_to_image::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::String(String::new()), false)],
|
||||
input_metadata: vec![
|
||||
("Empty", "Has no effect, since the image is loaded from the URL.").into(),
|
||||
("URL", "The web address or local asset path of the image to load.").into(),
|
||||
],
|
||||
output_names: vec!["Image".to_string()],
|
||||
output_descriptions: vec!["The loaded image.".to_string()],
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("Loads an image from a given URL."),
|
||||
inspector: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Regex Find",
|
||||
version: 1,
|
||||
category: "String: Regex",
|
||||
icon: Some("NodeRegexFind"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![
|
||||
// Primary output: the whole match (String)
|
||||
NodeInput::node(NodeId(1), 0),
|
||||
// Secondary output: capture groups (List<String>), each item carries `start`/`end`/`name` attributes from `regex_find`
|
||||
NodeInput::node(NodeId(2), 0),
|
||||
],
|
||||
nodes: [
|
||||
// Node 0: regex_find proto node — returns List<String> of [whole_match, ...capture_groups]
|
||||
NodeTemplate {
|
||||
inputs: vec![
|
||||
NodeInput::import(item!(String), 0),
|
||||
NodeInput::import(item!(String), 1),
|
||||
NodeInput::import(item!(i64), 2),
|
||||
NodeInput::import(item!(bool), 3),
|
||||
NodeInput::import(item!(bool), 4),
|
||||
],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(text_nodes::regex::regex_find::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// Node 1: item_at_index at index 0, extracts the whole match as a bare String (drops the item's start/end/name attributes since the unwrapped String can't carry them)
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::Integer(0), false)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::item_at_index::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// Node 2: remove_at_index at index 0, returns the capture group items as a List<String>, preserving each item's start/end/name attributes
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::Integer(0), false)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::remove_at_index::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 2)),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![
|
||||
NodeInput::value(TaggedValue::String(String::new()), true),
|
||||
NodeInput::value(TaggedValue::String(String::new()), false),
|
||||
NodeInput::value(TaggedValue::Integer(0), false),
|
||||
NodeInput::value(TaggedValue::Bool(false), false),
|
||||
NodeInput::value(TaggedValue::Bool(false), false),
|
||||
],
|
||||
input_metadata: vec![
|
||||
("String", "The string to search within.").into(),
|
||||
("Pattern", "The regular expression pattern to search for.").into(),
|
||||
(
|
||||
"Match Index",
|
||||
"Which non-overlapping occurrence of the pattern to return, starting from 0 for the first match. Negative indices count backwards from the last match.",
|
||||
)
|
||||
.into(),
|
||||
("Case Insensitive", "Match letters regardless of case.").into(),
|
||||
("Multiline", "Make `^` and `$` match the start and end of each line, not just the whole string.").into(),
|
||||
],
|
||||
output_names: vec!["Match".to_string(), "Captures".to_string()],
|
||||
output_descriptions: vec![
|
||||
"The whole portion of the string matching the pattern, or empty if there is no match.".to_string(),
|
||||
"The text matched by each capture group in the pattern, in order.".to_string(),
|
||||
],
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed(
|
||||
r#"Finds a portion of the string matching a regular expression pattern. With "Match Index" at its default 0, it selects the first non-overlapping occurrence, but others may be selected. Capture groups, if any, are produced as a list in the "Captures" output."#,
|
||||
),
|
||||
inspector: None,
|
||||
},
|
||||
];
|
||||
|
||||
document_node_derive::post_process_nodes(custom)
|
||||
}
|
||||
|
||||
type NodeInspector = HashMap<String, Box<dyn Fn(NodeId, &mut NodeInspectorContext) -> Vec<LayoutGroup> + Send + Sync>>;
|
||||
@@ -157,6 +676,7 @@ fn static_node_inspector() -> NodeInspector {
|
||||
map.insert("hue_saturation_inspector".to_string(), Box::new(node_inspector::hue_saturation_inspector));
|
||||
map.insert("black_and_white_inspector".to_string(), Box::new(node_inspector::black_and_white_inspector));
|
||||
map.insert("threshold_inspector".to_string(), Box::new(node_inspector::threshold_inspector));
|
||||
map.insert("blend_if_inspector".to_string(), Box::new(node_inspector::blend_if_inspector));
|
||||
map.insert("vibrance_inspector".to_string(), Box::new(node_inspector::vibrance_inspector));
|
||||
map.insert("color_balance_inspector".to_string(), Box::new(node_inspector::color_balance_inspector));
|
||||
map.insert("fill_inspector".to_string(), Box::new(node_inspector::fill_inspector));
|
||||
@@ -218,10 +738,91 @@ fn static_input_inspector() -> InputInspector {
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"number".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let mut number_input = NumberInput::default();
|
||||
if let Some(unit) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "unit", context.selection_network_path)
|
||||
.and_then(|value| value.as_str())
|
||||
{
|
||||
number_input = number_input.unit(unit);
|
||||
}
|
||||
if let Some(min) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "min", context.selection_network_path)
|
||||
.and_then(|value| value.as_f64())
|
||||
{
|
||||
number_input = number_input.min(min);
|
||||
}
|
||||
if let Some(max) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "max", context.selection_network_path)
|
||||
.and_then(|value| value.as_f64())
|
||||
{
|
||||
number_input = number_input.max(max);
|
||||
}
|
||||
if let Some(step) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "step", context.selection_network_path)
|
||||
.and_then(|value| value.as_f64())
|
||||
{
|
||||
number_input = number_input.step(step);
|
||||
}
|
||||
if let Some(mode) = context.network_interface.input_data(&node_id, index, "mode", context.selection_network_path).map(|value| {
|
||||
let mode: NumberInputMode = serde_json::from_value(value.clone()).unwrap();
|
||||
mode
|
||||
}) {
|
||||
number_input = number_input.mode(mode);
|
||||
}
|
||||
if let Some(range_min) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "range_min", context.selection_network_path)
|
||||
.and_then(|value| value.as_f64())
|
||||
{
|
||||
number_input = number_input.range_min(Some(range_min));
|
||||
}
|
||||
if let Some(range_max) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "range_max", context.selection_network_path)
|
||||
.and_then(|value| value.as_f64())
|
||||
{
|
||||
number_input = number_input.range_max(Some(range_max));
|
||||
}
|
||||
if let Some(is_integer) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "is_integer", context.selection_network_path)
|
||||
.and_then(|value| value.as_bool())
|
||||
{
|
||||
number_input = number_input.is_integer(is_integer);
|
||||
}
|
||||
let blank_assist = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "blank_assist", context.selection_network_path)
|
||||
.and_then(|value| value.as_bool())
|
||||
.unwrap_or_else(|| {
|
||||
log::error!("Could not get blank assist when displaying number input for node {node_id}, index {index}");
|
||||
true
|
||||
});
|
||||
|
||||
Ok(vec![LayoutGroup::row(node_inspector::number_widget(
|
||||
ParameterWidgetsInfo::at_index(node_id, index, blank_assist, context),
|
||||
number_input,
|
||||
))])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
// The custom number input settings are only available on proto nodes
|
||||
"optional_f64".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let mut number_input = NumberInput::default();
|
||||
if let Some(field) = context.network_interface.field_metadata(&node_id, index, context.selection_network_path) {
|
||||
// The field is cloned so the lock is released before building the row below, which locks the node metadata again
|
||||
if let Some(field) = context
|
||||
.network_interface
|
||||
.implementation(&node_id, context.selection_network_path)
|
||||
.and_then(|implementation| if let DocumentNodeImplementation::ProtoNode(id) = implementation { Some(id) } else { None })
|
||||
.and_then(|proto_node_identifier| registry::NODE_METADATA.lock().unwrap().get(proto_node_identifier)?.fields.get(index).cloned())
|
||||
{
|
||||
if let Some(unit) = field.unit {
|
||||
number_input = number_input.unit(unit);
|
||||
}
|
||||
@@ -352,6 +953,57 @@ fn static_input_inspector() -> InputInspector {
|
||||
"type_choice".to_string(),
|
||||
Box::new(|node_id, index, context| Ok(vec![node_inspector::type_choice_widget(ParameterWidgetsInfo::at_index(node_id, index, true, context))])),
|
||||
);
|
||||
map.insert(
|
||||
"vec2".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let x = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "x", context.selection_network_path)
|
||||
.and_then(|value| value.as_str())
|
||||
.unwrap_or_else(|| {
|
||||
log::error!("Could not get x for vec2 input");
|
||||
""
|
||||
})
|
||||
.to_string();
|
||||
let y = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "y", context.selection_network_path)
|
||||
.and_then(|value| value.as_str())
|
||||
.unwrap_or_else(|| {
|
||||
log::error!("Could not get y for vec2 input");
|
||||
""
|
||||
})
|
||||
.to_string();
|
||||
let unit = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "unit", context.selection_network_path)
|
||||
.and_then(|value| value.as_str())
|
||||
.unwrap_or_else(|| {
|
||||
log::error!("Could not get unit for vec2 input");
|
||||
""
|
||||
})
|
||||
.to_string();
|
||||
let min = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "min", context.selection_network_path)
|
||||
.and_then(|value| value.as_f64());
|
||||
let is_integer = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "is_integer", context.selection_network_path)
|
||||
.and_then(|value| value.as_bool())
|
||||
.unwrap_or_default();
|
||||
|
||||
Ok(vec![node_inspector::vec2_widget(
|
||||
ParameterWidgetsInfo::at_index(node_id, index, true, context),
|
||||
&x,
|
||||
&y,
|
||||
&unit,
|
||||
min,
|
||||
is_integer,
|
||||
false,
|
||||
)])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"noise_inspector_scale".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
@@ -524,7 +1176,6 @@ fn static_input_inspector() -> InputInspector {
|
||||
"Y",
|
||||
"",
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
mandelbrot_to_julia.is_some_and(|percent| percent >= 100.),
|
||||
)])
|
||||
@@ -541,7 +1192,6 @@ fn static_input_inspector() -> InputInspector {
|
||||
"Y",
|
||||
"",
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
mandelbrot_to_julia.is_some_and(|percent| percent <= 0.),
|
||||
)])
|
||||
@@ -648,7 +1298,6 @@ fn static_input_inspector() -> InputInspector {
|
||||
"Y",
|
||||
" px",
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
false,
|
||||
)])
|
||||
@@ -664,7 +1313,6 @@ fn static_input_inspector() -> InputInspector {
|
||||
"H",
|
||||
"x",
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
false,
|
||||
)])
|
||||
@@ -785,7 +1433,7 @@ fn static_input_inspector() -> InputInspector {
|
||||
"vec2_uv".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let parameter_widgets_info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
|
||||
Ok(vec![node_inspector::vec2_widget(parameter_widgets_info, "U", "V", "", None, None, false, false)])
|
||||
Ok(vec![node_inspector::vec2_widget(parameter_widgets_info, "U", "V", "", None, false, false)])
|
||||
}),
|
||||
);
|
||||
map
|
||||
@@ -1033,18 +1681,6 @@ mod test {
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graph_craft::document::NodeId;
|
||||
|
||||
// A `#[graph]` node with an inner node that has no definition is left out of the catalog with only a logged error
|
||||
#[test]
|
||||
fn every_registered_graph_has_a_definition() {
|
||||
// Released before resolving, since building the catalog locks the registry too
|
||||
let identifiers: Vec<&str> = graphene_std::registry::GRAPH_METADATA.lock().unwrap().iter().map(|graph| graph.identifier).collect();
|
||||
assert!(!identifiers.is_empty(), "the `#[graph]` nodes in `graphene_std::subgraphs` should be registered");
|
||||
|
||||
for identifier in identifiers {
|
||||
assert!(resolve_network_node_type(identifier).is_some(), "the '{identifier}' graph should have a definition");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rasterize_defaults_to_a_1000_px_square_at_full_resolution() {
|
||||
use glam::{DAffine2, UVec2};
|
||||
@@ -1185,36 +1821,21 @@ mod test_type_constraints {
|
||||
|
||||
#[test]
|
||||
fn every_definition_default_value_satisfies_its_constraint() {
|
||||
// Checks a node's inputs against what its implementations accept, then each node inside it, whose values a subgraph's author writes too
|
||||
fn check(node_template: &NodeTemplate, name: &str, violations: &mut Vec<String>) {
|
||||
let constraints = InputTypeConstraint::constraints_for_all_inputs(node_template, name);
|
||||
let mut violations = Vec::new();
|
||||
for definition in super::DOCUMENT_NODE_TYPES.values() {
|
||||
let name = &definition.node_template.display_name;
|
||||
let constraints = InputTypeConstraint::constraints_for_all_inputs(&definition.node_template, name);
|
||||
|
||||
for (index, (constraint, input)) in constraints.iter().zip(&node_template.inputs).enumerate() {
|
||||
for (index, (constraint, input)) in constraints.iter().zip(&definition.node_template.inputs).enumerate() {
|
||||
if let Some(value) = input.as_value()
|
||||
&& !constraint.accepts_default_value(&value.ty())
|
||||
{
|
||||
violations.push(format!("{name} input {index}: {} does not satisfy {constraint:?}", value.ty()));
|
||||
}
|
||||
|
||||
let takes_nothing = matches!(constraint, InputTypeConstraint::Limited(types) if !types.is_empty() && types.iter().all(|ty| ty == "()"));
|
||||
if takes_nothing && matches!(input, NodeInput::Node { .. } | NodeInput::Import { .. }) {
|
||||
violations.push(format!("{name} input {index}: a wire feeds it, but it takes nothing"));
|
||||
}
|
||||
}
|
||||
|
||||
if let NodeTemplateImplementation::Network(network) = &node_template.implementation {
|
||||
for (node_id, inner) in &network.nodes {
|
||||
check(inner, &format!("{name}, node {node_id}"), violations);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut violations = Vec::new();
|
||||
for definition in super::DOCUMENT_NODE_TYPES.values() {
|
||||
check(&definition.node_template, &definition.node_template.display_name, &mut violations);
|
||||
}
|
||||
|
||||
assert!(violations.is_empty(), "Values rejected by their input constraints:\n{}", violations.join("\n"));
|
||||
assert!(violations.is_empty(), "Default values rejected by their input constraints:\n{}", violations.join("\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1231,7 +1852,7 @@ mod test_type_constraints {
|
||||
|
||||
#[test]
|
||||
fn single_protonode() {
|
||||
let node_type = resolve_proto_node_type(test_node_accept_f32_f64_dvec2::IDENTIFIER).expect("test node to exist");
|
||||
let node_type = resolve_proto_node_type(test_node_accept_f_32_f_64_dvec_2::IDENTIFIER).expect("test node to exist");
|
||||
let constraint = InputTypeConstraint::constraints_for_all_inputs(&node_type.node_template, "name");
|
||||
all_satisifed(&constraint[0], [concrete!(f32), concrete!(f64), concrete!(glam::DVec2)]);
|
||||
assert!(!constraint[0].satisfies(&concrete!(String)));
|
||||
@@ -1245,7 +1866,7 @@ mod test_type_constraints {
|
||||
|
||||
#[test]
|
||||
fn single_protonode2() {
|
||||
let node_type = resolve_proto_node_type(test_node_accept_f32_f64_string::IDENTIFIER).expect("test node to exist");
|
||||
let node_type = resolve_proto_node_type(test_node_accept_f_32_f_64_string::IDENTIFIER).expect("test node to exist");
|
||||
let constraint = InputTypeConstraint::constraints_for_all_inputs(&node_type.node_template, "name");
|
||||
all_satisifed(&constraint[0], [concrete!(f32), concrete!(f64), concrete!(String)]);
|
||||
assert!(!constraint[0].satisfies(&concrete!(glam::DVec2)));
|
||||
@@ -1254,8 +1875,8 @@ mod test_type_constraints {
|
||||
|
||||
#[test]
|
||||
fn network() {
|
||||
let atan_definition = resolve_proto_node_type(test_node_accept_f32_f64_dvec2::IDENTIFIER).expect("test node to exist");
|
||||
let min_definition = resolve_proto_node_type(test_node_accept_f32_f64_string::IDENTIFIER).expect("test node to exist");
|
||||
let atan_definition = resolve_proto_node_type(test_node_accept_f_32_f_64_dvec_2::IDENTIFIER).expect("test node to exist");
|
||||
let min_definition = resolve_proto_node_type(test_node_accept_f_32_f_64_string::IDENTIFIER).expect("test node to exist");
|
||||
let atan_node = atan_definition.node_template_input_override([Some(NodeInput::import(generic!(X), 0))]);
|
||||
let min_node = min_definition.node_template_input_override([Some(NodeInput::import(generic!(X), 0))]);
|
||||
let inner_network = NodeNetworkTemplate {
|
||||
|
||||
+30
-421
@@ -1,17 +1,11 @@
|
||||
use super::DocumentNodeDefinition;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{
|
||||
InputMetadata, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, WidgetOverride,
|
||||
};
|
||||
use glam::IVec2;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputMetadata, NodeTemplate, NodeTemplateImplementation, WidgetOverride};
|
||||
use graphene_std::registry::*;
|
||||
use graphene_std::*;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
/// Generates every definition, from the node macro's metadata for proto nodes and the graph macro's for built-in subgraphs.
|
||||
pub(super) fn derive_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
|
||||
pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
|
||||
let mut definitions_map = HashMap::new();
|
||||
|
||||
// Add the protonodes from the macro.
|
||||
@@ -81,7 +75,16 @@ pub(super) fn derive_definitions() -> HashMap<DefinitionIdentifier, DocumentNode
|
||||
inputs,
|
||||
call_argument: input_type.clone(),
|
||||
implementation: NodeTemplateImplementation::ProtoNode(id.clone()),
|
||||
input_metadata: input_metadata(fields),
|
||||
// TODO: Store information for input overrides in the node macro
|
||||
input_metadata: fields
|
||||
.iter()
|
||||
.map(|f| match f.widget_override {
|
||||
RegistryWidgetOverride::None => (f.name, f.description).into(),
|
||||
RegistryWidgetOverride::Hidden => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::Hidden),
|
||||
RegistryWidgetOverride::String(str) => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::String(str.to_string())),
|
||||
RegistryWidgetOverride::Custom(str) => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::Custom(str.to_string())),
|
||||
})
|
||||
.collect(),
|
||||
output_names,
|
||||
..Default::default()
|
||||
},
|
||||
@@ -93,242 +96,25 @@ pub(super) fn derive_definitions() -> HashMap<DefinitionIdentifier, DocumentNode
|
||||
);
|
||||
}
|
||||
|
||||
let graphs = GRAPH_METADATA.lock().unwrap().clone();
|
||||
add_graph_definitions(graphs, &mut definitions_map);
|
||||
// Add the hand-written network nodes to the map and add the metadata for their internal protonodes
|
||||
for mut network_node in custom {
|
||||
fill_proto_node_metadata(&mut network_node.node_template, &definitions_map);
|
||||
|
||||
// Set the reference to the node identifier
|
||||
if let NodeTemplateImplementation::Network(network_template) = &mut network_node.node_template.implementation {
|
||||
network_template.reference = Some(network_node.identifier.to_string());
|
||||
// If it is not a merge node, then set the display name to the identifier/reference
|
||||
if network_node.identifier != "Merge" {
|
||||
network_node.node_template.display_name = network_node.identifier.to_string();
|
||||
}
|
||||
}
|
||||
definitions_map.insert(DefinitionIdentifier::Network(network_node.identifier.to_string()), network_node);
|
||||
}
|
||||
|
||||
definitions_map
|
||||
}
|
||||
|
||||
/// The name, description, and any widget override of each parameter, for a proto node's fields or a graph's imports.
|
||||
/// The rest of a parameter's widget settings are read from its field when the Inspector draws it.
|
||||
fn input_metadata(fields: &[FieldMetadata]) -> Vec<InputMetadata> {
|
||||
fields
|
||||
.iter()
|
||||
.map(|field| {
|
||||
let (name, description) = (field.name, field.description);
|
||||
match field.widget_override {
|
||||
RegistryWidgetOverride::None => (name, description).into(),
|
||||
RegistryWidgetOverride::Hidden => InputMetadata::with_name_description_override(name, description, WidgetOverride::Hidden),
|
||||
RegistryWidgetOverride::String(text) => InputMetadata::with_name_description_override(name, description, WidgetOverride::String(text.to_string())),
|
||||
RegistryWidgetOverride::Custom(key) => InputMetadata::with_name_description_override(name, description, WidgetOverride::Custom(key.to_string())),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Why a `#[graph]` node has no definition yet, or can't have one.
|
||||
enum GraphDefinitionError {
|
||||
/// A node inside it has no definition, which may be another graph not yet added.
|
||||
MissingNode(String),
|
||||
/// The graph's wiring is invalid, so it's left out of the catalog.
|
||||
Invalid(String),
|
||||
}
|
||||
|
||||
/// Adds the nodes defined as subgraphs by `#[graph]`, each once the definitions of the nodes inside it exist.
|
||||
fn add_graph_definitions(graphs: Vec<GraphMetadata>, definitions_map: &mut HashMap<DefinitionIdentifier, DocumentNodeDefinition>) {
|
||||
// Every graph sharing an identifier is left out, so the catalog doesn't depend on registration order
|
||||
let mut identifier_counts = HashMap::new();
|
||||
for graph in &graphs {
|
||||
*identifier_counts.entry(graph.identifier).or_insert(0) += 1;
|
||||
}
|
||||
let mut rejected = HashSet::new();
|
||||
let mut pending_graphs: Vec<(GraphMetadata, String)> = graphs
|
||||
.into_iter()
|
||||
.filter(|graph| {
|
||||
let taken = identifier_counts[graph.identifier] > 1;
|
||||
if taken {
|
||||
log::error!("The '{}' graph has no definition, since another graph has the same identifier", graph.identifier);
|
||||
rejected.insert(graph.identifier);
|
||||
}
|
||||
!taken
|
||||
})
|
||||
.map(|graph| (graph, String::new()))
|
||||
.collect();
|
||||
|
||||
loop {
|
||||
let pending_count = pending_graphs.len();
|
||||
|
||||
let mut ready = Vec::new();
|
||||
pending_graphs.retain_mut(|(graph, missing)| {
|
||||
// A graph built on a left-out graph is left out too, rather than embedding another definition of that name
|
||||
let rejected_inner_graph = graph.nodes.iter().find_map(|node| match node.implementation {
|
||||
GraphNodeImplementation::Graph(identifier) if rejected.contains(identifier) => Some(identifier),
|
||||
_ => None,
|
||||
});
|
||||
if let Some(inner_graph) = rejected_inner_graph {
|
||||
log::error!("The '{}' graph has no definition, since the '{inner_graph}' graph inside it has none", graph.identifier);
|
||||
rejected.insert(graph.identifier);
|
||||
return false;
|
||||
}
|
||||
|
||||
match graph_definition(graph, definitions_map) {
|
||||
Ok(definition) => {
|
||||
ready.push(definition);
|
||||
false
|
||||
}
|
||||
Err(GraphDefinitionError::MissingNode(missing_node)) => {
|
||||
*missing = missing_node;
|
||||
true
|
||||
}
|
||||
Err(GraphDefinitionError::Invalid(reason)) => {
|
||||
log::error!("The '{}' graph has no definition, since {reason}", graph.identifier);
|
||||
rejected.insert(graph.identifier);
|
||||
false
|
||||
}
|
||||
}
|
||||
});
|
||||
for definition in ready {
|
||||
let definition = prepare_network_definition(definition, definitions_map);
|
||||
definitions_map.insert(DefinitionIdentifier::Network(definition.identifier.to_string()), definition);
|
||||
}
|
||||
|
||||
if pending_graphs.is_empty() || pending_graphs.len() == pending_count {
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (graph, missing_node) in pending_graphs {
|
||||
log::error!("The '{}' graph has no definition, since the '{missing_node}' node inside it has none", graph.identifier);
|
||||
}
|
||||
}
|
||||
|
||||
/// Fills a network definition's nested proto node metadata and points its network at the definition.
|
||||
fn prepare_network_definition(mut network_node: DocumentNodeDefinition, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) -> DocumentNodeDefinition {
|
||||
fill_proto_node_metadata(&mut network_node.node_template, definitions_map);
|
||||
|
||||
// Set the reference to the node identifier
|
||||
if let NodeTemplateImplementation::Network(network_template) = &mut network_node.node_template.implementation {
|
||||
network_template.reference = Some(network_node.identifier.to_string());
|
||||
// If it is not a merge node, then set the display name to the identifier/reference
|
||||
if network_node.identifier != "Merge" {
|
||||
network_node.node_template.display_name = network_node.identifier.to_string();
|
||||
}
|
||||
}
|
||||
|
||||
network_node
|
||||
}
|
||||
|
||||
/// Builds the catalog definition of a node defined as a subgraph by `#[graph]`.
|
||||
fn graph_definition(graph: &GraphMetadata, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) -> Result<DocumentNodeDefinition, GraphDefinitionError> {
|
||||
let mut nodes = HashMap::new();
|
||||
for (index, node) in graph.nodes.iter().enumerate() {
|
||||
// Start from the node's own definition, so each input the graph leaves out matches a new instance of it
|
||||
let (identifier, name) = match &node.implementation {
|
||||
GraphNodeImplementation::ProtoNode(identifier) => (DefinitionIdentifier::ProtoNode(identifier.clone()), identifier.as_str().to_string()),
|
||||
GraphNodeImplementation::Graph(identifier) => (DefinitionIdentifier::Network(identifier.to_string()), identifier.to_string()),
|
||||
};
|
||||
let Some(definition) = definitions_map.get(&identifier) else {
|
||||
return Err(GraphDefinitionError::MissingNode(name));
|
||||
};
|
||||
let mut template = definition.default_node_template();
|
||||
|
||||
if let Some(call_argument) = &node.call_argument {
|
||||
template.call_argument = call_argument.clone();
|
||||
}
|
||||
template.visible = !node.hidden;
|
||||
template.locked = node.locked;
|
||||
template.pinned = node.pinned;
|
||||
if let Some(display_name) = node.display_name {
|
||||
template.display_name = display_name.to_string();
|
||||
}
|
||||
|
||||
let position = node.position.map_or(IVec2::ZERO, |(x, y)| IVec2::new(x, y));
|
||||
template.node_type_metadata = if node.layer {
|
||||
NodeTypePersistentMetadata::layer(position)
|
||||
} else {
|
||||
NodeTypePersistentMetadata::node(position)
|
||||
};
|
||||
|
||||
for (input_index, source) in &node.inputs {
|
||||
let Some(input) = template.inputs.get_mut(*input_index) else {
|
||||
return Err(GraphDefinitionError::Invalid(format!("its node {index}, '{name}', has no input {input_index} for it to set")));
|
||||
};
|
||||
|
||||
// An input the compiler fills in can't be set, which the macro already prevents for the graphs it builds
|
||||
if matches!(input, NodeInput::Scope(_) | NodeInput::Reflection(_)) {
|
||||
return Err(GraphDefinitionError::Invalid(format!(
|
||||
"it sets input {input_index} of its node {index}, '{name}', which the compiler fills in"
|
||||
)));
|
||||
}
|
||||
|
||||
*input = graph_input(source, input);
|
||||
}
|
||||
|
||||
nodes.insert(NodeId(index as u64), template);
|
||||
}
|
||||
|
||||
// Each import starts from its `#[default(...)]` or else its type, as a proto node's parameter does
|
||||
let inputs = preprocessor::node_inputs(&graph.imports, &NodeIOTypes::empty());
|
||||
|
||||
let exports = graph.exports.iter().map(|export| graph_input(&export.source, &NodeInput::value(TaggedValue::None, false))).collect();
|
||||
|
||||
Ok(DocumentNodeDefinition {
|
||||
identifier: graph.identifier,
|
||||
version: graph.version,
|
||||
category: graph.category,
|
||||
icon: graph.icon,
|
||||
description: Cow::Borrowed(graph.description),
|
||||
inspector: None,
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate { exports, nodes, ..Default::default() }),
|
||||
inputs,
|
||||
input_metadata: input_metadata(&graph.imports),
|
||||
output_names: graph.exports.iter().map(|export| export.name.to_string()).collect(),
|
||||
output_descriptions: graph.exports.iter().map(|export| export.description.to_string()).collect(),
|
||||
node_type_metadata: if graph.layer {
|
||||
NodeTypePersistentMetadata::layer(IVec2::ZERO)
|
||||
} else {
|
||||
NodeTypePersistentMetadata::node(IVec2::ZERO)
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/// The input a graph definition writes, where `default` is what the node's own definition starts that input with.
|
||||
fn graph_input(source: &GraphInputSource, default: &NodeInput) -> NodeInput {
|
||||
match source {
|
||||
GraphInputSource::Node { node, output } => NodeInput::node(NodeId(*node as u64), *output),
|
||||
GraphInputSource::Import { index, ty } => NodeInput::import(ty.clone(), *index),
|
||||
GraphInputSource::Value { value, exposed } => {
|
||||
let ty = match default {
|
||||
NodeInput::Value { tagged_value, .. } => tagged_value.ty(),
|
||||
NodeInput::Import { import_type, .. } => import_type.clone(),
|
||||
_ => generic!(T),
|
||||
};
|
||||
NodeInput::value(graph_value(value, &ty), exposed.unwrap_or(default.is_exposed()))
|
||||
}
|
||||
GraphInputSource::Scope(key) => NodeInput::scope(*key),
|
||||
GraphInputSource::NodePath => NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::DocumentNodePath),
|
||||
GraphInputSource::SourceId => NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::SourceId),
|
||||
}
|
||||
}
|
||||
|
||||
/// The type of the elements a wire of this type carries, past any `Item`, `List`, or lazy wrapping.
|
||||
fn element_type(ty: &Type) -> &Type {
|
||||
let mut element = ty;
|
||||
while let Type::Item(inner) | Type::List(inner) | Type::Fn(_, inner) = element {
|
||||
element = inner;
|
||||
}
|
||||
element
|
||||
}
|
||||
|
||||
/// Converts a value written in a graph definition to the type of the input it feeds.
|
||||
fn graph_value(value: &GraphValue, ty: &Type) -> TaggedValue {
|
||||
// An integer literal feeds an integer input as an integer, and any other as a number
|
||||
let is_integer = *element_type(ty) == concrete!(i64);
|
||||
|
||||
match value {
|
||||
GraphValue::Integer(integer) if is_integer => TaggedValue::Integer(*integer),
|
||||
GraphValue::Integer(integer) => TaggedValue::Number(*integer as f64),
|
||||
GraphValue::Number(number) => TaggedValue::Number(*number),
|
||||
GraphValue::Bool(boolean) => TaggedValue::Bool(*boolean),
|
||||
GraphValue::String(string) => TaggedValue::String(string.clone()),
|
||||
GraphValue::Vec2(vec2) => TaggedValue::DVec2(*vec2),
|
||||
GraphValue::Color(color) => TaggedValue::Color(*color),
|
||||
}
|
||||
}
|
||||
|
||||
/// Recursively gives each nested proto node its definition's input and output metadata, and its display name if the network's author gave none.
|
||||
/// Recursively fills each nested proto node's editor metadata from its definition, preserving only the authored position.
|
||||
fn fill_proto_node_metadata(node_template: &mut NodeTemplate, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) {
|
||||
match &mut node_template.implementation {
|
||||
NodeTemplateImplementation::Network(network_template) => {
|
||||
@@ -342,190 +128,13 @@ fn fill_proto_node_metadata(node_template: &mut NodeTemplate, definitions_map: &
|
||||
return;
|
||||
};
|
||||
|
||||
// A display name, lock, or pin the network's author gave the node is kept
|
||||
let definition_template = &definition.node_template;
|
||||
if node_template.display_name.is_empty() {
|
||||
node_template.display_name = definition_template.display_name.clone();
|
||||
}
|
||||
node_template.display_name = definition_template.display_name.clone();
|
||||
node_template.input_metadata = definition_template.input_metadata.clone();
|
||||
node_template.output_names = definition_template.output_names.clone();
|
||||
node_template.locked |= definition_template.locked;
|
||||
node_template.pinned |= definition_template.pinned;
|
||||
node_template.locked = definition_template.locked;
|
||||
node_template.pinned = definition_template.pinned;
|
||||
}
|
||||
NodeTemplateImplementation::Definition(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
|
||||
|
||||
fn number_import() -> FieldMetadata {
|
||||
FieldMetadata {
|
||||
name: "Value",
|
||||
description: "",
|
||||
internal: false,
|
||||
exposed: true,
|
||||
widget_override: RegistryWidgetOverride::None,
|
||||
value_source: RegistryValueSource::None,
|
||||
default_colors: None,
|
||||
default_type: Some(Type::Item(Box::new(concrete!(f64)))),
|
||||
number_soft_min: None,
|
||||
number_soft_max: None,
|
||||
number_hard_min: None,
|
||||
number_hard_max: None,
|
||||
number_mode_range: false,
|
||||
number_display_decimal_places: None,
|
||||
number_step: None,
|
||||
unit: None,
|
||||
multiline: false,
|
||||
progression: false,
|
||||
constant: false,
|
||||
labels: None,
|
||||
integer: false,
|
||||
blank_assist: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// A graph exporting one node, which is fed by the given inputs.
|
||||
fn one_node_graph(identifier: &'static str, implementation: GraphNodeImplementation, inputs: Vec<(usize, GraphInputSource)>) -> GraphMetadata {
|
||||
GraphMetadata {
|
||||
identifier,
|
||||
category: "Test",
|
||||
icon: None,
|
||||
description: "",
|
||||
version: 1,
|
||||
layer: false,
|
||||
imports: vec![number_import()],
|
||||
exports: vec![GraphExportMetadata {
|
||||
name: "Out",
|
||||
description: "",
|
||||
source: GraphInputSource::Node { node: 0, output: 0 },
|
||||
}],
|
||||
nodes: vec![GraphNodeMetadata {
|
||||
implementation,
|
||||
inputs,
|
||||
position: None,
|
||||
layer: false,
|
||||
display_name: None,
|
||||
hidden: false,
|
||||
locked: false,
|
||||
pinned: false,
|
||||
call_argument: None,
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
fn from_import() -> Vec<(usize, GraphInputSource)> {
|
||||
let ty = Type::Item(Box::new(concrete!(f64)));
|
||||
vec![(0, GraphInputSource::Import { index: 0, ty })]
|
||||
}
|
||||
|
||||
/// The definitions a test graph builds on: only the As Number proto node.
|
||||
fn proto_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
|
||||
let identifier = DefinitionIdentifier::ProtoNode(math_nodes::as_number::IDENTIFIER);
|
||||
let definition = resolve_document_node_type(&identifier).expect("As Number should have a definition").clone();
|
||||
HashMap::from([(identifier, definition)])
|
||||
}
|
||||
|
||||
fn has_graph(definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>, identifier: &str) -> bool {
|
||||
definitions_map.contains_key(&DefinitionIdentifier::Network(identifier.to_string()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_graph_resolves_when_registered_before_a_graph_inside_it() {
|
||||
let outer = one_node_graph("Test Outer", GraphNodeImplementation::Graph("Test Inner"), from_import());
|
||||
let inner = one_node_graph("Test Inner", math_nodes::as_number::IDENTIFIER.into(), from_import());
|
||||
|
||||
let mut definitions_map = proto_definitions();
|
||||
add_graph_definitions(vec![outer, inner], &mut definitions_map);
|
||||
|
||||
assert!(has_graph(&definitions_map, "Test Inner"));
|
||||
assert!(has_graph(&definitions_map, "Test Outer"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_graph_setting_an_input_its_node_lacks_is_left_out() {
|
||||
let mut inputs = from_import();
|
||||
inputs.push((
|
||||
100,
|
||||
GraphInputSource::Value {
|
||||
value: GraphValue::Number(1.),
|
||||
exposed: None,
|
||||
},
|
||||
));
|
||||
let graph = one_node_graph("Test Missing Input", math_nodes::as_number::IDENTIFIER.into(), inputs);
|
||||
|
||||
let mut definitions_map = proto_definitions();
|
||||
add_graph_definitions(vec![graph], &mut definitions_map);
|
||||
|
||||
assert!(!has_graph(&definitions_map, "Test Missing Input"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn graphs_sharing_an_identifier_and_graphs_built_on_them_are_left_out() {
|
||||
let first = one_node_graph("Test Twin", math_nodes::as_number::IDENTIFIER.into(), from_import());
|
||||
let second = one_node_graph("Test Twin", math_nodes::as_number::IDENTIFIER.into(), from_import());
|
||||
let dependent = one_node_graph("Test Dependent", GraphNodeImplementation::Graph("Test Twin"), from_import());
|
||||
|
||||
let mut definitions_map = proto_definitions();
|
||||
add_graph_definitions(vec![first, second, dependent], &mut definitions_map);
|
||||
|
||||
assert!(!has_graph(&definitions_map, "Test Twin"));
|
||||
assert!(!has_graph(&definitions_map, "Test Dependent"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_integer_value_takes_the_type_of_the_input_it_feeds() {
|
||||
let integer = Type::Item(Box::new(concrete!(i64)));
|
||||
let number = Type::Item(Box::new(concrete!(f64)));
|
||||
|
||||
assert!(matches!(graph_value(&GraphValue::Integer(3), &integer), TaggedValue::Integer(3)));
|
||||
assert!(matches!(graph_value(&GraphValue::Integer(3), &number), TaggedValue::Number(value) if value == 3.));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imports_start_from_their_default_or_type() {
|
||||
let unit_primary = FieldMetadata {
|
||||
default_type: Some(concrete!(())),
|
||||
..number_import()
|
||||
};
|
||||
let with_default = FieldMetadata {
|
||||
value_source: RegistryValueSource::Default("2.5"),
|
||||
..number_import()
|
||||
};
|
||||
let graph = GraphMetadata {
|
||||
imports: vec![unit_primary, with_default],
|
||||
..one_node_graph("Test Defaults", math_nodes::as_number::IDENTIFIER.into(), from_import())
|
||||
};
|
||||
|
||||
let mut definitions_map = proto_definitions();
|
||||
add_graph_definitions(vec![graph], &mut definitions_map);
|
||||
let inputs = &definitions_map[&DefinitionIdentifier::Network("Test Defaults".to_string())].node_template.inputs;
|
||||
|
||||
// A `()` primary has nothing to connect, and an exposed parameter's default is parsed by its type
|
||||
assert!(!inputs[0].is_exposed());
|
||||
assert!(matches!(inputs[1].as_value(), Some(TaggedValue::Number(value)) if *value == 2.5));
|
||||
assert!(inputs[1].is_exposed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_graph_nodes_widget_settings_come_from_its_import() {
|
||||
use crate::messages::prelude::DocumentMessageHandler;
|
||||
|
||||
let node_id = NodeId(1);
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
let artboard = resolve_document_node_type(&DefinitionIdentifier::Network("Artboard".into())).expect("Artboard should exist");
|
||||
document.network_interface.insert_node(node_id, artboard.default_node_template(), &[]);
|
||||
|
||||
let location = graphene_std::subgraphs::artboard::LocationInput::INDEX;
|
||||
let field = document
|
||||
.network_interface
|
||||
.field_metadata(&node_id, location, &[])
|
||||
.expect("the location input should have its import's settings");
|
||||
assert_eq!(field.labels, Some(("X", "Y")));
|
||||
assert!(field.integer);
|
||||
assert!(!document.network_interface.is_internal_input(&node_id, location, &[]));
|
||||
}
|
||||
}
|
||||
@@ -41,7 +41,7 @@ use graphene_std::vector::style::{
|
||||
build_transform_with_y_preservation,
|
||||
};
|
||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
|
||||
use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, GlowSource, GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution, Vector};
|
||||
use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, GlowSource, GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution, Vector};
|
||||
use graphene_std::{DisplaceMode, RadialBlurMethod, WaveType};
|
||||
use graphene_std::{NodeParameter, ParameterRef};
|
||||
use math_parser::parser::{MessagePart, ParseError};
|
||||
@@ -240,7 +240,7 @@ pub fn start_widgets(parameter_widgets_info: &ParameterWidgetsInfo) -> Vec<Widge
|
||||
}
|
||||
|
||||
/// The presentation of a parameter's widget, sourced from the node's field metadata: numeric bounds, widget modes, and unit of measure.
|
||||
#[derive(Clone, Copy)]
|
||||
#[derive(Clone, Copy, Default)]
|
||||
pub(crate) struct ParameterOptions {
|
||||
pub soft_min: Option<f64>,
|
||||
pub soft_max: Option<f64>,
|
||||
@@ -252,50 +252,6 @@ pub(crate) struct ParameterOptions {
|
||||
pub unit: Option<&'static str>,
|
||||
pub display_decimal_places: Option<u32>,
|
||||
pub step: Option<f64>,
|
||||
pub labels: Option<(&'static str, &'static str)>,
|
||||
pub integer: bool,
|
||||
pub blank_assist: bool,
|
||||
}
|
||||
|
||||
impl Default for ParameterOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
soft_min: None,
|
||||
soft_max: None,
|
||||
hard_min: None,
|
||||
hard_max: None,
|
||||
slider: false,
|
||||
multiline: false,
|
||||
progression: false,
|
||||
unit: None,
|
||||
display_decimal_places: None,
|
||||
step: None,
|
||||
labels: None,
|
||||
integer: false,
|
||||
blank_assist: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ParameterOptions {
|
||||
/// The options a proto node's field or a graph's import gives its widget.
|
||||
pub(crate) fn from_field(field: &graphene_std::registry::FieldMetadata) -> Self {
|
||||
Self {
|
||||
soft_min: field.number_soft_min,
|
||||
soft_max: field.number_soft_max,
|
||||
hard_min: field.number_hard_min,
|
||||
hard_max: field.number_hard_max,
|
||||
slider: field.number_mode_range,
|
||||
multiline: field.multiline,
|
||||
progression: field.progression,
|
||||
unit: field.unit,
|
||||
display_decimal_places: field.number_display_decimal_places,
|
||||
step: field.number_step,
|
||||
labels: field.labels,
|
||||
integer: field.integer,
|
||||
blank_assist: field.blank_assist,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The values a range slider's two ends map to linearly and the one its double-click restores, if known.
|
||||
@@ -349,12 +305,9 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
unit,
|
||||
display_decimal_places,
|
||||
step,
|
||||
labels,
|
||||
integer,
|
||||
blank_assist,
|
||||
} = options;
|
||||
|
||||
let mut number_input = NumberInput::default().is_integer(integer);
|
||||
let mut number_input = NumberInput::default();
|
||||
if slider {
|
||||
number_input = number_input.mode_range();
|
||||
}
|
||||
@@ -397,7 +350,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
}
|
||||
};
|
||||
|
||||
let default_info = ParameterWidgetsInfo::at_index(node_id, index, blank_assist, context);
|
||||
let default_info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
|
||||
|
||||
// A type with no widget can only be supplied through the graph, labeled with a placeholder row
|
||||
let unsupported_widgets = |default_info: ParameterWidgetsInfo, type_label: String| {
|
||||
@@ -441,10 +394,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
true => text_area_widget(default_info).into(),
|
||||
false => text_widget(default_info).into(),
|
||||
},
|
||||
Some(x) if id_is::<DVec2>(x) => {
|
||||
let (x_label, y_label) = labels.unwrap_or(("X", "Y"));
|
||||
vec2_widget(default_info, x_label, y_label, unit.unwrap_or(""), hard_min, hard_max, integer, false)
|
||||
}
|
||||
Some(x) if id_is::<DVec2>(x) => vec2_widget(default_info, "X", "Y", unit.unwrap_or(""), None, false, false),
|
||||
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, unit, &mut extra_widgets),
|
||||
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
@@ -514,6 +464,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
Some(x) if id_is::<BevelDirection>(x) => enum_choice::<BevelDirection>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<BevelTechnique>(x) => enum_choice::<BevelTechnique>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<NoiseDistribution>(x) => enum_choice::<NoiseDistribution>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<BlendIfChannel>(x) => enum_choice::<BlendIfChannel>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<QRCodeErrorCorrectionLevel>(x) => enum_choice::<QRCodeErrorCorrectionLevel>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<ScaleType>(x) => enum_choice::<ScaleType>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<InterpolationDistribution>(x) => enum_choice::<InterpolationDistribution>().for_socket(default_info).inspector_row(),
|
||||
@@ -954,7 +905,7 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, size_unit:
|
||||
}
|
||||
}
|
||||
|
||||
pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &str, unit: &str, min: Option<f64>, max: Option<f64>, is_integer: bool, disabled: bool) -> LayoutGroup {
|
||||
pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &str, unit: &str, min: Option<f64>, is_integer: bool, disabled: bool) -> LayoutGroup {
|
||||
let mut widgets = start_widgets(¶meter_widgets_info);
|
||||
|
||||
let Some(input) = parameter_widgets_info.input() else {
|
||||
@@ -969,7 +920,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
||||
.label(x)
|
||||
.unit(unit)
|
||||
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
|
||||
.max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.is_integer(is_integer)
|
||||
.disabled(disabled)
|
||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), dvec2.y))))
|
||||
@@ -980,7 +931,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
||||
.label(y)
|
||||
.unit(unit)
|
||||
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
|
||||
.max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.is_integer(is_integer)
|
||||
.disabled(disabled)
|
||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(dvec2.x, input.value.unwrap()))))
|
||||
@@ -995,7 +946,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
||||
.label(x)
|
||||
.unit(unit)
|
||||
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
|
||||
.max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.is_integer(is_integer)
|
||||
.disabled(disabled)
|
||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), value))))
|
||||
@@ -1006,7 +957,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
||||
.label(y)
|
||||
.unit(unit)
|
||||
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
|
||||
.max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.is_integer(is_integer)
|
||||
.disabled(disabled)
|
||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(value, input.value.unwrap()))))
|
||||
@@ -1966,6 +1917,8 @@ pub(crate) fn levels_inspector(node_id: NodeId, context: &mut NodeInspectorConte
|
||||
enum MarkerScale {
|
||||
/// A 0..100 percentage, placed linearly.
|
||||
Percent,
|
||||
/// A 0..100 percentage of a channel's 256 levels, placed linearly and shown to a tenth, which tells neighboring levels apart.
|
||||
LevelPercent,
|
||||
/// A gamma of 0.01..9.99 running from 9.99 at the left to 0.01 at the right, logarithmic on each side of the 1 at its center.
|
||||
Gamma,
|
||||
/// A hue of 0..360 degrees, placed linearly on a track that wraps around.
|
||||
@@ -1975,7 +1928,7 @@ enum MarkerScale {
|
||||
impl MarkerScale {
|
||||
fn position(self, value: f64) -> f64 {
|
||||
match self {
|
||||
Self::Percent => value / 100.,
|
||||
Self::Percent | Self::LevelPercent => value / 100.,
|
||||
Self::Gamma if value >= 1. => 0.5 - 0.5 * value.log10() / 9.99_f64.log10(),
|
||||
Self::Gamma => 0.5 + 0.5 * value.log10() / 0.01_f64.log10(),
|
||||
Self::Degrees => {
|
||||
@@ -1989,7 +1942,7 @@ impl MarkerScale {
|
||||
|
||||
fn value(self, position: f64) -> f64 {
|
||||
match self {
|
||||
Self::Percent => (position * 100.).clamp(0., 100.),
|
||||
Self::Percent | Self::LevelPercent => (position * 100.).clamp(0., 100.),
|
||||
Self::Gamma if position <= 0.5 => 9.99_f64.powf(1. - 2. * position).clamp(1., 9.99),
|
||||
Self::Gamma => 0.01_f64.powf(2. * position - 1.).clamp(0.01, 1.),
|
||||
Self::Degrees => (position * 360.).clamp(0., 360.),
|
||||
@@ -1999,6 +1952,7 @@ impl MarkerScale {
|
||||
fn number_input(self) -> NumberInput {
|
||||
match self {
|
||||
Self::Percent => NumberInput::default().mode_increment().unit("%").min(0.).max(100.).display_decimal_places(0),
|
||||
Self::LevelPercent => NumberInput::default().mode_increment().unit("%").min(0.).max(100.).display_decimal_places(1),
|
||||
Self::Gamma => NumberInput::default().mode_increment().min(0.01).max(9.99).display_decimal_places(2),
|
||||
Self::Degrees => NumberInput::default().mode_increment().unit("°").min(0.).max(360.).display_decimal_places(0),
|
||||
}
|
||||
@@ -2023,6 +1977,8 @@ struct SliderSectionParam {
|
||||
dash_to_next: bool,
|
||||
/// Whether the marker takes its scale position within the span between its neighbors rather than the whole track, following them as they move.
|
||||
between_neighbors: bool,
|
||||
/// How the marker and the next parameter's marker may pass each other (see [`overlap_bounds`]).
|
||||
overlap_next: MarkerOverlap,
|
||||
}
|
||||
|
||||
impl SliderSectionParam {
|
||||
@@ -2035,6 +1991,7 @@ impl SliderSectionParam {
|
||||
pair_with_next: false,
|
||||
dash_to_next: false,
|
||||
between_neighbors: false,
|
||||
overlap_next: MarkerOverlap::Never,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2052,11 +2009,52 @@ impl SliderSectionParam {
|
||||
self.dash_to_next = true;
|
||||
self
|
||||
}
|
||||
|
||||
fn overlap_next(mut self, overlap: MarkerOverlap) -> Self {
|
||||
self.overlap_next = overlap;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// The span the marker at `index` may move within where markers may overlap their next (see [`MarkerOverlap`]).
|
||||
fn overlap_bounds(positions: &[f64], overlaps_next: &[MarkerOverlap], index: usize) -> (f64, f64) {
|
||||
let overlap = |i: Option<usize>| i.and_then(|i| overlaps_next.get(i)).copied().unwrap_or_default();
|
||||
let position = |i: Option<usize>| i.and_then(|i| positions.get(i)).copied();
|
||||
let (previous, before_previous, next, after_next) = (index.checked_sub(1), index.checked_sub(2), Some(index + 1), Some(index + 2));
|
||||
let mut lower = 0_f64;
|
||||
let mut upper = 1_f64;
|
||||
|
||||
// A neighbor bounds the marker unless they overlap
|
||||
if overlap(previous) == MarkerOverlap::Never
|
||||
&& let Some(previous) = position(previous)
|
||||
{
|
||||
lower = lower.max(previous);
|
||||
}
|
||||
if overlap(Some(index)) == MarkerOverlap::Never
|
||||
&& let Some(next) = position(next)
|
||||
{
|
||||
upper = upper.min(next);
|
||||
}
|
||||
|
||||
// Past a neighbor overlapping only its next, the marker beyond bounds it too, unless either overlaps freely
|
||||
let bounds_beyond = |near: MarkerOverlap, far: MarkerOverlap| (near == MarkerOverlap::NextOnly || far == MarkerOverlap::NextOnly) && near != MarkerOverlap::Freely && far != MarkerOverlap::Freely;
|
||||
if bounds_beyond(overlap(previous), overlap(before_previous))
|
||||
&& let Some(before_previous) = position(before_previous)
|
||||
{
|
||||
lower = lower.max(before_previous);
|
||||
}
|
||||
if bounds_beyond(overlap(Some(index)), overlap(next))
|
||||
&& let Some(after_next) = position(after_next)
|
||||
{
|
||||
upper = upper.min(after_next);
|
||||
}
|
||||
|
||||
(lower, upper)
|
||||
}
|
||||
|
||||
/// Append a section of related parameters as rows: a shared slider over `track` (with one marker per non-exposed parameter) sits on the first non-exposed row
|
||||
/// alongside its 60px number input, and the remaining non-exposed rows show only their 60px number input. Exposed parameters render as the standard exposed-row display.
|
||||
/// Marker positions are clamped to non-decreasing display order so they never visually cross even if the underlying values do.
|
||||
/// Marker positions are clamped to non-decreasing display order so they never visually cross even if the underlying values do, except where they may overlap.
|
||||
fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorContext, track: &Gradient, params: &[SliderSectionParam], layout: &mut Vec<LayoutGroup>) {
|
||||
// Snapshot exposure and values before the mutable-borrow loop
|
||||
let exposure_and_value: Vec<(bool, f64)> = match get_document_node(node_id, context) {
|
||||
@@ -2084,6 +2082,7 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
|
||||
let mut marker_scales = Vec::new();
|
||||
let mut marker_positions = Vec::new();
|
||||
let mut marker_between = Vec::new();
|
||||
let mut marker_overlaps = Vec::new();
|
||||
let mut marker_colors_and_links = Vec::new();
|
||||
for (i, param) in params.iter().enumerate() {
|
||||
let (exposed, value) = exposure_and_value[i];
|
||||
@@ -2096,13 +2095,21 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
|
||||
marker_default_positions.push(param.scale.position(param.default_value));
|
||||
marker_scales.push(param.scale);
|
||||
marker_between.push(param.between_neighbors);
|
||||
marker_overlaps.push(if next_has_marker { param.overlap_next } else { MarkerOverlap::Never });
|
||||
marker_colors_and_links.push((param.handle_color, param.pair_with_next && next_has_marker, param.dash_to_next && next_has_marker));
|
||||
}
|
||||
|
||||
// Enforce non-decreasing order so markers never visually cross, matching the node's algorithm where shadows takes precedence.
|
||||
// A marker placed between its neighbors bounds nothing here and instead takes its scale position within their settled span.
|
||||
let cyclic = params.iter().any(|param| param.scale.cyclic());
|
||||
if !cyclic {
|
||||
let overlapping = marker_overlaps.iter().any(|&overlap| overlap != MarkerOverlap::Never);
|
||||
if overlapping {
|
||||
// Markers allowed to overlap are held only past those they can't pass, each bounded by markers earlier in the list
|
||||
for i in 0..marker_positions.len() {
|
||||
let (lower, _) = overlap_bounds(&marker_positions, &marker_overlaps, i);
|
||||
marker_positions[i] = marker_positions[i].max(lower);
|
||||
}
|
||||
} else if !cyclic {
|
||||
let mut floor = 0.;
|
||||
for (position, &between) in marker_positions.iter_mut().zip(&marker_between) {
|
||||
if between {
|
||||
@@ -2123,8 +2130,8 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
|
||||
let slider_markers: Vec<SliderMarker> = marker_positions
|
||||
.iter()
|
||||
.zip(&marker_colors_and_links)
|
||||
.zip(&marker_between)
|
||||
.map(|((&position, &(handle_color, paired, dashed)), &between)| {
|
||||
.zip(marker_between.iter().zip(&marker_overlaps))
|
||||
.map(|((&position, &(handle_color, paired, dashed)), (&between, &overlap))| {
|
||||
let mut marker = SliderMarker::new(position, 0.5, handle_color);
|
||||
if paired {
|
||||
marker = marker.pair_with_next();
|
||||
@@ -2135,6 +2142,7 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
|
||||
if between {
|
||||
marker = marker.between_neighbors();
|
||||
}
|
||||
marker = marker.overlap_next(overlap);
|
||||
marker
|
||||
})
|
||||
.collect();
|
||||
@@ -2156,6 +2164,7 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
|
||||
let marker_scales = marker_scales.clone();
|
||||
let marker_positions = marker_positions.clone();
|
||||
let marker_between = marker_between.clone();
|
||||
let marker_overlaps = marker_overlaps.clone();
|
||||
move |update: &SliderInputUpdate| {
|
||||
let i = match update {
|
||||
SliderInputUpdate::MoveMarker { index, .. } | SliderInputUpdate::ResetMarker { index } => *index as usize,
|
||||
@@ -2170,8 +2179,13 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
|
||||
// The span the marker's scale maps onto: its neighbors' positions when placed between them, otherwise the track between the
|
||||
// nearest markers that bound it, which a marker placed between its neighbors never does
|
||||
let bounding = |j: usize| between || !marker_between[j];
|
||||
let left = (0..i).rev().find(|&j| bounding(j)).map_or(0., |j| marker_positions[j]);
|
||||
let right = (i + 1..marker_positions.len()).find(|&j| bounding(j)).map_or(1., |j| marker_positions[j]);
|
||||
let (left, right) = if overlapping {
|
||||
overlap_bounds(&marker_positions, &marker_overlaps, i)
|
||||
} else {
|
||||
let left = (0..i).rev().find(|&j| bounding(j)).map_or(0., |j| marker_positions[j]);
|
||||
let right = (i + 1..marker_positions.len()).find(|&j| bounding(j)).map_or(1., |j| marker_positions[j]);
|
||||
(left, right)
|
||||
};
|
||||
|
||||
let scale_position = match update {
|
||||
SliderInputUpdate::MoveMarker { position, .. } if between => {
|
||||
@@ -2596,6 +2610,105 @@ pub(crate) fn threshold_inspector(node_id: NodeId, context: &mut NodeInspectorCo
|
||||
layout
|
||||
}
|
||||
|
||||
pub(crate) fn blend_if_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||
use graphene_std::blending_nodes::blend_if::blend_if::*;
|
||||
|
||||
let channel = enum_choice::<BlendIfChannel>()
|
||||
.for_socket(ParameterWidgetsInfo::new(node_id, ChannelInput, true, context))
|
||||
.inspector_row();
|
||||
|
||||
let channel_value = match get_document_node(node_id, context).ok().and_then(|document_node| document_node.input_value(ChannelInput).cloned()) {
|
||||
Some(TaggedValue::BlendIfChannel(channel)) => channel,
|
||||
_ => BlendIfChannel::Gray,
|
||||
};
|
||||
let ([content, underlying], track_color): ([[ParameterRef; 4]; 2], Color) = match channel_value {
|
||||
BlendIfChannel::Gray => (
|
||||
[
|
||||
[
|
||||
ContentFalloffStartInput.into(),
|
||||
ContentRangeStartInput.into(),
|
||||
ContentRangeEndInput.into(),
|
||||
ContentFalloffEndInput.into(),
|
||||
],
|
||||
[
|
||||
UnderlyingFalloffStartInput.into(),
|
||||
UnderlyingRangeStartInput.into(),
|
||||
UnderlyingRangeEndInput.into(),
|
||||
UnderlyingFalloffEndInput.into(),
|
||||
],
|
||||
],
|
||||
Color::WHITE,
|
||||
),
|
||||
BlendIfChannel::Red => (
|
||||
[
|
||||
[
|
||||
RedContentFalloffStartInput.into(),
|
||||
RedContentRangeStartInput.into(),
|
||||
RedContentRangeEndInput.into(),
|
||||
RedContentFalloffEndInput.into(),
|
||||
],
|
||||
[
|
||||
RedUnderlyingFalloffStartInput.into(),
|
||||
RedUnderlyingRangeStartInput.into(),
|
||||
RedUnderlyingRangeEndInput.into(),
|
||||
RedUnderlyingFalloffEndInput.into(),
|
||||
],
|
||||
],
|
||||
Color::RED,
|
||||
),
|
||||
BlendIfChannel::Green => (
|
||||
[
|
||||
[
|
||||
GreenContentFalloffStartInput.into(),
|
||||
GreenContentRangeStartInput.into(),
|
||||
GreenContentRangeEndInput.into(),
|
||||
GreenContentFalloffEndInput.into(),
|
||||
],
|
||||
[
|
||||
GreenUnderlyingFalloffStartInput.into(),
|
||||
GreenUnderlyingRangeStartInput.into(),
|
||||
GreenUnderlyingRangeEndInput.into(),
|
||||
GreenUnderlyingFalloffEndInput.into(),
|
||||
],
|
||||
],
|
||||
Color::GREEN,
|
||||
),
|
||||
BlendIfChannel::Blue => (
|
||||
[
|
||||
[
|
||||
BlueContentFalloffStartInput.into(),
|
||||
BlueContentRangeStartInput.into(),
|
||||
BlueContentRangeEndInput.into(),
|
||||
BlueContentFalloffEndInput.into(),
|
||||
],
|
||||
[
|
||||
BlueUnderlyingFalloffStartInput.into(),
|
||||
BlueUnderlyingRangeStartInput.into(),
|
||||
BlueUnderlyingRangeEndInput.into(),
|
||||
BlueUnderlyingFalloffEndInput.into(),
|
||||
],
|
||||
],
|
||||
Color::BLUE,
|
||||
),
|
||||
};
|
||||
|
||||
// Each side's range runs along its channel's levels as a black split handle joined to a white one, with the fully shown range dashed between them
|
||||
let track = Gradient::from(vec![Color::BLACK, track_color]);
|
||||
let mut layout = vec![channel];
|
||||
for [falloff_start, range_start, range_end, falloff_end] in [content, underlying] {
|
||||
let params = [
|
||||
SliderSectionParam::new(falloff_start, Color::BLACK, 0., MarkerScale::LevelPercent).pair_with_next(),
|
||||
SliderSectionParam::new(range_start, Color::BLACK, 0., MarkerScale::LevelPercent)
|
||||
.dash_to_next()
|
||||
.overlap_next(MarkerOverlap::Freely),
|
||||
SliderSectionParam::new(range_end, Color::WHITE, 100., MarkerScale::LevelPercent).pair_with_next(),
|
||||
SliderSectionParam::new(falloff_end, Color::WHITE, 100., MarkerScale::LevelPercent),
|
||||
];
|
||||
build_shared_slider_section(node_id, context, &track, ¶ms, &mut layout);
|
||||
}
|
||||
layout
|
||||
}
|
||||
|
||||
pub(crate) fn vibrance_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||
use graphene_std::raster::vibrance::*;
|
||||
|
||||
@@ -2848,10 +2961,10 @@ pub(crate) fn grid_inspector(node_id: NodeId, context: &mut NodeInspectorContext
|
||||
ParameterWidgetsInfo::new(node_id, SpacingInput, true, context),
|
||||
NumberInput::default().label("H").min(0.).unit(" px"),
|
||||
));
|
||||
let angles = vec2_widget(ParameterWidgetsInfo::new(node_id, AnglesInput, true, context), "", "", "°", None, None, false, false);
|
||||
let angles = vec2_widget(ParameterWidgetsInfo::new(node_id, AnglesInput, true, context), "", "", "°", None, false, false);
|
||||
widgets.extend([spacing, angles]);
|
||||
} else {
|
||||
let spacing = vec2_widget(ParameterWidgetsInfo::new(node_id, SpacingInput, true, context), "W", "H", " px", Some(0.), None, false, false);
|
||||
let spacing = vec2_widget(ParameterWidgetsInfo::new(node_id, SpacingInput, true, context), "W", "H", " px", Some(0.), false, false);
|
||||
widgets.push(spacing);
|
||||
}
|
||||
}
|
||||
@@ -3314,20 +3427,40 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
|
||||
}
|
||||
|
||||
let row = context.call_widget_override(&node_id, input_index).unwrap_or_else(|| {
|
||||
let field = context.network_interface.field_metadata(&node_id, input_index, context.selection_network_path);
|
||||
let options = field.as_ref().map(ParameterOptions::from_field).unwrap_or_default();
|
||||
|
||||
let Some(implementation) = context.network_interface.implementation(&node_id, context.selection_network_path) else {
|
||||
log::error!("Could not get implementation for node {node_id}");
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
let mut options = ParameterOptions::default();
|
||||
let input_type = match implementation {
|
||||
DocumentNodeImplementation::ProtoNode(proto_node_identifier) => 'early_return: {
|
||||
// Clone to end the `network_interface` borrow held via `implementation`, freeing the mutable borrow `input_type` needs below
|
||||
let proto_node_identifier = proto_node_identifier.clone();
|
||||
|
||||
if let Some(default) = field.and_then(|field| field.default_type) {
|
||||
let mut default_type = None;
|
||||
if let Some(field) = graphene_std::registry::NODE_METADATA
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get(&proto_node_identifier)
|
||||
.and_then(|metadata| metadata.fields.get(input_index))
|
||||
{
|
||||
options = ParameterOptions {
|
||||
soft_min: field.number_soft_min,
|
||||
soft_max: field.number_soft_max,
|
||||
hard_min: field.number_hard_min,
|
||||
hard_max: field.number_hard_max,
|
||||
slider: field.number_mode_range,
|
||||
multiline: field.multiline,
|
||||
progression: field.progression,
|
||||
unit: field.unit,
|
||||
display_decimal_places: field.number_display_decimal_places,
|
||||
step: field.number_step,
|
||||
};
|
||||
default_type = field.default_type.clone();
|
||||
}
|
||||
|
||||
if let Some(default) = default_type {
|
||||
break 'early_return default;
|
||||
}
|
||||
|
||||
@@ -3343,21 +3476,12 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
|
||||
let Some(input_type) = input_type else { return Vec::new() };
|
||||
input_type.clone()
|
||||
}
|
||||
_ => {
|
||||
// A graph import's declared type still picks its widget while its wire's type is unresolved, such as during an error inside the subgraph
|
||||
let declared_type = field.and_then(|field| field.default_type).map(|declared_type| match declared_type {
|
||||
Type::Item(element) => *element,
|
||||
declared_type => declared_type,
|
||||
});
|
||||
|
||||
context
|
||||
.network_interface
|
||||
.input_type(&InputConnector::node_at_index(node_id, input_index), context.selection_network_path)
|
||||
.compiled_nested_type()
|
||||
.cloned()
|
||||
.or(declared_type)
|
||||
.unwrap_or(concrete!(()))
|
||||
}
|
||||
_ => context
|
||||
.network_interface
|
||||
.input_type(&InputConnector::node_at_index(node_id, input_index), context.selection_network_path)
|
||||
.compiled_nested_type()
|
||||
.cloned()
|
||||
.unwrap_or(concrete!(())),
|
||||
};
|
||||
|
||||
inspector_row_from_type(node_id, input_index, &input_type, options, context).unwrap_or_else(|value| value)
|
||||
@@ -3862,7 +3986,7 @@ pub(crate) fn displace_inspector(node_id: NodeId, context: &mut NodeInspectorCon
|
||||
if !matches!(mode, Some(DisplaceMode::Angle)) {
|
||||
layout.push(color_widget(ParameterWidgetsInfo::new(node_id, XDisplacementInput, true, context), ColorInput::default()));
|
||||
layout.push(color_widget(ParameterWidgetsInfo::new(node_id, YDisplacementInput, true, context), ColorInput::default()));
|
||||
layout.push(vec2_widget(ParameterWidgetsInfo::new(node_id, OffsetInput, true, context), "X", "Y", " px", None, None, false, false));
|
||||
layout.push(vec2_widget(ParameterWidgetsInfo::new(node_id, OffsetInput, true, context), "X", "Y", " px", None, false, false));
|
||||
}
|
||||
|
||||
let edge_mode = enum_choice::<GradientSpread>()
|
||||
|
||||
@@ -59,6 +59,7 @@ use crate::messages::portfolio::document::utility_types::network_interface::reso
|
||||
use crate::messages::portfolio::document::utility_types::text_metrics::text_width;
|
||||
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_thick_wire_center_line, build_vector_wire};
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use crate::messages::tool::tool_messages::tool_prelude::NumberInputMode;
|
||||
use deserialization::deserialize_node_persistent_metadata;
|
||||
use glam::{DAffine2, DVec2, IVec2};
|
||||
use graph_craft::Type;
|
||||
@@ -73,7 +74,7 @@ use graphene_std::vector::click_target::{ClickTarget, ClickTargetType, FreePoint
|
||||
use graphene_std::vector::{Vector, VectorModificationType};
|
||||
use kurbo::BezPath;
|
||||
use memo_network::MemoNetwork;
|
||||
use serde_json::Value;
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::hash::Hash;
|
||||
use std::ops::Deref;
|
||||
|
||||
+1
-1
@@ -2613,7 +2613,7 @@ async fn shaking_a_node_spliced_in_by_a_secondary_input_keeps_the_dot_on_its_wir
|
||||
// Numbers to Vec2 hides its primary input, so it takes the flow by its first exposed input instead
|
||||
let source = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await;
|
||||
let shaken = editor
|
||||
.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec2::IDENTIFIER), 10, 0)
|
||||
.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec_2::IDENTIFIER), 10, 0)
|
||||
.await;
|
||||
let dot = editor.create_node_by_name_at(passthrough_definition(), 20, 0).await;
|
||||
let consumer = editor.create_node_by_name_at(fill_definition(), 30, 0).await;
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
use super::*;
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
/// Index of the Artboard definition's Clip input, which must match the input order authored in document_node_definitions.rs.
|
||||
pub(crate) const ARTBOARD_CLIP_INPUT_INDEX: usize = 5;
|
||||
|
||||
impl NodeNetworkInterface {
|
||||
/// Runs a query against a resolved [`NetworkView`], logging any error at this message-boundary wrapper and mapping it to None.
|
||||
pub(crate) fn query<'a, 'p, T>(&'a self, network_path: &'p [NodeId], caller: &str, query: impl FnOnce(NetworkView<'a, 'p>) -> Result<T, NetworkError>) -> Option<T> {
|
||||
@@ -826,27 +829,17 @@ impl NodeNetworkInterface {
|
||||
self.view(network_path).ok().and_then(|view| view.persistent_input_metadata(node_id, index).ok())
|
||||
}
|
||||
|
||||
/// Whether the input is internal state of its node (named with a leading `_`), which is never exposed to the graph.
|
||||
/// Whether the input is internal state of its proto node (named with a leading `_`), which is never exposed to the graph.
|
||||
pub fn is_internal_input(&self, node_id: &NodeId, index: usize, network_path: &[NodeId]) -> bool {
|
||||
self.field_metadata(node_id, index, network_path).is_some_and(|field| field.internal)
|
||||
}
|
||||
|
||||
/// The metadata the node macro records for a proto node's parameter, or the `#[graph]` macro for a graph node's import.
|
||||
/// A graph node's input has it only while it still has that import's name, since an edited subgraph can reorder its imports.
|
||||
pub fn field_metadata(&self, node_id: &NodeId, index: usize, network_path: &[NodeId]) -> Option<graphene_std::registry::FieldMetadata> {
|
||||
if let Some(DocumentNodeImplementation::ProtoNode(proto_node_identifier)) = self.implementation(node_id, network_path) {
|
||||
let node_metadata = graphene_std::registry::NODE_METADATA.lock().ok()?;
|
||||
return node_metadata.get(proto_node_identifier)?.fields.get(index).cloned();
|
||||
}
|
||||
|
||||
let Some(DefinitionIdentifier::Network(identifier)) = self.reference(node_id, network_path) else {
|
||||
return None;
|
||||
let Some(DocumentNodeImplementation::ProtoNode(proto_node_identifier)) = self.implementation(node_id, network_path) else {
|
||||
return false;
|
||||
};
|
||||
let input_name = self.persistent_input_metadata(node_id, index, network_path)?.input_name.clone();
|
||||
let Ok(node_metadata) = graphene_std::registry::NODE_METADATA.lock() else { return false };
|
||||
|
||||
let graphs = graphene_std::registry::GRAPH_METADATA.lock().ok()?;
|
||||
let field = graphs.iter().find(|graph| graph.identifier == identifier)?.imports.get(index)?;
|
||||
(field.name == input_name).then(|| field.clone())
|
||||
node_metadata
|
||||
.get(proto_node_identifier)
|
||||
.and_then(|metadata| metadata.fields.get(index))
|
||||
.is_some_and(|field| field.internal)
|
||||
}
|
||||
|
||||
/// The description stored for a node's output, or else for a proto node, the doc comment on its field in the struct a multi-output node returns.
|
||||
@@ -1086,7 +1079,7 @@ impl NodeNetworkInterface {
|
||||
/// Whether the artboard layer clips the content inside it to its bounds.
|
||||
fn artboard_clips_content(&self, artboard: LayerNodeIdentifier) -> bool {
|
||||
self.document_node(&artboard.to_node(), &[])
|
||||
.and_then(|artboard| artboard.inputs.get(graphene_std::subgraphs::artboard::ClipInput::INDEX))
|
||||
.and_then(|artboard| artboard.inputs.get(ARTBOARD_CLIP_INPUT_INDEX))
|
||||
.is_some_and(|clip_input| matches!(clip_input, NodeInput::Value { tagged_value, .. } if tagged_value.clone().deref() == &TaggedValue::Bool(true)))
|
||||
}
|
||||
|
||||
|
||||
@@ -773,11 +773,51 @@ impl PartialEq for DocumentNodeMetadata {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct NumberInputSettings {
|
||||
pub unit: Option<String>,
|
||||
pub min: Option<f64>,
|
||||
pub max: Option<f64>,
|
||||
pub step: Option<f64>,
|
||||
pub mode: NumberInputMode,
|
||||
pub range_min: Option<f64>,
|
||||
pub range_max: Option<f64>,
|
||||
pub is_integer: bool,
|
||||
pub blank_assist: bool,
|
||||
}
|
||||
|
||||
impl Default for NumberInputSettings {
|
||||
fn default() -> Self {
|
||||
NumberInputSettings {
|
||||
unit: None,
|
||||
min: None,
|
||||
max: None,
|
||||
step: None,
|
||||
mode: NumberInputMode::default(),
|
||||
range_min: None,
|
||||
range_max: None,
|
||||
is_integer: false,
|
||||
blank_assist: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct Vec2InputSettings {
|
||||
pub x: String,
|
||||
pub y: String,
|
||||
pub unit: String,
|
||||
pub min: Option<f64>,
|
||||
pub is_integer: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub enum WidgetOverride {
|
||||
None,
|
||||
Hidden,
|
||||
String(String),
|
||||
Number(NumberInputSettings),
|
||||
Vec2(Vec2InputSettings),
|
||||
Custom(String),
|
||||
}
|
||||
|
||||
@@ -814,6 +854,40 @@ impl InputPersistentMetadata {
|
||||
self.input_data.insert("string_inspector".to_string(), Value::String(string_inspector));
|
||||
self.widget_override = Some("string".to_string());
|
||||
}
|
||||
WidgetOverride::Number(mut number_inspector) => {
|
||||
if let Some(unit) = number_inspector.unit.take() {
|
||||
self.input_data.insert("unit".to_string(), json!(unit));
|
||||
}
|
||||
if let Some(min) = number_inspector.min.take() {
|
||||
self.input_data.insert("min".to_string(), json!(min));
|
||||
}
|
||||
if let Some(max) = number_inspector.max.take() {
|
||||
self.input_data.insert("max".to_string(), json!(max));
|
||||
}
|
||||
if let Some(step) = number_inspector.step.take() {
|
||||
self.input_data.insert("step".to_string(), json!(step));
|
||||
}
|
||||
if let Some(range_min) = number_inspector.range_min.take() {
|
||||
self.input_data.insert("range_min".to_string(), json!(range_min));
|
||||
}
|
||||
if let Some(range_max) = number_inspector.range_max.take() {
|
||||
self.input_data.insert("range_max".to_string(), json!(range_max));
|
||||
}
|
||||
self.input_data.insert("mode".to_string(), json!(number_inspector.mode));
|
||||
self.input_data.insert("is_integer".to_string(), Value::Bool(number_inspector.is_integer));
|
||||
self.input_data.insert("blank_assist".to_string(), Value::Bool(number_inspector.blank_assist));
|
||||
self.widget_override = Some("number".to_string());
|
||||
}
|
||||
WidgetOverride::Vec2(vec2_inspector) => {
|
||||
self.input_data.insert("x".to_string(), json!(vec2_inspector.x));
|
||||
self.input_data.insert("y".to_string(), json!(vec2_inspector.y));
|
||||
self.input_data.insert("unit".to_string(), json!(vec2_inspector.unit));
|
||||
self.input_data.insert("is_integer".to_string(), Value::Bool(vec2_inspector.is_integer));
|
||||
if let Some(min) = vec2_inspector.min {
|
||||
self.input_data.insert("min".to_string(), json!(min));
|
||||
}
|
||||
self.widget_override = Some("vec2".to_string());
|
||||
}
|
||||
WidgetOverride::Custom(lambda_name) => {
|
||||
self.widget_override = Some(lambda_name);
|
||||
}
|
||||
|
||||
@@ -472,9 +472,9 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
],
|
||||
},
|
||||
// The old 'Vec2 Value' node took separate X and Y inputs, a role now filled by 'Numbers to Vec2', while the new 'Vec2 Value' node takes a single vec2 input.
|
||||
// Old references (including these older aliases) are remapped here to `vec2_value::IDENTIFIER` so the per-node migration in `migrate_node` can detect the leftover 3-input shape and convert it into a 'Numbers to Vec2' node.
|
||||
// Old references (including these older aliases) are remapped here to `vec_2_value::IDENTIFIER` so the per-node migration in `migrate_node` can detect the leftover 3-input shape and convert it into a 'Numbers to Vec2' node.
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::vec2_value::IDENTIFIER,
|
||||
node: graphene_std::math_nodes::vec_2_value::IDENTIFIER,
|
||||
aliases: &[
|
||||
"graphene_math_nodes::Vec2ValueNode",
|
||||
"graphene_core::ops::ConstructVector2",
|
||||
@@ -484,7 +484,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::numbers_to_vec2::IDENTIFIER,
|
||||
node: graphene_std::math_nodes::numbers_to_vec_2::IDENTIFIER,
|
||||
aliases: &["math_nodes::CombineVec2Node"],
|
||||
},
|
||||
// ================================
|
||||
@@ -1576,8 +1576,8 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
// A wrapper saved before these gained a hidden primary output had each field one output lower, so its wires shift up by one.
|
||||
// Pre-pass for the same reason as the Brush, Transform, and Image migrations above: replacing the outer network impl orphans its child paths.
|
||||
let split_wrapper_replacements = [
|
||||
("Split Vec2", graphene_std::math_nodes::vec2_to_numbers::IDENTIFIER),
|
||||
("Split Vector2", graphene_std::math_nodes::vec2_to_numbers::IDENTIFIER),
|
||||
("Split Vec2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
|
||||
("Split Vector2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
|
||||
("Split Channels", graphene_std::raster_nodes::adjustments::image_to_channels::IDENTIFIER),
|
||||
];
|
||||
for (old_reference, new_identifier) in split_wrapper_replacements {
|
||||
@@ -1641,7 +1641,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
let DocumentNodeImplementation::ProtoNode(protonode_id) = &node.implementation else { return None };
|
||||
let name = protonode_id.as_str().split('<').next().unwrap_or_default();
|
||||
if EXTRACT_XY.contains(&name) {
|
||||
Some((*node_id, path, graphene_std::math_nodes::vec2_to_numbers::IDENTIFIER, "Extract XY"))
|
||||
Some((*node_id, path, graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER, "Extract XY"))
|
||||
} else if EXTRACT_CHANNEL.contains(&name) {
|
||||
Some((*node_id, path, graphene_std::raster_nodes::adjustments::image_to_channels::IDENTIFIER, "Extract Channel"))
|
||||
} else {
|
||||
@@ -2931,8 +2931,8 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
|
||||
// Convert the old 'Vec2 Value' node, identified by its leftover 3-input shape with separate X and Y inputs,
|
||||
// into the 'Numbers to Vec2' node which now fills that role (the new 'Vec2 Value' node instead takes a single vec2 input)
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::vec2_value::IDENTIFIER) && inputs_count == 3 {
|
||||
let numbers_to_vec2_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec2::IDENTIFIER);
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::vec_2_value::IDENTIFIER) && inputs_count == 3 {
|
||||
let numbers_to_vec2_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec_2::IDENTIFIER);
|
||||
let mut node_template = resolve_document_node_type(&numbers_to_vec2_reference)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
|
||||
@@ -5230,11 +5230,7 @@ mod tests {
|
||||
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
|
||||
panic!("Blend should be a network node")
|
||||
};
|
||||
let (&count_conversion_id, count_conversion) = network_template
|
||||
.nodes
|
||||
.iter_mut()
|
||||
.find(|(_, node)| node.inputs.iter().any(|input| matches!(input, NodeInput::Import { import_index: 1, .. })))
|
||||
.expect("Blend should have a count conversion node");
|
||||
let count_conversion = network_template.nodes.get_mut(&NodeId(3)).expect("Blend should have a count conversion node");
|
||||
count_conversion.implementation = NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::floor::IDENTIFIER);
|
||||
count_conversion.inputs = vec![NodeInput::import(item!(f64), 1)];
|
||||
document.network_interface.insert_node(node_id, node_template, &[]);
|
||||
@@ -5251,7 +5247,7 @@ mod tests {
|
||||
panic!("Blend should stay a network node")
|
||||
};
|
||||
assert_eq!(
|
||||
inner.nodes[&shipped_node_id("Blend", count_conversion_id)].implementation,
|
||||
inner.nodes[&shipped_node_id("Blend", NodeId(3))].implementation,
|
||||
DocumentNodeImplementation::ProtoNode(graphene_std::math_nodes::as_number::IDENTIFIER)
|
||||
);
|
||||
}
|
||||
@@ -5268,11 +5264,7 @@ mod tests {
|
||||
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
|
||||
panic!("Blend should be a network node")
|
||||
};
|
||||
let (&edited_subtract_id, edited_subtract) = network_template
|
||||
.nodes
|
||||
.iter_mut()
|
||||
.find(|(_, node)| node.implementation == NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::subtract::IDENTIFIER))
|
||||
.expect("Blend should have an open-path denominator node");
|
||||
let edited_subtract = network_template.nodes.get_mut(&NodeId(5)).expect("Blend should have an open-path denominator node");
|
||||
edited_subtract.inputs[1] = NodeInput::value(TaggedValue::Number(42.), false);
|
||||
document.network_interface.insert_node(node_id, node_template, &[]);
|
||||
|
||||
@@ -5282,7 +5274,7 @@ mod tests {
|
||||
let (DocumentNodeImplementation::Definition(definition), Some(inner)) = (implementation, document.network_interface.document_network().implementation_network(implementation)) else {
|
||||
panic!("Blend should stay a network node")
|
||||
};
|
||||
let edited_subtract = derived_node_id(*definition, edited_subtract_id);
|
||||
let edited_subtract = derived_node_id(*definition, NodeId(5));
|
||||
assert_eq!(inner.nodes[&edited_subtract].inputs.get(1).and_then(|input| input.as_value()).cloned(), Some(TaggedValue::Number(42.)));
|
||||
}
|
||||
|
||||
@@ -5364,15 +5356,8 @@ mod tests {
|
||||
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
|
||||
panic!("Regex Find should be a network node")
|
||||
};
|
||||
let inner_node_id = |identifier: graphene_std::ProtoNodeIdentifier| {
|
||||
let implementation = NodeTemplateImplementation::ProtoNode(identifier);
|
||||
network_template.nodes.iter().find(|(_, node)| node.implementation == implementation).map(|(&id, _)| id)
|
||||
};
|
||||
let find_id = inner_node_id(graphene_std::text_nodes::regex::regex_find::IDENTIFIER).expect("Regex Find should have a find node");
|
||||
let item_at_index_id = inner_node_id(graphene_std::graphic::item_at_index::IDENTIFIER).expect("Regex Find should have an item-at-index node");
|
||||
|
||||
network_template.nodes.get_mut(&find_id).expect("the find node should exist").inputs[2] = NodeInput::import(item!(f64), 2);
|
||||
network_template.nodes.get_mut(&item_at_index_id).expect("the item-at-index node should exist").inputs[1] = NodeInput::value(TaggedValue::Number(0.), false);
|
||||
network_template.nodes.get_mut(&NodeId(0)).expect("Regex Find should have a find node").inputs[2] = NodeInput::import(item!(f64), 2);
|
||||
network_template.nodes.get_mut(&NodeId(1)).expect("Regex Find should have an item-at-index node").inputs[1] = NodeInput::value(TaggedValue::Number(0.), false);
|
||||
document.network_interface.insert_node(node_id, node_template, &[]);
|
||||
|
||||
migrate(&mut document);
|
||||
@@ -5386,9 +5371,9 @@ mod tests {
|
||||
let Some(inner) = document.network_interface.document_network().implementation_network(&node.implementation) else {
|
||||
panic!("Regex Find should stay a network node")
|
||||
};
|
||||
assert_eq!(inner.nodes[&shipped_node_id("Regex Find", find_id)].inputs.get(2), Some(&NodeInput::import(item!(i64), 2)));
|
||||
assert_eq!(inner.nodes[&shipped_node_id("Regex Find", NodeId(0))].inputs.get(2), Some(&NodeInput::import(item!(i64), 2)));
|
||||
assert_eq!(
|
||||
inner.nodes[&shipped_node_id("Regex Find", item_at_index_id)].inputs.get(1).and_then(|input| input.as_value()).cloned(),
|
||||
inner.nodes[&shipped_node_id("Regex Find", NodeId(1))].inputs.get(1).and_then(|input| input.as_value()).cloned(),
|
||||
Some(TaggedValue::Integer(0))
|
||||
);
|
||||
}
|
||||
|
||||
@@ -175,6 +175,8 @@ pub struct SnapSession {
|
||||
gesture: Option<Gesture>,
|
||||
/// The targets woken by resting the pointer on them, from the one woken longest ago to the latest.
|
||||
awake: Vec<Awake>,
|
||||
/// Those of them woken during the gesture under way, which go back to sleep when it ends.
|
||||
woken_in_gesture: Vec<Awake>,
|
||||
/// The layers each woken point of its own was found on, by its ID, which it goes back to sleep with.
|
||||
position_sources: HashMap<u64, Vec<LayerId>>,
|
||||
rest: Option<Rest>,
|
||||
@@ -495,13 +497,17 @@ impl SnapSession {
|
||||
landed
|
||||
}
|
||||
|
||||
/// Ends a gesture, however it ended, and forgets what the pointer was snapped to.
|
||||
/// Ends a gesture, however it ended, and forgets what the pointer was snapped to. What the gesture woke goes back to sleep with it.
|
||||
pub fn end_gesture(&mut self) {
|
||||
self.gesture = None;
|
||||
self.constructions = None;
|
||||
self.rest = None;
|
||||
self.crossings.clear();
|
||||
self.forget();
|
||||
|
||||
let woken_in_gesture = std::mem::take(&mut self.woken_in_gesture);
|
||||
self.awake.retain(|target| !woken_in_gesture.contains(target));
|
||||
self.forget_targets_gone_to_sleep();
|
||||
}
|
||||
|
||||
/// Forgets what the pointer was last snapped to, as when the pointer is no longer placing anything.
|
||||
@@ -545,11 +551,14 @@ impl SnapSession {
|
||||
if let Awake::Position { id, .. } = target {
|
||||
self.position_sources.insert(id, sources.clone());
|
||||
}
|
||||
if self.gesture.is_some() {
|
||||
self.woken_in_gesture.push(target);
|
||||
}
|
||||
self.awake.push(target);
|
||||
}
|
||||
let over_the_limit = self.awake.len().saturating_sub(AWAKE_LIMIT);
|
||||
self.awake.drain(..over_the_limit);
|
||||
self.forget_sources_of_sleeping_positions();
|
||||
self.forget_targets_gone_to_sleep();
|
||||
self.constructions = None;
|
||||
|
||||
true
|
||||
@@ -563,6 +572,7 @@ impl SnapSession {
|
||||
/// Puts every woken target back to sleep, and keeps the pointer from waking them again until it moves.
|
||||
pub fn sleep_all(&mut self) {
|
||||
self.awake.clear();
|
||||
self.woken_in_gesture.clear();
|
||||
self.position_sources.clear();
|
||||
self.constructions = None;
|
||||
|
||||
@@ -583,10 +593,12 @@ impl SnapSession {
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn forget_sources_of_sleeping_positions(&mut self) {
|
||||
/// Lets go of what is kept about woken targets that have since gone back to sleep.
|
||||
fn forget_targets_gone_to_sleep(&mut self) {
|
||||
let awake = &self.awake;
|
||||
self.position_sources
|
||||
.retain(|id, _| awake.iter().any(|target| matches!(target, Awake::Position { id: awake_id, .. } if awake_id == id)));
|
||||
self.woken_in_gesture.retain(|target| awake.contains(target));
|
||||
}
|
||||
|
||||
/// The woken targets, oldest first.
|
||||
@@ -721,7 +733,7 @@ impl SnapSession {
|
||||
Awake::Anchor { layer, .. } | Awake::Curve { layer, .. } | Awake::Box { layer } => !changed.contains(layer),
|
||||
Awake::Position { id, .. } => position_sources.get(id).is_none_or(|sources| !sources.iter().any(|layer| changed.contains(layer))),
|
||||
});
|
||||
self.forget_sources_of_sleeping_positions();
|
||||
self.forget_targets_gone_to_sleep();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1100,6 +1112,45 @@ mod tests {
|
||||
assert!(session.tick(1000 + WAKE_DWELL_IN_GESTURE));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_gesture_keeps_track_of_only_the_targets_it_woke_that_are_still_awake() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(100., 100., 300., 240.).await;
|
||||
editor.draw_rect(500., 100., 700., 240.).await;
|
||||
let mut session = SnapSession::default();
|
||||
let input = InputPreprocessorMessageHandler::default();
|
||||
session.begin_gesture(SnapView::new(editor.active_document(), DOCUMENT, &input), Moving::default());
|
||||
|
||||
// Once the limit has put the first edge back to sleep, resting on it again wakes it a second time
|
||||
let along_edges = [(150., 100.), (300., 140.), (250., 240.), (100., 200.), (550., 100.), (700., 140.), (150., 100.)];
|
||||
for (index, position) in along_edges.into_iter().enumerate() {
|
||||
assert!(rest(&mut session, &editor, position.into(), index as u64 * 2000), "nothing woke at {position:?}");
|
||||
}
|
||||
assert_eq!(session.woken_in_gesture, session.awake);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn what_a_gesture_wakes_goes_back_to_sleep_when_it_ends_while_what_was_woken_before_it_stays_awake() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(100., 100., 300., 240.).await;
|
||||
let mut session = SnapSession::default();
|
||||
|
||||
// The top edge is woken before the gesture, and the right edge during it
|
||||
assert!(rest(&mut session, &editor, DVec2::new(150., 100.), 0));
|
||||
let woken_before = session.awake.clone();
|
||||
|
||||
let input = InputPreprocessorMessageHandler::default();
|
||||
session.begin_gesture(SnapView::new(editor.active_document(), DOCUMENT, &input), Moving::default());
|
||||
snap_at_time(&mut session, &editor, DVec2::new(300., 140.), 2000);
|
||||
assert!(session.tick(2000 + WAKE_DWELL_IN_GESTURE));
|
||||
assert_eq!(session.awake.len(), 2);
|
||||
|
||||
session.end_gesture();
|
||||
assert_eq!(session.awake, woken_before);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn only_the_latest_few_woken_targets_stay_awake() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
|
||||
@@ -398,8 +398,7 @@ fn expand_to_thumbnail_aspect(bounds: [DVec2; 2]) -> [DVec2; 2] {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, NodeTemplateImplementation, shipped_node_id};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, shipped_node_id};
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use glam::UVec2;
|
||||
use graph_craft::document::NodeId;
|
||||
@@ -430,20 +429,8 @@ mod tests {
|
||||
editor.draw_rect(0., 0., 10., 10.).await;
|
||||
let layer = editor.get_selected_layer().await.expect("The drawn rectangle should be selected").to_node();
|
||||
|
||||
// The node adding Merge's content to the stack
|
||||
let Some(NodeTemplateImplementation::Network(merge_network)) = resolve_network_node_type("Merge").map(|merge| &merge.node_template.implementation) else {
|
||||
panic!("Merge should be a network node")
|
||||
};
|
||||
let Some((&extend_id, _)) = merge_network
|
||||
.nodes
|
||||
.iter()
|
||||
.find(|(_, node)| node.implementation == NodeTemplateImplementation::ProtoNode(graphene_std::graphic::extend::IDENTIFIER))
|
||||
else {
|
||||
panic!("Merge should extend the stack with its content")
|
||||
};
|
||||
|
||||
compile_and_run(&mut editor).await;
|
||||
let merge_content = compiled_id(&editor, &[layer, layer_path_writer_id(shipped_node_id("Merge", extend_id))]);
|
||||
let merge_content = compiled_id(&editor, &[layer, layer_path_writer_id(shipped_node_id("Merge", NodeId(2)))]);
|
||||
assert!(merge_content.is_some(), "The Merge layer's content should be compiled");
|
||||
assert_eq!(
|
||||
editor.runtime.thumbnails.sources.get(&layer).copied(),
|
||||
|
||||
@@ -140,7 +140,9 @@
|
||||
const reorder = allowReorder && allowSelect;
|
||||
let held = position;
|
||||
|
||||
if (!reorder && !allowWrap) {
|
||||
if (!reorder && !allowWrap && markers.some((marker) => marker.overlapNext !== "Never")) {
|
||||
held = holdWithOverlaps(first, last, position);
|
||||
} else if (!reorder && !allowWrap) {
|
||||
const lower = neighborBound(first, -1) ?? 0;
|
||||
const upper = (neighborBound(last, 1) ?? 1) - spacing;
|
||||
held = Math.max(lower, Math.min(upper, position));
|
||||
@@ -156,6 +158,33 @@
|
||||
return wrap ? held - Math.floor(held) : Math.max(0, Math.min(1 - spacing, held));
|
||||
}
|
||||
|
||||
// Holds markers `first..=last` moving to `position` within the track and each member's bounds from the markers outside the run, as the backend's `overlap_bounds` gives them
|
||||
function holdWithOverlaps(first: number, last: number, position: number): number {
|
||||
const outsideRun = (i: number) => i >= 0 && i < markers.length && (i < first || i > last);
|
||||
const overlap = (i: number) => (i >= 0 && i < markers.length ? markers[i].overlapNext : "Never");
|
||||
const boundsBeyond = (near: number, far: number) => (overlap(near) === "NextOnly" || overlap(far) === "NextOnly") && overlap(near) !== "Freely" && overlap(far) !== "Freely";
|
||||
|
||||
let lower = 0;
|
||||
let upper = 1;
|
||||
for (let k = first; k <= last; k += 1) {
|
||||
const offset = markers[k].position - markers[first].position;
|
||||
lower = Math.max(lower, -offset);
|
||||
upper = Math.min(upper, 1 - offset);
|
||||
|
||||
// A neighbor bounds the marker unless they overlap, and past a neighbor overlapping only its next, so does the marker beyond it
|
||||
const lowerBounds = [overlap(k - 1) === "Never" ? k - 1 : -1, boundsBeyond(k - 1, k - 2) ? k - 2 : -1];
|
||||
const upperBounds = [overlap(k) === "Never" ? k + 1 : -1, boundsBeyond(k, k + 1) ? k + 2 : -1];
|
||||
lowerBounds.filter(outsideRun).forEach((i) => {
|
||||
lower = Math.max(lower, markers[i].position - offset);
|
||||
});
|
||||
upperBounds.filter(outsideRun).forEach((i) => {
|
||||
upper = Math.min(upper, markers[i].position - offset);
|
||||
});
|
||||
}
|
||||
|
||||
return Math.max(lower, Math.min(upper, position));
|
||||
}
|
||||
|
||||
// The position of the nearest marker past `index` in the direction of `step` that bounds others, skipping any placed between its neighbors since those follow them instead
|
||||
function neighborBound(index: number, step: -1 | 1): number | undefined {
|
||||
for (let i = index + step; i >= 0 && i < markers.length; i += step) {
|
||||
@@ -657,7 +686,10 @@
|
||||
}
|
||||
$: midpointPositions = diamondPositions(markers, showMidpoints, trackCyclic, trackInterpolation);
|
||||
$: strips = markerSpans(markers, allowWrap, (marker) => marker.pairedWithNext);
|
||||
$: dashes = markerSpans(markers, allowWrap, (marker) => marker.dashedToNext);
|
||||
// A dashed link vanishes while the markers it joins have overlapped past each other, leaving no span between them
|
||||
$: dashes = markerSpans(markers, allowWrap, (marker) => marker.dashedToNext).filter(
|
||||
({ index }) => markers[index].overlapNext === "Never" || markers[index + 1].position >= markers[index].position,
|
||||
);
|
||||
|
||||
onMount(() => {
|
||||
document.addEventListener("keydown", deleteShortcut);
|
||||
|
||||
+2
-24
@@ -32,7 +32,7 @@ pub struct DocumentNodeDefinition {
|
||||
}
|
||||
```
|
||||
|
||||
None of these definitions are written by hand. A node implemented as a single proto-node has its definition generated from the metadata the `node` macro records about its function signature (see [Creating a new node](#creating-a-new-node)), keyed by the proto-node identifier, which for the Opacity node is `graphene_std::blending_nodes::opacity::IDENTIFIER`. A built-in node made from a subgraph has its definition generated from the `graph` macro (see [Creating a node from a subgraph](#creating-a-node-from-a-subgraph)), keyed by its name.
|
||||
Only the definitions of built-in nodes made from a nested network are written by hand in that file. A node implemented as a single proto-node has its definition generated from the metadata the `node` macro records about its function signature (see [Creating a new node](#creating-a-new-node)), keyed by the proto-node identifier, which for the Opacity node is `graphene_std::blending_nodes::opacity::IDENTIFIER`.
|
||||
|
||||
## Inspector
|
||||
|
||||
@@ -127,29 +127,7 @@ fn opacity<T>(
|
||||
|
||||
## Additional Macro Options
|
||||
|
||||
The macro invocation can be extended with additional attributes. The currently supported attributes are (`name`, `path`, `skip_impl`, `category`). When using generics the `#[implementations()]` attribute can be used to automatically populate the node_registry for you. You can also use the `default`, `expose`, `soft`, `hard`, `range`, `step`, `display_decimal_places`, `unit`, `integer`, `labels`, `blank_assist`, `multiline`, and `progression` attributes to influence how the Inspector widgets are generated. The `#[unit("...")]` attribute appends a suffix like `%` or ` px` to a number's widget, `#[display_decimal_places(2)]` sets how many decimal places a number's widget shows, `#[integer]` makes a number or Vec2 widget take only integers, `#[labels("W", "H")]` names a Vec2 widget's two fields, and `#[blank_assist(false)]` drops the space a widget leaves for its assist area. `#[multiline]` gives a `String` the text area widget and `#[progression]` splits a number into its whole and fractional parts. The `#[soft(a..b)]` and `#[hard(a..b)]` attributes set the slider's suggested extent and its enforced clamp, respectively (either endpoint may be omitted, e.g. `0..` or `..100`; both endpoints are inclusive, so there is no `..=` form), and `#[range]` renders the input as a draggable slider. Values typed into the input may exceed the soft extent but are clamped to the hard bounds, so `#[soft]` is only meaningful together with `#[range]`.
|
||||
|
||||
## Creating a node from a subgraph
|
||||
|
||||
A node built from other nodes uses the `graph` macro, which registers the subgraph as a catalog definition. It takes `category`, `icon`, `name`, and `version` as `node` does, plus `layer` for a node that starts as a layer. Unlike a proto node's, a graph's name (or the title derived from its function name) is also its catalog identifier, which documents store. The function's parameters are the subgraph's imports, which are parsed like a proto node's parameters and take the same value and widget attributes. On an import, `#[hard]` bounds the Inspector widget without clamping a value wired into it. `out!(...)` names the exports. In the body, `>>` feeds its left side into the primary input of the node on its right, every other parameter is named in the call, and a bare name feeds the binding or import of that name into the parameter of the same name. State methods after a call, each written once, set the node's position in grid units (`.at(x, y)`), its display name (`.named("…")`), its flags (`.layer()`, `.hidden()`, `.locked()`, and `.pinned()`), and its call argument (`.call_argument::<Footprint>()`, or `impl Any` for a generic one). An output's name after the call or a binding, like `.captures`, wires from that output instead of the primary one, and goes after any state methods. The body ends with one value per export, as a final expression or with `return`. This is the Load Image node as it exists in `node-graph/nodes/gstd/src/subgraphs.rs`:
|
||||
|
||||
```rs
|
||||
/// Loads an image from a given URL.
|
||||
#[node_macro::graph(category("Data: I/O"), icon("NodeLoadImage"))]
|
||||
pub fn load_image(
|
||||
_: (),
|
||||
/// The web address or local asset path of the image to load.
|
||||
#[name("URL")]
|
||||
url: Item<String>,
|
||||
) -> out!(
|
||||
/// The loaded image.
|
||||
image,
|
||||
) {
|
||||
load_resource(url).at(0, 0) >> bytes_to_image().at(7, 0)
|
||||
}
|
||||
```
|
||||
|
||||
Each node, parameter, and output name resolves through the module the `node` or `graph` macro generates for that node, named after its function, so a misspelled one is reported where it's written. The module's `PARAMETER_COUNT` lets the macro reject `>>` into a node with no parameters. Proto nodes don't name their outputs in that module, so only a graph's outputs can be chosen by name. Every input a call leaves out keeps the default from the node's own definition.
|
||||
The macro invocation can be extended with additional attributes. The currently supported attributes are (`name`, `path`, `skip_impl`, `category`). When using generics the `#[implementations()]` attribute can be used to automatically populate the node_registry for you. You can also use the `default`, `expose`, `soft`, `hard`, `range`, `unit`, `multiline`, and `progression` attributes to influence how the Inspector widgets are generated. The `#[unit("...")]` attribute appends a suffix like `%` or ` px` to a number's widget, while `#[multiline]` gives a `String` the text area widget and `#[progression]` splits a number into its whole and fractional parts. The `#[soft(a..b)]` and `#[hard(a..b)]` attributes set the slider's suggested extent and its enforced clamp, respectively (either endpoint may be omitted, e.g. `0..` or `..100`; both endpoints are inclusive, so there is no `..=` form), and `#[range]` renders the input as a draggable slider. Values typed into the input may exceed the soft extent but are clamped to the hard bounds, so `#[soft]` is only meaningful together with `#[range]`.
|
||||
|
||||
## Executing a document `NodeNetwork`
|
||||
|
||||
|
||||
@@ -551,6 +551,7 @@ tagged_value! {
|
||||
WarpStyle(graphic_types::WarpStyle),
|
||||
WaveType(graphic_types::WaveType),
|
||||
DisplaceMode(graphic_types::DisplaceMode),
|
||||
BlendIfChannel(graphic_types::BlendIfChannel),
|
||||
GridType(vector::misc::GridType),
|
||||
GridTopology(vector::misc::GridTopology),
|
||||
ArcType(vector::misc::ArcType),
|
||||
|
||||
@@ -29,7 +29,7 @@ use graphene_std::vector::misc::{
|
||||
use graphene_std::vector::style::{DashPattern, GradientForm, GradientHueDirection, GradientInterpolation, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector, VectorModification};
|
||||
use graphene_std::{Artboard, Context, Graphic, NodeIO, NodeIOTypes, ProtoNodeIdentifier, concrete, fn_type};
|
||||
use graphene_std::{BevelDirection, BevelStyle, BevelTechnique, GlowSource, GlowTechnique, MaskMode, MinimumMaximumMode, NoiseDistribution};
|
||||
use graphene_std::{BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, GlowSource, GlowTechnique, MaskMode, MinimumMaximumMode, NoiseDistribution};
|
||||
use graphene_std::{DisplaceMode, RadialBlurMethod, WaveType};
|
||||
use node_registry_macros::async_node;
|
||||
use std::collections::HashMap;
|
||||
@@ -303,6 +303,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
WarpStyle,
|
||||
WaveType,
|
||||
DisplaceMode,
|
||||
BlendIfChannel,
|
||||
Stroke,
|
||||
ScaleType,
|
||||
ReferencePoint,
|
||||
|
||||
@@ -60,12 +60,6 @@ pub struct FieldMetadata {
|
||||
pub progression: bool,
|
||||
/// Whether the input must be fed by a value known at compile time, from `#[constant]`.
|
||||
pub constant: bool,
|
||||
/// The X and Y labels of a Vec2 parameter's widget, from `#[labels("W", "H")]`.
|
||||
pub labels: Option<(&'static str, &'static str)>,
|
||||
/// Whether a number or Vec2 parameter's widget only takes integers, from `#[integer]`. Integer types always do.
|
||||
pub integer: bool,
|
||||
/// Whether the widget leaves room for the assist area beside it, which `#[blank_assist(false)]` turns off.
|
||||
pub blank_assist: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -228,167 +222,6 @@ pub static NODE_REGISTRY: NodeRegistry = LazyLock::new(|| Mutex::new(HashMap::ne
|
||||
|
||||
pub static NODE_METADATA: LazyLock<Mutex<HashMap<ProtoNodeIdentifier, NodeMetadata>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||
|
||||
/// Every node defined as a subgraph by the `#[graph]` macro, in registration order.
|
||||
pub static GRAPH_METADATA: LazyLock<Mutex<Vec<GraphMetadata>>> = LazyLock::new(|| Mutex::new(Vec::new()));
|
||||
|
||||
/// A node defined as a subgraph by `#[graph]`, which the editor turns into a catalog definition alongside the proto nodes.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GraphMetadata {
|
||||
/// The definition's identifier and display name.
|
||||
pub identifier: &'static str,
|
||||
pub category: &'static str,
|
||||
pub icon: Option<&'static str>,
|
||||
pub description: &'static str,
|
||||
/// The declaration version from `#[graph(version(N))]`, starting at 1.
|
||||
pub version: u32,
|
||||
/// Whether a new instance starts as a layer, from `#[graph(layer)]`.
|
||||
pub layer: bool,
|
||||
/// The subgraph's imports, which become the inputs of each instance, described like a proto node's parameters.
|
||||
/// Each one's `default_type` is the type it was declared with.
|
||||
pub imports: Vec<FieldMetadata>,
|
||||
pub exports: Vec<GraphExportMetadata>,
|
||||
/// The nodes inside the subgraph, where each node's position in this list is its ID.
|
||||
pub nodes: Vec<GraphNodeMetadata>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GraphExportMetadata {
|
||||
pub name: &'static str,
|
||||
pub description: &'static str,
|
||||
pub source: GraphInputSource,
|
||||
}
|
||||
|
||||
/// A node inside a subgraph defined by `#[graph]`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GraphNodeMetadata {
|
||||
pub implementation: GraphNodeImplementation,
|
||||
/// The inputs the definition sets, by index. Every other input keeps the default from the node's own definition.
|
||||
pub inputs: Vec<(usize, GraphInputSource)>,
|
||||
/// The absolute position in grid units, from `.at(x, y)`.
|
||||
pub position: Option<(i32, i32)>,
|
||||
/// From `.layer()`.
|
||||
pub layer: bool,
|
||||
/// From `.named("…")`.
|
||||
pub display_name: Option<&'static str>,
|
||||
/// From `.hidden()`.
|
||||
pub hidden: bool,
|
||||
/// From `.locked()`.
|
||||
pub locked: bool,
|
||||
/// From `.pinned()`.
|
||||
pub pinned: bool,
|
||||
/// From `.call_argument::<T>()`.
|
||||
pub call_argument: Option<Type>,
|
||||
}
|
||||
|
||||
/// What a node inside a subgraph is an instance of.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum GraphNodeImplementation {
|
||||
ProtoNode(ProtoNodeIdentifier),
|
||||
/// Another node defined by `#[graph]`, named by its identifier.
|
||||
Graph(&'static str),
|
||||
}
|
||||
|
||||
impl From<ProtoNodeIdentifier> for GraphNodeImplementation {
|
||||
fn from(identifier: ProtoNodeIdentifier) -> Self {
|
||||
Self::ProtoNode(identifier)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&'static str> for GraphNodeImplementation {
|
||||
fn from(identifier: &'static str) -> Self {
|
||||
Self::Graph(identifier)
|
||||
}
|
||||
}
|
||||
|
||||
/// What feeds an input, or an export, of a subgraph defined by `#[graph]`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum GraphInputSource {
|
||||
/// The output of another node in the subgraph, by its position in [`GraphMetadata::nodes`].
|
||||
Node { node: usize, output: usize },
|
||||
/// One of the subgraph's imports, with the type its wire records.
|
||||
Import { index: usize, ty: Type },
|
||||
/// A value. Without an exposure, the input keeps the one from the node's own definition.
|
||||
Value { value: GraphValue, exposed: Option<bool> },
|
||||
/// A scope input, from `scope("…")`.
|
||||
Scope(&'static str),
|
||||
/// The document path of the node, from `reflect(NodePath)`.
|
||||
NodePath,
|
||||
/// The source ID of the node, from `reflect(SourceId)`.
|
||||
SourceId,
|
||||
}
|
||||
|
||||
/// A value written in a subgraph definition. The editor converts it to the type of the input it feeds.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum GraphValue {
|
||||
/// A number written without a fractional part, which feeds an integer input as an integer and any other as a number.
|
||||
Integer(i64),
|
||||
Number(f64),
|
||||
Bool(bool),
|
||||
String(String),
|
||||
Vec2(glam::DVec2),
|
||||
Color(Color),
|
||||
}
|
||||
|
||||
impl GraphValue {
|
||||
pub fn vec2(x: f64, y: f64) -> Self {
|
||||
Self::Vec2(glam::DVec2::new(x, y))
|
||||
}
|
||||
|
||||
/// An opaque color from `rgb(0xRRGGBB)`.
|
||||
pub fn rgb(hex: u32) -> Self {
|
||||
let [_, red, green, blue] = hex.to_be_bytes();
|
||||
Self::Color(crate::color::SRGBA8::new(red, green, blue, 255).into())
|
||||
}
|
||||
|
||||
/// A color with alpha from `rgba(0xRRGGBBAA)`.
|
||||
pub fn rgba(hex: u32) -> Self {
|
||||
let [red, green, blue, alpha] = hex.to_be_bytes();
|
||||
Self::Color(crate::color::SRGBA8::new(red, green, blue, alpha).into())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for GraphValue {
|
||||
fn from(value: &str) -> Self {
|
||||
Self::String(value.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<String> for GraphValue {
|
||||
fn from(value: String) -> Self {
|
||||
Self::String(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<bool> for GraphValue {
|
||||
fn from(value: bool) -> Self {
|
||||
Self::Bool(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<f64> for GraphValue {
|
||||
fn from(value: f64) -> Self {
|
||||
Self::Number(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<i64> for GraphValue {
|
||||
fn from(value: i64) -> Self {
|
||||
Self::Integer(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<glam::DVec2> for GraphValue {
|
||||
fn from(value: glam::DVec2) -> Self {
|
||||
Self::Vec2(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Color> for GraphValue {
|
||||
fn from(value: Color) -> Self {
|
||||
Self::Color(value)
|
||||
}
|
||||
}
|
||||
|
||||
/// All multi-output proto nodes (those returning a [`Destructure`] struct), keyed by their identifier.
|
||||
/// Snapshotted on first access, which must happen after startup registration of the node metadata completes.
|
||||
pub static MULTI_OUTPUT_NODES: LazyLock<HashMap<ProtoNodeIdentifier, DestructureMetadata>> = LazyLock::new(|| {
|
||||
|
||||
@@ -300,7 +300,7 @@ impl Adjustment {
|
||||
pub enum DesaturateMethod {
|
||||
/// Light level of the color, the Y (luminance) of Rec. 709, which weights the linear-light RGB channels by `0.2126, 0.7152, 0.0722`.
|
||||
///
|
||||
/// Accessibility contrast ratios and SVG luminance masks use this.
|
||||
/// Accessibility contrast ratios use this.
|
||||
#[default]
|
||||
#[label("Luminance (Rec. 709)")]
|
||||
#[cfg_attr(feature = "serde", serde(alias = "SRGB"))]
|
||||
|
||||
@@ -0,0 +1,361 @@
|
||||
//! Blend If, shaped for PSD interop as its blending ranges: the content shows only where its own colors, and the colors of what lies beneath it, fall within a range of each channel's levels.
|
||||
//! The content's own range fades it like its fill does, leaving the shadows and glows cast from it as they are, and the range beneath fades everything the content draws like its opacity does.
|
||||
|
||||
use crate::effect_layers::is_pixel_filter;
|
||||
use crate::effects::EffectOperation;
|
||||
use crate::parameters::ParameterVisitor;
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use dyn_any::DynAny;
|
||||
|
||||
/// For PSD interop, the gray channel weighs the levels of the gamma-encoded red, green, and blue channels by these percentages.
|
||||
pub const GRAY_PERCENTAGES: [usize; 3] = [30, 59, 11];
|
||||
|
||||
/// How many levels each renderer reads a channel at before weighing it, the 8 bits browsers filter with, so every renderer cuts off the same pixels.
|
||||
pub const CHANNEL_LEVELS: usize = 256;
|
||||
|
||||
/// How near a cutoff a channel may lie, as a fraction of its full scale, and still count as reaching it: a quarter of a level, so a cutoff given in percent lands on the level it names.
|
||||
const CUTOFF_TOLERANCE: f64 = 1. / 1024.;
|
||||
|
||||
/// Which channel of the colors a Blend If range reads.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
#[widget(Dropdown)]
|
||||
pub enum BlendIfChannel {
|
||||
/// The lightness of the colors, weighing red, green, and blue by 30%, 59%, and 11%.
|
||||
#[default]
|
||||
Gray,
|
||||
Red,
|
||||
Green,
|
||||
Blue,
|
||||
}
|
||||
|
||||
/// A range of one channel's levels, in percent, which shows the content fully from its range start to its end and fades it out linearly to nothing at its falloff start and end.
|
||||
/// A falloff that meets its end of the range is a sharp cutoff, which shows the content at the level it lies on.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, CacheHash)]
|
||||
pub struct BlendRange {
|
||||
pub falloff_start: f64,
|
||||
pub range_start: f64,
|
||||
pub range_end: f64,
|
||||
pub falloff_end: f64,
|
||||
}
|
||||
|
||||
impl Default for BlendRange {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
falloff_start: 0.,
|
||||
range_start: 0.,
|
||||
range_end: 100.,
|
||||
falloff_end: 100.,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl BlendRange {
|
||||
/// How strongly the content shows where the channel is `value`, from 0 to 1.
|
||||
pub fn weight(&self, value: f64) -> f64 {
|
||||
let value = value * 100.;
|
||||
let tolerance = CUTOFF_TOLERANCE * 100.;
|
||||
|
||||
// Each side rises (or falls) across its falloff, with its ends taken in either order
|
||||
let side = |falloff: f64, range: f64, rising: bool| {
|
||||
let (low, high) = (falloff.min(range), falloff.max(range));
|
||||
match (high - low > tolerance, rising) {
|
||||
(true, true) => ((value - low) / (high - low)).clamp(0., 1.),
|
||||
(true, false) => ((high - value) / (high - low)).clamp(0., 1.),
|
||||
(false, true) => f64::from(value >= low - tolerance),
|
||||
(false, false) => f64::from(value <= high + tolerance),
|
||||
}
|
||||
};
|
||||
|
||||
side(self.falloff_start, self.range_start, true) * side(self.falloff_end, self.range_end, false)
|
||||
}
|
||||
|
||||
/// Whether the range shows every level fully, so it changes nothing.
|
||||
pub fn shows_everything(&self) -> bool {
|
||||
// Rising then falling, it's full everywhere once it's full at both ends
|
||||
self.weight(0.) >= 1. && self.weight(1.) >= 1.
|
||||
}
|
||||
|
||||
/// The weight at each of the [`CHANNEL_LEVELS`] levels, from black to white.
|
||||
pub fn level_weights(&self) -> Vec<f64> {
|
||||
(0..CHANNEL_LEVELS).map(|level| self.weight(level as f64 / (CHANNEL_LEVELS - 1) as f64)).collect()
|
||||
}
|
||||
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str) {
|
||||
let key = |parameter: &str| format!("{group}_{parameter}");
|
||||
visitor.parameter(&key("falloff_start"), &mut self.falloff_start, 0.);
|
||||
visitor.parameter(&key("range_start"), &mut self.range_start, 0.);
|
||||
visitor.parameter(&key("range_end"), &mut self.range_end, 100.);
|
||||
visitor.parameter(&key("falloff_end"), &mut self.falloff_end, 100.);
|
||||
}
|
||||
}
|
||||
|
||||
/// The ranges each channel's levels must fall within for the content to show, which multiply.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct ChannelRanges {
|
||||
pub gray: BlendRange,
|
||||
pub red: BlendRange,
|
||||
pub green: BlendRange,
|
||||
pub blue: BlendRange,
|
||||
}
|
||||
|
||||
impl ChannelRanges {
|
||||
/// Each channel with its range, in the order the GPU takes them.
|
||||
pub fn channels(&self) -> [(BlendIfChannel, &BlendRange); 4] {
|
||||
[
|
||||
(BlendIfChannel::Gray, &self.gray),
|
||||
(BlendIfChannel::Red, &self.red),
|
||||
(BlendIfChannel::Green, &self.green),
|
||||
(BlendIfChannel::Blue, &self.blue),
|
||||
]
|
||||
}
|
||||
|
||||
/// The channels with ranges that hide some levels.
|
||||
pub fn limiting(&self) -> impl Iterator<Item = (BlendIfChannel, &BlendRange)> {
|
||||
self.channels().into_iter().filter(|(_, range)| !range.shows_everything())
|
||||
}
|
||||
|
||||
/// Whether every channel's range shows every level fully, so they change nothing.
|
||||
pub fn show_everything(&self) -> bool {
|
||||
self.limiting().next().is_none()
|
||||
}
|
||||
|
||||
/// How strongly the content shows for a straight gamma-encoded `color`, each channel (and the gray from them) read at its nearest level.
|
||||
pub fn weight(&self, color: [f64; 3]) -> f64 {
|
||||
self.channel_weights(color).into_iter().product()
|
||||
}
|
||||
|
||||
/// The weight each channel's range gives a straight gamma-encoded `color`, in the order of [`Self::channels`], which multiply to its [`Self::weight`].
|
||||
pub fn channel_weights(&self, color: [f64; 3]) -> [f64; 4] {
|
||||
let levels = color.map(channel_level);
|
||||
let value = |level: usize| level as f64 / (CHANNEL_LEVELS - 1) as f64;
|
||||
let [red, green, blue] = levels.map(value);
|
||||
|
||||
[self.gray.weight(value(gray_level(levels))), self.red.weight(red), self.green.weight(green), self.blue.weight(blue)]
|
||||
}
|
||||
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, side: &str) {
|
||||
self.gray.visit_parameters(visitor, side);
|
||||
self.red.visit_parameters(visitor, &format!("red_{side}"));
|
||||
self.green.visit_parameters(visitor, &format!("green_{side}"));
|
||||
self.blue.visit_parameters(visitor, &format!("blue_{side}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// The level from 0 to 255 nearest a channel's `value` from 0 to 1, with halves rounding up as the browsers' 8-bit filters round them.
|
||||
pub fn channel_level(value: f64) -> usize {
|
||||
((value.clamp(0., 1.) * (CHANNEL_LEVELS - 1) as f64 + 0.5).floor() as usize).min(CHANNEL_LEVELS - 1)
|
||||
}
|
||||
|
||||
/// The gray level of red, green, and blue levels, worked out in whole numbers so a gray exactly between two levels rounds up in every renderer.
|
||||
pub fn gray_level(levels: [usize; 3]) -> usize {
|
||||
let weighed: usize = levels.iter().zip(GRAY_PERCENTAGES).map(|(level, percentage)| level * percentage).sum();
|
||||
(weighed + 50) / 100
|
||||
}
|
||||
|
||||
/// The ranges of Blend If's two sides: those of the content's own colors, which fade the content like its fill, and those of what lies beneath it, which fade all it draws like its opacity.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct BlendIfRanges {
|
||||
pub content: ChannelRanges,
|
||||
pub underlying: ChannelRanges,
|
||||
}
|
||||
|
||||
impl BlendIfRanges {
|
||||
pub(crate) fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor) {
|
||||
self.content.visit_parameters(visitor, "content");
|
||||
self.underlying.visit_parameters(visitor, "underlying");
|
||||
}
|
||||
}
|
||||
|
||||
/// How strongly all the content draws shows over a backdrop pixel with the straight gamma-encoded `color` and `alpha`, by the `underlying` ranges.
|
||||
/// Where nothing lies beneath, nothing is hidden, so the weight eases to full as the backdrop turns transparent.
|
||||
pub fn underlying_weight(underlying: &ChannelRanges, color: [f64; 3], alpha: f64) -> f64 {
|
||||
1. - alpha.clamp(0., 1.) * (1. - underlying.weight(color))
|
||||
}
|
||||
|
||||
/// The Blend If rows that act just before the row at `index` among `rows`: once `index` is the first row (or follows a pixel filter, like a blur or adjustment), those from it up to the next pixel filter.
|
||||
/// So each Blend If reads and fades the content as the pixel filters before it leave it, ahead of the shadows and glows around it, which are knocked out by the content as it then shows.
|
||||
pub fn blend_ifs_acting_before(rows: &[EffectOperation], index: usize) -> Vec<&BlendIfRanges> {
|
||||
let follows_pixel_filter = index.checked_sub(1).is_none_or(|previous| processes_pixels(&rows[previous]));
|
||||
if !follows_pixel_filter {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
(rows[index..].iter())
|
||||
.take_while(|operation| !processes_pixels(operation))
|
||||
.filter_map(|operation| match operation {
|
||||
EffectOperation::BlendIf(ranges) => Some(ranges.as_ref()),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether a solid paint overlay at `index` among `rows` may mix into the content's own colors ahead of the other effects.
|
||||
/// Not where a Blend If reading those colors acts in the same stretch between pixel filters, since it reads them before the overlay paints.
|
||||
pub fn paint_overlay_folds(rows: &[EffectOperation], index: usize) -> bool {
|
||||
let start = rows[..index].iter().rposition(processes_pixels).map_or(0, |previous| previous + 1);
|
||||
let end = rows[index..].iter().position(processes_pixels).map_or(rows.len(), |next| index + next);
|
||||
!fades_content(&rows[start..end])
|
||||
}
|
||||
|
||||
/// Whether a Blend If among the `operations` fades the content by its own colors, as a fill varying across it does.
|
||||
pub fn fades_content(operations: &[EffectOperation]) -> bool {
|
||||
operations
|
||||
.iter()
|
||||
.any(|operation| matches!(operation, EffectOperation::BlendIf(ranges) if !ranges.content.show_everything()))
|
||||
}
|
||||
|
||||
/// Whether a row processes the pixels of everything before it, as a pixel filter (like a blur or adjustment) that changes something does, which ends a stretch of rows that Blend Ifs act at the start of.
|
||||
fn processes_pixels(operation: &EffectOperation) -> bool {
|
||||
is_pixel_filter(operation) && !operation.changes_nothing()
|
||||
}
|
||||
|
||||
/// The ranges beneath of each Blend If row among the `operations` that hides anything by what lies beneath, which multiply.
|
||||
pub fn underlying_ranges<'a>(operations: impl IntoIterator<Item = &'a EffectOperation>) -> Vec<ChannelRanges> {
|
||||
(operations.into_iter())
|
||||
.filter_map(|operation| match operation {
|
||||
EffectOperation::BlendIf(ranges) if !ranges.underlying.show_everything() => Some(ranges.underlying),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn range(falloff_start: f64, range_start: f64, range_end: f64, falloff_end: f64) -> BlendRange {
|
||||
BlendRange {
|
||||
falloff_start,
|
||||
range_start,
|
||||
range_end,
|
||||
falloff_end,
|
||||
}
|
||||
}
|
||||
|
||||
/// A level from 0 to 255 as a channel value.
|
||||
fn level(level: f64) -> f64 {
|
||||
level / 255.
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ranges_fade_linearly_across_their_falloffs() {
|
||||
let percent = |level: f64| level / 255. * 100.;
|
||||
let soft = range(percent(64.), percent(128.), percent(192.), percent(224.));
|
||||
|
||||
assert_eq!(soft.weight(level(32.)), 0.);
|
||||
assert!((soft.weight(level(96.)) - 0.5).abs() < 1e-12);
|
||||
assert_eq!(soft.weight(level(160.)), 1.);
|
||||
assert!((soft.weight(level(208.)) - 0.5).abs() < 1e-12);
|
||||
assert_eq!(soft.weight(level(240.)), 0.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsplit_cutoffs_keep_the_level_they_lie_on() {
|
||||
// For PSD interop, black at 64 keeps 64 and white at 192 keeps 192, given in percent as they'd be imported
|
||||
let percent = |level: f64| level / 255. * 100.;
|
||||
let hard = range(percent(64.), percent(64.), percent(192.), percent(192.));
|
||||
|
||||
assert_eq!(hard.weight(level(63.)), 0.);
|
||||
assert_eq!(hard.weight(level(64.)), 1.);
|
||||
assert_eq!(hard.weight(level(192.)), 1.);
|
||||
assert_eq!(hard.weight(level(193.)), 0.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_range_shows_everything() {
|
||||
assert!(BlendRange::default().shows_everything());
|
||||
assert!(ChannelRanges::default().show_everything());
|
||||
assert!(!range(0., 10., 100., 100.).shows_everything());
|
||||
assert!(!range(0., 0., 100., 99.).shows_everything());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn channels_multiply_with_gray_weighing_the_color() {
|
||||
let ranges = ChannelRanges {
|
||||
gray: range(0., 50., 100., 100.),
|
||||
red: range(0., 0., 50., 100.),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// The gray of a light pink shows fully, but its red at full strength fades it to nothing
|
||||
assert_eq!(ranges.weight([1., 0.5, 0.5]), 0.);
|
||||
// A dark red's gray, read at its own level, lies partway up its falloff, while its red lies within its range
|
||||
let red = level(77.);
|
||||
let gray = gray_level([77, 0, 0]) as f64 / 255.;
|
||||
let expected = (gray * 100. / 50.) * ((100. - red * 100.) / 50.).min(1.);
|
||||
assert!((ranges.weight([red, 0., 0.]) - expected).abs() < 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_beneath_hides_nothing() {
|
||||
let underlying = ChannelRanges {
|
||||
gray: range(50., 50., 100., 100.),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
assert_eq!(underlying_weight(&underlying, [0.; 3], 0.), 1.);
|
||||
assert_eq!(underlying_weight(&underlying, [0.; 3], 1.), 0.);
|
||||
assert!((underlying_weight(&underlying, [0.; 3], 0.25) - 0.75).abs() < 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blend_ifs_act_after_the_blurs_and_adjustments_before_them() {
|
||||
let blend_if = EffectOperation::BlendIf(Box::default());
|
||||
let blur = EffectOperation::Blur {
|
||||
radius_mask: Default::default(),
|
||||
radius: 2.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
};
|
||||
let shadow = EffectOperation::default_for(crate::EffectKind::DropShadow);
|
||||
let rows = [shadow.clone(), blend_if.clone(), blur, shadow, blend_if];
|
||||
|
||||
// The first acts ahead of the shadow before it, and the second just after the blur, ahead of the shadow between them
|
||||
let acting: Vec<usize> = (0..rows.len()).map(|index| blend_ifs_acting_before(&rows, index).len()).collect();
|
||||
assert_eq!(acting, [1, 0, 0, 1, 0]);
|
||||
|
||||
// A blur of no radius changes nothing, so it starts no stretch of its own
|
||||
let no_blur = EffectOperation::Blur {
|
||||
radius_mask: Default::default(),
|
||||
radius: 0.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
};
|
||||
let rows = [EffectOperation::default_for(crate::EffectKind::DropShadow), no_blur, EffectOperation::BlendIf(Box::default())];
|
||||
assert_eq!(blend_ifs_acting_before(&rows, 0).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grays_between_two_levels_round_up() {
|
||||
// Blue at 250 weighs 27.5 levels of gray, and 249 weighs 27.39
|
||||
assert_eq!(gray_level([0, 0, 250]), 28);
|
||||
assert_eq!(gray_level([0, 0, 249]), 27);
|
||||
assert_eq!(gray_level([5, 0, 0]), 2);
|
||||
assert_eq!(gray_level([255, 255, 255]), 255);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paint_overlays_keep_their_strength_where_a_blend_if_reads_the_content_beside_them() {
|
||||
let overlay = EffectOperation::Adjustment(crate::Adjustment::ColorOverlay {
|
||||
color: core_types::Color::RED,
|
||||
blend_mode: core_types::blending::BlendMode::Normal,
|
||||
opacity: 100.,
|
||||
});
|
||||
let mut ranges = BlendIfRanges::default();
|
||||
ranges.content.gray.range_start = 40.;
|
||||
let blend_if = EffectOperation::BlendIf(Box::new(ranges));
|
||||
let blur = EffectOperation::Blur {
|
||||
radius_mask: Default::default(),
|
||||
radius: 2.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
};
|
||||
|
||||
assert!(!paint_overlay_folds(&[overlay.clone(), blend_if.clone(), blur.clone()], 0));
|
||||
assert!(paint_overlay_folds(&[overlay.clone(), blur.clone(), blend_if.clone()], 0));
|
||||
assert!(paint_overlay_folds(&[blend_if, blur, overlay.clone()], 2));
|
||||
assert!(paint_overlay_folds(&[overlay, EffectOperation::BlendIf(Box::default())], 0));
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,8 @@ pub enum PiecePlace {
|
||||
IntoContent { over: bool },
|
||||
/// The part of an interior piece blending with what shows through the content's fill, in a layer of its mode beneath the content's, or with `over`, over it.
|
||||
Through { over: bool },
|
||||
/// What lies beneath the content, filtered and cut to its silhouette, at the bottom of the content's own layer.
|
||||
Backdrop,
|
||||
}
|
||||
|
||||
/// One coverage of an effect that draws as a piece of its own, named like the map of it.
|
||||
@@ -63,8 +65,11 @@ pub struct EffectLayers {
|
||||
/// How many of the effects, from the first, are carried out within the content's image.
|
||||
pub flattened: usize,
|
||||
pub layers: Vec<EffectLayer>,
|
||||
/// The rows from the first mask after every other effect to the end, which fade each finished layer at each pixel like the item's opacity. Empty where those masks flatten what's before them instead.
|
||||
/// The rows from the first mask after every other effect to the end: masks, and Blend Ifs reading only what lies beneath, which fade each finished layer at each pixel like the item's opacity.
|
||||
/// Empty where those masks flatten what's before them instead.
|
||||
pub trailing_masks: Range<usize>,
|
||||
/// Whether a Blend If fades every layer by the colors of what lies beneath.
|
||||
pub fades_by_underlying: bool,
|
||||
}
|
||||
|
||||
impl EffectLayers {
|
||||
@@ -74,9 +79,10 @@ impl EffectLayers {
|
||||
let operations: Vec<EffectOperation> = effects.operations().collect();
|
||||
let blend_mode = if blend_mode.to_svg_style_name().is_some() { blend_mode } else { BlendMode::Normal };
|
||||
|
||||
// Normal content at full fill hides what lies beneath its share, so its interior pieces blend with it alone, in any mode, within its own layer
|
||||
// Normal content at full fill hides what lies beneath its share, so its interior pieces blend with it alone, in any mode, within its own layer.
|
||||
// A Blend If fading the content by its colors acts as a fill below full wherever it hides any.
|
||||
let shares_content = blend_mode == BlendMode::Normal;
|
||||
let blends_into_content = shares_content && fill >= 1.;
|
||||
let blends_into_content = shares_content && fill >= 1. && !crate::blend_if::fades_content(&operations);
|
||||
|
||||
// The masks after every other effect fade the layers rather than the content's image, so they flatten nothing before them
|
||||
let no_rows = operations.len()..operations.len();
|
||||
@@ -115,10 +121,16 @@ impl EffectLayers {
|
||||
.chain([(LayerPart::Content, blend_mode)])
|
||||
.collect();
|
||||
|
||||
// A shadow not knocked out in the content's layer, flattened or layered, would hide a part placed beneath that layer
|
||||
// A blurred backdrop, or a shadow not knocked out (flattened or layered), in the content's layer would hide a part placed beneath that layer
|
||||
let backdrop: Vec<LayerPart> = pieces_from(0, operations.len())
|
||||
.into_iter()
|
||||
.filter(|(piece, _)| piece.place == PiecePlace::Backdrop)
|
||||
.map(|(piece, _)| LayerPart::Piece(piece))
|
||||
.collect();
|
||||
let shows_through = |piece: &EffectPiece| piece.place == PiecePlace::Beneath && !piece.knocks_out;
|
||||
let mut content_run = parts.iter().rev().skip(1).take_while(|(_, mode)| *mode == BlendMode::Normal);
|
||||
let covered_beneath = content_run.any(|(part, _)| matches!(part, LayerPart::Piece(piece) if shows_through(piece))) || unmerged.iter().any(|(piece, _)| shows_through(piece));
|
||||
let covered_beneath =
|
||||
!backdrop.is_empty() || content_run.any(|(part, _)| matches!(part, LayerPart::Piece(piece) if shows_through(piece))) || unmerged.iter().any(|(piece, _)| shows_through(piece));
|
||||
|
||||
// Interior pieces of normal content blend within its share, in its layer. Below a full fill, a blended one splits off its part through the fill into a layer beneath
|
||||
// the content's, or over it when its mode isn't straight along what lies beneath or a shadow covers that, as every later piece then does to keep their order.
|
||||
@@ -166,8 +178,10 @@ impl EffectLayers {
|
||||
layers.splice(content_layer..content_layer, through);
|
||||
}
|
||||
|
||||
// One normal layer at a full fill draws the same with all its effects flattened into the content's image, which takes fewer passes
|
||||
if blends_into_content && matches!(layers.as_slice(), [layer] if layer.blend_mode == BlendMode::Normal) {
|
||||
let fades_by_underlying = !crate::blend_if::underlying_ranges(&operations).is_empty();
|
||||
|
||||
// One normal layer at a full fill draws the same with all its effects flattened into the content's image, which takes fewer passes, unless it reads what lies beneath
|
||||
if blends_into_content && backdrop.is_empty() && !fades_by_underlying && matches!(layers.as_slice(), [layer] if layer.blend_mode == BlendMode::Normal) {
|
||||
let content = EffectLayer {
|
||||
blend_mode: BlendMode::Normal,
|
||||
parts: vec![LayerPart::Content],
|
||||
@@ -176,10 +190,21 @@ impl EffectLayers {
|
||||
flattened: operations.len(),
|
||||
layers: vec![content],
|
||||
trailing_masks: no_rows,
|
||||
fades_by_underlying,
|
||||
};
|
||||
}
|
||||
|
||||
Self { flattened, layers, trailing_masks }
|
||||
// What lies beneath, filtered, goes at the bottom of the content's own layer, which fades and blends it with the content, even from a row flattened into the content
|
||||
if let Some(content_layer) = layers.iter_mut().find(|layer| layer.holds_content()) {
|
||||
content_layer.parts.splice(0..0, backdrop);
|
||||
}
|
||||
|
||||
Self {
|
||||
flattened,
|
||||
layers,
|
||||
trailing_masks,
|
||||
fades_by_underlying,
|
||||
}
|
||||
}
|
||||
|
||||
/// Like [`Self::plan`], for effects stamped in more than one space (see [`Effects::runs`]), as renderers draw them.
|
||||
@@ -201,6 +226,16 @@ impl EffectLayers {
|
||||
planned
|
||||
}
|
||||
|
||||
/// Whether a layered piece, or a Blend If fading the layers, reads what lies beneath the content.
|
||||
pub fn reads_backdrop(&self) -> bool {
|
||||
self.fades_by_underlying || self.reads_around_backdrop()
|
||||
}
|
||||
|
||||
/// Whether a layered piece reads what lies around each pixel beneath the content, as a background blur does, where a Blend If reads only the pixel itself.
|
||||
pub fn reads_around_backdrop(&self) -> bool {
|
||||
(self.layers.iter().flat_map(|layer| &layer.parts)).any(|part| matches!(part, LayerPart::Piece(piece) if piece.place == PiecePlace::Backdrop))
|
||||
}
|
||||
|
||||
/// The index of the layer holding the content.
|
||||
pub fn content_layer(&self) -> Option<usize> {
|
||||
self.layers.iter().position(EffectLayer::holds_content)
|
||||
@@ -263,6 +298,15 @@ impl EffectLayers {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether any of the effects reads what lies beneath the content, like a background blur.
|
||||
pub fn effects_read_backdrop(effects: &Effects) -> bool {
|
||||
effects.operations().any(|operation| match &operation {
|
||||
EffectOperation::BackgroundBlur { .. } => !operation.changes_nothing(),
|
||||
EffectOperation::BlendIf(ranges) => !ranges.underlying.show_everything(),
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether an effect row can draw as layered pieces, rather than being carried out within the content's image.
|
||||
/// Blurs, adjustments, masks, and feathers process the pixels of everything before them, and blend modes CSS lacks can't blend against the backdrop in SVG or a GPU layer,
|
||||
/// though interior pieces that `blend_into_content` blend with the content alone, which the renderers do themselves.
|
||||
@@ -310,31 +354,39 @@ fn merged_into_content(operations: &[EffectOperation]) -> usize {
|
||||
.map_or(0, |index| index + 1)
|
||||
}
|
||||
|
||||
/// The effects carried out in the content's own image, which make a clipping base's shape: every row through the last pixel filter, which merges the pieces before it into that image, then the trailing masks fading it.
|
||||
/// The effects carried out in the content's own image, which make a clipping base's shape: every row through the last pixel filter, which merges the pieces before it into that image, then the trailing masks fading it, leaving out each Blend If that reads only what lies beneath.
|
||||
/// The other pieces are cast from or laid over the content, so for PSD interop they don't shape a clip. Borrowed if nothing is left out.
|
||||
pub fn content_image_effects(effects: &Effects) -> Cow<'_, Effects> {
|
||||
let operations: Vec<EffectOperation> = effects.operations().collect();
|
||||
let trailing_masks = trailing_masks(&operations);
|
||||
let merged = merged_into_content(&operations[..trailing_masks.start]);
|
||||
if merged == trailing_masks.start {
|
||||
|
||||
// A Blend If reading only what lies beneath fades the finished layers wherever it sits, so it shapes no clip (and it's the only kind the trailing masks can hold)
|
||||
let kept: Vec<usize> = (0..merged).chain(trailing_masks).filter(|&index| !reads_only_beneath(&operations[index])).collect();
|
||||
if kept.len() == operations.len() {
|
||||
return Cow::Borrowed(effects);
|
||||
}
|
||||
|
||||
Cow::Owned(Effects((0..merged).chain(trailing_masks).filter_map(|index| effects.0.clone_item(index)).collect()))
|
||||
Cow::Owned(Effects(kept.into_iter().filter_map(|index| effects.0.clone_item(index)).collect()))
|
||||
}
|
||||
|
||||
/// The rows from the first mask after every other effect that changes something to the end, or none without such a mask or an effect before it.
|
||||
/// A Blend If reading only what lies beneath is passed over, since it fades the finished layers as the masks do, but one reading the content's colors counts as another effect.
|
||||
fn trailing_masks(operations: &[EffectOperation]) -> Range<usize> {
|
||||
let no_rows = operations.len()..operations.len();
|
||||
let is_mask = |operation: &EffectOperation| matches!(operation, EffectOperation::Mask { .. });
|
||||
let is_other = |operation: &EffectOperation| !operation.changes_nothing() && !is_mask(operation) && !reads_only_beneath(operation);
|
||||
|
||||
let Some(last_other) = operations.iter().rposition(|operation| !operation.changes_nothing() && !is_mask(operation)) else {
|
||||
return no_rows;
|
||||
};
|
||||
let first_mask = operations[last_other + 1..].iter().position(|operation| !operation.changes_nothing());
|
||||
let Some(last_other) = operations.iter().rposition(is_other) else { return no_rows };
|
||||
let first_mask = operations[last_other + 1..].iter().position(|operation| !operation.changes_nothing() && is_mask(operation));
|
||||
first_mask.map_or(no_rows, |offset| last_other + 1 + offset..operations.len())
|
||||
}
|
||||
|
||||
/// Whether the effect is a Blend If without ranges of the content's own colors, so it reads only what lies beneath (or changes nothing).
|
||||
fn reads_only_beneath(operation: &EffectOperation) -> bool {
|
||||
matches!(operation, EffectOperation::BlendIf(ranges) if ranges.content.show_everything())
|
||||
}
|
||||
|
||||
/// The pieces the effect at `index` draws, each with the mode it blends by, leaving out those painting no color.
|
||||
fn pieces(index: usize, operation: &EffectOperation) -> Vec<(EffectPiece, BlendMode)> {
|
||||
// Only a drop shadow can show through the content
|
||||
@@ -392,6 +444,7 @@ fn pieces(index: usize, operation: &EffectOperation) -> Vec<(EffectPiece, BlendM
|
||||
inside.into_iter().chain(outside).flatten().collect()
|
||||
}
|
||||
EffectOperation::PaintOverlay { blend_mode, .. } => vec![piece(0, Within, None, *blend_mode)],
|
||||
EffectOperation::BackgroundBlur { .. } => vec![piece(0, Backdrop, None, BlendMode::Normal)],
|
||||
EffectOperation::Adjustment(Adjustment::ColorOverlay { color, blend_mode, .. }) => vec![piece(0, Within, Some(*color), *blend_mode)],
|
||||
EffectOperation::Blur { .. }
|
||||
| EffectOperation::MotionBlur { .. }
|
||||
@@ -416,6 +469,7 @@ fn pieces(index: usize, operation: &EffectOperation) -> Vec<(EffectPiece, BlendM
|
||||
| EffectOperation::HighPass { .. }
|
||||
| EffectOperation::AddNoise { .. }
|
||||
| EffectOperation::Dissolve { .. }
|
||||
| EffectOperation::BlendIf(_)
|
||||
| EffectOperation::Adjustment(_) => Vec::new(),
|
||||
};
|
||||
pieces.into_iter().flatten().collect()
|
||||
@@ -568,6 +622,11 @@ mod tests {
|
||||
fn interior_pieces_go_over_the_content_where_its_layer_covers_what_lies_beneath_it() {
|
||||
let red = RED.with_alpha(0.75);
|
||||
let through_over = PiecePlace::Through { over: true };
|
||||
let background_blur = EffectOperation::BackgroundBlur {
|
||||
radius: 4.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
};
|
||||
|
||||
let with_knockout = |knocks_out: bool| {
|
||||
let mut shadow = drop_shadow(Color::BLACK.with_alpha(0.75), BlendMode::Multiply);
|
||||
@@ -577,10 +636,12 @@ mod tests {
|
||||
shadow
|
||||
};
|
||||
|
||||
// A shadow not knocked out beneath the content in its layer would hide even a straight piece's part beneath that layer
|
||||
let layers = EffectLayers::plan(&Effects::from_operations([with_knockout(false), inner_shadow(red, BlendMode::Screen)]), BlendMode::Normal, 0.5, true);
|
||||
assert_eq!(modes(&layers), [BlendMode::Normal, BlendMode::Screen]);
|
||||
assert_eq!(parts(&layers)[1], [Some((1, 0, through_over))]);
|
||||
// A blurred backdrop, or a shadow not knocked out, beneath the content in its layer would hide even a straight piece's part beneath that layer
|
||||
for beneath in [background_blur, with_knockout(false)] {
|
||||
let layers = EffectLayers::plan(&Effects::from_operations([beneath.clone(), inner_shadow(red, BlendMode::Screen)]), BlendMode::Normal, 0.5, true);
|
||||
assert_eq!(modes(&layers), [BlendMode::Normal, BlendMode::Screen], "{beneath:?}");
|
||||
assert_eq!(parts(&layers)[1], [Some((1, 0, through_over))], "{beneath:?}");
|
||||
}
|
||||
|
||||
// A knocked-out shadow doesn't cover it there
|
||||
let layers = EffectLayers::plan(&Effects::from_operations([with_knockout(true), inner_shadow(red, BlendMode::Screen)]), BlendMode::Normal, 0.5, true);
|
||||
@@ -758,6 +819,95 @@ mod tests {
|
||||
assert_eq!(kinds(filtered), [EffectKind::Mask, EffectKind::InnerShadow, EffectKind::Blur, EffectKind::Mask]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_background_blur_lies_at_the_bottom_of_the_contents_layer() {
|
||||
let blue = Color::from_rgbaf32_unchecked(0., 0., 1., 1.);
|
||||
let background_blur = EffectOperation::BackgroundBlur {
|
||||
radius: 4.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
};
|
||||
let blur = EffectOperation::Blur {
|
||||
radius_mask: Default::default(),
|
||||
radius: 2.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
};
|
||||
|
||||
// Even beside a blended shadow, and flattened by a later blur, it fades and blends with the content
|
||||
let effects = Effects::from_operations([drop_shadow(blue, BlendMode::Multiply), background_blur, blur]);
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Screen, 1., true);
|
||||
assert!(layers.reads_backdrop());
|
||||
let content_layer = layers.content_layer().unwrap();
|
||||
assert_eq!(layers.layers[content_layer].blend_mode, BlendMode::Screen);
|
||||
assert_eq!(parts(&layers)[content_layer], [Some((1, 0, PiecePlace::Backdrop)), None]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blend_ifs_draw_no_pieces_and_read_the_backdrop_only_by_their_ranges_beneath() {
|
||||
let mut ranges = crate::blend_if::BlendIfRanges::default();
|
||||
ranges.content.gray.range_start = 50.;
|
||||
let content_only = Effects::from_operations([EffectOperation::BlendIf(Box::new(ranges))]);
|
||||
let layers = EffectLayers::plan(&content_only, BlendMode::Normal, 1., true);
|
||||
assert_eq!(layers.layers.len(), 1);
|
||||
assert!(!layers.reads_backdrop() && !effects_read_backdrop(&content_only));
|
||||
|
||||
ranges.underlying.blue.falloff_end = 50.;
|
||||
let beneath = Effects::from_operations([EffectOperation::BlendIf(Box::new(ranges))]);
|
||||
let layers = EffectLayers::plan(&beneath, BlendMode::Normal, 1., true);
|
||||
assert_eq!(layers.layers[0].parts, [LayerPart::Content]);
|
||||
assert!(layers.reads_backdrop() && effects_read_backdrop(&beneath));
|
||||
|
||||
// Fading the content by its colors, it splits a blended interior piece as a partial fill does, even at a full fill
|
||||
let screen = Effects::from_operations([inner_shadow(RED.with_alpha(0.75), BlendMode::Screen), EffectOperation::BlendIf(Box::new(ranges))]);
|
||||
let layers = EffectLayers::plan(&screen, BlendMode::Normal, 1., true);
|
||||
assert_eq!(modes(&layers), [BlendMode::Screen, BlendMode::Normal]);
|
||||
assert!(layers.reads_through_share());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blend_ifs_after_trailing_masks_leave_them_trailing() {
|
||||
let mut ranges = crate::blend_if::BlendIfRanges::default();
|
||||
ranges.underlying.gray.range_start = 50.;
|
||||
let blend_if = EffectOperation::BlendIf(Box::new(ranges));
|
||||
let kinds = |effects: &Effects| -> Vec<EffectKind> { content_image_effects(effects).operations().map(|operation| operation.kind()).collect() };
|
||||
|
||||
// After the mask as before it, the shadow keeps its layer and mode while the mask fades each layer, and a clipping base takes the mask alone
|
||||
for operations in [
|
||||
[drop_shadow(RED, BlendMode::Multiply), mask(), blend_if.clone()],
|
||||
[drop_shadow(RED, BlendMode::Multiply), blend_if.clone(), mask()],
|
||||
] {
|
||||
let effects = Effects::from_operations(operations);
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., true);
|
||||
assert_eq!(layers.flattened, 0, "{:?}", effects.operations().map(|operation| operation.kind()).collect::<Vec<_>>());
|
||||
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Normal]);
|
||||
assert!(layers.fades_layers());
|
||||
assert_eq!(kinds(&effects), [EffectKind::Mask]);
|
||||
}
|
||||
|
||||
// With nothing else to trail, a clipping base still takes the mask alone in either order
|
||||
assert_eq!(kinds(&Effects::from_operations([blend_if.clone(), mask()])), [EffectKind::Mask]);
|
||||
assert_eq!(kinds(&Effects::from_operations([mask(), blend_if])), [EffectKind::Mask]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blend_ifs_reading_the_content_after_masks_keep_them_from_trailing() {
|
||||
let mut ranges = crate::blend_if::BlendIfRanges::default();
|
||||
ranges.content.gray.range_start = 50.;
|
||||
let blend_if = EffectOperation::BlendIf(Box::new(ranges));
|
||||
let kinds = |operations: Vec<EffectOperation>| -> Vec<EffectKind> { content_image_effects(&Effects::from_operations(operations)).operations().map(|operation| operation.kind()).collect() };
|
||||
|
||||
// The mask merges the shadow flattened before it into the content's image, which the Blend If then reads
|
||||
let effects = Effects::from_operations([drop_shadow(RED, BlendMode::LinearBurn), mask(), blend_if.clone()]);
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., true);
|
||||
assert_eq!(layers.flattened, 2);
|
||||
assert!(!layers.fades_layers());
|
||||
|
||||
// A clipping base takes the mask alone, with the Blend If before it or after it
|
||||
assert_eq!(kinds(vec![blend_if.clone(), mask()]), [EffectKind::Mask]);
|
||||
assert_eq!(kinds(vec![mask(), blend_if]), [EffectKind::Mask]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn knocked_out_pieces_hide_behind_however_the_content_covers_them() {
|
||||
let same_layer = EffectLayers::plan(&Effects::from_operations([drop_shadow(RED, BlendMode::Normal)]), BlendMode::Normal, 0.5, true);
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
use crate::Graphic;
|
||||
use crate::adjustment::Adjustment;
|
||||
use crate::blend_if::BlendIfRanges;
|
||||
use crate::filters::{Convolution, NoiseDistribution};
|
||||
use crate::masks::{MaskMode, mask_feather_sigma};
|
||||
use crate::parameters::{ParameterVisitor, ReadParameters, WriteParameters};
|
||||
@@ -91,6 +92,10 @@ pub enum EffectKind {
|
||||
Pixelate,
|
||||
/// Prints each color channel of the content as dots on its own turned screen, as a press prints ink.
|
||||
ColorHalftone,
|
||||
/// Blurs what lies beneath the content within its silhouette, as if seen through frosted glass.
|
||||
BackgroundBlur,
|
||||
/// Shows the content only where its own colors, and those of what lies beneath it, fall within ranges of their channels.
|
||||
BlendIf,
|
||||
// The adjustments, which change each color of the content on its own, as their nodes of the same names do
|
||||
Desaturate,
|
||||
GammaCorrection,
|
||||
@@ -148,6 +153,8 @@ impl std::fmt::Display for EffectKind {
|
||||
Self::Displace => "Displace",
|
||||
Self::Pixelate => "Pixelate",
|
||||
Self::ColorHalftone => "Color Halftone",
|
||||
Self::BackgroundBlur => "Background Blur",
|
||||
Self::BlendIf => "Blend If",
|
||||
Self::Desaturate => "Desaturate",
|
||||
Self::GammaCorrection => "Gamma Correction",
|
||||
Self::MakeOpaque => "Make Opaque",
|
||||
@@ -452,7 +459,7 @@ impl Effects {
|
||||
self.effects().skip(rows.start).take(rows.len()).map(Effect::operation)
|
||||
}
|
||||
|
||||
/// How far past the content the effects together can paint, in the effect space of a run of them.
|
||||
/// How far past the content the effects together can paint, or a background blur among them reads what lies beneath, in the effect space of a run of them.
|
||||
/// It leaves out what [`Effects::reach_around`] adds from the content's bounds and what it paints past its frame, for the effects relative to its extent.
|
||||
pub fn reach(&self) -> f64 {
|
||||
self.operations().map(|operation| operation.painted_reach()).sum()
|
||||
@@ -1228,6 +1235,17 @@ pub enum EffectOperation {
|
||||
/// Percent of the spacing between dots that each screen's dots lie past the `offset` along both of its axes.
|
||||
phase: f64,
|
||||
},
|
||||
/// Blurs the backdrop beneath the content within the content's silhouette, beneath the content and its effects.
|
||||
BackgroundBlur {
|
||||
/// The standard deviation of the Gaussian, or the half width of the box.
|
||||
radius: f64,
|
||||
/// Whether to average a box of pixels rather than weighting them by a Gaussian.
|
||||
box_blur: bool,
|
||||
/// Whether to blend the colors with their gamma encoding rather than in linear light.
|
||||
gamma: bool,
|
||||
},
|
||||
/// Fades the content by how its own colors fall within ranges, as its fill does, and everything it draws by how the colors beneath fall within others, as its opacity does.
|
||||
BlendIf(Box<BlendIfRanges>),
|
||||
Adjustment(Adjustment),
|
||||
}
|
||||
|
||||
@@ -1285,6 +1303,8 @@ impl EffectOperation {
|
||||
Self::Displace { .. } => EffectKind::Displace,
|
||||
Self::Pixelate { .. } => EffectKind::Pixelate,
|
||||
Self::ColorHalftone { .. } => EffectKind::ColorHalftone,
|
||||
Self::BackgroundBlur { .. } => EffectKind::BackgroundBlur,
|
||||
Self::BlendIf(_) => EffectKind::BlendIf,
|
||||
Self::Adjustment(adjustment) => adjustment.kind(),
|
||||
}
|
||||
}
|
||||
@@ -1315,7 +1335,7 @@ impl EffectOperation {
|
||||
/// Whether this operation leaves the content as it is, like a blur of no radius or a shadow of no opacity.
|
||||
pub fn changes_nothing(&self) -> bool {
|
||||
match self {
|
||||
Self::Blur { radius, .. } => *radius <= 0.,
|
||||
Self::Blur { radius, .. } | Self::BackgroundBlur { radius, .. } => *radius <= 0.,
|
||||
Self::DropShadow { color, .. } | Self::InnerShadow { color, .. } | Self::Satin { color, .. } => color.a() <= 0.,
|
||||
Self::OuterGlow { color, noise, .. } | Self::InnerGlow { color, noise, .. } => GlowFill::of(color).is_none_or(|fill| fill.is_invisible(*noise)),
|
||||
Self::Outline { paint, weight, contour_gradient, .. } => *weight <= 0. || OutlineFill::of(paint, *contour_gradient).is_none_or(|fill| fill.is_invisible()),
|
||||
@@ -1367,6 +1387,7 @@ impl EffectOperation {
|
||||
// The four neighbors lie a fixed distance away, so only the blur needs a radius
|
||||
Self::Sharpen { amount, radius, edges_only, .. } => *amount <= 0. || (!*edges_only && *radius <= 0.),
|
||||
Self::MinimumMaximum { radius, .. } => *radius <= 0.,
|
||||
Self::BlendIf(ranges) => ranges.content.show_everything() && ranges.underlying.show_everything(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1375,6 +1396,16 @@ impl EffectOperation {
|
||||
matches!(self, Self::Blur { radius_mask, .. } if !radius_mask.draws_nothing())
|
||||
}
|
||||
|
||||
/// Whether this operation paints nothing past the content, whatever it reads there, like an inner shadow finding the edges it casts from.
|
||||
pub fn paints_only_within_content(&self) -> bool {
|
||||
match self {
|
||||
Self::InnerShadow { .. } | Self::InnerGlow { .. } | Self::Satin { .. } | Self::Mask { .. } | Self::Feather { .. } | Self::BackgroundBlur { .. } => true,
|
||||
Self::Outline { align, .. } => *align == StrokeAlign::Inside,
|
||||
Self::BevelAndEmboss { style, .. } => *style == BevelStyle::InnerBevel,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this operation reads the pixels around each one of the image the effects before it leave, like a blur or a warp, rather than casting from the content's shape or changing each pixel alone.
|
||||
pub fn reads_pixels_around(&self) -> bool {
|
||||
match self {
|
||||
@@ -1383,7 +1414,7 @@ impl EffectOperation {
|
||||
true
|
||||
}
|
||||
Self::ConvolutionKernel { .. } | Self::Emboss { .. } | Self::FindEdges | Self::MinimumMaximum { .. } | Self::Sharpen { .. } | Self::HighPass { .. } => true,
|
||||
// Cast from the content's shape, reading a mask's own image or a feather's map, or changing each pixel alone
|
||||
// Cast from the content's shape, reading a mask's or the backdrop's own image or a feather's map, or changing each pixel alone
|
||||
Self::DropShadow { .. }
|
||||
| Self::InnerShadow { .. }
|
||||
| Self::OuterGlow { .. }
|
||||
@@ -1392,7 +1423,7 @@ impl EffectOperation {
|
||||
| Self::Outline { .. }
|
||||
| Self::BevelAndEmboss { .. }
|
||||
| Self::Feather { .. } => false,
|
||||
Self::PaintOverlay { .. } | Self::Mask { .. } | Self::AddNoise { .. } | Self::Dissolve { .. } | Self::Adjustment(_) => false,
|
||||
Self::PaintOverlay { .. } | Self::Mask { .. } | Self::BackgroundBlur { .. } | Self::AddNoise { .. } | Self::Dissolve { .. } | Self::BlendIf(_) | Self::Adjustment(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1429,8 +1460,9 @@ impl EffectOperation {
|
||||
pub fn reach(&self) -> f64 {
|
||||
match self {
|
||||
// A box reaches its half width, and the pixel past it for a fractional one, while a Gaussian fades out over three standard deviations
|
||||
Self::Blur { radius, box_blur: true, .. } => radius.max(0.) + 1.,
|
||||
Self::Blur { radius, .. } => 3. * radius.max(0.),
|
||||
Self::Blur { radius, box_blur: true, .. } | Self::BackgroundBlur { radius, box_blur: true, .. } => radius.max(0.) + 1.,
|
||||
// A background blur reads as far past the content as its Gaussian reaches
|
||||
Self::Blur { radius, .. } | Self::BackgroundBlur { radius, .. } => 3. * radius.max(0.),
|
||||
// An inner shadow paints within the content but reads this far out to find the edges it casts from.
|
||||
// Shadows and glows end within their size, past which a precise glow fades over one more unit.
|
||||
Self::DropShadow { distance, size, .. } | Self::InnerShadow { distance, size, .. } => distance.abs() + size.max(0.) + 1.,
|
||||
@@ -1459,7 +1491,7 @@ impl EffectOperation {
|
||||
Self::Ripple { .. } | Self::Wave { .. } | Self::Displace { .. } => self.displacement_reach() + 1.,
|
||||
// Within the frame they paint the content's own cells or dots, reading a cell's or a dot's area around each point there, which `Effects::source_region` finds
|
||||
Self::Pixelate { .. } | Self::ColorHalftone { .. } => 0.,
|
||||
Self::PaintOverlay { .. } | Self::AddNoise { .. } | Self::Dissolve { .. } | Self::Adjustment(_) => 0.,
|
||||
Self::PaintOverlay { .. } | Self::AddNoise { .. } | Self::Dissolve { .. } | Self::BlendIf(_) | Self::Adjustment(_) => 0.,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1516,7 +1548,7 @@ impl EffectOperation {
|
||||
};
|
||||
|
||||
match &mut self {
|
||||
Self::Blur { radius, .. } => finite(radius),
|
||||
Self::Blur { radius, .. } | Self::BackgroundBlur { radius, .. } => finite(radius),
|
||||
Self::DropShadow { angle, distance, spread, size, .. }
|
||||
| Self::InnerShadow {
|
||||
angle, distance, choke: spread, size, ..
|
||||
@@ -1594,7 +1626,7 @@ impl EffectOperation {
|
||||
offset,
|
||||
phase,
|
||||
} => [radius, red_angle, green_angle, blue_angle, &mut offset.x, &mut offset.y, phase].into_iter().for_each(finite),
|
||||
Self::PaintOverlay { .. } | Self::ConvolutionKernel { .. } | Self::FindEdges | Self::Adjustment(_) => {}
|
||||
Self::PaintOverlay { .. } | Self::ConvolutionKernel { .. } | Self::FindEdges | Self::BlendIf(_) | Self::Adjustment(_) => {}
|
||||
}
|
||||
self
|
||||
}
|
||||
@@ -1801,6 +1833,12 @@ impl EffectOperation {
|
||||
offset: DVec2::ZERO,
|
||||
phase: 0.,
|
||||
},
|
||||
EffectKind::BackgroundBlur => Self::BackgroundBlur {
|
||||
radius: 0.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
},
|
||||
EffectKind::BlendIf => Self::BlendIf(Box::default()),
|
||||
EffectKind::Desaturate => Self::Adjustment(Adjustment::Desaturate { method: Default::default() }),
|
||||
EffectKind::GammaCorrection => Self::Adjustment(Adjustment::GammaCorrection { gamma: 0., inverse: false }),
|
||||
EffectKind::MakeOpaque => Self::Adjustment(Adjustment::MakeOpaque { strength: 0. }),
|
||||
@@ -1853,6 +1891,11 @@ impl EffectOperation {
|
||||
visitor.parameter("box_blur", box_blur, false);
|
||||
visitor.parameter("gamma", gamma, false);
|
||||
}
|
||||
Self::BackgroundBlur { radius, box_blur, gamma } => {
|
||||
visitor.parameter("radius", radius, 10.);
|
||||
visitor.parameter("box_blur", box_blur, false);
|
||||
visitor.parameter("gamma", gamma, false);
|
||||
}
|
||||
Self::DropShadow {
|
||||
color,
|
||||
blend_mode,
|
||||
@@ -2183,6 +2226,7 @@ impl EffectOperation {
|
||||
visitor.parameter("offset", offset, DVec2::ZERO);
|
||||
visitor.parameter("phase", phase, 0.);
|
||||
}
|
||||
Self::BlendIf(ranges) => ranges.visit_parameters(visitor),
|
||||
Self::Adjustment(adjustment) => adjustment.visit_parameters(visitor),
|
||||
}
|
||||
}
|
||||
@@ -2193,6 +2237,23 @@ mod tests {
|
||||
use super::*;
|
||||
use vector_types::{Gradient, GradientStop};
|
||||
|
||||
#[test]
|
||||
fn box_blurs_reach_their_half_width_and_a_pixel_while_gaussians_reach_three_radii() {
|
||||
let blur = |box_blur| EffectOperation::Blur {
|
||||
radius_mask: Graphic::default(),
|
||||
radius: 6.,
|
||||
box_blur,
|
||||
gamma: false,
|
||||
};
|
||||
let background_blur = |box_blur| EffectOperation::BackgroundBlur { radius: 6., box_blur, gamma: false };
|
||||
|
||||
// Whether it blurs the content or what lies beneath it, a blur reaches as far as its kernel reads
|
||||
for (box_blur, reach) in [(true, 7.), (false, 18.)] {
|
||||
assert_eq!(blur(box_blur).reach(), reach, "box: {box_blur}");
|
||||
assert_eq!(background_blur(box_blur).reach(), reach, "box: {box_blur}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rows_round_trip_their_operations_eliding_defaults() {
|
||||
let operations = [
|
||||
@@ -2436,10 +2497,16 @@ mod tests {
|
||||
offset: DVec2::new(-4., 6.),
|
||||
phase: 25.,
|
||||
},
|
||||
EffectOperation::BlendIf(Box::new({
|
||||
let mut ranges = BlendIfRanges::default();
|
||||
ranges.content.gray.range_start = 25.;
|
||||
ranges.underlying.red.falloff_end = 80.;
|
||||
ranges
|
||||
})),
|
||||
];
|
||||
|
||||
for operation in operations {
|
||||
assert_eq!(Effect::new(&operation).operation(), operation);
|
||||
for operation in &operations {
|
||||
assert_eq!(Effect::new(operation).operation(), *operation);
|
||||
}
|
||||
|
||||
// A solid paint decodes into the color overlay adjustment, which the Paint Overlay row also carries
|
||||
@@ -2461,6 +2528,13 @@ mod tests {
|
||||
|
||||
let default_row = Effect::new(&EffectOperation::default_for(EffectKind::DropShadow));
|
||||
assert_eq!(default_row.0.attributes().iter_any().count(), 0, "a default operation stamps no parameters");
|
||||
|
||||
// Blend If's ranges ride attributes named like its node's inputs
|
||||
let blend_if = operations.iter().find(|operation| operation.kind() == EffectKind::BlendIf).unwrap();
|
||||
let row = Effect::new(blend_if);
|
||||
assert_eq!(row.0.attribute::<f64>("content_range_start"), Some(&25.));
|
||||
assert_eq!(row.0.attribute::<f64>("red_underlying_falloff_end"), Some(&80.));
|
||||
assert_eq!(row.0.attributes().iter_any().count(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2780,6 +2854,16 @@ mod tests {
|
||||
assert_eq!(runs, vec![0..3, 3..4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effects_painting_only_within_the_content_paint_nothing_past_it() {
|
||||
// An inner shadow reads past the content to find the edges it casts from, but paints only within it
|
||||
let (inner_shadow, drop_shadow) = (EffectOperation::default_for(EffectKind::InnerShadow), EffectOperation::default_for(EffectKind::DropShadow));
|
||||
let painted = |effects: Effects| effects.reach_around_by(DAffine2::IDENTITY, [DVec2::ZERO; 2], 0., |operation| !operation.paints_only_within_content());
|
||||
assert!(Effects::from_operations([inner_shadow.clone()]).reach() > 0.);
|
||||
assert_eq!(painted(Effects::from_operations([inner_shadow.clone()])), DVec2::ZERO);
|
||||
assert_eq!(painted(Effects::from_operations([inner_shadow, drop_shadow.clone()])), DVec2::splat(drop_shadow.reach()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adjustment_rows_elide_their_defaults_and_name_grouped_parameters() {
|
||||
use EffectKind::*;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
pub mod adjustment;
|
||||
pub mod appearance;
|
||||
pub mod artboard;
|
||||
pub mod blend_if;
|
||||
pub mod effect_layers;
|
||||
pub mod effects;
|
||||
pub mod filters;
|
||||
@@ -20,6 +21,7 @@ pub use vector_types;
|
||||
pub use adjustment::Adjustment;
|
||||
pub use appearance::{Appearance, Cover, CoverPlacement, Coverage, FillAndStroke, stamp_coverage};
|
||||
pub use artboard::Artboard;
|
||||
pub use blend_if::BlendIfChannel;
|
||||
pub use effects::{
|
||||
BevelDirection, BevelStyle, BevelTechnique, Effect, EffectKind, EffectOperation, Effects, GlowSource, GlowTechnique, MinimumMaximumMode, linked_to_content, paint_with_envelope_effects,
|
||||
stamp_effect, stamped_transform,
|
||||
|
||||
@@ -7,26 +7,45 @@ use dyn_any::DynAny;
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
#[widget(Radio)]
|
||||
#[widget(Dropdown)]
|
||||
pub enum MaskMode {
|
||||
/// White shows the content and black hides it, with transparent areas also hiding it.
|
||||
/// White shows the content and black hides it, with transparent areas also hiding it. Brightness is judged by weighting the gamma-encoded RGB channels by `0.3, 0.59, 0.11`.
|
||||
///
|
||||
/// This matches the Luminosity family of blend modes.
|
||||
#[default]
|
||||
Luminance,
|
||||
/// Like Luminance, but brightness is judged by weighting the gamma-encoded RGB channels by `0.2125, 0.7154, 0.0721`, so greens show more of the content, and reds and blues less.
|
||||
///
|
||||
/// SVG luminance masks use this, so masks brought in from SVG keep their look.
|
||||
#[label("Luminance (SVG)")]
|
||||
LuminanceSvg,
|
||||
/// Opaque areas show the content and transparent areas hide it, whatever their colors.
|
||||
Alpha,
|
||||
}
|
||||
|
||||
/// The weights of the red, green, and blue channels in a mask's luminance, those of SVG's `luminanceToAlpha`, taken on gamma-encoded channels as an SVG mask does.
|
||||
pub const MASK_LUMINANCE_WEIGHTS: [f32; 3] = [0.2125, 0.7154, 0.0721];
|
||||
/// The weights of the red, green, and blue channels in the luminance of a mask in the `Luminance` mode, taken on gamma-encoded channels, those the Luminosity family of blend modes uses.
|
||||
pub const MASK_LUMINANCE_WEIGHTS: [f32; 3] = [0.3, 0.59, 0.11];
|
||||
|
||||
/// The weights of the red, green, and blue channels in SVG's `luminanceToAlpha`, taken on gamma-encoded channels as an SVG mask does.
|
||||
/// They weigh the luminance of a mask in the `LuminanceSvg` mode and of the maps that vary other effects, which SVG reads by `luminanceToAlpha`.
|
||||
pub const SVG_LUMINANCE_WEIGHTS: [f32; 3] = [0.2125, 0.7154, 0.0721];
|
||||
|
||||
impl MaskMode {
|
||||
/// The weights of a mask graphic's premultiplied gamma-encoded red, green, blue, and alpha channels that sum to how much it shows the content.
|
||||
pub fn channel_weights(self) -> [f32; 4] {
|
||||
let ([red, green, blue], alpha) = match self {
|
||||
Self::Luminance => (MASK_LUMINANCE_WEIGHTS, 0.),
|
||||
Self::LuminanceSvg => (SVG_LUMINANCE_WEIGHTS, 0.),
|
||||
Self::Alpha => ([0.; 3], 1.),
|
||||
};
|
||||
[red, green, blue, alpha]
|
||||
}
|
||||
}
|
||||
|
||||
/// How much a pixel of the mask graphic, given as premultiplied gamma-encoded channels, shows the content, from 0 to 1.
|
||||
/// The luminance of premultiplied channels is that of the straight color times its alpha, so transparent areas hide the content in either mode.
|
||||
pub fn mask_coverage([red, green, blue, alpha]: [f32; 4], mode: MaskMode) -> f32 {
|
||||
let [red_weight, green_weight, blue_weight] = MASK_LUMINANCE_WEIGHTS;
|
||||
let coverage = match mode {
|
||||
MaskMode::Luminance => red * red_weight + green * green_weight + blue * blue_weight,
|
||||
MaskMode::Alpha => alpha,
|
||||
};
|
||||
/// The luminance of premultiplied channels is that of the straight color times its alpha, so transparent areas hide the content in every mode.
|
||||
pub fn mask_coverage(channels: [f32; 4], mode: MaskMode) -> f32 {
|
||||
let coverage: f32 = channels.into_iter().zip(mode.channel_weights()).map(|(channel, weight)| channel * weight).sum();
|
||||
coverage.clamp(0., 1.)
|
||||
}
|
||||
|
||||
@@ -89,7 +108,7 @@ pub fn masked_radius_blur_levels(radius: f64, pixels_per_length: f64) -> Vec<f64
|
||||
|
||||
/// The 8-bit code of a masked radius blur map's luminance at a pixel, given as premultiplied gamma-encoded channels, which picks the pixel's interpolation between blurs.
|
||||
pub fn masked_radius_blur_code(channels: [f32; 4]) -> u8 {
|
||||
(mask_coverage(channels, MaskMode::Luminance) * 255.).round() as u8
|
||||
(mask_coverage(channels, MaskMode::LuminanceSvg) * 255.).round() as u8
|
||||
}
|
||||
|
||||
/// For a masked radius blur map's luminance as an 8-bit `code`, the level below it among the `levels` (from [`masked_radius_blur_levels`]) and how many of 255 parts of the interpolation the level above takes, the rest going to the level below.
|
||||
@@ -120,3 +139,21 @@ pub fn masked_radius_blur_weight(level: usize, code: u8, levels: &[f64]) -> u32
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn luminance_modes_weigh_pure_red_green_and_blue_by_their_own_weights() {
|
||||
let level = |channels: [f32; 4], mode| (mask_coverage(channels, mode) * 255.).round() as u8;
|
||||
let primaries = [[1., 0., 0., 1.], [0., 1., 0., 1.], [0., 0., 1., 1.]];
|
||||
|
||||
assert_eq!(primaries.map(|primary| level(primary, MaskMode::Luminance)), [77, 150, 28]);
|
||||
assert_eq!(primaries.map(|primary| level(primary, MaskMode::LuminanceSvg)), [54, 182, 18]);
|
||||
assert_eq!(primaries.map(|primary| level(primary, MaskMode::Alpha)), [255; 3]);
|
||||
|
||||
// Premultiplied channels count the color by its alpha
|
||||
assert_eq!(level([0., 0.5, 0., 0.5], MaskMode::Luminance), 75);
|
||||
}
|
||||
}
|
||||
@@ -1076,10 +1076,10 @@ pub enum DisplaceMode {
|
||||
/// For PSD interop, the 8-bit level of a displacement map's luminance that moves nothing, which black lies the farthest from.
|
||||
pub const DISPLACEMENT_NEUTRAL_LEVEL: f64 = 128.;
|
||||
|
||||
/// The share of its distance that a displacement map's premultiplied gamma-encoded `color` moves the content, by its luminance as a mask reads it:
|
||||
/// The share of its distance that a displacement map's premultiplied gamma-encoded `color` moves the content, by its luminance as an SVG luminance mask reads it:
|
||||
/// -1 at black, none at the neutral level, and 127/128 at white. Where the map is translucent it's seen over the neutral level.
|
||||
pub fn displacement_amount(color: [f32; 4]) -> f64 {
|
||||
let luminance = mask_coverage(color, MaskMode::Luminance) as f64;
|
||||
let luminance = mask_coverage(color, MaskMode::LuminanceSvg) as f64;
|
||||
let level = luminance * 255. + DISPLACEMENT_NEUTRAL_LEVEL * (1. - color[3] as f64);
|
||||
(level - DISPLACEMENT_NEUTRAL_LEVEL) / DISPLACEMENT_NEUTRAL_LEVEL
|
||||
}
|
||||
@@ -1745,6 +1745,8 @@ impl EffectOperation {
|
||||
| Self::HighPass { .. }
|
||||
| Self::AddNoise { .. }
|
||||
| Self::Dissolve { .. }
|
||||
| Self::BackgroundBlur { .. }
|
||||
| Self::BlendIf(_)
|
||||
| Self::Adjustment(_) => false,
|
||||
}
|
||||
}
|
||||
@@ -2849,7 +2851,7 @@ mod tests {
|
||||
assert!((displacement_amount([0., 0., 0., 1.]) + 1.).abs() < 1e-5);
|
||||
assert_eq!(displacement_amount([0., 0., 0., 0.]), 0.);
|
||||
|
||||
// A color moves the content by its luminance, as a mask reads it, and a pixel reads from the opposite way
|
||||
// A color moves the content by its luminance, as an SVG luminance mask reads it, and a pixel reads from the opposite way
|
||||
let red = displacement_amount([1., 0., 0., 1.]);
|
||||
assert!((red - (0.2125 * 255. - DISPLACEMENT_NEUTRAL_LEVEL) / DISPLACEMENT_NEUTRAL_LEVEL).abs() < 1e-5);
|
||||
assert_eq!(map_displacement([1., 0., 0., 1.], DVec2::new(10., -4.)), DVec2::new(10., -4.) * -red);
|
||||
|
||||
@@ -90,7 +90,7 @@ pub(crate) fn masked_radius_blur_codes(colors: &[Color]) -> Vec<u8> {
|
||||
pub(crate) fn masked_box_blur_luminances(colors: &[Color]) -> Vec<f32> {
|
||||
let luminance = |color: Color| {
|
||||
let [red, green, blue, alpha] = color.to_gamma_srgb_channels();
|
||||
mask_coverage([red * alpha, green * alpha, blue * alpha, alpha], MaskMode::Luminance).clamp(0., 1.)
|
||||
mask_coverage([red * alpha, green * alpha, blue * alpha, alpha], MaskMode::LuminanceSvg).clamp(0., 1.)
|
||||
};
|
||||
colors.iter().map(|&color| half::f16::from_f32(luminance(color)).to_f32()).collect()
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ use crate::generators::pattern_sampler;
|
||||
use crate::layer_blending::blend_layer;
|
||||
use crate::masks::{feather_strength, mask_strength, masked, masked_box_blur_luminances, masked_radius_blur, masked_radius_blur_codes, variable_box_blur};
|
||||
use crate::resample_kernels::{MotionBlurShear, displaced, frame_warped, halftoned, motion_blurred, pixelated, radial_blurred};
|
||||
use crate::value_effects::{adjusted_gradient, adjustments, evaluate_gradient_effects, filled_color};
|
||||
use crate::value_effects::{adjusted_gradient_with_blend_ifs, adjustments, content_blend_ifs, evaluate_gradient_effects, filled_color_with_blend_ifs};
|
||||
use crate::warp_kernels::WarpRasterizer;
|
||||
use core_types::FallibleVec2Operations;
|
||||
use core_types::blending::BlendMode;
|
||||
@@ -19,6 +19,7 @@ use core_types::{ATTR_BLEND_MODE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFOR
|
||||
use glam::{DAffine2, DMat2, DVec2};
|
||||
use graphic_types::Graphic;
|
||||
use graphic_types::adjustment::Adjustment;
|
||||
use graphic_types::blend_if::{ChannelRanges, blend_ifs_acting_before, paint_overlay_folds};
|
||||
use graphic_types::effect_layers::{EffectLayers, LayerPart, PiecePlace};
|
||||
use graphic_types::effects::{
|
||||
BevelDirection, BevelStyle, BevelTechnique, EffectCapture, EffectOperation, Effects, GlowFill, GlowSource, GlowTechnique, OutlineFill, bevel_light, contour_gradient_span, effect_space,
|
||||
@@ -31,6 +32,7 @@ use graphic_types::resampling::{DisplacementField, EffectFrame, FrameWarp, Halft
|
||||
use raster_types::parallel_rows::fill_rows;
|
||||
use raster_types::{CPU, Image, Raster};
|
||||
use std::collections::HashMap;
|
||||
use std::ops::Range;
|
||||
use vector_types::gradient::{Gradient, GradientForm, GradientSettings, GradientSpread};
|
||||
|
||||
mod styles;
|
||||
@@ -118,9 +120,22 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Each row's run and its place in it, which Blend Ifs act within as the renderers' runs do
|
||||
let operations: Vec<EffectOperation> = rows.iter().map(|(operation, ..)| operation.clone()).collect();
|
||||
let runs: Vec<Range<usize>> = effects.runs().into_iter().map(|(_, rows)| rows).collect();
|
||||
let in_run = |index: usize| match runs.iter().find(|rows| rows.contains(&index)) {
|
||||
Some(rows) => (&operations[rows.clone()], index - rows.start),
|
||||
None => (&operations[..], index),
|
||||
};
|
||||
|
||||
// Unless a fill fades them first, leading adjustments flattened into the image change its own colors, keeping even transparent pixels' colors
|
||||
let layers = EffectLayers::plan_runs(effects, BlendMode::Normal, fill, true);
|
||||
let leading_adjustments = rows.iter().take(layers.flattened).take_while(|_| fill == 1.).map_while(|(operation, ..)| match operation {
|
||||
let overlay_folds = |index: usize| {
|
||||
let (run, row) = in_run(index);
|
||||
paint_overlay_folds(run, row)
|
||||
};
|
||||
let leading_adjustments = (rows.iter().enumerate().take(layers.flattened).take_while(|_| fill == 1.)).map_while(|(index, (operation, ..))| match operation {
|
||||
EffectOperation::Adjustment(Adjustment::ColorOverlay { .. }) if !overlay_folds(index) => None,
|
||||
EffectOperation::Adjustment(adjustment) => Some(adjustment),
|
||||
_ => None,
|
||||
});
|
||||
@@ -181,9 +196,13 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
|
||||
let mut pieces: HashMap<EffectCapture, Plane<[f32; 4]>> = HashMap::new();
|
||||
// How much the trailing masks together show of each finished layer
|
||||
let mut layer_fade: Option<Plane<f32>> = None;
|
||||
// How strongly the Blend Ifs so far show the content, which fades it like a fill varying across it
|
||||
let mut blend_if_weight: Option<Plane<f32>> = None;
|
||||
|
||||
// Each run after the first takes the result of those before it as its content at full strength, like the renderers' nested runs
|
||||
let mut run_fill = fill;
|
||||
// The leading adjustments carried out on the image's colors still start stretches that Blend Ifs act at the start of
|
||||
let mut rows_reached = 0;
|
||||
for (index, &(ref operation, effect_to_pixels, starts_later_run)) in rows.iter().enumerate().skip(leading) {
|
||||
if starts_later_run {
|
||||
full = match (filled.take(), beneath.take()) {
|
||||
@@ -192,7 +211,23 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
|
||||
(None, None) => full,
|
||||
};
|
||||
run_fill = 1.;
|
||||
blend_if_weight = None;
|
||||
}
|
||||
|
||||
let acting_blend_ifs = (rows_reached..=index).flat_map(|row| {
|
||||
let (run, row) = in_run(row);
|
||||
blend_ifs_acting_before(run, row)
|
||||
});
|
||||
for ranges in acting_blend_ifs.filter(|ranges| !ranges.content.show_everything()) {
|
||||
let weight = blend_if_weights(&full, &ranges.content);
|
||||
filled = Some(filled.as_ref().unwrap_or(&full).zip(&weight, |pixel, weight| pixel.map(|channel| channel * weight)));
|
||||
blend_if_weight = Some(match blend_if_weight {
|
||||
Some(previous) => previous.zip(&weight, |previous, weight| previous * weight),
|
||||
None => weight,
|
||||
});
|
||||
}
|
||||
rows_reached = index + 1;
|
||||
|
||||
if operation.changes_nothing() {
|
||||
continue;
|
||||
}
|
||||
@@ -210,6 +245,7 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
|
||||
let layered = index >= layers.flattened;
|
||||
let piece = |plane: usize| layered.then_some(EffectCapture { index, plane });
|
||||
let knockout_fill = if layered { 1. } else { run_fill };
|
||||
let knockout_weight = blend_if_weight.as_ref().filter(|_| !layered);
|
||||
|
||||
match *operation {
|
||||
EffectOperation::Blur { radius, box_blur, gamma, .. } if !operation.varies_blur_radius() => {
|
||||
@@ -273,7 +309,7 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
|
||||
let silhouette = full.map(|[_, _, _, alpha]| alpha).shifted(offset.x, offset.y);
|
||||
let strength = cast(silhouette, size, spread, GlowTechnique::Softer, 100., contour, pixels_per_length);
|
||||
let shadow = tinted(&strength, color);
|
||||
let shadow = if knockout { knocked_out(shadow, &full, knockout_fill) } else { shadow };
|
||||
let shadow = if knockout { knocked_out(shadow, &full, knockout_fill, knockout_weight) } else { shadow };
|
||||
place_beneath(&mut pieces, piece(0), &mut beneath, shadow);
|
||||
}
|
||||
EffectOperation::OuterGlow {
|
||||
@@ -293,7 +329,7 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
|
||||
let strength = shaped(raw.clone(), range, contour);
|
||||
let grain = styles::GlowGrain::new(&paint, noise, jitter, seed, pixels_to_effect);
|
||||
let fades = matches!(paint, GlowFill::Gradient { .. }) || noise > 0.;
|
||||
let glow = knocked_out(glow_tint(&paint, &strength, &raw, fades, grain.as_ref()), &full, knockout_fill);
|
||||
let glow = knocked_out(glow_tint(&paint, &strength, &raw, fades, grain.as_ref()), &full, knockout_fill, knockout_weight);
|
||||
place_beneath(&mut pieces, piece(0), &mut beneath, glow);
|
||||
}
|
||||
EffectOperation::InnerShadow {
|
||||
@@ -411,7 +447,7 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
|
||||
|
||||
// The band outside lies beneath the content like a shadow, and the band inside over it like an inner shadow
|
||||
if let Some(band) = &bands.outside {
|
||||
let band = knocked_out(painted(band), &full, knockout_fill);
|
||||
let band = knocked_out(painted(band), &full, knockout_fill, knockout_weight);
|
||||
place_beneath(&mut pieces, piece(0), &mut beneath, band);
|
||||
}
|
||||
if let Some(band) = &bands.inside {
|
||||
@@ -492,7 +528,7 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
|
||||
place_within(&mut pieces, piece(plane), &mut full, &mut filled, tinted(&amount, color), blend_mode);
|
||||
}
|
||||
for (plane, (amount, (color, _))) in outside.into_iter().flatten().zip(colors).enumerate() {
|
||||
let slope = knocked_out(tinted(&amount, color), &full, knockout_fill);
|
||||
let slope = knocked_out(tinted(&amount, color), &full, knockout_fill, knockout_weight);
|
||||
place_beneath(&mut pieces, piece(plane + 2), &mut beneath, slope);
|
||||
}
|
||||
}
|
||||
@@ -511,6 +547,8 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
|
||||
};
|
||||
place_within(&mut pieces, piece(0), &mut full, &mut filled, painted, blend_mode);
|
||||
}
|
||||
// An image of its own has nothing beneath it to blur, or for Blend If to read, which fades the content where it acts
|
||||
EffectOperation::BackgroundBlur { .. } | EffectOperation::BlendIf(_) => {}
|
||||
// A solid paint overlay paints within the content alone, like any other paint overlay
|
||||
EffectOperation::Adjustment(Adjustment::ColorOverlay { color, blend_mode, opacity }) => {
|
||||
let painted = premultiplied_gamma_channels(color.with_alpha(color.a() * (opacity / 100.) as f32));
|
||||
@@ -670,7 +708,7 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
|
||||
let Some(frame) = &frame else { continue };
|
||||
let Some(screens) = HalftoneScreen::of(operation, frame) else { continue };
|
||||
|
||||
// Each pixel's share of the content that the fill left fades the printed dots, rather than printing the faded content's fainter dots
|
||||
// Each pixel's share of the content that the fill and the Blend Ifs left fades the printed dots, rather than printing the faded content's fainter dots
|
||||
merge_beneath(&mut full, &mut filled, &mut beneath);
|
||||
let shares = filled.as_ref().map(|filled| crate::filter_kernels::fill_shares(&full, filled));
|
||||
let unfaded = filled.map(|filled| crate::filter_kernels::at_full_coverage(&filled, &full));
|
||||
@@ -879,19 +917,31 @@ fn tinted(coverage: &Plane<f32>, color: Color) -> Plane<[f32; 4]> {
|
||||
coverage.map(|coverage| color.map(|channel| channel * coverage))
|
||||
}
|
||||
|
||||
/// A tinted image of what lies beneath, hidden behind the full-strength content where the content covers it as strongly as `fill`.
|
||||
fn knocked_out(tinted: Plane<[f32; 4]>, full_content: &Plane<[f32; 4]>, fill: f32) -> Plane<[f32; 4]> {
|
||||
if fill >= 1. {
|
||||
/// A tinted image of what lies beneath, hidden behind the full-strength content where the content covers it as strongly as `fill`, times the Blend If weight if any fades it.
|
||||
fn knocked_out(tinted: Plane<[f32; 4]>, full_content: &Plane<[f32; 4]>, fill: f32, blend_if_weight: Option<&Plane<f32>>) -> Plane<[f32; 4]> {
|
||||
if fill >= 1. && blend_if_weight.is_none() {
|
||||
return tinted;
|
||||
}
|
||||
|
||||
// The faded content shows what's beneath through 1 - fill × alpha of it, of which only 1 - alpha may show this
|
||||
tinted.zip(full_content, |tinted, content| {
|
||||
let shown = (1. - content[3]) / (1. - fill * content[3]).max(f32::EPSILON);
|
||||
let covering = match blend_if_weight {
|
||||
Some(weight) => full_content.zip(weight, |content, weight| [content[3], weight * fill, 0., 0.]),
|
||||
None => full_content.map(|content| [content[3], fill, 0., 0.]),
|
||||
};
|
||||
tinted.zip(&covering, |tinted, [alpha, fill, ..]| {
|
||||
let shown = (1. - alpha) / (1. - fill * alpha).max(f32::EPSILON);
|
||||
tinted.map(|channel| channel * shown)
|
||||
})
|
||||
}
|
||||
|
||||
/// How strongly Blend If's `ranges` show each pixel of a premultiplied gamma-encoded `image`, by its straight color.
|
||||
fn blend_if_weights(image: &Plane<[f32; 4]>, ranges: &ChannelRanges) -> Plane<f32> {
|
||||
image.map(|[red, green, blue, alpha]| {
|
||||
let straight = if alpha > 0. { [red, green, blue].map(|channel| (channel / alpha) as f64) } else { [0.; 3] };
|
||||
ranges.weight(straight) as f32
|
||||
})
|
||||
}
|
||||
|
||||
/// Places a tinted image beneath the content: as the layered `piece` if it names one, or else stacked over what lies `beneath` the content so far.
|
||||
fn place_beneath(pieces: &mut HashMap<EffectCapture, Plane<[f32; 4]>>, piece: Option<EffectCapture>, beneath: &mut Option<Plane<[f32; 4]>>, tinted: Plane<[f32; 4]>) {
|
||||
match piece {
|
||||
@@ -955,7 +1005,7 @@ fn composite_layers(
|
||||
PiecePlace::Within => SharePart::Whole,
|
||||
PiecePlace::IntoContent { over: false } => SharePart::IntoContent,
|
||||
PiecePlace::IntoContent { over: true } => SharePart::IntoContentBeneathPartOver { opacity: OPACITY, fade },
|
||||
PiecePlace::Beneath | PiecePlace::Through { .. } => continue,
|
||||
PiecePlace::Beneath | PiecePlace::Through { .. } | PiecePlace::Backdrop => continue,
|
||||
};
|
||||
content = composite_in_share(&content, tinted, full_content, piece.blend_mode, part);
|
||||
}
|
||||
@@ -977,7 +1027,8 @@ fn composite_layers(
|
||||
PiecePlace::Beneath => tinted.clone(),
|
||||
PiecePlace::Within if !holds_content => tinted.zip(full_content, |tinted, content| tinted.map(|channel| channel * content[3])),
|
||||
PiecePlace::Through { .. } => tinted.zip(&through_shares(full_content, &content, OPACITY, fade), |tinted, share| tinted.map(|channel| channel * share)),
|
||||
PiecePlace::Within | PiecePlace::IntoContent { .. } => continue,
|
||||
// What lies beneath, for a backdrop the image doesn't have
|
||||
PiecePlace::Within | PiecePlace::IntoContent { .. } | PiecePlace::Backdrop => continue,
|
||||
};
|
||||
stack = Some(stack_over(stack, upper));
|
||||
}
|
||||
@@ -1189,8 +1240,9 @@ fn paint_sampler(paint: &Graphic) -> Option<Box<dyn Fn(DVec2) -> Color + Sync +
|
||||
// The fill fades the color beneath its paint overlays, which paint over it at full strength, as the renderers fill an endless color
|
||||
let opacity = item.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.) as f32;
|
||||
let fill = item.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, 1.) as f32;
|
||||
let adjustments = item.attribute::<Effects>(ATTR_EFFECTS).map(adjustments).unwrap_or_default();
|
||||
let color = filled_color(*item.element(), &adjustments, fill);
|
||||
let effects = item.attribute::<Effects>(ATTR_EFFECTS);
|
||||
let (adjustments, blend_ifs) = (effects.map(adjustments).unwrap_or_default(), effects.map(content_blend_ifs).unwrap_or_default());
|
||||
let color = filled_color_with_blend_ifs(*item.element(), &adjustments, &blend_ifs, fill);
|
||||
Some(Box::new(move |_| faded(color, opacity)))
|
||||
}
|
||||
Graphic::RasterCPU(item) => {
|
||||
@@ -1341,12 +1393,13 @@ fn displacement_map_sampler(map: &Graphic) -> Option<Box<dyn Fn(DVec2) -> [f32;
|
||||
Some(Box::new(move |point| sample_gamma(&image, to_pixels.transform_point2(point)).map(|channel| channel * opacity)))
|
||||
}
|
||||
Graphic::Gradient(item) => {
|
||||
// The GPU fades a gradient by its fill in the layer of its opacity, unless adjustments act on the ramp the fill fades
|
||||
let adjustments = item.attribute::<Effects>(ATTR_EFFECTS).filter(|effects| !effects.change_nothing()).map(adjustments).unwrap_or_default();
|
||||
// The GPU fades a gradient by its fill in the layer of its opacity, unless effects act on the ramp the fill fades
|
||||
let effects = item.attribute::<Effects>(ATTR_EFFECTS).filter(|effects| !effects.change_nothing());
|
||||
let (adjustments, blend_ifs) = (effects.map(adjustments).unwrap_or_default(), effects.map(content_blend_ifs).unwrap_or_default());
|
||||
let opacity = item.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.) as f32;
|
||||
let fill = item.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, 1.) as f32;
|
||||
let settings = GradientSettings::from_item_attributes(item);
|
||||
let (gradient, settings, opacity) = match adjusted_gradient(item.element(), settings, &adjustments, fill) {
|
||||
let (gradient, settings, opacity) = match adjusted_gradient_with_blend_ifs(item.element(), settings, &adjustments, &blend_ifs, fill) {
|
||||
Some((adjusted, adjusted_settings)) => (std::borrow::Cow::Owned(adjusted), adjusted_settings, opacity),
|
||||
None => (std::borrow::Cow::Borrowed(item.element()), settings, opacity * fill),
|
||||
};
|
||||
@@ -1360,12 +1413,16 @@ fn displacement_map_sampler(map: &Graphic) -> Option<Box<dyn Fn(DVec2) -> [f32;
|
||||
}))
|
||||
}
|
||||
Graphic::Color(item) => {
|
||||
// The GPU fills a solid color from 8-bit channels in a layer of its opacity, which the fill fades too unless adjustments act on the faded color
|
||||
let adjustments = item.attribute::<Effects>(ATTR_EFFECTS).filter(|effects| !effects.change_nothing()).map(adjustments).unwrap_or_default();
|
||||
// The GPU fills a solid color from 8-bit channels in a layer of its opacity, which the fill fades too unless effects act on the faded color
|
||||
let effects = item.attribute::<Effects>(ATTR_EFFECTS).filter(|effects| !effects.change_nothing());
|
||||
let (adjustments, blend_ifs) = (effects.map(adjustments).unwrap_or_default(), effects.map(content_blend_ifs).unwrap_or_default());
|
||||
let fill = item.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, 1.) as f32;
|
||||
let (color, opacity) = match adjustments.is_empty() {
|
||||
let (color, opacity) = match adjustments.is_empty() && blend_ifs.is_empty() {
|
||||
true => (*item.element(), paint_opacity(item)),
|
||||
false => (filled_color(*item.element(), &adjustments, fill), item.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.) as f32),
|
||||
false => (
|
||||
filled_color_with_blend_ifs(*item.element(), &adjustments, &blend_ifs, fill),
|
||||
item.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.) as f32,
|
||||
),
|
||||
};
|
||||
let (color, opacity) = (core_types::color::SRGBA8::from(color), layer_opacity(opacity));
|
||||
|
||||
@@ -2446,6 +2503,60 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn halftones_keep_the_fade_of_blend_ifs_before_them() {
|
||||
use graphic_types::blend_if::{BlendIfRanges, BlendRange};
|
||||
|
||||
// A Blend If hiding the white content stays hiding it once a halftone prints it, which white leaves as white
|
||||
let mut ranges = BlendIfRanges::default();
|
||||
ranges.content.gray = BlendRange {
|
||||
falloff_start: 0.,
|
||||
range_start: 0.,
|
||||
range_end: 50.,
|
||||
falloff_end: 50.,
|
||||
};
|
||||
let halftone = EffectOperation::ColorHalftone {
|
||||
radius: 4.,
|
||||
red_angle: 45.,
|
||||
green_angle: 45.,
|
||||
blue_angle: 45.,
|
||||
offset: DVec2::ZERO,
|
||||
phase: 0.,
|
||||
};
|
||||
let mut item = Item::new_from_element(Raster::new_cpu(Image::new(24, 24, Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(24.)));
|
||||
[EffectOperation::BlendIf(Box::new(ranges)), halftone]
|
||||
.iter()
|
||||
.for_each(|operation| graphic_types::stamp_effect(&mut item, graphic_types::Effect::new(operation)));
|
||||
|
||||
let evaluated = evaluate_raster_effects(item);
|
||||
assert!(evaluated.element().data.iter().all(|color| color.a() < 1e-5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blend_ifs_still_act_after_leading_adjustments_that_change_nothing() {
|
||||
use graphic_types::blend_if::{BlendIfRanges, BlendRange};
|
||||
|
||||
// A Blend If hiding the white content hides it before the invert, though the image's own colors take the Make Opaque of no strength ahead of it
|
||||
let mut ranges = BlendIfRanges::default();
|
||||
ranges.content.gray = BlendRange {
|
||||
falloff_start: 0.,
|
||||
range_start: 0.,
|
||||
range_end: 50.,
|
||||
falloff_end: 50.,
|
||||
};
|
||||
let mut item = Item::new_from_element(Raster::new_cpu(Image::new(8, 8, Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(8.)));
|
||||
[
|
||||
EffectOperation::Adjustment(Adjustment::MakeOpaque { strength: 0. }),
|
||||
EffectOperation::BlendIf(Box::new(ranges)),
|
||||
EffectOperation::Adjustment(Adjustment::Invert),
|
||||
]
|
||||
.iter()
|
||||
.for_each(|operation| graphic_types::stamp_effect(&mut item, graphic_types::Effect::new(operation)));
|
||||
|
||||
let evaluated = evaluate_raster_effects(item);
|
||||
assert!(evaluated.element().data.iter().all(|color| color.a() < 1e-5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn halftones_too_fine_to_print_show_their_tone() {
|
||||
// Dots a fraction of a pixel apart print the tone they average to, which for opaque content is the content
|
||||
|
||||
@@ -7,6 +7,7 @@ use core_types::Color;
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, Item};
|
||||
use graphic_types::adjustment::Adjustment;
|
||||
use graphic_types::blend_if::{ChannelRanges, blend_ifs_acting_before, fades_content};
|
||||
use graphic_types::effects::{EffectOperation, Effects};
|
||||
use std::hash::{DefaultHasher, Hasher};
|
||||
use std::sync::{Mutex, PoisonError};
|
||||
@@ -29,6 +30,47 @@ pub fn adjustments(effects: &Effects) -> Vec<Adjustment> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A step a value's Blend Ifs take among its adjustments (see [`content_blend_ifs`]).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum BlendIfStep {
|
||||
/// A Blend If reads the value's colors and fades the value by these content ranges, as a fill does.
|
||||
Fade(ChannelRanges),
|
||||
/// An effect run after the first starts (see [`Effects::runs`]), taking the value as the runs before it leave it as its content at full strength.
|
||||
NextRun,
|
||||
}
|
||||
|
||||
/// Where each Blend If among the effects that fades a value by its own colors reads it, after how many of the [`adjustments`], with where each effect run after the first starts.
|
||||
/// Empty if no Blend If fades the value.
|
||||
pub fn content_blend_ifs(effects: &Effects) -> Vec<(usize, BlendIfStep)> {
|
||||
let operations: Vec<EffectOperation> = effects.operations().collect();
|
||||
if !fades_content(&operations) {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
// Each run's Blend Ifs act from its own start, as the renderers draw each run's effects on the result of those before it
|
||||
let mut adjustments_before = 0;
|
||||
let mut steps = Vec::new();
|
||||
for (run_index, (_, rows)) in effects.runs().into_iter().enumerate() {
|
||||
if run_index > 0 {
|
||||
steps.push((adjustments_before, BlendIfStep::NextRun));
|
||||
}
|
||||
|
||||
let run = &operations[rows];
|
||||
for (row, operation) in run.iter().enumerate() {
|
||||
let acting = blend_ifs_acting_before(run, row).into_iter().filter(|ranges| !ranges.content.show_everything());
|
||||
steps.extend(acting.map(|ranges| (adjustments_before, BlendIfStep::Fade(ranges.content))));
|
||||
|
||||
adjustments_before += usize::from(matches!(operation, EffectOperation::Adjustment(_)));
|
||||
}
|
||||
}
|
||||
steps
|
||||
}
|
||||
|
||||
/// Whether a Blend If fades a value with effects in more than one run, so later runs read and paint within the result of those before them.
|
||||
pub fn blend_ifs_span_runs(effects: &Effects) -> bool {
|
||||
content_blend_ifs(effects).iter().any(|(_, step)| *step == BlendIfStep::NextRun)
|
||||
}
|
||||
|
||||
/// The color with `adjustments` carried out on it in order.
|
||||
pub fn adjusted_color(color: Color, adjustments: &[Adjustment]) -> Color {
|
||||
adjustments.iter().fold(color, |color, adjustment| adjust_color(adjustment, color))
|
||||
@@ -37,19 +79,60 @@ pub fn adjusted_color(color: Color, adjustments: &[Adjustment]) -> Color {
|
||||
/// The color an endless paint of `color` shows with `adjustments` carried out over it and its `fill` fading it, though not the paint overlays painted over it.
|
||||
/// Without edges, each paint overlay blends with the paint itself, which is exact where the paint is opaque.
|
||||
pub fn filled_color(color: Color, adjustments: &[Adjustment], fill: f32) -> Color {
|
||||
if fill >= 1. {
|
||||
return adjusted_color(color, adjustments);
|
||||
}
|
||||
fill_through(color, adjustments, fill, |index, color| adjust_color(&adjustments[index], color))
|
||||
filled_color_with_blend_ifs(color, adjustments, &[], fill)
|
||||
}
|
||||
|
||||
/// Carries out `adjustments` over a paint faded by `fill` as [`filled_color`] does, with `adjust` carrying out each one besides a paint overlay, given its index.
|
||||
fn fill_through(color: Color, adjustments: &[Adjustment], fill: f32, adjust: impl Fn(usize, Color) -> Color) -> Color {
|
||||
/// Like [`filled_color`], with the steps of the `blend_ifs` (see [`content_blend_ifs`]) also fading the paint by each one's content ranges where it reads the paint's colors.
|
||||
pub fn filled_color_with_blend_ifs(color: Color, adjustments: &[Adjustment], blend_ifs: &[(usize, BlendIfStep)], fill: f32) -> Color {
|
||||
if fill >= 1. && blend_ifs.is_empty() {
|
||||
return adjusted_color(color, adjustments);
|
||||
}
|
||||
fill_through(color, adjustments, blend_ifs, fill, |index, color| adjust_color(&adjustments[index], color), ChannelRanges::weight)
|
||||
}
|
||||
|
||||
/// Carries out `adjustments` over a paint faded by `fill` and the `blend_ifs` as [`filled_color_with_blend_ifs`] does, with `adjust` carrying out each one besides a paint overlay, given its index.
|
||||
/// `weigh` gives how strongly a Blend If's ranges show the gamma-encoded channels it reads.
|
||||
fn fill_through(
|
||||
color: Color,
|
||||
adjustments: &[Adjustment],
|
||||
blend_ifs: &[(usize, BlendIfStep)],
|
||||
fill: f32,
|
||||
adjust: impl Fn(usize, Color) -> Color,
|
||||
mut weigh: impl FnMut(&ChannelRanges, [f64; 3]) -> f64,
|
||||
) -> Color {
|
||||
// Each Blend If fades the faded color by how strongly it shows the full-strength one, which each later run resets to the faded color
|
||||
let mut steps = blend_ifs.iter().peekable();
|
||||
let mut take_steps = |full: &mut Color, filled: &mut Color, adjusted_count: usize| {
|
||||
let mut weight = 1.;
|
||||
let mut faded = false;
|
||||
while let Some((_, step)) = steps.next_if(|(before, _)| *before <= adjusted_count) {
|
||||
match step {
|
||||
BlendIfStep::Fade(ranges) => {
|
||||
let [red, green, blue, _] = full.to_gamma_srgb_channels();
|
||||
weight *= weigh(ranges, [red, green, blue].map(f64::from));
|
||||
faded = true;
|
||||
}
|
||||
BlendIfStep::NextRun => {
|
||||
*filled = filled.with_alpha(filled.a() * std::mem::replace(&mut weight, 1.) as f32);
|
||||
*full = *filled;
|
||||
}
|
||||
}
|
||||
}
|
||||
*filled = filled.with_alpha(filled.a() * weight as f32);
|
||||
faded
|
||||
};
|
||||
|
||||
// The color at full strength, which each paint overlay blends with, and the color the fill fades, which it paints over at full strength
|
||||
let (mut full, mut filled) = (color, color.with_alpha(color.a() * fill));
|
||||
|
||||
// Once a Blend If fades them, adjustments keep the colors empty where they're empty, as the renderers keep empty pixels
|
||||
let mut faded = false;
|
||||
for (index, adjustment) in adjustments.iter().enumerate() {
|
||||
faded |= take_steps(&mut full, &mut filled, index);
|
||||
|
||||
let Adjustment::ColorOverlay { color: paint, blend_mode, opacity } = *adjustment else {
|
||||
(full, filled) = (adjust(index, full), adjust(index, filled));
|
||||
let adjusted = |color: Color| if !faded || color.a() > 0. { adjust(index, color) } else { color };
|
||||
(full, filled) = (adjusted(full), adjusted(filled));
|
||||
continue;
|
||||
};
|
||||
|
||||
@@ -64,18 +147,39 @@ fn fill_through(color: Color, adjustments: &[Adjustment], fill: f32, adjust: imp
|
||||
filled = Color::from_gamma_srgb_channels(mix(red, under_red), mix(green, under_green), mix(blue, under_blue), alpha);
|
||||
full = overlay_paint(full, paint, blend_mode, (opacity / 100.) as f32);
|
||||
}
|
||||
take_steps(&mut full, &mut filled, adjustments.len());
|
||||
filled
|
||||
}
|
||||
|
||||
/// Carries out `adjustments` in order on any number of colors with the `fill` fading them, with each one's kernel prepared once.
|
||||
fn prepared(adjustments: &[Adjustment], fill: f32) -> Box<dyn Fn(Color) -> Color> {
|
||||
/// Carries out `adjustments` in order on any number of colors with the `fill` and the `blend_ifs` fading them, with each one's kernel prepared once.
|
||||
fn prepared(adjustments: &[Adjustment], blend_ifs: &[(usize, BlendIfStep)], fill: f32) -> Box<dyn Fn(Color) -> Color> {
|
||||
let kernels: Vec<PreparedAdjustment> = adjustments.iter().map(PreparedAdjustment::new).collect();
|
||||
if fill >= 1. {
|
||||
if fill >= 1. && blend_ifs.is_empty() {
|
||||
return Box::new(move |color| kernels.iter().fold(color, |color, kernel| kernel.adjust(color)));
|
||||
}
|
||||
|
||||
let adjustments = adjustments.to_vec();
|
||||
Box::new(move |color| fill_through(color, &adjustments, fill, |index, color| kernels[index].adjust(color)))
|
||||
let (adjustments, blend_ifs) = (adjustments.to_vec(), blend_ifs.to_vec());
|
||||
Box::new(move |color| fill_through(color, &adjustments, &blend_ifs, fill, |index, color| kernels[index].adjust(color), ChannelRanges::weight))
|
||||
}
|
||||
|
||||
/// Tells apart the colors each channel's range of each of the `blend_ifs` shows fully, partly, or not at all, as it reads them where [`fill_through`] fades by it.
|
||||
fn blend_if_regions(adjustments: &[Adjustment], blend_ifs: &[(usize, BlendIfStep)], fill: f32) -> impl Fn(Color) -> u64 {
|
||||
let kernels: Vec<PreparedAdjustment> = adjustments.iter().map(PreparedAdjustment::new).collect();
|
||||
let (adjustments, blend_ifs) = (adjustments.to_vec(), blend_ifs.to_vec());
|
||||
|
||||
// Each channel's state (hidden, partly shown, or shown) is a digit in base 3, so up to ten Blend Ifs stay apart exactly
|
||||
move |color| {
|
||||
let mut region = 0_u64;
|
||||
let weigh = |ranges: &ChannelRanges, channels: [f64; 3]| {
|
||||
for weight in ranges.channel_weights(channels) {
|
||||
let state = u64::from(weight > 0.) + u64::from(weight >= 1.);
|
||||
region = region.wrapping_mul(3).wrapping_add(state);
|
||||
}
|
||||
ranges.weight(channels)
|
||||
};
|
||||
fill_through(color, &adjustments, &blend_ifs, fill, |index, color| kernels[index].adjust(color), weigh);
|
||||
region
|
||||
}
|
||||
}
|
||||
|
||||
/// The gradient with `adjustments` carried out along its ramp, with the settings to read the result with, or `None` if there are no adjustments.
|
||||
@@ -83,17 +187,28 @@ fn prepared(adjustments: &[Adjustment], fill: f32) -> Box<dyn Fn(Color) -> Color
|
||||
/// A stepped ramp holds each stop's color, so adjusting the stops is exact. Elsewhere an adjustment can bend the ramp between stops,
|
||||
/// so the adjusted ramp is resampled into stops that interpolate linearly in gamma.
|
||||
pub fn adjusted_gradient(gradient: &Gradient, settings: GradientSettings, adjustments: &[Adjustment], fill: f32) -> Option<(Gradient, GradientSettings)> {
|
||||
if adjustments.is_empty() {
|
||||
adjusted_gradient_with_blend_ifs(gradient, settings, adjustments, &[], fill)
|
||||
}
|
||||
|
||||
/// Like [`adjusted_gradient`], with the `blend_ifs` also fading the ramp as [`filled_color_with_blend_ifs`] fades a color, or `None` if there are neither adjustments nor Blend Ifs.
|
||||
pub fn adjusted_gradient_with_blend_ifs(
|
||||
gradient: &Gradient,
|
||||
settings: GradientSettings,
|
||||
adjustments: &[Adjustment],
|
||||
blend_ifs: &[(usize, BlendIfStep)],
|
||||
fill: f32,
|
||||
) -> Option<(Gradient, GradientSettings)> {
|
||||
if adjustments.is_empty() && blend_ifs.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
// A gradient without stops reads as black, so its adjusted ramp is one stop of the adjusted black
|
||||
if gradient.is_empty() {
|
||||
return Some((Gradient::from(vec![prepared(adjustments, fill)(Color::BLACK)]), settings));
|
||||
return Some((Gradient::from(vec![prepared(adjustments, blend_ifs, fill)(Color::BLACK)]), settings));
|
||||
}
|
||||
|
||||
if settings.interpolation == GradientInterpolation::Stepped {
|
||||
let adjust = prepared(adjustments, fill);
|
||||
let adjust = prepared(adjustments, blend_ifs, fill);
|
||||
return Some((gradient.map_colors(|color| adjust(*color)), settings));
|
||||
}
|
||||
|
||||
@@ -102,6 +217,16 @@ pub fn adjusted_gradient(gradient: &Gradient, settings: GradientSettings, adjust
|
||||
gradient.cache_hash(&mut hasher);
|
||||
settings.cache_hash(&mut hasher);
|
||||
adjustments.iter().for_each(|adjustment| adjustment.cache_hash(&mut hasher));
|
||||
for (before, step) in blend_ifs {
|
||||
hasher.write_usize(*before);
|
||||
match step {
|
||||
BlendIfStep::Fade(ranges) => {
|
||||
hasher.write_u8(0);
|
||||
ranges.cache_hash(&mut hasher);
|
||||
}
|
||||
BlendIfStep::NextRun => hasher.write_u8(1),
|
||||
}
|
||||
}
|
||||
hasher.write_u32(fill.to_bits());
|
||||
let key = hasher.finish();
|
||||
|
||||
@@ -114,7 +239,11 @@ pub fn adjusted_gradient(gradient: &Gradient, settings: GradientSettings, adjust
|
||||
return Some(result);
|
||||
}
|
||||
|
||||
let resampled = gradient.map_ramp(settings, prepared(adjustments, fill));
|
||||
// A Blend If cuts the ramp off wherever the colors it reads cross its ranges, which may lie between the resampling's probes
|
||||
let resampled = match blend_ifs.is_empty() {
|
||||
true => gradient.map_ramp(settings, prepared(adjustments, blend_ifs, fill)),
|
||||
false => gradient.map_ramp_by_regions(settings, prepared(adjustments, blend_ifs, fill), blend_if_regions(adjustments, blend_ifs, fill)),
|
||||
};
|
||||
let resampled_settings = GradientSettings {
|
||||
space: GradientSpace::RgbGamma,
|
||||
interpolation: GradientInterpolation::Linear,
|
||||
@@ -129,29 +258,43 @@ pub fn adjusted_gradient(gradient: &Gradient, settings: GradientSettings, adjust
|
||||
Some((resampled, resampled_settings))
|
||||
}
|
||||
|
||||
/// The color with the adjustments among its effects carried out and the effects consumed, for nodes that read the color.
|
||||
/// The color with the adjustments among the effects carried out on it, faded by each Blend If where it reads the color, for the paints and nodes that read the value.
|
||||
pub fn color_after_effects(color: Color, effects: &Effects) -> Color {
|
||||
filled_color_with_blend_ifs(color, &adjustments(effects), &content_blend_ifs(effects), 1.)
|
||||
}
|
||||
|
||||
/// Carries out the effects on any number of colors as [`color_after_effects`] does on one, with each adjustment's kernel prepared once.
|
||||
pub fn prepared_color_after_effects(effects: &Effects) -> Box<dyn Fn(Color) -> Color> {
|
||||
prepared(&adjustments(effects), &content_blend_ifs(effects), 1.)
|
||||
}
|
||||
|
||||
/// The gradient with the effects carried out along its ramp as [`color_after_effects`] carries them out on a color, with the settings to read the result with, or `None` with nothing to carry out.
|
||||
pub fn gradient_after_effects(gradient: &Gradient, settings: GradientSettings, effects: &Effects) -> Option<(Gradient, GradientSettings)> {
|
||||
adjusted_gradient_with_blend_ifs(gradient, settings, &adjustments(effects), &content_blend_ifs(effects), 1.)
|
||||
}
|
||||
|
||||
/// The color with its effects carried out as [`color_after_effects`] does and consumed, for nodes that read the color.
|
||||
/// A color without the effects attribute is returned as it is.
|
||||
pub fn evaluate_color_effects(item: Item<Color>) -> Item<Color> {
|
||||
let Some(adjustments) = item.attribute::<Effects>(ATTR_EFFECTS).map(adjustments) else {
|
||||
let Some(color) = item.attribute::<Effects>(ATTR_EFFECTS).map(|effects| color_after_effects(*item.element(), effects)) else {
|
||||
return item;
|
||||
};
|
||||
|
||||
let mut item = item;
|
||||
*item.element_mut() = adjusted_color(*item.element(), &adjustments);
|
||||
*item.element_mut() = color;
|
||||
item.remove_attribute::<Effects>(ATTR_EFFECTS);
|
||||
item
|
||||
}
|
||||
|
||||
/// The gradient with the adjustments among its effects carried out along its ramp and the effects consumed, for nodes that read its colors.
|
||||
/// The gradient with its effects carried out along its ramp as [`gradient_after_effects`] does and consumed, for nodes that read its colors.
|
||||
/// A gradient without the effects attribute is returned as it is.
|
||||
pub fn evaluate_gradient_effects(item: Item<Gradient>) -> Item<Gradient> {
|
||||
let Some(adjustments) = item.attribute::<Effects>(ATTR_EFFECTS).map(adjustments) else {
|
||||
return item;
|
||||
};
|
||||
let Some(effects) = item.attribute::<Effects>(ATTR_EFFECTS) else { return item };
|
||||
let settings = GradientSettings::from_item_attributes(&item);
|
||||
let adjusted = gradient_after_effects(item.element(), settings, effects);
|
||||
|
||||
let mut item = item;
|
||||
let settings = match adjusted_gradient(item.element(), settings, &adjustments, 1.) {
|
||||
let settings = match adjusted {
|
||||
Some((gradient, adjusted_settings)) => {
|
||||
*item.element_mut() = gradient;
|
||||
adjusted_settings
|
||||
@@ -180,6 +323,16 @@ mod tests {
|
||||
actual.iter().zip(expected).all(|(actual, expected)| (actual - expected).abs() < 1e-4)
|
||||
}
|
||||
|
||||
/// The `element` with each row stamped on it while it's placed by the row's scale, so a row stamped at a new scale starts a run of its own.
|
||||
fn stamped<T>(element: T, rows: &[(EffectOperation, f64)]) -> Item<T> {
|
||||
let mut item = Item::new_from_element(element);
|
||||
for (operation, scale) in rows {
|
||||
item.set_attribute(core_types::ATTR_TRANSFORM, glam::DAffine2::from_scale(glam::DVec2::splat(*scale)));
|
||||
graphic_types::stamp_effect(&mut item, graphic_types::Effect::new(operation));
|
||||
}
|
||||
item
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paint_overlays_mix_in_gamma_unfaded_by_the_fill() {
|
||||
let half_white = [Adjustment::ColorOverlay {
|
||||
@@ -198,6 +351,162 @@ mod tests {
|
||||
assert!(close(gamma(filled_color(Color::BLACK, &half_white, 0.5)), [2. / 3., 2. / 3., 2. / 3., 0.75]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn consumed_effects_fade_values_by_their_blend_ifs_where_they_read_the_colors() {
|
||||
use graphic_types::blend_if::BlendIfRanges;
|
||||
|
||||
// Shown only where the gray is at least half
|
||||
let mut hides_darks = BlendIfRanges::default();
|
||||
hides_darks.content.gray.falloff_start = 50.;
|
||||
hides_darks.content.gray.range_start = 50.;
|
||||
let blend_if = EffectOperation::BlendIf(Box::new(hides_darks));
|
||||
let invert = EffectOperation::Adjustment(Adjustment::Invert);
|
||||
let red = EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
||||
color: Color::RED,
|
||||
blend_mode: BlendMode::Normal,
|
||||
opacity: 100.,
|
||||
});
|
||||
let black_through = |operations: Vec<EffectOperation>| evaluate_color_effects(Item::new_from_element(Color::BLACK).with_attribute(ATTR_EFFECTS, Effects::from_operations(operations)));
|
||||
|
||||
// Black is hidden, whether inverted after the Blend If reads it or not, but shows once inverted before
|
||||
assert_eq!(black_through(vec![blend_if.clone()]).element().a(), 0.);
|
||||
assert_eq!(black_through(vec![blend_if.clone(), invert.clone()]).element().a(), 0.);
|
||||
assert!(close(gamma(*black_through(vec![invert, blend_if.clone()]).element()), [1.; 4]));
|
||||
|
||||
// An overlay after it paints over the hidden color at full strength, as over a fill of none, and the effects are consumed
|
||||
let overlaid = black_through(vec![blend_if.clone(), red]);
|
||||
assert!(close(gamma(*overlaid.element()), [1., 0., 0., 1.]));
|
||||
assert!(overlaid.attribute::<Effects>(ATTR_EFFECTS).is_none());
|
||||
|
||||
// A gradient's dark start is hidden and its light end shown
|
||||
let gradient = Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE])).with_attribute(ATTR_EFFECTS, Effects::from_operations([blend_if]));
|
||||
let evaluated = evaluate_gradient_effects(gradient);
|
||||
let settings = GradientSettings::from_item_attributes(&evaluated);
|
||||
assert!(evaluated.element().evaluate(0., settings).a() < 1e-6);
|
||||
assert!(close(gamma(evaluated.element().evaluate(1., settings)), [1.; 4]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn consumed_values_fade_by_blend_ifs_reading_each_effect_run_as_the_runs_before_it_leave_it() {
|
||||
use graphic_types::blend_if::BlendIfRanges;
|
||||
|
||||
// Shown only where the gray is at least half
|
||||
let mut hides_darks = BlendIfRanges::default();
|
||||
hides_darks.content.gray.falloff_start = 50.;
|
||||
hides_darks.content.gray.range_start = 50.;
|
||||
let blend_if = EffectOperation::BlendIf(Box::new(hides_darks));
|
||||
let overlay = |color: Color| {
|
||||
EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
||||
color,
|
||||
blend_mode: BlendMode::Normal,
|
||||
opacity: 100.,
|
||||
})
|
||||
};
|
||||
|
||||
// White painted blue is read as blue by a Blend If after a scale, which hides it, but in the same run the Blend If reads the white beneath the overlay
|
||||
let color_through = |color: Color, rows: &[(EffectOperation, f64)]| *evaluate_color_effects(stamped(color, rows)).element();
|
||||
assert_eq!(color_through(Color::WHITE, &[(overlay(Color::BLUE), 1.), (blend_if.clone(), 2.)]).a(), 0.);
|
||||
assert!(close(gamma(color_through(Color::WHITE, &[(overlay(Color::BLUE), 1.), (blend_if.clone(), 1.)])), [0., 0., 1., 1.]));
|
||||
|
||||
// Black hidden before a scale leaves nothing for an overlay after it to paint within
|
||||
assert_eq!(color_through(Color::BLACK, &[(blend_if.clone(), 1.), (overlay(Color::RED), 2.)]).a(), 0.);
|
||||
assert!(close(gamma(color_through(Color::BLACK, &[(blend_if.clone(), 1.), (overlay(Color::RED), 1.)])), [1., 0., 0., 1.]));
|
||||
|
||||
// A ramp painted blue is hidden all along by a Blend If after a scale
|
||||
let ramp = stamped(Gradient::from(vec![Color::BLACK, Color::WHITE]), &[(overlay(Color::BLUE), 1.), (blend_if, 2.)]);
|
||||
let evaluated = evaluate_gradient_effects(ramp);
|
||||
let settings = GradientSettings::from_item_attributes(&evaluated);
|
||||
for t in [0., 0.25, 0.75, 1.] {
|
||||
let shown = evaluated.element().evaluate(t, settings);
|
||||
assert!(shown.a() < 1e-6, "hidden at {t}: {:?}", gamma(shown));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn values_a_blend_if_hides_stay_hidden_through_adjustments_raising_alpha_as_rasters_do() {
|
||||
use crate::raster_effects::{evaluate_raster_effects, premultiplied_gamma_channels};
|
||||
use graphic_types::EffectKind;
|
||||
use graphic_types::blend_if::BlendIfRanges;
|
||||
use raster_types::{Image, Raster};
|
||||
|
||||
// Shown only where the gray is at least half
|
||||
let mut hides_darks = BlendIfRanges::default();
|
||||
hides_darks.content.gray.falloff_start = 50.;
|
||||
hides_darks.content.gray.range_start = 50.;
|
||||
let blend_if = EffectOperation::BlendIf(Box::new(hides_darks));
|
||||
let make_opaque = EffectOperation::default_for(EffectKind::MakeOpaque);
|
||||
let red = EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
||||
color: Color::RED,
|
||||
blend_mode: BlendMode::Normal,
|
||||
opacity: 100.,
|
||||
});
|
||||
|
||||
// Black consumed as a color, which agrees with a raster's pixel of it
|
||||
let black_through = |name: &str, rows: &[(EffectOperation, f64)]| {
|
||||
let color = *evaluate_color_effects(stamped(Color::BLACK, rows)).element();
|
||||
let raster = evaluate_raster_effects(stamped(Raster::new_cpu(Image::new(1, 1, Color::BLACK)), rows));
|
||||
let pixel = raster.element().data.first().copied().unwrap_or(Color::TRANSPARENT);
|
||||
let (color_channels, pixel_channels) = (premultiplied_gamma_channels(color), premultiplied_gamma_channels(pixel));
|
||||
assert!(close(color_channels, pixel_channels), "black {name}: {color_channels:?} vs the raster's {pixel_channels:?}");
|
||||
color
|
||||
};
|
||||
|
||||
// Hidden black stays hidden when made opaque, in its run or the next, where an overlay finds nothing to paint within either
|
||||
let hidden = [
|
||||
("made opaque", vec![(blend_if.clone(), 1.), (make_opaque.clone(), 1.)]),
|
||||
("made opaque in the next run", vec![(blend_if.clone(), 1.), (make_opaque.clone(), 2.)]),
|
||||
("made opaque and painted in the next run", vec![(blend_if.clone(), 1.), (make_opaque.clone(), 2.), (red.clone(), 2.)]),
|
||||
];
|
||||
for (name, rows) in hidden {
|
||||
assert_eq!(black_through(name, &rows).a(), 0., "black {name}");
|
||||
}
|
||||
|
||||
// In its own run, an overlay still paints within the full-strength black
|
||||
let painted = black_through("made opaque and painted", &[(blend_if.clone(), 1.), (make_opaque.clone(), 1.), (red, 1.)]);
|
||||
assert!(close(gamma(painted), [1., 0., 0., 1.]), "{:?}", gamma(painted));
|
||||
|
||||
// A ramp made opaque stays hidden where it's dark, in the Blend If's run or the next
|
||||
for scale in [1., 2.] {
|
||||
let ramp = stamped(Gradient::from(vec![Color::BLACK, Color::WHITE]), &[(blend_if.clone(), 1.), (make_opaque.clone(), scale)]);
|
||||
let evaluated = evaluate_gradient_effects(ramp);
|
||||
let settings = GradientSettings::from_item_attributes(&evaluated);
|
||||
for (t, alpha) in [(0., 0.), (0.25, 0.), (0.75, 1.), (1., 1.)] {
|
||||
let shown = evaluated.element().evaluate(t, settings).a();
|
||||
assert!((shown - alpha).abs() < 1e-6, "the alpha at {t} with the scale {scale} is {shown}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ramp_keeps_the_band_a_blend_if_shows_between_where_resampling_probes_it() {
|
||||
use graphic_types::blend_if::{BlendIfRanges, BlendRange};
|
||||
|
||||
// Shown only where the gray lies from 30% to 40%, which neither end of the ramp nor any of its quarter points lands within
|
||||
let mut band = BlendIfRanges::default();
|
||||
band.content.gray = BlendRange {
|
||||
falloff_start: 30.,
|
||||
range_start: 30.,
|
||||
range_end: 40.,
|
||||
falloff_end: 40.,
|
||||
};
|
||||
let effects = Effects::from_operations([EffectOperation::BlendIf(Box::new(band))]);
|
||||
let gamma_settings = GradientSettings {
|
||||
space: GradientSpace::RgbGamma,
|
||||
interpolation: GradientInterpolation::Linear,
|
||||
..Default::default()
|
||||
};
|
||||
let (resampled, settings) = gradient_after_effects(&Gradient::from(vec![Color::BLACK, Color::WHITE]), gamma_settings, &effects).expect("the Blend If fades the ramp");
|
||||
|
||||
// The band shows its own grays from level 77 to 102, which lie from 30% to just past 40% along the ramp, with sharp edges
|
||||
for t in [0.301, 0.35, 0.4] {
|
||||
let shown = resampled.evaluate(t, settings);
|
||||
assert!(close(gamma(shown), [t as f32, t as f32, t as f32, 1.]), "the band shows at {t}: {:?}", gamma(shown));
|
||||
}
|
||||
for t in [0., 0.25, 0.299, 0.403, 0.5, 0.75, 1.] {
|
||||
assert!(resampled.evaluate(t, settings).a() < 1e-6, "hidden at {t}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gradient_without_stops_adjusts_the_black_it_reads_as() {
|
||||
let empty = Gradient::from(Vec::<Color>::new());
|
||||
|
||||
@@ -34,6 +34,7 @@ log = { workspace = true }
|
||||
num-traits = { workspace = true }
|
||||
usvg = { workspace = true }
|
||||
kurbo = { workspace = true }
|
||||
linesweeper = { workspace = true }
|
||||
vector-types = { workspace = true }
|
||||
graphic-types = { workspace = true }
|
||||
raster-kernels = { workspace = true }
|
||||
|
||||
@@ -1,19 +1,23 @@
|
||||
//! What SVG can't express, which the GPU renders as images for an SVG to take, once the SVG is drawn.
|
||||
//! An effect whose coverage SVG filters can't work out, like the shadows and glows shaped for PSD interop, goes in its filter as a map of that coverage, while the content keeps its own markup.
|
||||
//! Content with an effect no filter can carry out at all is drawn as an image of it in place of its markup.
|
||||
//! Content with an effect no filter can carry out, and a backdrop whose copy in markup would nest, are drawn as images in place of markup.
|
||||
//! Placeholders stand in for each until it's resolved, leaving an SVG that never is short of those effects.
|
||||
|
||||
use crate::renderer::{CanvasImage, Render, RenderOutputType, RenderParams, RenderSvgSegmentList, SvgRender, render_raster_cpu_image_svg};
|
||||
use crate::renderer::{CanvasImage, Render, RenderOutputType, RenderParams, RenderSvgSegmentList, SvgRender, format_transform_matrix, render_raster_cpu_image_svg};
|
||||
use crate::vello_scene_builder::{MAX_EFFECTS_AREA_PER_VIEWPORT_AREA, VelloSceneBuilder};
|
||||
use core_types::Color;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::list::List;
|
||||
use core_types::math::quad::Quad;
|
||||
use core_types::transform::Footprint;
|
||||
use glam::{DAffine2, DVec2, UVec2};
|
||||
use graphic_types::Graphic;
|
||||
use graphic_types::effects::EffectCapture;
|
||||
use graphic_types::raster_types::{CPU, Raster};
|
||||
use kurbo::{Affine, BezPath};
|
||||
use std::sync::Arc;
|
||||
use vello_gpu::peniko::Fill;
|
||||
|
||||
/// The most pixels across or down a map or image may have.
|
||||
pub const MAX_DEFERRED_IMAGE_PIXELS: u32 = 8192;
|
||||
@@ -183,13 +187,12 @@ pub fn substitute_effect_map(svg: &mut String, placement: &EffectMapPlacement, m
|
||||
svg.replace_range(span, &image);
|
||||
}
|
||||
|
||||
/// One item of content an SVG draws as an image the GPU renders of it, since its effects hold one SVG filters can't carry out.
|
||||
/// Content an SVG draws as an image the GPU renders of it, since SVG can't carry it out as markup.
|
||||
#[derive(Clone)]
|
||||
pub struct DeferredImage {
|
||||
/// Names the markers around the content's own markup in the SVG, which the image replaces.
|
||||
pub id: u64,
|
||||
/// The item with its effects, but without its opacity and blend mode, which the image takes instead.
|
||||
pub content: Graphic,
|
||||
pub content: DeferredContent,
|
||||
pub render_params: RenderParams,
|
||||
/// Maps the user space the markers sit in into the document.
|
||||
pub user_to_document: DAffine2,
|
||||
@@ -199,6 +202,69 @@ pub struct DeferredImage {
|
||||
pub margin: f64,
|
||||
pub opacity: f32,
|
||||
pub blend_mode: BlendMode,
|
||||
/// The reference for the mask fading the image by Blend If's ranges of what lies beneath, if any.
|
||||
pub mask: Option<String>,
|
||||
}
|
||||
|
||||
/// What the GPU renders an image of for an SVG.
|
||||
#[derive(Clone)]
|
||||
pub enum DeferredContent {
|
||||
/// An item with effects SVG filters can't carry out, but without its opacity and blend mode, which the image takes instead.
|
||||
Item(Graphic),
|
||||
/// What lies beneath content reading its backdrop, drawn in order, for which the markers stand around no markup.
|
||||
/// The outline of the backdrop root's `clip`, a path in the document filled by the nonzero rule, cuts it as it's drawn, as it cuts what a copy of it would hold.
|
||||
Beneath { clip: Option<BezPath>, drawn: Vec<DrawnContent> },
|
||||
}
|
||||
|
||||
/// Content an SVG draws, which the GPU draws again into images of what lies beneath content drawn after it.
|
||||
#[derive(Clone)]
|
||||
pub struct DrawnContent {
|
||||
items: Arc<dyn DrawnItems>,
|
||||
/// How many of the items are drawn, since content drawn among them lies over only those before it.
|
||||
pub(crate) count: usize,
|
||||
/// Maps the user space the items are drawn in into the document.
|
||||
user_to_document: DAffine2,
|
||||
render_params: RenderParams,
|
||||
}
|
||||
|
||||
impl DrawnContent {
|
||||
/// The `items` drawn in a user space that `user_to_document` maps into the document, none of them drawn yet.
|
||||
pub(crate) fn new(items: Arc<dyn DrawnItems>, user_to_document: DAffine2, render_params: &RenderParams) -> Self {
|
||||
Self {
|
||||
items,
|
||||
count: 0,
|
||||
user_to_document,
|
||||
render_params: render_params.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A list of graphical content, or one item of it, whose first items the GPU can draw.
|
||||
pub(crate) trait DrawnItems: Send + Sync {
|
||||
/// Draws the first `count` items into a scene of the document, from the user space that `transform` maps into it.
|
||||
fn draw_first(&self, count: usize, scene: &mut VelloSceneBuilder, transform: DAffine2, render_params: &RenderParams);
|
||||
}
|
||||
|
||||
impl<T: Clone + Send + Sync + 'static> DrawnItems for List<T>
|
||||
where
|
||||
List<T>: Render,
|
||||
{
|
||||
fn draw_first(&self, count: usize, scene: &mut VelloSceneBuilder, transform: DAffine2, render_params: &RenderParams) {
|
||||
if count >= self.len() {
|
||||
return self.render_to_vello(scene, transform, render_params);
|
||||
}
|
||||
|
||||
let first: List<T> = (0..count).filter_map(|index| self.clone_item(index)).collect();
|
||||
first.render_to_vello(scene, transform, render_params);
|
||||
}
|
||||
}
|
||||
|
||||
impl DrawnItems for Graphic {
|
||||
fn draw_first(&self, count: usize, scene: &mut VelloSceneBuilder, transform: DAffine2, render_params: &RenderParams) {
|
||||
if count > 0 {
|
||||
self.render_to_vello(scene, transform, render_params);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How an SVG draws the image the GPU rendered of an item of deferred content.
|
||||
@@ -212,6 +278,7 @@ pub struct DeferredImagePlacement {
|
||||
pub user_to_document: DAffine2,
|
||||
pub opacity: f32,
|
||||
pub blend_mode: BlendMode,
|
||||
pub mask: Option<String>,
|
||||
/// Whether the image is drawn to a canvas rather than embedded in the SVG.
|
||||
pub to_canvas: bool,
|
||||
/// Screen pixels per document unit, which sizes an image drawn to a canvas.
|
||||
@@ -225,9 +292,22 @@ pub struct DeferredImageLayout {
|
||||
pub size: UVec2,
|
||||
}
|
||||
|
||||
/// The starts of the markers around the markup standing in for an item of deferred content, which its ID and `-->` follow.
|
||||
pub(crate) const DEFERRED_IMAGE_OPENING: &str = "<!--deferred-image-";
|
||||
pub(crate) const DEFERRED_IMAGE_CLOSING: &str = "<!--/deferred-image-";
|
||||
|
||||
/// The starts of the markers around a copy of that markup in a Blend If mask, which can't draw the canvas of its image, followed by its ID, a hyphen and the key color's hex (for the opening), and `-->`.
|
||||
pub(crate) const DEFERRED_COVER_OPENING: &str = "<!--deferred-cover-";
|
||||
pub(crate) const DEFERRED_COVER_CLOSING: &str = "<!--/deferred-cover-";
|
||||
|
||||
/// The markers that open and close the markup standing in for the item of deferred content `id` names.
|
||||
pub(crate) fn image_markers(id: u64) -> (String, String) {
|
||||
(format!("<!--deferred-image-{id}-->"), format!("<!--/deferred-image-{id}-->"))
|
||||
(format!("{DEFERRED_IMAGE_OPENING}{id}-->"), format!("{DEFERRED_IMAGE_CLOSING}{id}-->"))
|
||||
}
|
||||
|
||||
/// Whether the `markup` holds markers of markup standing in for an item of deferred content.
|
||||
pub(crate) fn holds_image_markers(markup: &str) -> bool {
|
||||
markup.contains(DEFERRED_IMAGE_OPENING)
|
||||
}
|
||||
|
||||
impl DeferredImage {
|
||||
@@ -242,6 +322,7 @@ impl DeferredImage {
|
||||
user_to_document: self.user_to_document,
|
||||
opacity: self.opacity,
|
||||
blend_mode: self.blend_mode,
|
||||
mask: self.mask.clone(),
|
||||
to_canvas: self.render_params.to_canvas(),
|
||||
canvas_image_scale: self.render_params.canvas_image_scale,
|
||||
},
|
||||
@@ -252,8 +333,25 @@ impl DeferredImage {
|
||||
|
||||
/// Draws the content with its effects into a scene of the document, which the `layout` places in the image's pixels.
|
||||
pub fn draw(&self, scene: &mut VelloSceneBuilder, layout: &DeferredImageLayout) {
|
||||
self.content
|
||||
.render_to_vello(scene, self.user_to_document, &image_render_params(&self.render_params, layout.document_to_pixels, layout.size));
|
||||
let image_params = |render_params: &RenderParams| image_render_params(render_params, layout.document_to_pixels, layout.size);
|
||||
|
||||
match &self.content {
|
||||
DeferredContent::Item(content) => content.render_to_vello(scene, self.user_to_document, &image_params(&self.render_params)),
|
||||
DeferredContent::Beneath { clip, drawn } => {
|
||||
// A clip rather than a layer, within which content reading what lies beneath it would find nothing
|
||||
if let Some(clip) = clip {
|
||||
scene.push_clip_layer(Fill::NonZero, Affine::IDENTITY, clip);
|
||||
}
|
||||
|
||||
for drawn in drawn {
|
||||
drawn.items.draw_first(drawn.count, scene, drawn.user_to_document, &image_params(&drawn.render_params));
|
||||
}
|
||||
|
||||
if clip.is_some() {
|
||||
scene.pop_layer();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -272,11 +370,41 @@ pub fn substitute_deferred_image(svg: &mut String, image_data: &mut Vec<(u64, Ca
|
||||
canvas_image_scale: placement.canvas_image_scale,
|
||||
..Default::default()
|
||||
};
|
||||
render_raster_cpu_image_svg(image, placement.transform, placement.opacity, placement.blend_mode, &mut render, &render_params);
|
||||
let opacity = if placement.opacity < 1. { format!(r#" opacity="{}""#, placement.opacity) } else { String::new() };
|
||||
let style = if placement.blend_mode != BlendMode::Normal {
|
||||
format!(r#" style="{}""#, placement.blend_mode.render())
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
|
||||
let markup = render.svg.to_svg_string();
|
||||
// A mask goes on a group taking the image's opacity and blend mode, which still blends with what lies beneath
|
||||
let markup = match &placement.mask {
|
||||
Some(mask) => {
|
||||
render_raster_cpu_image_svg(image, placement.transform, 1., BlendMode::Normal, &mut render, &render_params);
|
||||
format!(r#"<g mask="{mask}"{opacity}{style}>{}</g>"#, render.svg.to_svg_string())
|
||||
}
|
||||
None => {
|
||||
render_raster_cpu_image_svg(image, placement.transform, placement.opacity, placement.blend_mode, &mut render, &render_params);
|
||||
render.svg.to_svg_string()
|
||||
}
|
||||
};
|
||||
while let Some(span) = marked_span(svg, &opening, &closing) {
|
||||
svg.replace_range(span, &markup);
|
||||
}
|
||||
image_data.extend(render.image_data);
|
||||
|
||||
// A Blend If mask can't draw the canvas in its copy of what lies beneath, so a rectangle of the color its ranges show in full covers the image there
|
||||
if placement.to_canvas {
|
||||
let (opening, closing) = (format!("{DEFERRED_COVER_OPENING}{}-", placement.id), format!("{DEFERRED_COVER_CLOSING}{}-->", placement.id));
|
||||
let transform = format_transform_matrix(placement.transform);
|
||||
while let Some(start) = svg.find(&opening) {
|
||||
let key_start = start + opening.len();
|
||||
let Some(key_end) = svg[key_start..].find("-->").map(|offset| key_start + offset) else { break };
|
||||
let Some(end) = svg[key_end..].find(&closing).map(|offset| key_end + offset + closing.len()) else {
|
||||
break;
|
||||
};
|
||||
let cover = format!(r##"<rect width="1" height="1" transform="{transform}" fill="#{}"{opacity}{style} />"##, &svg[key_start..key_end]);
|
||||
svg.replace_range(start..end, &cover);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,8 @@ pub mod convert_usvg_path;
|
||||
pub mod deferred_image;
|
||||
pub mod render_ext;
|
||||
mod renderer;
|
||||
mod svg_backdrop;
|
||||
mod svg_blend_if;
|
||||
pub mod to_peniko;
|
||||
pub mod vello_scene_builder;
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -8,7 +8,7 @@ use core_types::list::{ATTR_APPEARANCE, ATTR_EFFECTS, Item, List};
|
||||
use core_types::uuid::generate_uuid;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::effects::{EffectOperation, Effects, spans_along_axes};
|
||||
use graphic_types::masks::{MaskMode, mask_density_line, mask_feather_sigma, masked_radius_blur_weight};
|
||||
use graphic_types::masks::{MASK_LUMINANCE_WEIGHTS, MaskMode, mask_density_line, mask_feather_sigma, masked_radius_blur_weight};
|
||||
use graphic_types::{Appearance, Graphic};
|
||||
use raster_kernels::effect_kernels::NEGLIGIBLE_LENGTH;
|
||||
use std::fmt::Write;
|
||||
@@ -98,7 +98,7 @@ pub(super) fn placed(mask: &Graphic, placement: DAffine2) -> Graphic {
|
||||
|
||||
/// Writes into `svg_defs` the masks for the effects in each of the `ranges`, given the markup of the graphics the effects draw with in order, and the content's `bounds` in the user space, which is the effects' own.
|
||||
/// Returns the reference to each range's mask, which shows the content as much as all its masks together do.
|
||||
pub(super) fn write_native_masks(svg_defs: &mut String, effects: &Effects, ranges: [Range<usize>; 2], paints: &[String], bounds: [DVec2; 2]) -> [Option<String>; 2] {
|
||||
pub(super) fn write_native_masks<const N: usize>(svg_defs: &mut String, effects: &Effects, ranges: [Range<usize>; N], paints: &[String], bounds: [DVec2; 2]) -> [Option<String>; N] {
|
||||
let length_scale = DVec2::ONE;
|
||||
let region = svg_effects_region(effects, bounds, length_scale);
|
||||
|
||||
@@ -308,15 +308,19 @@ impl SvgFilterPrimitives {
|
||||
|
||||
/// The `mode`'s coverage of a mask graphic's `image`, in the alpha of the result, matching the GPU's `mask_coverage`.
|
||||
pub(super) fn mask_coverage(&mut self, image: &str, mode: MaskMode) -> String {
|
||||
match mode {
|
||||
// Over black, the luminance of the opaque result is that of the premultiplied channels
|
||||
let luminance = match mode {
|
||||
MaskMode::Luminance => {
|
||||
let black = self.push("feFlood", r#"flood-color="black""#, "");
|
||||
let opaque = self.push("feComposite", &format!(r#"in="{image}" in2="{black}" operator="over""#), "");
|
||||
self.push("feColorMatrix", &format!(r#"in="{opaque}" type="luminanceToAlpha""#), "")
|
||||
let [red, green, blue] = MASK_LUMINANCE_WEIGHTS;
|
||||
format!(r#"type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 {red} {green} {blue} 0 0""#)
|
||||
}
|
||||
MaskMode::Alpha => image.to_string(),
|
||||
}
|
||||
MaskMode::LuminanceSvg => r#"type="luminanceToAlpha""#.to_string(),
|
||||
MaskMode::Alpha => return image.to_string(),
|
||||
};
|
||||
|
||||
// Over black, the luminance of the opaque result is that of the premultiplied channels
|
||||
let black = self.push("feFlood", r#"flood-color="black""#, "");
|
||||
let opaque = self.push("feComposite", &format!(r#"in="{image}" in2="{black}" operator="over""#), "");
|
||||
self.push("feColorMatrix", &format!(r#"in="{opaque}" {luminance}"#), "")
|
||||
}
|
||||
|
||||
/// How much the mask graphic's `image` shows the content, in the alpha of the result, matching the GPU's mask passes.
|
||||
|
||||
@@ -0,0 +1,436 @@
|
||||
//! What lies beneath content in an SVG, which filters can't read, copied for content that reads it, like a background blur.
|
||||
//! Per the W3C's Backdrop Root, the backdrop is everything drawn before the content since the innermost group that isolates it, or since the start of the render.
|
||||
|
||||
use crate::deferred_image::{self, DeferredContent, DeferredImage, DrawnContent, DrawnItems};
|
||||
use crate::renderer::{RenderParams, SvgRender, SvgSegment, format_transform_matrix};
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::math::quad::Quad;
|
||||
use core_types::uuid::generate_uuid;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::effects::spans_along_axes;
|
||||
use graphic_types::{EffectOperation, Effects};
|
||||
use kurbo::{BezPath, PathEl, Shape};
|
||||
use linesweeper::topology::Topology;
|
||||
use raster_kernels::effect_kernels::NEGLIGIBLE_LENGTH;
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::Write;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// A group an SVG render has open, where the content drawn so far lies beneath what's drawn next inside it.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct OpenGroup {
|
||||
/// Where the group's opening tag starts among the render's segments.
|
||||
pub tag_start: usize,
|
||||
/// Where the group's content starts among the render's segments.
|
||||
pub content_start: usize,
|
||||
/// Whether the group isolates what's drawn inside it from what lies beneath it, as opacity, a filter, a mask, a clip path, or a blend mode does.
|
||||
pub isolates: bool,
|
||||
/// The group's `clip-path` attribute, which a copy of its content takes too.
|
||||
pub clip_path: Option<String>,
|
||||
/// Maps the user space of the group's content into the document, once its content begins.
|
||||
pub user_to_document: Option<DAffine2>,
|
||||
/// Whether a copy of what lies beneath, or an image of it, is drawn inside the group so far.
|
||||
pub holds_backdrop: bool,
|
||||
/// The content drawn directly inside the group so far, for the GPU to draw again in an image of what lies beneath content drawn after it.
|
||||
pub drawn: Vec<DrawnContent>,
|
||||
}
|
||||
|
||||
impl OpenGroup {
|
||||
pub fn new(tag_start: usize, content_start: usize, isolates: bool, clip_path: Option<String>) -> Self {
|
||||
Self {
|
||||
tag_start,
|
||||
content_start,
|
||||
isolates,
|
||||
clip_path,
|
||||
user_to_document: None,
|
||||
holds_backdrop: false,
|
||||
drawn: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The groups an SVG render has open, from the render's own start inward to the innermost.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct OpenGroups {
|
||||
pub groups: Vec<OpenGroup>,
|
||||
/// Whether the attributes of the tag being opened isolate its content.
|
||||
pub opening_isolates: bool,
|
||||
/// The `clip-path` attribute of the tag being opened.
|
||||
pub opening_clip_path: Option<String>,
|
||||
/// Whether the render draws a clipping base's clip.
|
||||
pub clip: bool,
|
||||
/// The shapes of the clip paths in the render's defs, paths in the document each filled by the nonzero rule, by the `clip-path` attribute referencing each.
|
||||
/// Images of what lies beneath inside one are cut to the union of its shapes.
|
||||
pub clip_shapes: HashMap<String, Vec<BezPath>>,
|
||||
}
|
||||
|
||||
impl Default for OpenGroups {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
groups: vec![OpenGroup::new(0, 0, true, None)],
|
||||
opening_isolates: false,
|
||||
opening_clip_path: None,
|
||||
clip: false,
|
||||
clip_shapes: HashMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether an attribute makes the element carrying it an isolated group, which the content inside it blends within.
|
||||
pub(crate) fn isolates(name: &str, value: &str) -> bool {
|
||||
match name {
|
||||
"opacity" | "filter" | "mask" | "clip-path" => true,
|
||||
"style" => value.contains("mix-blend-mode") || value.contains("isolation"),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
impl SvgRender {
|
||||
/// Records the `items` drawn next, from the user space `user_to_document` maps into the document, in the innermost open group, returning where for [`Self::drew_items`].
|
||||
/// Nothing is recorded where no image can replace markup, since no image of what lies beneath could.
|
||||
pub(crate) fn record_drawn<T: DrawnItems + 'static>(&mut self, items: impl FnOnce() -> T, user_to_document: DAffine2, render_params: &RenderParams) -> Option<usize> {
|
||||
if !self.images_replace_markup(render_params) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let group = self.open_groups.groups.last_mut()?;
|
||||
group.drawn.push(DrawnContent::new(Arc::new(items()), user_to_document, render_params));
|
||||
Some(group.drawn.len() - 1)
|
||||
}
|
||||
|
||||
/// Notes that the first `count` of the items recorded at `record` are drawn, in place of anything recorded after them while they were drawn.
|
||||
pub(crate) fn drew_items(&mut self, record: Option<usize>, count: usize) {
|
||||
let (Some(record), Some(group)) = (record, self.open_groups.groups.last_mut()) else { return };
|
||||
|
||||
group.drawn.truncate(record + 1);
|
||||
if let Some(drawn) = group.drawn.get_mut(record) {
|
||||
drawn.count = count;
|
||||
}
|
||||
}
|
||||
|
||||
/// Records the `shapes` of the clip path a `clip-path` attribute of the `reference` cuts by (see [`OpenGroups::clip_shapes`]), for images of what lies beneath inside it.
|
||||
pub(crate) fn record_clip_shapes(&mut self, reference: &str, shapes: impl FnOnce() -> Vec<BezPath>, render_params: &RenderParams) {
|
||||
if self.images_replace_markup(render_params) {
|
||||
self.open_groups.clip_shapes.insert(reference.to_string(), shapes());
|
||||
}
|
||||
}
|
||||
|
||||
/// The outline of the clip path a `clip-path` attribute of the `reference` cuts by, its shapes united into one path filled by the nonzero rule,
|
||||
/// or `None` if its shapes aren't recorded or can't be united.
|
||||
fn clip_outline(&mut self, reference: &str) -> Option<BezPath> {
|
||||
let shapes = self.open_groups.clip_shapes.get(reference)?;
|
||||
if let [shape] = shapes.as_slice() {
|
||||
return Some(shape.clone());
|
||||
}
|
||||
|
||||
// United once, the outline is kept in place of the shapes, which are forgotten if they can't be
|
||||
let outline = united_outline(shapes);
|
||||
match &outline {
|
||||
Some(outline) => _ = self.open_groups.clip_shapes.insert(reference.to_string(), vec![outline.clone()]),
|
||||
None => _ = self.open_groups.clip_shapes.remove(reference),
|
||||
}
|
||||
outline
|
||||
}
|
||||
|
||||
/// Markup showing what lies beneath the content drawn next, within the `region` of the current user space it reads, or `None` if nothing does.
|
||||
/// It copies the markup drawn since the backdrop root, or where that holds a copy already, stands for an image the GPU renders of it or else leaves held copies out.
|
||||
/// The image is embedded `for_mask`, which draws no canvas.
|
||||
pub(crate) fn backdrop_copy(&mut self, render_params: &RenderParams, region: [DVec2; 2], read_reach: f64, for_mask: bool) -> Option<BackdropCopy> {
|
||||
if self.drawing_deferred_markup || !self.transform.matrix2.determinant().is_normal() {
|
||||
return None;
|
||||
}
|
||||
let root = self.open_groups.groups.iter().rposition(|group| group.isolates)?;
|
||||
|
||||
// A clip's own stack lies over nothing, as in the GPU's layer for it, though a group isolated within it still reads what it drew
|
||||
if root == 0 && self.open_groups.clip {
|
||||
return None;
|
||||
}
|
||||
|
||||
// The backdrop root's own clip cuts every level's copy as it cuts the originals, from a group around them in the space of its content
|
||||
let root_group = &self.open_groups.groups[root];
|
||||
let holds_backdrop = root_group.holds_backdrop;
|
||||
let clip = root_group.clip_path.clone().zip(root_group.user_to_document);
|
||||
let copies_to_document = clip.as_ref().map_or(self.transform, |(_, root_to_document)| *root_to_document);
|
||||
|
||||
// A mask draws no canvas, so where one stands in for what lies beneath, the GPU's image of it shows what's displayed, as it does for later readers
|
||||
let images = holds_backdrop || (for_mask && self.draws_canvases_since(root, render_params));
|
||||
|
||||
// An image needs the outline of the root's clip, if it has one, to cut what it holds by
|
||||
let image_clip = match images && self.images_replace_markup(render_params) {
|
||||
true => match &clip {
|
||||
Some((reference, _)) => self.clip_outline(reference).map(Some),
|
||||
None => Some(None),
|
||||
},
|
||||
false => None,
|
||||
};
|
||||
|
||||
// Elsewhere, copies leave out the blurred copies earlier content holds, so they never nest, losing only the blur of a blur where it overlaps
|
||||
let image = images && image_clip.is_some();
|
||||
let copies = match (images, image_clip) {
|
||||
(false, _) => self.backdrop_markup_copies(root, copies_to_document, render_params.to_canvas(), false),
|
||||
(true, Some(clip)) => {
|
||||
let image_params = RenderParams {
|
||||
embeds_images: render_params.embeds_images || for_mask,
|
||||
..render_params.clone()
|
||||
};
|
||||
self.backdrop_image(root, copies_to_document, clip, region, read_reach, &image_params)
|
||||
}
|
||||
(true, None) => self.backdrop_markup_copies(root, copies_to_document, true, true),
|
||||
}?;
|
||||
|
||||
// Every open group now holds it
|
||||
for group in &mut self.open_groups.groups {
|
||||
group.holds_backdrop = true;
|
||||
}
|
||||
|
||||
let markup = match clip {
|
||||
Some((clip_path, root_to_document)) => {
|
||||
let matrix = format_transform_matrix(self.transform.inverse() * root_to_document);
|
||||
let transform = if matrix.is_empty() { String::new() } else { format!(r#" transform="{matrix}""#) };
|
||||
format!(r#"<g{transform} clip-path="{clip_path}">{copies}</g>"#)
|
||||
}
|
||||
None => copies,
|
||||
};
|
||||
Some(BackdropCopy { markup, image })
|
||||
}
|
||||
|
||||
/// Whether the markup drawn since the backdrop `root` draws through canvases, as images and the GPU's images of content do in the viewport. O(segments drawn since the root).
|
||||
fn draws_canvases_since(&self, root: usize, render_params: &RenderParams) -> bool {
|
||||
let start = self.open_groups.groups[root].content_start;
|
||||
let draws_canvas = |segment: &SvgSegment| segment.as_str().contains("data-canvas-placeholder") || deferred_image::holds_image_markers(segment.as_str());
|
||||
render_params.to_canvas() && self.svg[start..].iter().any(draws_canvas)
|
||||
}
|
||||
|
||||
/// Copies of the content drawn at each level of the groups open since the backdrop `root`, in the space `copies_to_document` maps into the document, or `None` if there's none.
|
||||
/// Each is wrapped in a group with an ID for `<use>` copies, or with `repeats_markup`, copied as markup, keeping the viewport's canvases,
|
||||
/// and without the markup showing what lies beneath earlier content if `leaves_out_backdrops`. O(segments drawn since the root).
|
||||
fn backdrop_markup_copies(&mut self, root: usize, copies_to_document: DAffine2, repeats_markup: bool, leaves_out_backdrops: bool) -> Option<String> {
|
||||
let current = self.open_groups.groups.len() - 1;
|
||||
let kept = |segment: &&SvgSegment| !(leaves_out_backdrops && matches!(segment, SvgSegment::Backdrop(_)));
|
||||
|
||||
// From the innermost level out, so wrapping one level's content leaves the outer levels' positions as they are
|
||||
let mut copies = Vec::new();
|
||||
for level in (root..=current).rev() {
|
||||
let group = &self.open_groups.groups[level];
|
||||
let start = group.content_start;
|
||||
let end = self.open_groups.groups.get(level + 1).map_or(self.svg.len(), |inner| inner.tag_start);
|
||||
let drawn = self.svg[start..end].iter().filter(kept).any(|segment| segment.as_str().contains('<'));
|
||||
let Some(user_to_document) = group.user_to_document.filter(|_| drawn) else { continue };
|
||||
|
||||
let matrix = format_transform_matrix(copies_to_document.inverse() * user_to_document);
|
||||
let attributes = if matrix.is_empty() { String::new() } else { format!(r#" transform="{matrix}""#) };
|
||||
|
||||
if repeats_markup {
|
||||
let markup: String = self.svg[start..end].iter().filter(kept).map(SvgSegment::as_str).collect();
|
||||
copies.push(format!("<g{attributes}>{markup}</g>"));
|
||||
continue;
|
||||
}
|
||||
|
||||
let id = format!("backdrop-{}", generate_uuid());
|
||||
self.svg.insert(end, "</g>".into());
|
||||
self.svg.insert(start, format!(r#"<g id="{id}">"#).into());
|
||||
for inner in &mut self.open_groups.groups[level + 1..] {
|
||||
inner.tag_start += 2;
|
||||
inner.content_start += 2;
|
||||
}
|
||||
copies.push(format!(r##"<use href="#{id}"{attributes} />"##));
|
||||
}
|
||||
if copies.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
copies.reverse();
|
||||
Some(copies.concat())
|
||||
}
|
||||
|
||||
/// The markers standing for an image the GPU renders of the content drawn since the backdrop `root`, cut by the outline of its `clip`, placed in the space `copies_to_document` maps into the document,
|
||||
/// or `None` if there's none. It covers the `region` of the current user space and how far past the view the reading reaches, `read_reach` in the document.
|
||||
fn backdrop_image(&mut self, root: usize, copies_to_document: DAffine2, clip: Option<BezPath>, region: [DVec2; 2], read_reach: f64, render_params: &RenderParams) -> Option<String> {
|
||||
let drawn: Vec<DrawnContent> = self.open_groups.groups[root..].iter().flat_map(|group| &group.drawn).filter(|drawn| drawn.count > 0).cloned().collect();
|
||||
if drawn.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let id = generate_uuid();
|
||||
let bounds = (copies_to_document.inverse() * self.transform * Quad::from_box(region)).bounding_box();
|
||||
self.deferred_images.push(DeferredImage {
|
||||
id,
|
||||
content: DeferredContent::Beneath { clip, drawn },
|
||||
render_params: render_params.clone(),
|
||||
user_to_document: copies_to_document,
|
||||
bounds,
|
||||
margin: self.ancestors_reach + read_reach,
|
||||
opacity: 1.,
|
||||
blend_mode: BlendMode::Normal,
|
||||
mask: None,
|
||||
});
|
||||
|
||||
let (opening, closing) = deferred_image::image_markers(id);
|
||||
Some(format!("{opening}{closing}"))
|
||||
}
|
||||
}
|
||||
|
||||
/// Markup showing what lies beneath content (see [`SvgRender::backdrop_copy`]).
|
||||
pub(crate) struct BackdropCopy {
|
||||
pub markup: String,
|
||||
/// Whether the markup stands for an image the GPU renders of what lies beneath, rather than copying what's drawn.
|
||||
pub image: bool,
|
||||
}
|
||||
|
||||
/// The outline of the union of the `shapes`, each filled by the nonzero rule, as one path filled by that rule, or `None` if their coordinates aren't finite or a sweep fails.
|
||||
/// Each shape's winding is resolved alone first, so the final sweep counts one winding rather than one per shape at every edge.
|
||||
fn united_outline(shapes: &[BezPath]) -> Option<BezPath> {
|
||||
const EPSILON: f64 = 1e-5;
|
||||
|
||||
// A fill closes each subpath, which the sweep takes only explicitly
|
||||
let closed: Vec<BezPath> = shapes.iter().map(closed_subpaths).collect();
|
||||
if !closed.iter().all(BezPath::is_finite) {
|
||||
return None;
|
||||
}
|
||||
let Some(bounds) = closed.iter().map(Shape::bounding_box).reduce(|first, second| first.union(second)) else {
|
||||
return Some(BezPath::new());
|
||||
};
|
||||
|
||||
// Far from the origin, the tolerance grows with the coordinates' magnitude, since the sweep can't resolve less
|
||||
let magnitude = bounds.min_x().min(bounds.min_y()).abs().max(bounds.max_x().max(bounds.max_y()).abs());
|
||||
let epsilon = EPSILON.max(magnitude * f64::EPSILON * 64.);
|
||||
|
||||
// Each shape alone is outlined first by what it fills, wound once around, so no shape's winding can cancel another's where they then unite
|
||||
let mut outlines = BezPath::new();
|
||||
for shape in &closed {
|
||||
outlines.extend(swept_outline(shape, epsilon, |&winding| winding != 0)?);
|
||||
}
|
||||
swept_outline(&outlines, epsilon, |&winding| winding > 0)
|
||||
}
|
||||
|
||||
/// The outline of where the `inside` test accepts the winding number of the closed `path`, wound once around what it holds, or `None` if the sweep fails.
|
||||
fn swept_outline(path: &BezPath, epsilon: f64, inside: impl Fn(&i32) -> bool) -> Option<BezPath> {
|
||||
let topology = Topology::<i32>::from_path(path, epsilon).ok()?;
|
||||
Some(topology.contours(inside).contours().flat_map(|contour| contour.path.elements().iter().copied()).collect())
|
||||
}
|
||||
|
||||
/// The `shape` with each of its subpaths closed, as a fill closes them.
|
||||
pub(crate) fn closed_subpaths(shape: &BezPath) -> BezPath {
|
||||
let mut closed = BezPath::new();
|
||||
for &element in shape.elements() {
|
||||
if matches!(element, PathEl::MoveTo(_)) && !matches!(closed.elements().last(), None | Some(PathEl::ClosePath)) {
|
||||
closed.close_path();
|
||||
}
|
||||
closed.push(element);
|
||||
}
|
||||
if !matches!(closed.elements().last(), None | Some(PathEl::ClosePath)) {
|
||||
closed.close_path();
|
||||
}
|
||||
closed
|
||||
}
|
||||
|
||||
/// What lies beneath content with background blurs, in SVG.
|
||||
pub(crate) struct SvgBackdrop {
|
||||
/// Each copy of what lies beneath, blurred by one background blur, stacked in order within a group the mask cuts to the content.
|
||||
pub markup: String,
|
||||
/// The opening tag of the mask cutting it to the content's silhouette, which the content's own markup goes in once it's drawn.
|
||||
pub mask_tag: String,
|
||||
/// The content's extent, which cuts it instead where the content draws through canvases, since a mask draws no `<foreignObject>`.
|
||||
pub content_bounds: [DVec2; 2],
|
||||
}
|
||||
|
||||
/// What lies beneath content with background blurs, or `None` with nothing beneath it, given the content's `bounds` in the effects' `space`.
|
||||
/// That space is placed in the current user space, or is the user space itself for `None`, and the markup lies in it.
|
||||
/// The filters go in the render's defs (see [`SvgRender::backdrop_copy`] for what they blur).
|
||||
/// A length in that space spans `pixels_per_length` screen pixels, across which a blur too slight to show is left out.
|
||||
pub(crate) fn backdrop_markup(render: &mut SvgRender, effects: &Effects, bounds: [DVec2; 2], space: Option<DAffine2>, pixels_per_length: f64, render_params: &RenderParams) -> Option<SvgBackdrop> {
|
||||
let blurs: Vec<(f64, bool, bool)> = (effects.operations())
|
||||
.filter(|operation| !operation.changes_nothing())
|
||||
.filter_map(|operation| match operation {
|
||||
EffectOperation::BackgroundBlur { radius, box_blur, gamma } => Some((radius, box_blur, gamma)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
if blurs.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
// SVG has no box blur, so a box becomes the Gaussian of the same variance, which reads past the box's own reach
|
||||
let sigma = |radius: f64, box_blur: bool| if box_blur { (radius * (radius + 1.) / 3.).sqrt() } else { radius };
|
||||
let box_overreach: f64 = blurs
|
||||
.iter()
|
||||
.filter(|(_, box_blur, _)| *box_blur)
|
||||
.map(|&(radius, ..)| (3. * sigma(radius, true) - radius - 1.).max(0.))
|
||||
.sum();
|
||||
|
||||
// The blurs read as far past the content as the effects reach
|
||||
let reach = effects.reach() + box_overreach;
|
||||
let (min, max) = (bounds[0] - reach, bounds[1] + reach);
|
||||
let region = format!(r#"x="{}" y="{}" width="{}" height="{}""#, min.x, min.y, max.x - min.x, max.y - min.y);
|
||||
|
||||
let space_to_user = space.unwrap_or_default();
|
||||
let read_region = (space_to_user * Quad::from_box([min, max])).bounding_box();
|
||||
let read_reach = reach * spans_along_axes((render.transform * space_to_user).matrix2).max_element();
|
||||
let copy = render.backdrop_copy(render_params, read_region, read_reach, false)?.markup;
|
||||
let copy = match space.map(|space| format_transform_matrix(space.inverse())) {
|
||||
Some(matrix) if !matrix.is_empty() => format!(r#"<g transform="{matrix}">{copy}</g>"#),
|
||||
_ => copy,
|
||||
};
|
||||
|
||||
let mut blurred = String::new();
|
||||
for (radius, box_blur, gamma) in blurs {
|
||||
if radius * pixels_per_length.max(1.) < NEGLIGIBLE_LENGTH {
|
||||
blurred.push_str(©);
|
||||
continue;
|
||||
}
|
||||
|
||||
let sigma = sigma(radius, box_blur);
|
||||
let space = if gamma { "sRGB" } else { "linearRGB" };
|
||||
let filter_id = format!("background-blur-{}", generate_uuid());
|
||||
write!(
|
||||
render.svg_defs,
|
||||
r#"<filter id="{filter_id}" filterUnits="userSpaceOnUse" {region}><feGaussianBlur stdDeviation="{sigma}" color-interpolation-filters="{space}" /></filter>"#
|
||||
)
|
||||
.unwrap();
|
||||
write!(blurred, r#"<g filter="url(#{filter_id})">{copy}</g>"#).unwrap();
|
||||
}
|
||||
|
||||
let mask_id = format!("backdrop-mask-{}", generate_uuid());
|
||||
Some(SvgBackdrop {
|
||||
markup: format!(r#"<g mask="url(#{mask_id})">{blurred}</g>"#),
|
||||
mask_tag: format!(r#"<mask id="{mask_id}" mask-type="alpha" maskUnits="userSpaceOnUse" {region}>"#),
|
||||
content_bounds: bounds,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn clip_shapes_with_coordinates_past_finite_ones_unite_into_no_outline() {
|
||||
let square = kurbo::Rect::new(0., 0., 10., 10.).to_path(0.1);
|
||||
let mut broken = BezPath::new();
|
||||
broken.move_to((0., 0.));
|
||||
broken.line_to((f64::NAN, 5.));
|
||||
broken.line_to((5., f64::INFINITY));
|
||||
|
||||
// Images inside such a clip path give way to copies leaving held ones out, rather than drawing an outline that's wrong
|
||||
assert!(united_outline(&[square.clone(), broken]).is_none());
|
||||
assert!(united_outline(&[square.clone(), square]).is_some_and(|outline| (outline.area().abs() - 100.).abs() < 1e-6));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thousands_of_overlapping_clip_shapes_wound_either_way_unite_quickly_into_what_they_cover() {
|
||||
// A 100 by 50 grid of squares a unit and a half wide, a unit apart so neighbors overlap, every other one wound the other way
|
||||
let squares: Vec<BezPath> = (0..5_000)
|
||||
.map(|index| {
|
||||
let corner = kurbo::Point::new((index % 100) as f64, (index / 100) as f64);
|
||||
let square = kurbo::Rect::from_origin_size(corner, (1.5, 1.5)).to_path(0.1);
|
||||
if index % 2 == 0 { square } else { square.reverse_subpaths() }
|
||||
})
|
||||
.collect();
|
||||
|
||||
// They unite into the rectangle they cover, none cancelling a neighbor wound against it
|
||||
let start = std::time::Instant::now();
|
||||
let outline = united_outline(&squares).expect("the squares unite");
|
||||
let elapsed = start.elapsed();
|
||||
assert!((outline.area().abs() - 100.5 * 50.5).abs() < 1e-6, "the union spans {}", outline.area().abs());
|
||||
assert!(elapsed < std::time::Duration::from_secs(10), "uniting took {elapsed:?}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
//! Blend If in SVG, all native: filter primitives weigh each pixel by its channels' levels through tables of the ranges' weights, fading the content within its effects filter,
|
||||
//! and a mask holding a copy of what lies beneath, filtered into its weights, fades every layer the content draws.
|
||||
|
||||
use crate::deferred_image::{DEFERRED_COVER_CLOSING, DEFERRED_COVER_OPENING, DEFERRED_IMAGE_CLOSING, DEFERRED_IMAGE_OPENING};
|
||||
use crate::renderer::{RenderParams, SvgRender};
|
||||
use core_types::uuid::generate_uuid;
|
||||
use glam::DVec2;
|
||||
use graphic_types::BlendIfChannel;
|
||||
use graphic_types::blend_if::{BlendRange, ChannelRanges, GRAY_PERCENTAGES};
|
||||
use graphic_types::effects::spans_along_axes;
|
||||
use std::fmt::Write;
|
||||
|
||||
/// Pushes the primitives weighing how strongly the `ranges` show each pixel of the `image` result by its straight color, given `push` (a primitive's tag, attributes, and children, returning its result's name).
|
||||
/// Returns the name of the result holding the weight in its alpha, or `None` if the ranges show everything.
|
||||
pub(crate) fn weight(push: &mut impl FnMut(&str, &str, &str) -> String, image: &str, ranges: &ChannelRanges) -> Option<String> {
|
||||
let mut weight: Option<String> = None;
|
||||
|
||||
for (channel, range) in ranges.limiting() {
|
||||
// A gray exactly between two levels gains a sliver of a level, so it rounds up as `gray_level` rounds it
|
||||
let [red, green, blue] = GRAY_PERCENTAGES.map(|percentage| percentage as f64 / 100.);
|
||||
let alpha_row = match channel {
|
||||
BlendIfChannel::Gray => format!("{red} {green} {blue} 0 {}", 0.005 / 255.),
|
||||
BlendIfChannel::Red => "1 0 0 0 0".to_string(),
|
||||
BlendIfChannel::Green => "0 1 0 0 0".to_string(),
|
||||
BlendIfChannel::Blue => "0 0 1 0 0".to_string(),
|
||||
};
|
||||
|
||||
// The channel's level moved into alpha, then looked up in the table of the range's weight at each level, which the browser's 8-bit filters index exactly
|
||||
let level = push(
|
||||
"feColorMatrix",
|
||||
&format!(r#"in="{image}" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 {alpha_row}" color-interpolation-filters="sRGB""#),
|
||||
"",
|
||||
);
|
||||
let table: Vec<String> = range.level_weights().iter().map(|weight| format_table_value(*weight)).collect();
|
||||
let shown = push(
|
||||
"feComponentTransfer",
|
||||
&format!(r#"in="{level}" color-interpolation-filters="sRGB""#),
|
||||
&format!(r#"<feFuncA type="table" tableValues="{}" />"#, table.join(" ")),
|
||||
);
|
||||
|
||||
weight = Some(match weight {
|
||||
Some(previous) => push("feComposite", &format!(r#"in="{shown}" in2="{previous}" operator="in""#), ""),
|
||||
None => shown,
|
||||
});
|
||||
}
|
||||
|
||||
weight
|
||||
}
|
||||
|
||||
/// The viewport's copy of what lies beneath as `markup`, with what a mask can't draw, so SVG can't read, covered by rectangles of the `key` color the ranges show in full.
|
||||
/// What's drawn over a cover still hides it, as it hides the image the cover stands in for.
|
||||
fn with_unreadable_covered(markup: &str, key: &str) -> String {
|
||||
with_canvases_covered(&with_deferred_images_marked_for_covers(markup, key), key)
|
||||
}
|
||||
|
||||
/// The `markup` with the canvases standing in for images covered with the `key` color, at their own placement, size, opacity, and blend mode, so a translucent image hides less of what lies beneath it.
|
||||
fn with_canvases_covered(markup: &str, key: &str) -> String {
|
||||
const OPENING: &str = "<foreignObject";
|
||||
const CLOSING: &str = "</foreignObject>";
|
||||
|
||||
let mut covered = String::with_capacity(markup.len());
|
||||
let mut rest = markup;
|
||||
while let Some(start) = rest.find(OPENING) {
|
||||
let Some(end) = rest[start..].find(CLOSING).map(|offset| start + offset + CLOSING.len()) else {
|
||||
break;
|
||||
};
|
||||
covered.push_str(&rest[..start]);
|
||||
|
||||
// A canvas's cover takes its opening tag's attributes
|
||||
let element = &rest[start..end];
|
||||
match (element.contains("data-canvas-placeholder"), element.find('>')) {
|
||||
(true, Some(tag_end)) => write!(covered, r#"<rect{} fill="{key}" />"#, &element[OPENING.len()..tag_end]).unwrap(),
|
||||
(true, None) => {}
|
||||
(false, _) => covered.push_str(element),
|
||||
}
|
||||
rest = &rest[end..];
|
||||
}
|
||||
covered.push_str(rest);
|
||||
covered
|
||||
}
|
||||
|
||||
/// The `markup` with the markup standing in for each image the GPU renders marked for a rectangle of the `key` color to cover once the image arrives (see [`crate::deferred_image::substitute_deferred_image`]).
|
||||
/// Without a GPU the markup is what's drawn, which the mask reads as it is.
|
||||
fn with_deferred_images_marked_for_covers(markup: &str, key: &str) -> String {
|
||||
let markup = markup.replace(DEFERRED_IMAGE_CLOSING, DEFERRED_COVER_CLOSING);
|
||||
let mut parts = markup.split(DEFERRED_IMAGE_OPENING);
|
||||
let mut marked = parts.next().unwrap_or_default().to_string();
|
||||
for part in parts {
|
||||
// Each opening marker's ID is followed by the end of the comment, before which the key goes
|
||||
match part.split_once("-->") {
|
||||
Some((id, rest)) => write!(marked, "{DEFERRED_COVER_OPENING}{id}-{}-->{rest}", key.trim_start_matches('#')).unwrap(),
|
||||
None => write!(marked, "{DEFERRED_IMAGE_OPENING}{part}").unwrap(),
|
||||
}
|
||||
}
|
||||
marked
|
||||
}
|
||||
|
||||
/// A color the `underlying` ranges, which multiply, show most strongly (in full if any color is shown in full), as a hex color.
|
||||
/// Each channel shows its levels in full in one span, and the gray rises with each channel, so the colors from every channel's lowest such level to every one's highest pass through each gray between them.
|
||||
fn key_color(underlying: &[ChannelRanges]) -> String {
|
||||
// The span of levels each channel shows most strongly, by itself
|
||||
let span = |range: fn(&ChannelRanges) -> &BlendRange| {
|
||||
let shown = |level: usize| underlying.iter().map(|ranges| range(ranges).weight(level as f64 / 255.)).product::<f64>();
|
||||
let most = (0..256).map(shown).fold(0., f64::max);
|
||||
let levels: Vec<usize> = (0..256).filter(|&level| shown(level) >= most).collect();
|
||||
[levels.first().copied().unwrap_or(0), levels.last().copied().unwrap_or(255)].map(|level| level as f64)
|
||||
};
|
||||
let spans = [span(|ranges| &ranges.red), span(|ranges| &ranges.green), span(|ranges| &ranges.blue)];
|
||||
|
||||
// O(256 × ranges): the colors along the way from the lowest ends to the highest, which the gray's ranges show most strongly somewhere
|
||||
let weight = |color: [f64; 3]| underlying.iter().map(|ranges| ranges.weight(color)).product::<f64>();
|
||||
let color_at = |step: usize| spans.map(|[low, high]| (low + (high - low) * step as f64 / 255.).round() / 255.);
|
||||
let best = (0..256).map(color_at).fold(color_at(0), |best, color| if weight(color) > weight(best) { color } else { best });
|
||||
let [red, green, blue] = best.map(|channel| (channel * 255.).round() as u8);
|
||||
format!("#{red:02x}{green:02x}{blue:02x}")
|
||||
}
|
||||
|
||||
/// A weight for a table, with no more digits than it needs.
|
||||
fn format_table_value(weight: f64) -> String {
|
||||
let rounded = format!("{weight:.4}");
|
||||
rounded.trim_end_matches('0').trim_end_matches('.').to_string()
|
||||
}
|
||||
|
||||
/// Writes a mask into the render's defs that fades what's drawn in the current user space by how strongly the `underlying` ranges, which multiply, show what lies beneath, returning its reference, or `None` with nothing beneath to read.
|
||||
/// `bounds` is the content's extent in this user space and `reach` how far its effects reach past it along each axis there.
|
||||
pub(crate) fn underlying_mask(render: &mut SvgRender, underlying: &[ChannelRanges], bounds: [DVec2; 2], reach: DVec2, render_params: &RenderParams) -> Option<String> {
|
||||
let mut markup = String::new();
|
||||
let mut count = 0;
|
||||
let mut push = |tag: &str, attributes: &str, children: &str| {
|
||||
count += 1;
|
||||
let result = format!("blend-if-{count}");
|
||||
match children.is_empty() {
|
||||
true => write!(markup, r#"<{tag} {attributes} result="{result}" />"#),
|
||||
false => write!(markup, r#"<{tag} {attributes} result="{result}">{children}</{tag}>"#),
|
||||
}
|
||||
.unwrap();
|
||||
result
|
||||
};
|
||||
|
||||
// Each side's channels multiply, and so do the sides
|
||||
let mut weight: Option<String> = None;
|
||||
for ranges in underlying {
|
||||
let Some(shown) = self::weight(&mut push, "SourceGraphic", ranges) else { continue };
|
||||
weight = Some(match weight {
|
||||
Some(previous) => push("feComposite", &format!(r#"in="{shown}" in2="{previous}" operator="in""#), ""),
|
||||
None => shown,
|
||||
});
|
||||
}
|
||||
let weight = weight?;
|
||||
|
||||
// Where nothing lies beneath, nothing is hidden: the weight is 1 - alpha × (1 - weight)
|
||||
let invert = r#"<feFuncA type="linear" slope="-1" intercept="1" />"#;
|
||||
let hidden = push("feComponentTransfer", &format!(r#"in="{weight}""#), invert);
|
||||
let hidden_beneath = push("feComposite", &format!(r#"in="{hidden}" in2="SourceAlpha" operator="in""#), "");
|
||||
push("feComponentTransfer", &format!(r#"in="{hidden_beneath}""#), invert);
|
||||
|
||||
// The mask covers how far the effects reach past the content, and a document pixel more for the pixels its edges cut through
|
||||
let reach = reach + spans_along_axes(render.transform.matrix2.inverse());
|
||||
let (min, max) = (bounds[0] - reach, bounds[1] + reach);
|
||||
let region = format!(r#"x="{}" y="{}" width="{}" height="{}""#, min.x, min.y, max.x - min.x, max.y - min.y);
|
||||
|
||||
// Each pixel reads only what lies beneath it, so an image of that reads nothing past the view
|
||||
let copy = render.backdrop_copy(render_params, [min, max], 0., true)?;
|
||||
|
||||
// Where canvases and the GPU's images stand in for what lies beneath in a copy of its markup, it can't be read, so nothing there is hidden
|
||||
let copy = match copy.image {
|
||||
true => copy.markup,
|
||||
false => with_unreadable_covered(©.markup, &key_color(underlying)),
|
||||
};
|
||||
|
||||
let (filter_id, mask_id) = (format!("blend-if-{}", generate_uuid()), format!("blend-if-mask-{}", generate_uuid()));
|
||||
write!(
|
||||
render.svg_defs,
|
||||
r#"<filter id="{filter_id}" filterUnits="userSpaceOnUse" {region} color-interpolation-filters="sRGB">{markup}</filter><mask id="{mask_id}" mask-type="alpha" maskUnits="userSpaceOnUse" {region}><g filter="url(#{filter_id})">{copy}</g></mask>"#
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
Some(format!("url(#{mask_id})"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn keys_are_colors_the_ranges_show_in_full_where_no_gray_is() {
|
||||
// Red from 60% up and blue up to 40%, which no gray passes both of
|
||||
let mut ranges = ChannelRanges::default();
|
||||
(ranges.red.falloff_start, ranges.red.range_start) = (60., 60.);
|
||||
(ranges.blue.range_end, ranges.blue.falloff_end) = (40., 40.);
|
||||
|
||||
let key = key_color(&[ranges]);
|
||||
let channel = |index: usize| u8::from_str_radix(&key[1 + 2 * index..3 + 2 * index], 16).unwrap() as f64 / 255.;
|
||||
assert_eq!(ranges.weight([channel(0), channel(1), channel(2)]), 1., "{key}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copies_where_no_image_stands_in_cover_canvases_and_the_gpus_images_with_the_key_color() {
|
||||
use crate::deferred_image::{DeferredImagePlacement, substitute_deferred_image};
|
||||
use core_types::Color;
|
||||
use core_types::blending::BlendMode;
|
||||
use glam::DAffine2;
|
||||
use graphic_types::raster_types::{Image, Raster};
|
||||
|
||||
let canvas = r#"<foreignObject x="1" y="2" width="3" height="4"><div data-canvas-placeholder="image-7"></div></foreignObject>"#;
|
||||
let stand_in = r#"<!--deferred-image-9--><path d="M0,0" /><!--/deferred-image-9-->"#;
|
||||
let covered = with_unreadable_covered(&format!("{canvas}{stand_in}"), "#000000");
|
||||
|
||||
// A canvas becomes a rectangle of the key color at its own placement, and the stand-in for the GPU's image is marked for one
|
||||
assert!(covered.starts_with(r##"<rect x="1" y="2" width="3" height="4" fill="#000000" />"##), "{covered}");
|
||||
assert!(covered.contains(r#"<!--deferred-cover-9-000000--><path d="M0,0" /><!--/deferred-cover-9-->"#), "{covered}");
|
||||
|
||||
// Once the GPU's image arrives in a canvas in place of the original stand-in, the rectangle replaces the copy's
|
||||
let placement = DeferredImagePlacement {
|
||||
id: 9,
|
||||
transform: DAffine2::IDENTITY,
|
||||
user_to_document: DAffine2::IDENTITY,
|
||||
opacity: 1.,
|
||||
blend_mode: BlendMode::Normal,
|
||||
mask: None,
|
||||
to_canvas: true,
|
||||
canvas_image_scale: 1.,
|
||||
};
|
||||
let mut svg = format!("{covered}{stand_in}");
|
||||
substitute_deferred_image(&mut svg, &mut Vec::new(), &placement, &Raster::new_cpu(Image::new(1, 1, Color::BLACK)));
|
||||
assert!(svg.contains(r##"<rect width="1" height="1" transform="" fill="#000000" />"##) && !svg.contains("deferred-"), "{svg}");
|
||||
}
|
||||
}
|
||||
@@ -47,6 +47,16 @@ pub struct VelloSceneBuilder<'a> {
|
||||
effects_renderer: Option<&'a mut dyn EffectsRenderer>,
|
||||
/// The coverage the next effects group drawn outputs in place of its result, for an SVG map of it.
|
||||
effect_capture: Option<EffectCapture>,
|
||||
/// How many placed drawings are open, each a backdrop root of its own, like a thumbnail of an atlas.
|
||||
placed_depth: u32,
|
||||
/// How many pixels past the scene's edges the content reading what lies beneath it reads, which a render of the scene grown by as much holds.
|
||||
backdrop_apron: u32,
|
||||
/// Each content drawn so far reading what lies beneath it, as its bounds in the scene and how many pixels past them it reads along each axis, for later content reading through it.
|
||||
backdrop_readers: Vec<(Rect, DVec2)>,
|
||||
/// The widest apron a render of the scene grown for content reading past its edges can have, up to which such content stops the drawing, or 0 to draw everything.
|
||||
largest_apron: u32,
|
||||
/// Whether the scene still draws, rather than only measuring the apron after content reading past its edges stopped it.
|
||||
drawing: bool,
|
||||
}
|
||||
|
||||
/// Renders the content of a scene's effects groups offscreen and carries out their effects, while the scene is drawn.
|
||||
@@ -58,6 +68,7 @@ pub trait EffectsRenderer: Send {
|
||||
/// returning one for each of the `layers` that `effects` carried out on it draw, with the mode it blends by.
|
||||
/// `effect_to_pixels` places the effects' space on the texture's pixels, `fill` fades the content but not the shadows and glows cast from it, and `opacity` fades the layers.
|
||||
/// The `frame`, in the texture's pixels, is what effects relative to the content's extent take as their own.
|
||||
/// `backdrop` is what lies beneath, for the effects that read it, with the placement of the textures' pixels in it.
|
||||
/// With a `capture`, the only texture instead holds that effect's coverage, as black with it in alpha.
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
fn render_effects(
|
||||
@@ -70,10 +81,17 @@ pub trait EffectsRenderer: Send {
|
||||
opacity: f32,
|
||||
effect_to_pixels: DAffine2,
|
||||
frame: Option<EffectFrame>,
|
||||
backdrop: Option<(&wgpu::Texture, Affine)>,
|
||||
capture: Option<EffectCapture>,
|
||||
draw_paint: &mut dyn FnMut(usize, &mut VelloSceneBuilder),
|
||||
draw: &mut dyn FnMut(&mut VelloSceneBuilder),
|
||||
) -> Vec<(wgpu::Texture, core_types::blending::BlendMode)>;
|
||||
|
||||
/// Renders a `scene` drawn so far, with the `images` it draws, into a premultiplied texture of its size, as the backdrop of what's drawn next.
|
||||
/// `None` if it fails to render.
|
||||
fn render_backdrop(&mut self, _scene: &vello_gpu::Scene, _images: &[SceneImage], _max_texture_size: u32) -> Option<wgpu::Texture> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// The pixels behind an image the scene draws.
|
||||
@@ -127,7 +145,12 @@ impl GeneratorTile {
|
||||
#[derive(Debug)]
|
||||
enum Pushed {
|
||||
Layer,
|
||||
Clip,
|
||||
/// With the path it clips to, given in the scene's space, so it can be pushed again in a scene continuing this one.
|
||||
Clip {
|
||||
path: BezPath,
|
||||
transform: Affine,
|
||||
fill_rule: Fill,
|
||||
},
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for VelloSceneBuilder<'_> {
|
||||
@@ -157,6 +180,11 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
pushed: Vec::new(),
|
||||
effects_renderer: None,
|
||||
effect_capture: None,
|
||||
placed_depth: 0,
|
||||
backdrop_apron: 0,
|
||||
backdrop_readers: Vec::new(),
|
||||
largest_apron: 0,
|
||||
drawing: true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -166,6 +194,18 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// Stops drawing at the first content reading what lies beneath it past the scene's edges by at most `largest_apron` pixels, which a render grown by as much draws instead.
|
||||
/// The scene then only measures how far past its edges the rest reads, for that render's apron.
|
||||
pub fn stopping_for_an_apron_up_to(mut self, largest_apron: u32) -> Self {
|
||||
self.largest_apron = largest_apron;
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether the scene drew all its content, rather than stopping at content reading past its edges.
|
||||
pub fn drew_everything(&self) -> bool {
|
||||
self.drawing
|
||||
}
|
||||
|
||||
/// Has the next effects group drawn output the coverage `capture` names in place of its result, leaving the groups drawn within it as they are.
|
||||
pub fn capture_next_effects(&mut self, capture: EffectCapture) {
|
||||
self.effect_capture = Some(capture);
|
||||
@@ -188,6 +228,11 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
self.max_texture_size
|
||||
}
|
||||
|
||||
/// How many pixels past the scene's edges the content drawn so far that reads what lies beneath it reads, which the scene doesn't hold.
|
||||
pub fn backdrop_apron(&self) -> u32 {
|
||||
self.backdrop_apron
|
||||
}
|
||||
|
||||
/// The finished Vello GPU scene and the images its external textures stand for, closing whatever layers and clips were left open.
|
||||
pub fn finish(mut self) -> (vello_gpu::Scene, Vec<SceneImage>) {
|
||||
if !self.pushed.is_empty() {
|
||||
@@ -206,10 +251,13 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
}
|
||||
|
||||
/// Draws what `draw` draws placed by `placement` within the view, as content with its own document space for its effects' lengths, like each thumbnail of an atlas.
|
||||
/// It's a backdrop root of its own with nothing beneath it to read, as a run of effects drawn into another run's content is.
|
||||
pub fn draw_placed(&mut self, placement: Affine, draw: impl FnOnce(&mut Self)) {
|
||||
let outer_view = self.view;
|
||||
self.view = outer_view * placement;
|
||||
self.placed_depth += 1;
|
||||
draw(self);
|
||||
self.placed_depth -= 1;
|
||||
self.view = outer_view;
|
||||
}
|
||||
|
||||
@@ -228,6 +276,9 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
|
||||
/// Like [`Self::fill`] for a path, which it draws without copying.
|
||||
pub fn fill_path<'b>(&mut self, fill_rule: Fill, transform: Affine, brush: impl Into<BrushRef<'b>>, brush_transform: Option<Affine>, path: &BezPath) {
|
||||
if !self.drawing {
|
||||
return;
|
||||
}
|
||||
let Some((paint, paint_to_brush)) = self.paint(brush.into()) else { return };
|
||||
self.scene.set_transform(self.view * transform);
|
||||
self.scene.set_fill_rule(fill_rule);
|
||||
@@ -238,6 +289,9 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
|
||||
/// Strokes a shape given in the space of `transform`, with the brush placed by `transform * brush_transform`.
|
||||
pub fn stroke<'b>(&mut self, stroke: &Stroke, transform: Affine, brush: impl Into<BrushRef<'b>>, brush_transform: Option<Affine>, shape: &impl Shape) {
|
||||
if !self.drawing {
|
||||
return;
|
||||
}
|
||||
let Some((paint, paint_to_brush)) = self.paint(brush.into()) else { return };
|
||||
self.scene.set_transform(self.view * transform);
|
||||
self.scene.set_stroke(stroke.clone());
|
||||
@@ -248,6 +302,9 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
|
||||
/// Fills the whole scene, which is how content without bounds (like a color or gradient layer) paints, with the brush placed by `brush_transform` in the space of the drawn content.
|
||||
pub fn fill_viewport<'b>(&mut self, brush: impl Into<BrushRef<'b>>, brush_transform: Option<Affine>) {
|
||||
if !self.drawing {
|
||||
return;
|
||||
}
|
||||
let Some((paint, paint_to_brush)) = self.paint(brush.into()) else { return };
|
||||
self.scene.set_transform(Affine::IDENTITY);
|
||||
self.scene.set_paint(paint);
|
||||
@@ -257,38 +314,99 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
|
||||
/// Begins an isolated layer clipped to `clip`, given in the space of `transform`. Must be balanced by [`Self::pop_layer`].
|
||||
pub fn push_layer(&mut self, fill_rule: Fill, blend_mode: impl Into<BlendMode>, alpha: f32, transform: Affine, clip: &impl Shape) {
|
||||
self.scene.set_transform(self.view * transform);
|
||||
self.scene.set_fill_rule(fill_rule);
|
||||
self.scene
|
||||
.push_layer(Some(&finite_path(&clip.to_path(SHAPE_TOLERANCE))), Some(blend_mode.into()), Some(alpha), None, None);
|
||||
if self.drawing {
|
||||
self.scene.set_transform(self.view * transform);
|
||||
self.scene.set_fill_rule(fill_rule);
|
||||
self.scene
|
||||
.push_layer(Some(&finite_path(&clip.to_path(SHAPE_TOLERANCE))), Some(blend_mode.into()), Some(alpha), None, None);
|
||||
}
|
||||
self.pushed.push(Pushed::Layer);
|
||||
}
|
||||
|
||||
/// Begins an isolated layer covering the whole scene, for content without bounds. Must be balanced by [`Self::pop_layer`].
|
||||
pub fn push_viewport_layer(&mut self, blend_mode: impl Into<BlendMode>, alpha: f32) {
|
||||
self.scene.push_layer(None, Some(blend_mode.into()), Some(alpha), None, None);
|
||||
if self.drawing {
|
||||
self.scene.push_layer(None, Some(blend_mode.into()), Some(alpha), None, None);
|
||||
}
|
||||
self.pushed.push(Pushed::Layer);
|
||||
}
|
||||
|
||||
/// Clips the content that follows to `clip`, given in the space of `transform`, without isolating it. Must be balanced by [`Self::pop_layer`].
|
||||
pub fn push_clip_layer(&mut self, fill_rule: Fill, transform: Affine, clip: &impl Shape) {
|
||||
self.scene.set_transform(self.view * transform);
|
||||
self.scene.set_fill_rule(fill_rule);
|
||||
self.scene.push_clip_path(&finite_path(&clip.to_path(SHAPE_TOLERANCE)));
|
||||
self.pushed.push(Pushed::Clip);
|
||||
// The path is kept to begin the clip again after a render of the scene so far, copied only if it had to be made finite
|
||||
let path = clip.to_path(SHAPE_TOLERANCE);
|
||||
let finite = match finite_path(&path) {
|
||||
Cow::Owned(finite) => Some(finite),
|
||||
Cow::Borrowed(_) => None,
|
||||
};
|
||||
let (path, transform) = (finite.unwrap_or(path), self.view * transform);
|
||||
if self.drawing {
|
||||
self.scene.set_transform(transform);
|
||||
self.scene.set_fill_rule(fill_rule);
|
||||
self.scene.push_clip_path(&path);
|
||||
}
|
||||
self.pushed.push(Pushed::Clip { path, transform, fill_rule });
|
||||
}
|
||||
|
||||
/// Ends the most recent layer or clip.
|
||||
pub fn pop_layer(&mut self) {
|
||||
match self.pushed.pop() {
|
||||
Some(Pushed::Layer) => self.scene.pop_layer(),
|
||||
Some(Pushed::Clip) => self.scene.pop_clip(),
|
||||
Some(Pushed::Layer) if self.drawing => self.scene.pop_layer(),
|
||||
Some(Pushed::Clip { .. }) if self.drawing => self.scene.pop_clip(),
|
||||
Some(_) => {}
|
||||
None => log::error!("A scene ends a layer or clip it never began"),
|
||||
}
|
||||
}
|
||||
|
||||
/// What's drawn so far, which lies beneath what's drawn next, in a premultiplied texture the size of the scene.
|
||||
/// The scene is rendered so far and continues from an image of that render. `None` where content has nothing beneath it to read, or once the scene stopped drawing.
|
||||
pub fn backdrop(&mut self) -> Option<wgpu::Texture> {
|
||||
if !self.drawing || !self.backdrop_readable() {
|
||||
return None;
|
||||
}
|
||||
let renderer = self.effects_renderer.as_deref_mut()?;
|
||||
|
||||
// The clips end for the render, then begin again in the scene continuing it
|
||||
self.pushed.iter().for_each(|_| self.scene.pop_clip());
|
||||
let rendered = renderer.render_backdrop(&self.scene, &self.images, self.max_texture_size);
|
||||
if rendered.is_some() {
|
||||
self.scene.reset();
|
||||
self.images.clear();
|
||||
self.image_ids.clear();
|
||||
}
|
||||
let backdrop = rendered.inspect(|backdrop| {
|
||||
self.images.push(SceneImage::Rendered(backdrop.clone()));
|
||||
let area = Rect::new(0., 0., backdrop.width() as f64, backdrop.height() as f64);
|
||||
self.scene.set_transform(Affine::IDENTITY);
|
||||
self.scene.set_paint(PaintType::Image(Image {
|
||||
image: ImageSource::external_texture(TextureId(0), TextureRegion::Full, true),
|
||||
sampler: peniko::ImageSampler::new(),
|
||||
}));
|
||||
self.scene.set_paint_transform(Affine::IDENTITY);
|
||||
self.scene.fill_rect(&area);
|
||||
});
|
||||
for pushed in &self.pushed {
|
||||
if let Pushed::Clip { path, transform, fill_rule } = pushed {
|
||||
self.scene.set_transform(*transform);
|
||||
self.scene.set_fill_rule(*fill_rule);
|
||||
self.scene.push_clip_path(path);
|
||||
}
|
||||
}
|
||||
|
||||
backdrop
|
||||
}
|
||||
|
||||
/// Whether content drawn now has what lies beneath it to read, which it hasn't within an isolated layer, where what lies beneath is only the part inside the layer,
|
||||
/// within a placed drawing, where the content lies over nothing of its own, or without a renderer.
|
||||
fn backdrop_readable(&self) -> bool {
|
||||
self.placed_depth == 0 && !self.pushed.iter().any(|pushed| matches!(pushed, Pushed::Layer)) && self.effects_renderer.is_some()
|
||||
}
|
||||
|
||||
/// Draws an image's rectangle of pixels, from the origin to its width and height, placed by `transform`.
|
||||
pub fn draw_image(&mut self, image: &peniko::ImageBrush, transform: Affine) {
|
||||
if !self.drawing {
|
||||
return;
|
||||
}
|
||||
let Some((source, texture_to_image, texture_size)) = self.image_source(SceneImage::Pixels(image.image.clone())) else {
|
||||
return;
|
||||
};
|
||||
@@ -297,6 +415,9 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
|
||||
/// Draws a CPU raster's rectangle of pixels with `adjustments` carried out on them, from the origin to its width and height, placed by `transform`.
|
||||
pub fn draw_raster(&mut self, raster: Raster<CPU>, adjustments: Vec<Adjustment>, sampler: peniko::ImageSampler, transform: Affine) {
|
||||
if !self.drawing {
|
||||
return;
|
||||
}
|
||||
let Some((source, texture_to_image, texture_size)) = self.image_source(SceneImage::Raster { raster, adjustments }) else {
|
||||
return;
|
||||
};
|
||||
@@ -305,6 +426,9 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
|
||||
/// Draws a GPU texture's rectangle of pixels, from the origin to its width and height, placed by `transform`.
|
||||
pub fn draw_texture(&mut self, texture: Texture, sampler: peniko::ImageSampler, transform: Affine) {
|
||||
if !self.drawing {
|
||||
return;
|
||||
}
|
||||
let Some((source, texture_to_image, texture_size)) = self.image_source(SceneImage::Texture(texture)) else {
|
||||
return;
|
||||
};
|
||||
@@ -317,7 +441,7 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
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() {
|
||||
if !self.drawing || !determinant.is_normal() {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -409,9 +533,12 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
let layers = EffectLayers::plan(effects, blend_mode, fill, layered);
|
||||
|
||||
// The texture follows the viewport's axes if the effect space only turns and evenly scales, or else its own axes, scaled evenly to keep every direction's detail.
|
||||
// A box blur or a minimum or maximum, whose square neighborhoods aren't round, turns with its space only along that space's axes.
|
||||
// A box blur (of the content or what lies beneath it) or a minimum or maximum, whose square neighborhoods aren't round, turns with its space only along that space's axes.
|
||||
let has_square_kernel = effects.operations().any(|operation| {
|
||||
let square = matches!(operation, EffectOperation::Blur { box_blur: true, .. } | EffectOperation::MinimumMaximum { .. });
|
||||
let square = matches!(
|
||||
operation,
|
||||
EffectOperation::Blur { box_blur: true, .. } | EffectOperation::BackgroundBlur { box_blur: true, .. } | EffectOperation::MinimumMaximum { .. }
|
||||
);
|
||||
square && !operation.changes_nothing()
|
||||
});
|
||||
let follows_viewport = is_similarity(effect_to_device.matrix2) && (!has_square_kernel || is_axis_aligned(effect_to_device.matrix2));
|
||||
@@ -483,16 +610,61 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
let size = UVec2::new(size_along(region.width()), size_along(region.height()));
|
||||
let origin = region.origin().to_vec2();
|
||||
|
||||
// What lies beneath, for the effects that read it, where each of the effects texture's pixels lands in it.
|
||||
// Content without bounds reads nothing, as in SVG, and content reading past the scene's edges asks for the scene to be rendered grown by as much.
|
||||
let reads_backdrop = layers.reads_backdrop() && capture.is_none() && bounds.is_some() && self.backdrop_readable();
|
||||
if reads_backdrop && layers.reads_around_backdrop() {
|
||||
// A box reaches as far along each axis of the view as its square turned into it does, and a Gaussian as far every way as its widest stretch
|
||||
let readers = (effects.operations()).filter(|operation| matches!(operation, graphic_types::EffectOperation::BackgroundBlur { .. }) && !operation.changes_nothing());
|
||||
let linear = effect_to_device.matrix2;
|
||||
let backdrop_reach: DVec2 = readers
|
||||
.map(|operation| match operation {
|
||||
graphic_types::EffectOperation::BackgroundBlur { box_blur: true, .. } => operation.reach() * (linear.abs() * DVec2::ONE),
|
||||
_ => DVec2::splat(operation.reach() * largest_stretch(linear)),
|
||||
})
|
||||
.sum();
|
||||
|
||||
// The content in view reads what lies beneath only within its backdrop readers' reach, however far past the view the region extends
|
||||
let region_in_device = Affine::new(frame_to_device.to_cols_array()).transform_rect_bbox(region);
|
||||
let mut read_region = region_in_device.intersect(viewport.inflate(backdrop_reach.x, backdrop_reach.y));
|
||||
|
||||
// Content farther from the view than its backdrop reach needs no apron of its own, though later content reading through it may
|
||||
if read_region.width() > 0. && read_region.height() > 0. {
|
||||
// Where it reads earlier content reading what lies beneath, it reads what that content read too, from the latest back. O(readers drawn so far).
|
||||
for &(earlier_bounds, earlier_reach) in self.backdrop_readers.iter().rev() {
|
||||
let overlap = earlier_bounds.intersect(read_region);
|
||||
if overlap.width() > 0. && overlap.height() > 0. {
|
||||
read_region = read_region.union(overlap.inflate(earlier_reach.x, earlier_reach.y));
|
||||
}
|
||||
}
|
||||
|
||||
let past_edges = (-read_region.x0).max(-read_region.y0).max(read_region.x1 - viewport.x1).max(read_region.y1 - viewport.y1);
|
||||
self.backdrop_apron = self.backdrop_apron.max(past_edges.max(0.).ceil() as u32);
|
||||
}
|
||||
self.backdrop_readers.extend(bounds.map(|bounds| (self.view.transform_rect_bbox(bounds), backdrop_reach)));
|
||||
}
|
||||
|
||||
// Content reading past the edges by no more than a grown render holds stops the drawing, leaving all of it to that render
|
||||
if (1..=self.largest_apron).contains(&self.backdrop_apron) {
|
||||
self.drawing = false;
|
||||
}
|
||||
if !self.drawing {
|
||||
return;
|
||||
}
|
||||
let backdrop = reads_backdrop.then(|| self.backdrop()).flatten();
|
||||
|
||||
let texture_to_device = Affine::new(frame_to_device.to_cols_array()) * Affine::translate(origin) * Affine::scale(1. / resolution);
|
||||
|
||||
let frame_to_pixels = Affine::scale(resolution) * Affine::translate(-origin);
|
||||
let content_view = frame_to_pixels * document_to_frame;
|
||||
let effect_to_pixels = DAffine2::from_cols_array(&content_view.as_coeffs()) * effect_space;
|
||||
let effect_frame = effect_frame.map(|frame| frame.placed(DAffine2::from_cols_array(&frame_to_pixels.as_coeffs())));
|
||||
let Some(renderer) = self.effects_renderer.as_deref_mut() else { return };
|
||||
let results = renderer.render_effects(size, content_view, effects, &layers, fill, opacity, effect_to_pixels, effect_frame, capture, draw_paint, draw);
|
||||
let backdrop = backdrop.as_ref().map(|backdrop| (backdrop, texture_to_device));
|
||||
let results = renderer.render_effects(size, content_view, effects, &layers, fill, opacity, effect_to_pixels, effect_frame, backdrop, capture, draw_paint, draw);
|
||||
|
||||
// Draw each layer where the content was, blended onto what lies beneath, except a captured coverage, which is drawn as it is
|
||||
let area = Rect::new(0., 0., size.x as f64, size.y as f64);
|
||||
let texture_to_device = Affine::new(frame_to_device.to_cols_array()) * Affine::translate(origin) * Affine::scale(1. / resolution);
|
||||
for (texture, blend_mode) in results {
|
||||
let isolated = capture.is_none() && (opacity < 1. || blend_mode != core_types::blending::BlendMode::Normal);
|
||||
if isolated {
|
||||
|
||||
@@ -2,6 +2,7 @@ use crate::clip::clipped_to;
|
||||
use crate::{bezpath, graphic_list};
|
||||
use core_types::Color;
|
||||
use core_types::list::{ATTR_APPEARANCE, ATTR_PAINT, Item, List};
|
||||
use graphic_types::masks::{MaskMode, mask_coverage};
|
||||
use graphic_types::{Appearance, CoverPlacement, Coverage, Graphic, Vector, stamp_coverage};
|
||||
use usvg::tiny_skia_path::PathBuilder;
|
||||
|
||||
@@ -50,5 +51,5 @@ fn luminance_to_alpha(content: &mut List<Graphic>) {
|
||||
|
||||
fn luminance_as_alpha(color: Color) -> Color {
|
||||
let [red, green, blue, alpha] = color.to_gamma_srgb_channels();
|
||||
Color::BLACK.with_alpha((0.2126 * red + 0.7152 * green + 0.0722 * blue) * alpha)
|
||||
Color::BLACK.with_alpha(mask_coverage([red * alpha, green * alpha, blue * alpha, alpha], MaskMode::LuminanceSvg))
|
||||
}
|
||||
@@ -282,11 +282,19 @@ fn a_stroked_even_odd_path_strokes_its_original_outline_above_the_converted_fill
|
||||
|
||||
#[test]
|
||||
fn a_luminance_mask_masks_by_the_luminance_of_its_paints_as_alpha() -> Result<(), Error> {
|
||||
let content = converted(r##"<mask id="mask"><rect width="8" height="8" fill="#808080"/></mask><g mask="url(#mask)"><rect width="8" height="8"/></g>"##)?;
|
||||
// Pure green takes SVG's own weight for it, as the Luminance (SVG) mask mode does
|
||||
for (fill, alpha) in [("#808080", 128. / 255.), ("#00ff00", 0.7154)] {
|
||||
let content = converted(&format!(
|
||||
r##"<mask id="mask"><rect width="8" height="8" fill="{fill}"/></mask><g mask="url(#mask)"><rect width="8" height="8"/></g>"##
|
||||
))?;
|
||||
|
||||
let masker = group(&content, 0).and_then(|masked| group(masked, 0));
|
||||
let masker_paint = masker.and_then(appearance_of).and_then(|appearance| appearance.first_paint_of(Cover::Fill));
|
||||
assert!(matches!(masker_paint, Some(Graphic::Color(color)) if color.element().with_alpha(1.) == Color::BLACK && (color.element().a() - 128. / 255.).abs() < 1e-5));
|
||||
let masker = group(&content, 0).and_then(|masked| group(masked, 0));
|
||||
let masker_paint = masker.and_then(appearance_of).and_then(|appearance| appearance.first_paint_of(Cover::Fill));
|
||||
assert!(
|
||||
matches!(masker_paint, Some(Graphic::Color(color)) if color.element().with_alpha(1.) == Color::BLACK && (color.element().a() - alpha).abs() < 1e-5),
|
||||
"{fill} masks by {masker_paint:?}"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -1437,8 +1437,20 @@ impl Gradient {
|
||||
/// of it, since a map that isn't linear in the gradient's own space bends the ramp between the stops. Read the result with
|
||||
/// [`GradientSpace::RgbGamma`] and [`GradientInterpolation::Linear`] in place of the space and interpolation in `settings`.
|
||||
pub fn map_ramp(&self, settings: GradientSettings, map: impl Fn(Color) -> Color) -> Self {
|
||||
self.map_ramp_anchored(settings, map, None::<fn(Color)>)
|
||||
}
|
||||
|
||||
/// Like [`Gradient::map_ramp`], for a map that jumps wherever the `region` of the ramp's colors changes, as a cutoff on their levels does.
|
||||
/// Scanning for each change at the finest spacing the resampling reaches keeps a region lying between its probes, and the colors on both sides anchor the change at one position.
|
||||
pub fn map_ramp_by_regions<R: PartialEq>(&self, settings: GradientSettings, map: impl Fn(Color) -> Color, region: impl Fn(Color) -> R) -> Self {
|
||||
self.map_ramp_anchored(settings, map, Some(region))
|
||||
}
|
||||
|
||||
fn map_ramp_anchored<R: PartialEq>(&self, settings: GradientSettings, map: impl Fn(Color) -> Color, region: Option<impl Fn(Color) -> R>) -> Self {
|
||||
/// Deeper than this, an interval is under 1/4096 of the ramp, too short to see a step in the mapped colors smear.
|
||||
const MAX_DEPTH: u32 = 12;
|
||||
/// How many times a change of region is narrowed down from the step of the scan it lies in, far closer than any renderer resolves.
|
||||
const REGION_BISECTIONS: u32 = 32;
|
||||
|
||||
fn subdivide(ramp: &impl Fn(f64) -> Color, left: f64, right: f64, color_left: Color, color_right: Color, result: &mut Vec<GradientStop>, depth: u32) {
|
||||
// Probe the quarter points as well as the center, since a map with a steep toe peaks its deviation off-center
|
||||
@@ -1466,14 +1478,55 @@ impl Gradient {
|
||||
let ramp = |position: f64| map(evaluator.evaluate(position));
|
||||
|
||||
// Each stop anchors its own color, keeping the jump between coincident stops, and a cyclic ramp's seam anchors at both ends
|
||||
let mut anchors: Vec<(f64, Color)> = stops.iter().map(|stop| (stop.position, map(stop.color))).collect();
|
||||
let mut anchors: Vec<(f64, Color)> = stops.iter().map(|stop| (stop.position, stop.color)).collect();
|
||||
if settings.cyclic && anchors.first().is_some_and(|&(position, _)| position > 0.) {
|
||||
anchors.insert(0, (0., ramp(0.)));
|
||||
anchors.insert(0, (0., evaluator.evaluate(0.)));
|
||||
}
|
||||
if settings.cyclic && anchors.last().is_some_and(|&(position, _)| position < 1.) {
|
||||
anchors.push((1., ramp(0.)));
|
||||
anchors.push((1., evaluator.evaluate(0.)));
|
||||
}
|
||||
|
||||
// Scanned for in steps of a 4096th of the ramp, each change of region anchors the colors on both its sides at one position
|
||||
if let Some(region) = region {
|
||||
let extent = anchors.first().zip(anchors.last()).map_or(0., |(&(first, _), &(last, _))| last - first);
|
||||
let mut anchored = Vec::with_capacity(anchors.len());
|
||||
|
||||
for (index, &(left, color_left)) in anchors.iter().enumerate() {
|
||||
anchored.push((left, color_left));
|
||||
let Some(&(right, color_right)) = anchors.get(index + 1).filter(|&&(right, _)| right > left) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let steps = ((right - left) / extent * f64::from(1_u32 << MAX_DEPTH)).ceil().max(1.) as usize;
|
||||
let (mut previous_position, mut previous_color, mut previous_region) = (left, color_left, region(color_left));
|
||||
for step in 1..=steps {
|
||||
let position = if step == steps { right } else { left + (right - left) * step as f64 / steps as f64 };
|
||||
let color = if step == steps { color_right } else { evaluator.evaluate(position) };
|
||||
let current_region = region(color);
|
||||
|
||||
if current_region != previous_region {
|
||||
let (mut low, mut color_low, mut high, mut color_high) = (previous_position, previous_color, position, color);
|
||||
for _ in 0..REGION_BISECTIONS {
|
||||
let middle = (low + high) / 2.;
|
||||
let color_middle = evaluator.evaluate(middle);
|
||||
if region(color_middle) == previous_region {
|
||||
(low, color_low) = (middle, color_middle);
|
||||
} else {
|
||||
(high, color_high) = (middle, color_middle);
|
||||
}
|
||||
}
|
||||
anchored.extend([(high, color_low), (high, color_high)]);
|
||||
}
|
||||
|
||||
(previous_position, previous_color, previous_region) = (position, color, current_region);
|
||||
}
|
||||
}
|
||||
|
||||
anchors = anchored;
|
||||
}
|
||||
|
||||
let anchors: Vec<(f64, Color)> = anchors.into_iter().map(|(position, color)| (position, map(color))).collect();
|
||||
|
||||
let mut result = Vec::new();
|
||||
for (index, &(position, color)) in anchors.iter().enumerate() {
|
||||
result.push(GradientStop { position, midpoint: 0.5, color });
|
||||
|
||||
@@ -84,9 +84,7 @@ impl WgpuExecutor {
|
||||
let view = vello_gpu::kurbo::Affine::new(view.to_cols_array());
|
||||
|
||||
let mut canvas = self.inner.document_canvas.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
self.inner
|
||||
.vello_renderer
|
||||
.render(&mut canvas, &self.context().device, &self.context().queue, draw, view, size, &texture)?;
|
||||
self.inner.vello_renderer.render(self, &mut canvas, draw, view, size, &texture)?;
|
||||
|
||||
Ok(texture)
|
||||
}
|
||||
@@ -95,7 +93,7 @@ impl WgpuExecutor {
|
||||
pub fn render_vello_scene_on_canvas(&self, canvas: &mut VelloCanvas, scene: VelloSceneBuilder) -> Result<Texture> {
|
||||
let texture = self.request_texture(UVec2::new(scene.width() as u32, scene.height() as u32));
|
||||
|
||||
self.inner.vello_renderer.render_scene(canvas, &self.context().device, &self.context().queue, scene, &texture);
|
||||
self.inner.vello_renderer.render_scene(self, canvas, scene, &texture);
|
||||
|
||||
Ok(texture)
|
||||
}
|
||||
@@ -165,7 +163,11 @@ impl WgpuExecutor {
|
||||
}
|
||||
|
||||
pub fn request_texture_with_format(&self, size: UVec2, format: wgpu::TextureFormat) -> Texture {
|
||||
self.inner.texture_cache.lock().unwrap().request_texture(&self.context().device, size, format)
|
||||
self.request_texture_with_mips(size, format, 1)
|
||||
}
|
||||
|
||||
pub fn request_texture_with_mips(&self, size: UVec2, format: wgpu::TextureFormat, mip_level_count: u32) -> Texture {
|
||||
self.inner.texture_cache.lock().unwrap().request_texture(self.context(), size, format, mip_level_count)
|
||||
}
|
||||
|
||||
pub fn create_buffer(&self, desc: &wgpu::BufferDescriptor) -> Buffer {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use crate::WgpuContext;
|
||||
use glam::UVec2;
|
||||
use raster_types::Texture;
|
||||
use std::collections::VecDeque;
|
||||
@@ -16,24 +17,23 @@ impl TextureCache {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn request_texture(&mut self, device: &wgpu::Device, size: UVec2, format: wgpu::TextureFormat) -> Texture {
|
||||
pub fn request_texture(&mut self, context: &WgpuContext, size: UVec2, format: wgpu::TextureFormat, mip_level_count: u32) -> Texture {
|
||||
let size = size.max(UVec2::ONE);
|
||||
|
||||
if let Some(pos) = self
|
||||
.textures
|
||||
.iter()
|
||||
.position(|texture| UVec2::new(texture.width(), texture.height()) == size && texture.format() == format && !texture.is_shared() && !texture.is_weakly_shared())
|
||||
{
|
||||
if let Some(pos) = self.textures.iter().position(|texture| {
|
||||
UVec2::new(texture.width(), texture.height()) == size && texture.format() == format && texture.mip_level_count() == mip_level_count && !texture.is_shared() && !texture.is_weakly_shared()
|
||||
}) {
|
||||
let entry = self.textures.remove(pos).unwrap();
|
||||
let texture = entry.clone();
|
||||
self.textures.push_back(entry);
|
||||
return texture;
|
||||
}
|
||||
|
||||
let incoming_bytes = size.x as u64 * size.y as u64 * format.block_copy_size(None).unwrap_or(4) as u64;
|
||||
self.evict_until_fits(incoming_bytes);
|
||||
self.evict_until_fits(memory_size_estimate(size, format, mip_level_count));
|
||||
|
||||
let texture: Texture = device
|
||||
let usage = wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT;
|
||||
let texture: Texture = context
|
||||
.device
|
||||
.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some(&format!("cached_{}x{}", size.x, size.y)),
|
||||
size: wgpu::Extent3d {
|
||||
@@ -41,11 +41,11 @@ impl TextureCache {
|
||||
height: size.y,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
mip_level_count,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format,
|
||||
usage: wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
usage: usage & context.adapter.get_texture_format_features(format).allowed_usages,
|
||||
view_formats: &[],
|
||||
})
|
||||
.into();
|
||||
@@ -83,12 +83,20 @@ impl TextureCache {
|
||||
}
|
||||
}
|
||||
|
||||
fn memory_size_estimate(size: UVec2, format: wgpu::TextureFormat, mip_level_count: u32) -> u64 {
|
||||
let texel_bytes = format.block_copy_size(None).unwrap_or(4) as u64;
|
||||
(0..mip_level_count)
|
||||
.map(|level| (size >> level).max(UVec2::ONE))
|
||||
.map(|level_size| level_size.x as u64 * level_size.y as u64 * texel_bytes)
|
||||
.sum()
|
||||
}
|
||||
|
||||
trait TextureMemoryCostEstimateExt {
|
||||
fn memory_size_estimate(&self) -> u64;
|
||||
}
|
||||
|
||||
impl TextureMemoryCostEstimateExt for wgpu::Texture {
|
||||
fn memory_size_estimate(&self) -> u64 {
|
||||
self.width() as u64 * self.height() as u64 * self.format().block_copy_size(None).unwrap_or(4) as u64
|
||||
memory_size_estimate(UVec2::new(self.width(), self.height()), self.format(), self.mip_level_count())
|
||||
}
|
||||
}
|
||||
@@ -2,10 +2,13 @@
|
||||
//! from `vello_adjustments.wgsl`, while the kinds that compilers struggle to build inside its loop each get a shader and pass of their own. Steps read their
|
||||
//! settings from a texture, so changing those recompiles nothing.
|
||||
|
||||
use crate::WgpuExecutor;
|
||||
use crate::vello_effects::{WORKING_FORMAT, pass_pipeline};
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use glam::UVec2;
|
||||
use graphic_types::Adjustment;
|
||||
use raster_kernels::adjustment_steps::{AdjustmentSteps, StepKind, shader_constants};
|
||||
use raster_types::{Texture, TextureWeakRef};
|
||||
use std::cmp::Reverse;
|
||||
use std::collections::HashMap;
|
||||
use std::ops::Range;
|
||||
@@ -22,11 +25,8 @@ const STANDALONE_KINDS: [StepKind; 2] = [StepKind::GradientMap, StepKind::ColorL
|
||||
/// How many runs of adjustments keep their encoded and uploaded steps past the render that last used them. Their tables are kept apart.
|
||||
const MAX_CACHED_RUNS: usize = 8;
|
||||
|
||||
/// How many bytes of tables stay uploaded past the render that last used them, the least recently used making way first.
|
||||
const TABLE_CACHE_BYTES: u64 = 256 << 20;
|
||||
|
||||
/// The most texels a run's tables span (128 MiB), past which they are resampled to fit. That's half of what the cache keeps and of the largest buffer
|
||||
/// wgpu allocates by default, which an upload passes through.
|
||||
/// The most texels a run's tables span (128 MiB), past which they are resampled to fit. That's half of the largest buffer wgpu allocates by default,
|
||||
/// which an upload passes through.
|
||||
const MAX_TABLE_TEXELS: usize = 1 << 23;
|
||||
|
||||
/// The format each pass of a run split across several hands its result on to the next in, where the GPU can render into it, so the split rounds nothing.
|
||||
@@ -344,15 +344,15 @@ fn texels_texture_descriptor(label: &'static str, width: u32, height: u32) -> wg
|
||||
}
|
||||
|
||||
/// A texture holding `texels` in rows as wide as the GPU allows, the last padded out, or `None` if they need more rows than it allows too.
|
||||
fn upload_texels(device: &wgpu::Device, queue: &wgpu::Queue, label: &'static str, texels: &[[f32; 4]]) -> Option<wgpu::Texture> {
|
||||
let max_dimension = device.limits().max_texture_dimension_2d as usize;
|
||||
fn upload_texels(executor: &WgpuExecutor, queue: &wgpu::Queue, texels: &[[f32; 4]]) -> Option<Texture> {
|
||||
let max_dimension = executor.context().device.limits().max_texture_dimension_2d as usize;
|
||||
let width = texels.len().clamp(1, max_dimension);
|
||||
let height = texels.len().div_ceil(width).max(1);
|
||||
if height > max_dimension {
|
||||
return None;
|
||||
}
|
||||
|
||||
let texture = device.create_texture(&texels_texture_descriptor(label, width as u32, height as u32));
|
||||
let texture = executor.request_texture_with_format(UVec2::new(width as u32, height as u32), wgpu::TextureFormat::Rgba32Float);
|
||||
let write_rows = |first_row: usize, rows: usize, data: &[[f32; 4]]| {
|
||||
let texture_rows = wgpu::TexelCopyTextureInfo {
|
||||
texture: &texture,
|
||||
@@ -397,12 +397,12 @@ pub(crate) struct PreparedPass {
|
||||
|
||||
/// The shader and the uploaded steps of each pass carrying out a run with these `steps`, each pass's texels starting with its step count,
|
||||
/// or `None` if any holds more than the GPU can read.
|
||||
fn upload_passes(device: &wgpu::Device, queue: &wgpu::Queue, steps: &AdjustmentSteps) -> Option<Vec<(AdjustmentShader, wgpu::Texture)>> {
|
||||
fn upload_passes(executor: &WgpuExecutor, queue: &wgpu::Queue, steps: &AdjustmentSteps) -> Option<Vec<(AdjustmentShader, Texture)>> {
|
||||
(pass_steps(steps.kinds()).into_iter())
|
||||
.map(|pass| {
|
||||
let shader = AdjustmentShader::for_pass(&steps.kinds()[pass.clone()]);
|
||||
let texels: Vec<[f32; 4]> = std::iter::once([pass.len() as f32, 0., 0., 0.]).chain(steps.step_texels(pass).iter().copied()).collect();
|
||||
upload_texels(device, queue, "vello_adjustments_steps", &texels).map(|texture| (shader, texture))
|
||||
upload_texels(executor, queue, &texels).map(|texture| (shader, texture))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -419,15 +419,14 @@ pub(crate) struct AdjustmentUploads {
|
||||
struct CachedRun {
|
||||
hash: u64,
|
||||
steps: AdjustmentSteps,
|
||||
passes: Option<Vec<(AdjustmentShader, wgpu::Texture)>>,
|
||||
passes: Option<Vec<(AdjustmentShader, TextureWeakRef)>>,
|
||||
last_used: u64,
|
||||
}
|
||||
|
||||
/// The tables of a run as uploaded, shared by every run reading the same ones, or `None` in place of the upload for tables too large for the GPU even resampled.
|
||||
struct CachedTables {
|
||||
key: u64,
|
||||
uploaded: Option<wgpu::Texture>,
|
||||
bytes: u64,
|
||||
uploaded: Option<TextureWeakRef>,
|
||||
last_used: u64,
|
||||
}
|
||||
|
||||
@@ -438,70 +437,95 @@ pub(crate) fn adjustment_run_hash(run: &[&Adjustment]) -> u64 {
|
||||
std::hash::Hasher::finish(&hasher)
|
||||
}
|
||||
|
||||
fn downgrade_passes(passes: &[(AdjustmentShader, Texture)]) -> Vec<(AdjustmentShader, TextureWeakRef)> {
|
||||
passes.iter().map(|(shader, texture)| (*shader, texture.downgrade())).collect()
|
||||
}
|
||||
|
||||
impl AdjustmentUploads {
|
||||
/// What each pass carrying out `run` reads in turn, encoding and uploading only what no recent render has. A run that changes no color
|
||||
/// or that holds more than the GPU can read takes no passes. Only the 64-bit hashes of the runs and of the tables' content tell them apart.
|
||||
pub(crate) fn prepare(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, run: &[&Adjustment], render_count: u64) -> Vec<PreparedPass> {
|
||||
/// What each pass carrying out `run` reads in turn, encoding and uploading only what no recent render has, with the uploads it reads added to `held`.
|
||||
/// A run that changes no color or that holds more than the GPU can read takes no passes. Only the 64-bit hashes of the runs and of the tables' content tell them apart.
|
||||
pub(crate) fn prepare(&mut self, executor: &WgpuExecutor, queue: &wgpu::Queue, run: &[&Adjustment], render_count: u64, held: &mut Vec<Texture>) -> Vec<PreparedPass> {
|
||||
let hash = adjustment_run_hash(run);
|
||||
let mut uploaded = None;
|
||||
let index = self.runs.iter().position(|cached| cached.hash == hash).unwrap_or_else(|| {
|
||||
let steps = AdjustmentSteps::encode(run);
|
||||
let passes = upload_passes(device, queue, &steps);
|
||||
if passes.is_none() {
|
||||
uploaded = upload_passes(executor, queue, &steps);
|
||||
if uploaded.is_none() {
|
||||
log::error!("Adjustments hold more settings than the GPU can read, so they're left out");
|
||||
}
|
||||
|
||||
self.runs.push(CachedRun {
|
||||
hash,
|
||||
steps,
|
||||
passes,
|
||||
passes: uploaded.as_deref().map(downgrade_passes),
|
||||
last_used: render_count,
|
||||
});
|
||||
self.runs.len() - 1
|
||||
});
|
||||
let cached_run = &mut self.runs[index];
|
||||
cached_run.last_used = render_count;
|
||||
let Some(passes) = cached_run.passes.clone() else { return Vec::new() };
|
||||
let Some(cached_passes) = &cached_run.passes else { return Vec::new() };
|
||||
let parked = cached_passes.iter().map(|(shader, texture)| Some((*shader, texture.upgrade()?))).collect();
|
||||
let passes = match uploaded.or(parked) {
|
||||
Some(passes) => passes,
|
||||
None => {
|
||||
let Some(passes) = upload_passes(executor, queue, &cached_run.steps) else { return Vec::new() };
|
||||
cached_run.passes = Some(downgrade_passes(&passes));
|
||||
passes
|
||||
}
|
||||
};
|
||||
if passes.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let tables = match cached_run.steps.table_key() {
|
||||
Some(key) => {
|
||||
let index = self.tables.iter().position(|cached| cached.key == key).unwrap_or_else(|| {
|
||||
// As many texels as one texture holds and one upload carries
|
||||
let limits = device.limits();
|
||||
let max_dimension = limits.max_texture_dimension_2d as usize;
|
||||
let max_uploaded = (limits.max_buffer_size / size_of::<[f32; 4]>() as u64) as usize;
|
||||
let texels = cached_run.steps.table_texels(MAX_TABLE_TEXELS.min(max_dimension * max_dimension).min(max_uploaded));
|
||||
let index = self.tables.iter().position(|cached| cached.key == key);
|
||||
let parked = index.map(|index| self.tables[index].uploaded.as_ref().map(TextureWeakRef::upgrade));
|
||||
let tables = match parked {
|
||||
// Failed to upload
|
||||
Some(None) => return Vec::new(),
|
||||
// Parked
|
||||
Some(Some(Some(tables))) => Some(tables),
|
||||
// Not parked
|
||||
Some(Some(None)) | None => {
|
||||
// As many texels as one texture holds and one upload carries
|
||||
let limits = executor.context().device.limits();
|
||||
let max_dimension = limits.max_texture_dimension_2d as usize;
|
||||
let max_uploaded = (limits.max_buffer_size / size_of::<[f32; 4]>() as u64) as usize;
|
||||
let texels = cached_run.steps.table_texels(MAX_TABLE_TEXELS.min(max_dimension * max_dimension).min(max_uploaded));
|
||||
|
||||
let uploaded = upload_texels(device, queue, "vello_adjustments_tables", &texels);
|
||||
if uploaded.is_none() {
|
||||
log::error!("Adjustments read lookup tables holding more data than the GPU can read, so they're left out");
|
||||
let uploaded = upload_texels(executor, queue, &texels);
|
||||
if uploaded.is_none() {
|
||||
log::error!("Adjustments read lookup tables holding more data than the GPU can read, so they're left out");
|
||||
}
|
||||
let cached = CachedTables {
|
||||
key,
|
||||
uploaded: uploaded.as_ref().map(Texture::downgrade),
|
||||
last_used: render_count,
|
||||
};
|
||||
match index {
|
||||
Some(index) => self.tables[index] = cached,
|
||||
None => self.tables.push(cached),
|
||||
}
|
||||
uploaded
|
||||
}
|
||||
|
||||
self.tables.push(CachedTables {
|
||||
key,
|
||||
bytes: uploaded
|
||||
.as_ref()
|
||||
.map_or(0, |texture| u64::from(texture.width()) * u64::from(texture.height()) * size_of::<[f32; 4]>() as u64),
|
||||
uploaded,
|
||||
last_used: render_count,
|
||||
});
|
||||
self.tables.len() - 1
|
||||
});
|
||||
let cached_tables = &mut self.tables[index];
|
||||
cached_tables.last_used = render_count;
|
||||
let Some(uploaded) = cached_tables.uploaded.clone() else { return Vec::new() };
|
||||
Some(uploaded)
|
||||
};
|
||||
let Some(tables) = tables else { return Vec::new() };
|
||||
if let Some(index) = index {
|
||||
self.tables[index].last_used = render_count;
|
||||
}
|
||||
Some(tables)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
|
||||
held.extend(passes.iter().map(|(_, steps)| steps.clone()).chain(tables.clone()));
|
||||
(passes.into_iter())
|
||||
.map(|(shader, steps)| PreparedPass {
|
||||
shader,
|
||||
steps,
|
||||
tables: tables.clone(),
|
||||
steps: (*steps).clone(),
|
||||
tables: tables.as_ref().map(|tables| (**tables).clone()),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -513,13 +537,7 @@ impl AdjustmentUploads {
|
||||
let used_this_render = self.runs.iter().take_while(|cached| cached.last_used == render_count).count();
|
||||
self.runs.truncate(used_this_render.max(MAX_CACHED_RUNS));
|
||||
|
||||
// Tables are kept within a byte budget instead, since one can take up hundreds of megabytes
|
||||
self.tables.sort_by_key(|cached| Reverse(cached.last_used));
|
||||
let mut kept_bytes = 0;
|
||||
self.tables.retain(|cached| {
|
||||
kept_bytes += cached.bytes;
|
||||
cached.last_used == render_count || kept_bytes <= TABLE_CACHE_BYTES
|
||||
});
|
||||
self.tables.retain(|cached| cached.uploaded.as_ref().is_none_or(|tables| tables.upgrade().is_some()));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
// Blend If's passes, appended to the effect passes: ranges of each channel's levels that a pixel shows within, matching `graphic_types::blend_if`
|
||||
|
||||
// How near a cutoff a channel may lie and still count as reaching it, matching `CUTOFF_TOLERANCE`
|
||||
const BLEND_IF_CUTOFF_TOLERANCE: f32 = 1. / 1024.;
|
||||
|
||||
// Each channel's nearest of 256 levels, with halves rounding up, matching `channel_level`
|
||||
fn blend_if_levels(color: vec3<f32>) -> vec3<u32> {
|
||||
return vec3<u32>(floor(clamp(color, vec3<f32>(0.), vec3<f32>(1.)) * 255. + 0.5));
|
||||
}
|
||||
|
||||
// One side of a range, rising across the span between its falloff and range ends (or falling, if not `rising`), or cutting off sharply where they meet
|
||||
fn blend_if_side(value: f32, falloff: f32, range: f32, rising: bool) -> f32 {
|
||||
let low = min(falloff, range);
|
||||
let high = max(falloff, range);
|
||||
if high - low > BLEND_IF_CUTOFF_TOLERANCE {
|
||||
return clamp(select(high - value, value - low, rising) / (high - low), 0., 1.);
|
||||
}
|
||||
return select(f32(value <= high + BLEND_IF_CUTOFF_TOLERANCE), f32(value >= low - BLEND_IF_CUTOFF_TOLERANCE), rising);
|
||||
}
|
||||
|
||||
// How strongly a range of (falloff start, range start, range end, falloff end) shows a channel's value
|
||||
fn blend_if_range(value: f32, edges: vec4<f32>) -> f32 {
|
||||
return blend_if_side(value, edges.x, edges.y, true) * blend_if_side(value, edges.w, edges.z, false);
|
||||
}
|
||||
|
||||
// How strongly the ranges in the first four taps (gray, red, green, and blue) show a premultiplied pixel, by its straight color
|
||||
fn blend_if_weight(pixel: vec4<f32>) -> f32 {
|
||||
var color = vec3<f32>(0.);
|
||||
if pixel.a > 0. {
|
||||
color = pixel.rgb / pixel.a;
|
||||
}
|
||||
// The gray in whole numbers, rounding halves up, matching `gray_level`
|
||||
let levels = blend_if_levels(color);
|
||||
let channels = vec3<f32>(levels) / 255.;
|
||||
let gray = f32((30u * levels.r + 59u * levels.g + 11u * levels.b + 50u) / 100u) / 255.;
|
||||
|
||||
let gray_weight = blend_if_range(gray, parameters.taps[0]);
|
||||
let red_weight = blend_if_range(channels.r, parameters.taps[1]);
|
||||
let green_weight = blend_if_range(channels.g, parameters.taps[2]);
|
||||
let blue_weight = blend_if_range(channels.b, parameters.taps[3]);
|
||||
return gray_weight * red_weight * green_weight * blue_weight;
|
||||
}
|
||||
|
||||
// How strongly the ranges in the taps show each pixel of the content (`source`), by its own colors
|
||||
@fragment
|
||||
fn blend_if_content_weight(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
return vec4<f32>(blend_if_weight(textureLoad(source, vec2<i32>(position.xy), 0)));
|
||||
}
|
||||
|
||||
// How strongly the ranges in the taps show each pixel by what lies beneath it, sampled from the scene's backdrop (`source`) where it lands as `sample_backdrop` places it.
|
||||
// With `values.z` 1 it multiplies the weight so far in `secondary`, and with `values.w` 1 it eases to full where nothing lies beneath, matching `underlying_weight`.
|
||||
@fragment
|
||||
fn blend_if_underlying_weight(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let point = backdrop_point(position.xy);
|
||||
let backdrop = textureSampleLevel(source, linear_sampler, point / vec2<f32>(textureDimensions(source)), 0.);
|
||||
|
||||
var weight = blend_if_weight(backdrop);
|
||||
if parameters.values.z > 0.5 {
|
||||
weight *= textureLoad(secondary, vec2<i32>(position.xy), 0).r;
|
||||
}
|
||||
if parameters.values.w > 0.5 {
|
||||
weight = 1. - backdrop.a * (1. - weight);
|
||||
}
|
||||
return vec4<f32>(weight);
|
||||
}
|
||||
|
||||
// An image (`source`) faded by the weight in `secondary`
|
||||
@fragment
|
||||
fn blend_if_fade(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let pixel = vec2<i32>(position.xy);
|
||||
return textureLoad(source, pixel, 0) * textureLoad(secondary, pixel, 0).r;
|
||||
}
|
||||
@@ -1,11 +1,13 @@
|
||||
//! The GPU passes that carry out an item's effects on its content, between rendering the content offscreen and drawing the result back.
|
||||
|
||||
use crate::WgpuExecutor;
|
||||
use crate::vello_adjustments::{AdjustmentShaders, AdjustmentUploads, PassEncodings, PreparedPass};
|
||||
use bytemuck::{Pod, Zeroable};
|
||||
use core_types::Color;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::transfer_curve::TransferCurve;
|
||||
use glam::{DAffine2, DVec2, UVec2};
|
||||
use graphic_types::blend_if::{blend_ifs_acting_before, fades_content, underlying_ranges};
|
||||
use graphic_types::effect_layers::{EffectLayers, EffectPiece, LayerPart, PiecePlace, is_pixel_filter};
|
||||
use graphic_types::effects::{EffectCapture, GRADIENT_GLOW_FADE, GRADIENT_TABLE_SIZE, GlowFill, OutlineFill, bevel_light, contour_gradient_span, grow_and_tent, outline_extents, shadow_offset};
|
||||
use graphic_types::masks::{mask_feather_sigma, masked_radius_blur_levels};
|
||||
@@ -13,10 +15,13 @@ use graphic_types::resampling::{DisplacementField, EffectFrame, FrameWarp, Halft
|
||||
use graphic_types::{Adjustment, BevelDirection, BevelStyle, BevelTechnique, EffectOperation, Effects, GlowSource, GlowTechnique};
|
||||
use raster_kernels::effect_kernels::{BlurKernel, MAX_DIRECT_BOX_RADIUS, NEGLIGIBLE_LENGTH, chamfer_passes};
|
||||
use raster_kernels::resample_kernels::MotionBlurShear;
|
||||
use raster_types::Texture;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Mutex, PoisonError};
|
||||
use vello_gpu::kurbo::Affine;
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
mod blend_if;
|
||||
mod filters;
|
||||
mod masks;
|
||||
mod resample;
|
||||
@@ -46,9 +51,6 @@ const GRADIENT_SAMPLES: u32 = GRADIENT_TABLE_SIZE as u32;
|
||||
const PARAMETER_TAPS: usize = 81;
|
||||
const _: () = assert!(PARAMETER_TAPS > 2 * raster_kernels::effect_kernels::MAX_KERNEL_REACH.div_ceil(2));
|
||||
|
||||
/// How many renders a pooled texture survives unused before it is freed.
|
||||
const UNUSED_TEXTURE_RENDER_LIMIT: u64 = 3;
|
||||
|
||||
/// The shader's parameters, laid out to match its `Parameters` struct.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Pod, Zeroable)]
|
||||
@@ -69,6 +71,20 @@ impl Default for Parameters {
|
||||
}
|
||||
}
|
||||
|
||||
impl Parameters {
|
||||
/// The parameters placing a pass's pixels in the scene's backdrop by `placement`, laid out as the shader's `backdrop_point` reads them.
|
||||
fn placed_in_backdrop(placement: Affine) -> Self {
|
||||
let [a, b, c, d, x, y] = placement.as_coeffs().map(|coefficient| coefficient as f32);
|
||||
|
||||
Self {
|
||||
step: [a, b],
|
||||
offset: [c, d],
|
||||
values: [x, y, 0., 0.],
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The kernel's taps for a texture halved `levels` times, each the distance and weight of a symmetric pair of taps that sample between two texels.
|
||||
fn kernel_taps(kernel: BlurKernel, levels: u32) -> Vec<[f32; 4]> {
|
||||
let weights = kernel.weights(levels);
|
||||
@@ -150,7 +166,7 @@ impl EffectPasses {
|
||||
log::warn!("This GPU can't render into the formats layer effects need, so content draws without its effects");
|
||||
}
|
||||
|
||||
// The filters', resampling, styles', and masks' passes live in files of their own, sharing this one's bindings and helpers
|
||||
// The filters', resampling, styles', masks', and Blend If's passes live in files of their own, sharing this one's bindings and helpers
|
||||
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("vello_effects.wgsl"),
|
||||
source: wgpu::ShaderSource::Wgsl(
|
||||
@@ -161,7 +177,8 @@ impl EffectPasses {
|
||||
include_str!("vello_resample.wgsl"),
|
||||
include_str!("vello_warp.wgsl"),
|
||||
include_str!("vello_styles.wgsl"),
|
||||
include_str!("vello_masks.wgsl")
|
||||
include_str!("vello_masks.wgsl"),
|
||||
include_str!("vello_blend_if.wgsl")
|
||||
)
|
||||
.into(),
|
||||
),
|
||||
@@ -249,11 +266,12 @@ impl EffectPasses {
|
||||
/// `effect_to_pixels` places the effects' space on the texture's pixels, `fill` fades the content but not the shadows and glows cast from it, and `opacity` fades the layers.
|
||||
/// The `frame`, in the texture's pixels, is the content's extent, which displacements take as their own.
|
||||
/// `paints` holds the effects' drawn paints in order, each rendered over the same pixels as the content.
|
||||
/// `backdrop` is what lies beneath, for the effects that read it, with the placement of the content texture's pixels in it.
|
||||
/// With a `capture`, the only result is instead that effect's coverage, as black with it in alpha, or the share [`EffectCapture::THROUGH_MASK`] names.
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
pub(crate) fn apply(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
executor: &WgpuExecutor,
|
||||
queue: &wgpu::Queue,
|
||||
textures: &mut EffectTextures,
|
||||
content: &wgpu::Texture,
|
||||
@@ -264,10 +282,13 @@ impl EffectPasses {
|
||||
effect_to_pixels: DAffine2,
|
||||
frame: Option<EffectFrame>,
|
||||
paints: &[wgpu::Texture],
|
||||
backdrop: Option<(&wgpu::Texture, Affine)>,
|
||||
capture: Option<EffectCapture>,
|
||||
) -> Vec<(wgpu::Texture, BlendMode)> {
|
||||
let device = &executor.context().device;
|
||||
let mut recorder = PassRecorder {
|
||||
passes: self,
|
||||
executor,
|
||||
device,
|
||||
queue,
|
||||
encoder: device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("vello_effects") }),
|
||||
@@ -287,28 +308,43 @@ impl EffectPasses {
|
||||
let mut pieces: HashMap<EffectCapture, wgpu::Texture> = HashMap::new();
|
||||
// How much the trailing masks together show of each finished layer
|
||||
let mut layer_fade: Option<wgpu::Texture> = None;
|
||||
// How strongly the Blend Ifs so far show the content, which fades it like a fill varying across it
|
||||
let mut blend_if_weight: Option<wgpu::Texture> = None;
|
||||
// How strongly all the masks together show the content, which they show what lies beneath it by too
|
||||
let mut masks_strength: Option<wgpu::Texture> = None;
|
||||
|
||||
// A captured coverage ends the passes in place of the effects' result, once the content's layer is finished if its knockout or share depends on that
|
||||
let mut captured: Option<wgpu::Texture> = None;
|
||||
let captured_piece = capture.and_then(|capture| layers.piece(capture)).map(|(_, piece)| piece);
|
||||
// At a full fill, the content's own layer has exactly the full-strength content's alpha, so knocking out a piece within it again changes nothing
|
||||
let knocks_out_by_layer = |piece: &EffectPiece| piece.knocks_out && (fill < 1. || layers.knockout_cover(piece.capture, opacity) < 1. || layers.masks_fade_knockout_cover(piece.capture));
|
||||
let every_operation: Vec<EffectOperation> = effects.operations().collect();
|
||||
// Unless a fill or a Blend If fades the content, its own layer has exactly the full-strength content's alpha, so knocking out a piece within it again changes nothing
|
||||
let content_faded = fill < 1. || fades_content(&every_operation);
|
||||
let knocks_out_by_layer = |piece: &EffectPiece| piece.knocks_out && (content_faded || layers.knockout_cover(piece.capture, opacity) < 1. || layers.masks_fade_knockout_cover(piece.capture));
|
||||
let capture_needs_content_layer = capture == Some(EffectCapture::THROUGH_MASK) || captured_piece.as_ref().is_some_and(knocks_out_by_layer);
|
||||
|
||||
// Each operation with its index, for a capture to name, leaving out those that change nothing so they don't split the runs of adjustments around them.
|
||||
// A blur whose result is captured runs however slight, so its map still holds the content.
|
||||
let captured_blur =
|
||||
|index: usize, operation: &EffectOperation| matches!(operation, EffectOperation::Blur { .. }) && !operation.changes_nothing() && capture.is_some_and(|capture| capture.index == index);
|
||||
let operations: Vec<(usize, EffectOperation)> = (effects.operations().enumerate())
|
||||
let operations: Vec<(usize, EffectOperation)> = (every_operation.iter().cloned().enumerate())
|
||||
.filter(|(index, operation)| captured_blur(*index, operation) || !changes_nothing(operation, length_scale))
|
||||
.collect();
|
||||
let mut paints = paints.iter();
|
||||
// The rows left out still start stretches that Blend Ifs act at the start of
|
||||
let mut rows_reached = 0;
|
||||
for (position, (index, operation)) in operations.iter().enumerate() {
|
||||
let index = *index;
|
||||
let acting_blend_ifs = (rows_reached..=index).flat_map(|row| blend_ifs_acting_before(&every_operation, row));
|
||||
for ranges in acting_blend_ifs.filter(|ranges| !ranges.content.show_everything()) {
|
||||
blend_if_weight = Some(recorder.blend_if_content(&ranges.content, full.as_ref().unwrap_or(content), &mut filled, blend_if_weight.take()));
|
||||
}
|
||||
rows_reached = index + 1;
|
||||
|
||||
// A layered effect's coverages become pieces, which the content knocks out once its layer is finished, and a flattened one is knocked out by the faded content now
|
||||
let layered = index >= layers.flattened;
|
||||
let piece = |plane: usize| EffectCapture { index, plane };
|
||||
let knockout_fill = if layered { 1. } else { fill };
|
||||
let knockout_weight = blend_if_weight.as_ref().filter(|_| !layered);
|
||||
|
||||
// A coverage is captured in black, and an already tinted image as it is
|
||||
let mut capture_plane = |recorder: &mut PassRecorder, plane: usize, coverage: &wgpu::Texture, tinted: bool| {
|
||||
@@ -374,26 +410,21 @@ impl EffectPasses {
|
||||
}
|
||||
}
|
||||
|
||||
// The full-strength content is read by a later operation, as the unfaded result, or as a box blur's map, and capturing one plane ends the passes
|
||||
// SVG takes a box's results as maps of planes 0 and 1, having no box of each pixel's own width, and a Gaussian's after a Blend If as 1 and 2 (see `masked_radius_blur_takes_maps`)
|
||||
let (full_plane, filled_plane) = if box_blur { (0, 1) } else { (1, 2) };
|
||||
|
||||
// The full-strength content is read by a later operation, as the unfaded result, or as a map, and capturing one plane ends the passes
|
||||
let captures_only = |plane: usize| capture == Some(piece(plane)) && !capture_needs_content_layer;
|
||||
let full_is_read = !captures_only(1) && (filled.is_none() || position + 1 < operations.len() || (box_blur && capture == Some(piece(0))));
|
||||
let full_is_read = !captures_only(filled_plane) && (filled.is_none() || position + 1 < operations.len() || capture == Some(piece(full_plane)));
|
||||
if captures_only(full_plane)
|
||||
&& let Some(filled) = filled.take()
|
||||
{
|
||||
recorder.textures.release(filled);
|
||||
}
|
||||
match box_blur {
|
||||
true => {
|
||||
if captures_only(0)
|
||||
&& let Some(filled) = filled.take()
|
||||
{
|
||||
recorder.textures.release(filled);
|
||||
}
|
||||
let radius = DVec2::splat(radius * length_scale);
|
||||
recorder.masked_box_blur(content, &mut full, &mut filled, &luminance, radius, !gamma, full_is_read);
|
||||
|
||||
// SVG has no box of each pixel's own width, so it takes the results as maps
|
||||
if let Some(full) = &full {
|
||||
capture_plane(&mut recorder, 0, full, true);
|
||||
}
|
||||
if let Some(filled) = &filled {
|
||||
capture_plane(&mut recorder, 1, filled, true);
|
||||
}
|
||||
}
|
||||
false => {
|
||||
let levels: Vec<f64> = masked_radius_blur_levels(radius, length_scale).into_iter().map(|level| level * length_scale).collect();
|
||||
@@ -401,6 +432,13 @@ impl EffectPasses {
|
||||
}
|
||||
}
|
||||
recorder.textures.release(luminance);
|
||||
|
||||
if let Some(full) = &full {
|
||||
capture_plane(&mut recorder, full_plane, full, true);
|
||||
}
|
||||
if let Some(filled) = &filled {
|
||||
capture_plane(&mut recorder, filled_plane, filled, true);
|
||||
}
|
||||
}
|
||||
EffectOperation::DropShadow {
|
||||
color,
|
||||
@@ -416,7 +454,7 @@ impl EffectPasses {
|
||||
let silhouette = recorder.silhouette(full_content, lengths_to_pixels * shadow_offset(angle, distance), false);
|
||||
let mut strength = recorder.cast(silhouette, size, spread, GlowTechnique::Softer, 100., contour, length_scale);
|
||||
if knockout {
|
||||
strength = recorder.knock_out(strength, full_content, knockout_fill);
|
||||
strength = recorder.knock_out(strength, full_content, knockout_fill, knockout_weight);
|
||||
}
|
||||
capture_plane(&mut recorder, 0, &strength, false);
|
||||
recorder.place_beneath(layered.then_some((&mut pieces, piece(0))), &mut beneath, strength, Some(color));
|
||||
@@ -455,7 +493,7 @@ impl EffectPasses {
|
||||
};
|
||||
[Some(raw), shaped].into_iter().flatten().for_each(|texture| recorder.textures.release(texture));
|
||||
|
||||
let coverage = recorder.knock_out(coverage, full_content, knockout_fill);
|
||||
let coverage = recorder.knock_out(coverage, full_content, knockout_fill, knockout_weight);
|
||||
capture_plane(&mut recorder, 0, &coverage, color.is_none());
|
||||
recorder.place_beneath(layered.then_some((&mut pieces, piece(0))), &mut beneath, coverage, color);
|
||||
}
|
||||
@@ -595,7 +633,7 @@ impl EffectPasses {
|
||||
|
||||
// The band outside lies beneath the content like a shadow, and the band inside over it like an inner shadow
|
||||
if let Some(band) = bands.outside {
|
||||
let band = recorder.knock_out(band, full.as_ref().unwrap_or(content), knockout_fill);
|
||||
let band = recorder.knock_out(band, full.as_ref().unwrap_or(content), knockout_fill, knockout_weight);
|
||||
capture_plane(&mut recorder, 0, &band, false);
|
||||
|
||||
let band = painted(&mut recorder, band);
|
||||
@@ -709,12 +747,37 @@ impl EffectPasses {
|
||||
};
|
||||
brighter.into_iter().for_each(|brighter| recorder.textures.release(brighter));
|
||||
for (plane, (amount, (color, _))) in outside.into_iter().flatten().zip(colors).enumerate() {
|
||||
let amount = recorder.knock_out(amount, full.as_ref().unwrap_or(content), knockout_fill);
|
||||
let amount = recorder.knock_out(amount, full.as_ref().unwrap_or(content), knockout_fill, knockout_weight);
|
||||
capture_plane(&mut recorder, plane + 2, &amount, false);
|
||||
recorder.place_beneath(layered.then_some((&mut pieces, piece(plane + 2))), &mut beneath, amount, Some(color));
|
||||
}
|
||||
recorder.textures.release(height);
|
||||
}
|
||||
// Blend If fades the content where it acts, and the layers once they're drawn
|
||||
EffectOperation::BlendIf(_) => {}
|
||||
// What lies beneath, blurred, is always a piece at the bottom of the content's own layer
|
||||
EffectOperation::BackgroundBlur { radius, box_blur, gamma } => {
|
||||
let Some((backdrop, placement)) = backdrop else { continue };
|
||||
let parameters = Parameters::placed_in_backdrop(placement);
|
||||
let mut seen = recorder.run("sample_backdrop", WORKING_FORMAT, recorder.size, backdrop, None, None, parameters);
|
||||
|
||||
let radius = radius * length_scale;
|
||||
if box_blur && radius > MAX_DIRECT_BOX_RADIUS {
|
||||
// Past the widest box blurred directly, a box sums running sums at the full radius everywhere, exact as the content's box blur is
|
||||
let every_pixel = Parameters { color: [1.; 4], ..Default::default() };
|
||||
let full_radius = recorder.run("flood", COVERAGE_FORMAT, recorder.size, &seen, None, None, every_pixel);
|
||||
let mut blurred = None;
|
||||
recorder.masked_box_blur(&seen, &mut blurred, &mut None, &full_radius, DVec2::splat(radius), !gamma, true);
|
||||
recorder.textures.release(full_radius);
|
||||
if let Some(blurred) = blurred {
|
||||
recorder.textures.release(std::mem::replace(&mut seen, blurred));
|
||||
}
|
||||
} else if radius >= NEGLIGIBLE_LENGTH {
|
||||
let kernel = if box_blur { BlurKernel::Box { radius } } else { BlurKernel::Gaussian { sigma: radius } };
|
||||
seen = recorder.blur(seen, kernel, !gamma);
|
||||
}
|
||||
pieces.insert(piece(0), seen);
|
||||
}
|
||||
EffectOperation::PaintOverlay { blend_mode, opacity, .. } => {
|
||||
let Some(paint) = paints.next() else { continue };
|
||||
let painted = recorder.scale(paint, (opacity / 100.) as f32);
|
||||
@@ -736,12 +799,24 @@ impl EffectPasses {
|
||||
let strength = recorder.mask_strength(mask, mode, density, mask_feather_sigma(feather) * length_scale, invert);
|
||||
capture_plane(&mut recorder, 0, &strength, false);
|
||||
|
||||
// Trailing masks fade every finished layer, what lies beneath in the content's own layer included, so only the others fade it here
|
||||
if layers.trailing_masks.contains(&index) {
|
||||
layer_fade = Some(recorder.faded_together(layer_fade.take(), strength));
|
||||
} else {
|
||||
recorder.merge_beneath(content, &mut full, &mut filled, beneath.take());
|
||||
recorder.fade_by(content, &mut full, &mut filled, &strength);
|
||||
recorder.textures.release(strength);
|
||||
masks_strength = match (backdrop.is_some(), masks_strength.take()) {
|
||||
(false, _) => {
|
||||
recorder.textures.release(strength);
|
||||
None
|
||||
}
|
||||
(true, None) => Some(strength),
|
||||
(true, Some(previous)) => {
|
||||
let combined = recorder.run("apply_mask", COVERAGE_FORMAT, recorder.size, &previous, Some(&strength), None, Parameters::default());
|
||||
[previous, strength].into_iter().for_each(|texture| recorder.textures.release(texture));
|
||||
Some(combined)
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
EffectOperation::Feather { distance } => {
|
||||
@@ -870,7 +945,7 @@ impl EffectPasses {
|
||||
let Some(frame) = &frame else { continue };
|
||||
let Some(screens) = HalftoneScreen::of(operation, frame) else { continue };
|
||||
|
||||
// Each texel's share of the content that the fill left fades the printed dots, rather than printing the faded content's fainter dots
|
||||
// Each texel's share of the content that the fill and the Blend Ifs left fades the printed dots, rather than printing the faded content's fainter dots
|
||||
recorder.merge_beneath(content, &mut full, &mut filled, beneath.take());
|
||||
let shares = (filled.as_ref()).map(|filled| {
|
||||
recorder.run(
|
||||
@@ -925,7 +1000,7 @@ impl EffectPasses {
|
||||
// The content at full strength is read only by an operation after the run, or shown as the result where no fill fades it
|
||||
let full_is_read = filled.is_none() || position + run.len() < operations.len();
|
||||
|
||||
let prepared_passes = recorder.textures.prepare_adjustments(device, queue, &run);
|
||||
let prepared_passes = recorder.textures.prepare_adjustments(recorder.executor, queue, &run);
|
||||
|
||||
// Each pass but the last hands its result on in the chained format, so splitting the run rounds nothing
|
||||
for (index, prepared) in prepared_passes.iter().enumerate() {
|
||||
@@ -953,7 +1028,7 @@ impl EffectPasses {
|
||||
}
|
||||
}
|
||||
if let Some(captured) = captured.take_if(|_| !capture_needs_content_layer) {
|
||||
let textures = [full, filled, beneath, layer_fade].into_iter().flatten().chain(pieces.into_values());
|
||||
let textures = [full, filled, beneath, layer_fade, blend_if_weight, masks_strength].into_iter().flatten().chain(pieces.into_values());
|
||||
textures.for_each(|texture| recorder.textures.release(texture));
|
||||
queue.submit([recorder.encoder.finish()]);
|
||||
return vec![(captured, BlendMode::Normal)];
|
||||
@@ -962,7 +1037,7 @@ impl EffectPasses {
|
||||
// A coverage the passes never reached, like that of a band too thin to draw at this resolution, covers nothing
|
||||
if capture.is_some_and(|capture| capture != EffectCapture::THROUGH_MASK) && captured.is_none() {
|
||||
let empty = recorder.scale(full.as_ref().unwrap_or(content), 0.);
|
||||
let textures = [full, filled, beneath, layer_fade].into_iter().flatten().chain(pieces.into_values());
|
||||
let textures = [full, filled, beneath, layer_fade, blend_if_weight, masks_strength].into_iter().flatten().chain(pieces.into_values());
|
||||
textures.for_each(|texture| recorder.textures.release(texture));
|
||||
queue.submit([recorder.encoder.finish()]);
|
||||
return vec![(empty, BlendMode::Normal)];
|
||||
@@ -995,7 +1070,7 @@ impl EffectPasses {
|
||||
PiecePlace::Within => 0.,
|
||||
PiecePlace::IntoContent { over: false } => 1.,
|
||||
PiecePlace::IntoContent { over: true } => 2.,
|
||||
PiecePlace::Beneath | PiecePlace::Through { .. } => continue,
|
||||
PiecePlace::Beneath | PiecePlace::Through { .. } | PiecePlace::Backdrop => continue,
|
||||
};
|
||||
let Some(tinted) = pieces.get(&piece.capture) else { continue };
|
||||
let parameters = Parameters {
|
||||
@@ -1031,7 +1106,10 @@ impl EffectPasses {
|
||||
// A coverage too small to draw, like an outline's band at a far zoom, covers nothing
|
||||
_ => recorder.run("flood", WORKING_FORMAT, recorder.size, full_content, None, None, Parameters::default()),
|
||||
};
|
||||
let textures = [full, Some(content_image), beneath, content_with_fade, layer_fade].into_iter().flatten().chain(pieces.into_values());
|
||||
let textures = [full, Some(content_image), beneath, content_with_fade, layer_fade, blend_if_weight, masks_strength]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.chain(pieces.into_values());
|
||||
textures.for_each(|texture| recorder.textures.release(texture));
|
||||
queue.submit([recorder.encoder.finish()]);
|
||||
return vec![(output, BlendMode::Normal)];
|
||||
@@ -1057,6 +1135,7 @@ impl EffectPasses {
|
||||
for (index, layer) in layers.layers.iter().enumerate() {
|
||||
let holds_content = Some(index) == content_layer;
|
||||
let mut stack = if holds_content { beneath.take() } else { None };
|
||||
let mut backdrop_stack: Option<wgpu::Texture> = None;
|
||||
|
||||
for part in &layer.parts {
|
||||
let LayerPart::Piece(part_piece) = part else { continue };
|
||||
@@ -1083,6 +1162,12 @@ impl EffectPasses {
|
||||
};
|
||||
recorder.run("through_mask", WORKING_FORMAT, recorder.size, tinted, Some(content_image), Some(fading_content), parameters)
|
||||
}),
|
||||
PiecePlace::Backdrop => {
|
||||
if let Some(tinted) = pieces.remove(&part_piece.capture) {
|
||||
backdrop_stack = Some(recorder.stack_over(backdrop_stack, tinted));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
PiecePlace::Within | PiecePlace::IntoContent { .. } => continue,
|
||||
};
|
||||
if let Some(upper) = upper {
|
||||
@@ -1090,13 +1175,26 @@ impl EffectPasses {
|
||||
}
|
||||
}
|
||||
|
||||
// What lies beneath, filtered and cut to the content's own silhouette before its effects and by its masks, goes beneath everything else in the layer
|
||||
let backdrop_stack = backdrop_stack.map(|backdrop_stack| {
|
||||
let cut = recorder.run("mask_within", WORKING_FORMAT, recorder.size, &backdrop_stack, None, Some(content), Parameters::default());
|
||||
recorder.textures.release(backdrop_stack);
|
||||
let Some(strength) = &masks_strength else { return cut };
|
||||
|
||||
let masked = recorder.run("apply_mask", WORKING_FORMAT, recorder.size, &cut, Some(strength), None, Parameters::default());
|
||||
recorder.textures.release(cut);
|
||||
masked
|
||||
});
|
||||
let image = match (holds_content, read_after) {
|
||||
(true, true) => content_image.as_ref().map(|image| recorder.scale(image, 1.)),
|
||||
(true, false) => content_image.take(),
|
||||
(false, _) => None,
|
||||
};
|
||||
let Some(mut result) = image.map(|image| recorder.stack_over(stack.take(), image)).or(stack) else {
|
||||
continue;
|
||||
let result = image.map(|image| recorder.stack_over(stack.take(), image)).or(stack);
|
||||
let mut result = match (result, backdrop_stack) {
|
||||
(Some(result), backdrop_stack) => recorder.stack_over(backdrop_stack, result),
|
||||
(None, Some(backdrop_stack)) => backdrop_stack,
|
||||
(None, None) => continue,
|
||||
};
|
||||
if let Some(fade) = &layer_fade {
|
||||
let faded = recorder.run("apply_mask", WORKING_FORMAT, recorder.size, &result, Some(fade), None, Parameters::default());
|
||||
@@ -1105,7 +1203,16 @@ impl EffectPasses {
|
||||
results.push((result, layer.blend_mode));
|
||||
}
|
||||
|
||||
let textures = [full, content_image, beneath, content_with_fade, layer_fade].into_iter().flatten().chain(pieces.into_values());
|
||||
// Blend If's ranges of what lies beneath fade every layer, like the opacity varying across them
|
||||
let underlying = underlying_ranges(&every_operation);
|
||||
if let Some(backdrop) = backdrop.filter(|_| !underlying.is_empty()) {
|
||||
recorder.blend_if_underlying(&underlying, backdrop, &mut results);
|
||||
}
|
||||
|
||||
let textures = [full, content_image, beneath, content_with_fade, layer_fade, blend_if_weight, masks_strength]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.chain(pieces.into_values());
|
||||
textures.for_each(|texture| recorder.textures.release(texture));
|
||||
queue.submit([recorder.encoder.finish()]);
|
||||
results
|
||||
@@ -1117,7 +1224,7 @@ impl EffectPasses {
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
pub(crate) fn adjust_image(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
executor: &WgpuExecutor,
|
||||
queue: &wgpu::Queue,
|
||||
textures: &mut EffectTextures,
|
||||
image: &wgpu::Texture,
|
||||
@@ -1126,8 +1233,10 @@ impl EffectPasses {
|
||||
target: &wgpu::Texture,
|
||||
) {
|
||||
let size = UVec2::new(image.width(), image.height());
|
||||
let device = &executor.context().device;
|
||||
let mut recorder = PassRecorder {
|
||||
passes: self,
|
||||
executor,
|
||||
device,
|
||||
queue,
|
||||
encoder: device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||
@@ -1159,19 +1268,20 @@ impl EffectPasses {
|
||||
}
|
||||
chained.into_iter().for_each(|texture| recorder.textures.release(texture));
|
||||
|
||||
self.record_mipmaps(device, &mut recorder.encoder, recorder.textures, target);
|
||||
self.record_mipmaps(executor, &mut recorder.encoder, recorder.textures, target);
|
||||
queue.submit([recorder.encoder.finish()]);
|
||||
}
|
||||
|
||||
/// Records the averaging of each of `texture`'s smaller mip levels from the one above it, like the levels of an uploaded image.
|
||||
/// Each is halved into a pooled texture and copied into place, since WebGL sets the levels read for a whole texture, so none is drawn into while another is read.
|
||||
pub(crate) fn record_mipmaps(&self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, textures: &mut EffectTextures, texture: &wgpu::Texture) {
|
||||
pub(crate) fn record_mipmaps(&self, executor: &WgpuExecutor, encoder: &mut wgpu::CommandEncoder, textures: &mut EffectTextures, texture: &wgpu::Texture) {
|
||||
let device = &executor.context().device;
|
||||
let format = texture.format();
|
||||
let mut above: Option<wgpu::Texture> = None;
|
||||
|
||||
for index in 1..texture.mip_level_count() {
|
||||
let level_size = UVec2::new(texture.width() >> index, texture.height() >> index).max(UVec2::ONE);
|
||||
let level = textures.acquire(device, level_size, format);
|
||||
let level = textures.acquire(executor, level_size, format);
|
||||
|
||||
// The first level reads the top one through a view of every level
|
||||
let source = above.as_ref().unwrap_or(texture).create_view(&wgpu::TextureViewDescriptor::default());
|
||||
@@ -1324,6 +1434,7 @@ fn premultiplied_gamma_channels(color: Color) -> [f32; 4] {
|
||||
/// Records the passes of one effects group, whose images all share one size.
|
||||
struct PassRecorder<'a> {
|
||||
passes: &'a EffectPasses,
|
||||
executor: &'a WgpuExecutor,
|
||||
device: &'a wgpu::Device,
|
||||
queue: &'a wgpu::Queue,
|
||||
encoder: wgpu::CommandEncoder,
|
||||
@@ -1344,7 +1455,7 @@ impl PassRecorder<'_> {
|
||||
content: Option<&wgpu::Texture>,
|
||||
parameters: Parameters,
|
||||
) -> wgpu::Texture {
|
||||
let target = self.textures.acquire(self.device, size, format);
|
||||
let target = self.textures.acquire(self.executor, size, format);
|
||||
|
||||
let view = |texture: &wgpu::Texture| texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let (source, secondary, content) = (view(source), secondary.map(view), content.map(view));
|
||||
@@ -1492,7 +1603,7 @@ impl PassRecorder<'_> {
|
||||
fn gradient_glow_tint(&mut self, paint: &GlowFill, strength: &wgpu::Texture, content: &wgpu::Texture, fades: bool, grain: Option<&styles::GlowGrain>) -> Option<wgpu::Texture> {
|
||||
let (samples, opacity) = paint.gradient_samples(GRADIENT_SAMPLES as usize)?;
|
||||
let samples: Vec<half::f16> = samples.into_iter().flatten().map(half::f16::from_f32).collect();
|
||||
let samples = self.row_texture("vello_effects_gradient", wgpu::TextureFormat::Rgba16Float, GRADIENT_SAMPLES, bytemuck::cast_slice(&samples));
|
||||
let samples = self.row_texture(wgpu::TextureFormat::Rgba16Float, GRADIENT_SAMPLES, bytemuck::cast_slice(&samples));
|
||||
|
||||
let parameters = Parameters {
|
||||
values: [if fades { 1. } else { 0. }, GRADIENT_GLOW_FADE as f32, opacity, grain.map_or(0., |grain| grain.amounts[0] as f32)],
|
||||
@@ -1547,27 +1658,17 @@ impl PassRecorder<'_> {
|
||||
let samples: Vec<half::f16> = (0..CONTOUR_SAMPLES)
|
||||
.map(|index| half::f16::from_f64(contour.evaluate(index as f64 / (CONTOUR_SAMPLES - 1) as f64).clamp(0., 1.)))
|
||||
.collect();
|
||||
self.row_texture("vello_effects_contour", COVERAGE_FORMAT, CONTOUR_SAMPLES, bytemuck::cast_slice(&samples))
|
||||
self.row_texture(COVERAGE_FORMAT, CONTOUR_SAMPLES, bytemuck::cast_slice(&samples))
|
||||
}
|
||||
|
||||
/// A texture one row of `width` texels tall holding `data` in the `format`, for shaders to interpolate between its samples.
|
||||
/// It's made fresh rather than pooled, since its upload runs ahead of the passes recorded before it that a pooled texture may still serve.
|
||||
fn row_texture(&mut self, label: &str, format: wgpu::TextureFormat, width: u32, data: &[u8]) -> wgpu::Texture {
|
||||
fn row_texture(&mut self, format: wgpu::TextureFormat, width: u32, data: &[u8]) -> wgpu::Texture {
|
||||
let extent = wgpu::Extent3d {
|
||||
width,
|
||||
height: 1,
|
||||
depth_or_array_layers: 1,
|
||||
};
|
||||
let texture = self.device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some(label),
|
||||
size: extent,
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[],
|
||||
});
|
||||
let texture = self.executor.request_texture_with_format(UVec2::new(width, 1), format);
|
||||
self.queue.write_texture(
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
texture: &texture,
|
||||
@@ -1583,16 +1684,22 @@ impl PassRecorder<'_> {
|
||||
},
|
||||
extent,
|
||||
);
|
||||
texture
|
||||
let row = (*texture).clone();
|
||||
self.textures.held.push(texture);
|
||||
row
|
||||
}
|
||||
|
||||
/// The coverage (or tinted image) of what lies beneath, hidden behind the full-strength content where a `fill` below 1 fades the content that shows over it.
|
||||
fn knock_out(&mut self, coverage: wgpu::Texture, full_content: &wgpu::Texture, fill: f32) -> wgpu::Texture {
|
||||
if fill >= 1. {
|
||||
/// The coverage (or tinted image) of what lies beneath, hidden behind the full-strength content where a `fill` below 1 (times the Blend If weight if any) fades the content that shows over it.
|
||||
fn knock_out(&mut self, coverage: wgpu::Texture, full_content: &wgpu::Texture, fill: f32, blend_if_weight: Option<&wgpu::Texture>) -> wgpu::Texture {
|
||||
if fill >= 1. && blend_if_weight.is_none() {
|
||||
return coverage;
|
||||
}
|
||||
let parameters = Parameters { amount: fill, ..Default::default() };
|
||||
let knocked_out = self.run("knock_out", coverage.format(), self.size, &coverage, None, Some(full_content), parameters);
|
||||
let parameters = Parameters {
|
||||
amount: fill,
|
||||
values: [if blend_if_weight.is_some() { 1. } else { 0. }, 0., 0., 0.],
|
||||
..Default::default()
|
||||
};
|
||||
let knocked_out = self.run("knock_out", coverage.format(), self.size, &coverage, blend_if_weight, Some(full_content), parameters);
|
||||
self.textures.release(coverage);
|
||||
knocked_out
|
||||
}
|
||||
@@ -1788,7 +1895,7 @@ impl PassRecorder<'_> {
|
||||
/// The image (of any format a shader can load from) with a pass of adjustments carried out on it into a texture of `format`, reading what was `prepared` for the pass,
|
||||
/// in the `encodings` of its source and result.
|
||||
fn adjust(&mut self, image: &wgpu::Texture, prepared: &PreparedPass, format: wgpu::TextureFormat, encodings: PassEncodings) -> wgpu::Texture {
|
||||
let target = self.textures.acquire(self.device, self.size, format);
|
||||
let target = self.textures.acquire(self.executor, self.size, format);
|
||||
|
||||
let view = |texture: &wgpu::Texture| texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
self.adjust_into(&view(&target), format, &view(image), prepared, encodings);
|
||||
@@ -1884,11 +1991,11 @@ impl PassRecorder<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Textures for the effect passes and the content they work on, kept between renders for reuse at the same sizes.
|
||||
/// Textures for the effect passes and the content they work on, taken from the texture pool and held until the render ends.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct EffectTextures {
|
||||
/// Each unused texture with the render it was last used in.
|
||||
free: Vec<(wgpu::Texture, u64)>,
|
||||
held: Vec<Texture>,
|
||||
released: Vec<wgpu::Texture>,
|
||||
/// The uploads of recent runs of adjustments.
|
||||
adjustments: AdjustmentUploads,
|
||||
render_count: u64,
|
||||
@@ -1899,43 +2006,32 @@ pub(crate) struct EffectTextures {
|
||||
|
||||
impl EffectTextures {
|
||||
/// What each pass carrying out a run of adjustments reads, as [`AdjustmentUploads::prepare`] gives it.
|
||||
pub(crate) fn prepare_adjustments(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, run: &[&Adjustment]) -> Vec<PreparedPass> {
|
||||
self.adjustments.prepare(device, queue, run, self.render_count)
|
||||
pub(crate) fn prepare_adjustments(&mut self, executor: &WgpuExecutor, queue: &wgpu::Queue, run: &[&Adjustment]) -> Vec<PreparedPass> {
|
||||
self.adjustments.prepare(executor, queue, run, self.render_count, &mut self.held)
|
||||
}
|
||||
|
||||
pub(crate) fn acquire(&mut self, device: &wgpu::Device, size: UVec2, format: wgpu::TextureFormat) -> wgpu::Texture {
|
||||
pub(crate) fn acquire(&mut self, executor: &WgpuExecutor, size: UVec2, format: wgpu::TextureFormat) -> wgpu::Texture {
|
||||
let size = size.max(UVec2::ONE);
|
||||
let matches = |texture: &wgpu::Texture| texture.width() == size.x && texture.height() == size.y && texture.format() == format;
|
||||
if let Some(index) = self.free.iter().position(|(texture, _)| matches(texture)) {
|
||||
return self.free.swap_remove(index).0;
|
||||
if let Some(index) = self.released.iter().position(matches) {
|
||||
return self.released.swap_remove(index);
|
||||
}
|
||||
|
||||
device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("vello_effects_texture"),
|
||||
size: wgpu::Extent3d {
|
||||
width: size.x,
|
||||
height: size.y,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format,
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[],
|
||||
})
|
||||
let texture = executor.request_texture_with_format(size, format);
|
||||
let acquired = (*texture).clone();
|
||||
self.held.push(texture);
|
||||
acquired
|
||||
}
|
||||
|
||||
/// Returns a texture to the pool once the passes recorded so far are done with it, since later passes are recorded and submitted after them.
|
||||
pub(crate) fn release(&mut self, texture: wgpu::Texture) {
|
||||
self.free.push((texture, self.render_count));
|
||||
self.released.push(texture);
|
||||
}
|
||||
|
||||
/// Frees the textures no recent render has used.
|
||||
pub(crate) fn finish_render(&mut self) {
|
||||
let render_count = self.render_count;
|
||||
self.free.retain(|(_, last_used)| render_count - last_used < UNUSED_TEXTURE_RENDER_LIMIT);
|
||||
self.adjustments.finish_render(render_count);
|
||||
self.released.clear();
|
||||
self.held.clear();
|
||||
self.adjustments.finish_render(self.render_count);
|
||||
|
||||
self.render_count += 1;
|
||||
}
|
||||
@@ -1978,7 +2074,10 @@ mod tests {
|
||||
use core_types::list::Item;
|
||||
use graphic_types::vector_types::Gradient;
|
||||
|
||||
let Some(context) = futures::executor::block_on(crate::WgpuContext::for_tests()) else { return };
|
||||
let Some(executor) = futures::executor::block_on(crate::WgpuContext::for_tests()).and_then(crate::WgpuExecutor::with_context) else {
|
||||
return;
|
||||
};
|
||||
let context = executor.context();
|
||||
let passes = EffectPasses::new(&context.device, &context.adapter);
|
||||
if !passes.renders_working_formats {
|
||||
return;
|
||||
@@ -2016,12 +2115,12 @@ mod tests {
|
||||
let effects = Effects::from_operations(operations);
|
||||
|
||||
let mut textures = EffectTextures::default();
|
||||
let content = textures.acquire(&context.device, UVec2::splat(16), wgpu::TextureFormat::Rgba8Unorm);
|
||||
let content = textures.acquire(&executor, UVec2::splat(16), wgpu::TextureFormat::Rgba8Unorm);
|
||||
let queue = context.queue.lock();
|
||||
let apply = |textures: &mut EffectTextures, effects: &Effects| {
|
||||
textures.drawn_passes.clear();
|
||||
let layers = EffectLayers::plan(effects, BlendMode::Normal, 1., false);
|
||||
let results = passes.apply(&context.device, &queue, textures, &content, effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None);
|
||||
let results = passes.apply(&executor, &queue, textures, &content, effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None, None);
|
||||
results.into_iter().for_each(|(result, _)| textures.release(result));
|
||||
};
|
||||
let draw = |textures: &mut EffectTextures| {
|
||||
@@ -2043,7 +2142,7 @@ mod tests {
|
||||
textures.drawn_passes.clear();
|
||||
let effects = Effects::from_operations(operations);
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, fill, false);
|
||||
let results = passes.apply(&context.device, &queue, &mut textures, &content, &effects, &layers, fill, 1., DAffine2::IDENTITY, None, &[], None);
|
||||
let results = passes.apply(&executor, &queue, &mut textures, &content, &effects, &layers, fill, 1., DAffine2::IDENTITY, None, &[], None, None);
|
||||
results.into_iter().for_each(|(result, _)| textures.release(result));
|
||||
textures.drawn_passes.clone()
|
||||
};
|
||||
@@ -2074,7 +2173,10 @@ mod tests {
|
||||
fn effects_blending_normally_at_a_full_fill_take_no_more_passes_when_layered() {
|
||||
use graphic_types::effects::EffectKind;
|
||||
|
||||
let Some(context) = futures::executor::block_on(crate::WgpuContext::for_tests()) else { return };
|
||||
let Some(executor) = futures::executor::block_on(crate::WgpuContext::for_tests()).and_then(crate::WgpuExecutor::with_context) else {
|
||||
return;
|
||||
};
|
||||
let context = executor.context();
|
||||
let passes = EffectPasses::new(&context.device, &context.adapter);
|
||||
if !passes.renders_working_formats {
|
||||
return;
|
||||
@@ -2082,12 +2184,12 @@ mod tests {
|
||||
|
||||
let effects = Effects::from_operations([EffectOperation::default_for(EffectKind::DropShadow), EffectOperation::default_for(EffectKind::InnerShadow)]);
|
||||
let mut textures = EffectTextures::default();
|
||||
let content = textures.acquire(&context.device, UVec2::splat(16), wgpu::TextureFormat::Rgba8Unorm);
|
||||
let content = textures.acquire(&executor, UVec2::splat(16), wgpu::TextureFormat::Rgba8Unorm);
|
||||
let queue = context.queue.lock();
|
||||
let mut drawn = |layered: bool| {
|
||||
textures.drawn_passes.clear();
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., layered);
|
||||
let results = passes.apply(&context.device, &queue, &mut textures, &content, &effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None);
|
||||
let results = passes.apply(&executor, &queue, &mut textures, &content, &effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None, None);
|
||||
results.into_iter().for_each(|(result, _)| textures.release(result));
|
||||
textures.drawn_passes.clone()
|
||||
};
|
||||
@@ -2098,7 +2200,10 @@ mod tests {
|
||||
fn a_bevel_without_a_gloss_contour_or_texture_lights_its_highlight_and_shadow_directly() {
|
||||
use graphic_types::effects::EffectKind;
|
||||
|
||||
let Some(context) = futures::executor::block_on(crate::WgpuContext::for_tests()) else { return };
|
||||
let Some(executor) = futures::executor::block_on(crate::WgpuContext::for_tests()).and_then(crate::WgpuExecutor::with_context) else {
|
||||
return;
|
||||
};
|
||||
let context = executor.context();
|
||||
let passes = EffectPasses::new(&context.device, &context.adapter);
|
||||
if !passes.renders_working_formats {
|
||||
return;
|
||||
@@ -2106,10 +2211,10 @@ mod tests {
|
||||
|
||||
let effects = Effects::from_operations([EffectOperation::default_for(EffectKind::BevelAndEmboss)]);
|
||||
let mut textures = EffectTextures::default();
|
||||
let content = textures.acquire(&context.device, UVec2::splat(16), wgpu::TextureFormat::Rgba8Unorm);
|
||||
let content = textures.acquire(&executor, UVec2::splat(16), wgpu::TextureFormat::Rgba8Unorm);
|
||||
let queue = context.queue.lock();
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., false);
|
||||
let results = passes.apply(&context.device, &queue, &mut textures, &content, &effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None);
|
||||
let results = passes.apply(&executor, &queue, &mut textures, &content, &effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None, None);
|
||||
results.into_iter().for_each(|(result, _)| textures.release(result));
|
||||
|
||||
let drawn = |label: &str| textures.drawn_passes.iter().filter(|&&drawn| drawn == label).count();
|
||||
@@ -2118,7 +2223,10 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn a_table_stays_uploaded_while_the_settings_beside_it_change() {
|
||||
let Some(context) = futures::executor::block_on(crate::WgpuContext::for_tests()) else { return };
|
||||
let Some(executor) = futures::executor::block_on(crate::WgpuContext::for_tests()).and_then(crate::WgpuExecutor::with_context) else {
|
||||
return;
|
||||
};
|
||||
let context = executor.context();
|
||||
let queue = context.queue.lock();
|
||||
|
||||
let lookup = Adjustment::ColorLookup {
|
||||
@@ -2128,7 +2236,7 @@ mod tests {
|
||||
let prepare = |textures: &mut EffectTextures, posterize_levels| {
|
||||
let posterize = Adjustment::Posterize { levels: posterize_levels };
|
||||
// Color Lookup's pass and then Posterize's, which share the run's tables
|
||||
let mut prepared = textures.prepare_adjustments(&context.device, &queue, &[&lookup, &posterize]);
|
||||
let mut prepared = textures.prepare_adjustments(&executor, &queue, &[&lookup, &posterize]);
|
||||
prepared.pop().map(|prepared| (prepared.steps, prepared.tables))
|
||||
};
|
||||
|
||||
@@ -2140,11 +2248,13 @@ mod tests {
|
||||
panic!("The run reads its table")
|
||||
};
|
||||
assert!(first_steps == again_steps && first_table == again_table);
|
||||
let Some((other_steps, _)) = prepare(&mut textures, 5) else { panic!("The run reads its table") };
|
||||
assert!(other_steps != first_steps);
|
||||
for levels in 5..20 {
|
||||
let Some((steps, Some(table))) = prepare(&mut textures, levels) else {
|
||||
let Some((_, Some(table))) = prepare(&mut textures, levels) else {
|
||||
panic!("The run reads its table")
|
||||
};
|
||||
assert!(steps != first_steps && table == first_table);
|
||||
assert!(table == first_table);
|
||||
textures.finish_render();
|
||||
}
|
||||
|
||||
|
||||
@@ -3,9 +3,9 @@
|
||||
struct Parameters {
|
||||
// Converts a target pixel's position into the normalized coordinates the inputs are sampled at
|
||||
target_to_uv: vec2<f32>,
|
||||
// One step along the axis a kernel runs, in normalized coordinates
|
||||
// One step along the axis a kernel runs, in normalized coordinates, or values described where a pass reads them
|
||||
step: vec2<f32>,
|
||||
// How far a silhouette is cast, in normalized coordinates
|
||||
// How far a silhouette is cast, in normalized coordinates, or values described where a pass reads them
|
||||
offset: vec2<f32>,
|
||||
// A pass's scalar setting, like a scale factor, fill, opacity, or knockout cover, described where it reads it
|
||||
amount: f32,
|
||||
@@ -306,13 +306,17 @@ fn tint(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
return parameters.color * textureLoad(source, vec2<i32>(position.xy), 0).r;
|
||||
}
|
||||
|
||||
// Hides the coverage of what lies beneath behind the `content` at full strength, where the fill `amount` fades the content showing over it.
|
||||
// Hides the coverage of what lies beneath behind the `content` at full strength, where the fill `amount` (times the Blend If weight in `secondary`, with `values.x` 1) fades the content showing over it.
|
||||
// The faded content shows what's beneath through 1 - fill × alpha of it, of which only 1 - alpha may show this.
|
||||
@fragment
|
||||
fn knock_out(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let pixel = vec2<i32>(position.xy);
|
||||
let alpha = textureLoad(content, pixel, 0).a;
|
||||
let shown = (1. - alpha) / max(1. - parameters.amount * alpha, 1e-6);
|
||||
var fill = parameters.amount;
|
||||
if parameters.values.x > 0.5 {
|
||||
fill *= textureLoad(secondary, pixel, 0).r;
|
||||
}
|
||||
let shown = (1. - alpha) / max(1. - fill * alpha, 1e-6);
|
||||
return textureLoad(source, pixel, 0) * shown;
|
||||
}
|
||||
|
||||
@@ -680,6 +684,17 @@ fn flood(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
return parameters.color;
|
||||
}
|
||||
|
||||
// Where a pixel at `position` lands in the scene's backdrop, in its pixels, placed by the linear map with the columns `step` and `offset`, then moved by `values.xy`
|
||||
fn backdrop_point(position: vec2<f32>) -> vec2<f32> {
|
||||
return parameters.values.xy + mat2x2<f32>(parameters.step, parameters.offset) * position;
|
||||
}
|
||||
|
||||
// What lies beneath the content, sampled from the scene's backdrop (`source`) where each pixel lands
|
||||
@fragment
|
||||
fn sample_backdrop(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
return textureSampleLevel(source, linear_sampler, backdrop_point(position.xy) / vec2<f32>(textureDimensions(source)), 0.);
|
||||
}
|
||||
|
||||
// A tinted image cut to the full-strength `content`, for a piece within the content drawn in a layer of its own
|
||||
@fragment
|
||||
fn mask_within(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
//! Blend If's GPU passes, which fade the content by its own colors and every layer by the colors of what lies beneath, matching the CPU's and the SVG filters' weights.
|
||||
|
||||
use super::{COVERAGE_FORMAT, PARAMETER_TAPS, Parameters, PassRecorder, WORKING_FORMAT};
|
||||
use core_types::blending::BlendMode;
|
||||
use graphic_types::blend_if::ChannelRanges;
|
||||
use vello_gpu::kurbo::Affine;
|
||||
|
||||
/// The ranges in the shader's first four taps, gray, red, green, and blue, each its falloff start, range start, range end, and falloff end from 0 to 1.
|
||||
fn range_taps(ranges: &ChannelRanges) -> [[f32; 4]; PARAMETER_TAPS] {
|
||||
let mut taps = [[0.; 4]; PARAMETER_TAPS];
|
||||
for (tap, (_, range)) in taps.iter_mut().zip(ranges.channels()) {
|
||||
*tap = [range.falloff_start, range.range_start, range.range_end, range.falloff_end].map(|percent| (percent / 100.) as f32);
|
||||
}
|
||||
taps
|
||||
}
|
||||
|
||||
impl PassRecorder<'_> {
|
||||
/// Fades the content's image (`filled`, or a copy of `full` if the fill fades nothing) by how strongly the `ranges` show the colors of `full`.
|
||||
/// Returns that weight times the `weight` so far, which the knockouts hide what's beneath behind.
|
||||
pub(super) fn blend_if_content(&mut self, ranges: &ChannelRanges, full: &wgpu::Texture, filled: &mut Option<wgpu::Texture>, weight: Option<wgpu::Texture>) -> wgpu::Texture {
|
||||
let parameters = Parameters {
|
||||
taps: range_taps(ranges),
|
||||
..Default::default()
|
||||
};
|
||||
let shown = self.run("blend_if_content_weight", COVERAGE_FORMAT, self.size, full, None, None, parameters);
|
||||
|
||||
let faded = self.run("blend_if_fade", WORKING_FORMAT, self.size, filled.as_ref().unwrap_or(full), Some(&shown), None, Parameters::default());
|
||||
self.replace_or_fill(filled, faded);
|
||||
|
||||
let Some(weight) = weight else { return shown };
|
||||
let combined = self.run("blend_if_fade", COVERAGE_FORMAT, self.size, &weight, Some(&shown), None, Parameters::default());
|
||||
self.textures.release(weight);
|
||||
self.textures.release(shown);
|
||||
combined
|
||||
}
|
||||
|
||||
/// Fades each layer's image in `results` by how strongly the `underlying` ranges, which multiply, show what lies beneath each pixel in the scene's `backdrop`.
|
||||
/// The backdrop's placement maps the layers' pixels into it.
|
||||
pub(super) fn blend_if_underlying(&mut self, underlying: &[ChannelRanges], (backdrop, placement): (&wgpu::Texture, Affine), results: &mut [(wgpu::Texture, BlendMode)]) {
|
||||
let placed = Parameters::placed_in_backdrop(placement);
|
||||
let [x, y, ..] = placed.values;
|
||||
|
||||
// Each range multiplies the weight before it, and the last eases it to full where nothing lies beneath
|
||||
let mut weight: Option<wgpu::Texture> = None;
|
||||
for (index, ranges) in underlying.iter().enumerate() {
|
||||
let flag = |set: bool| if set { 1. } else { 0. };
|
||||
let parameters = Parameters {
|
||||
values: [x, y, flag(weight.is_some()), flag(index + 1 == underlying.len())],
|
||||
taps: range_taps(ranges),
|
||||
..placed
|
||||
};
|
||||
let next = self.run("blend_if_underlying_weight", COVERAGE_FORMAT, self.size, backdrop, weight.as_ref(), None, parameters);
|
||||
self.replace_or_fill(&mut weight, next);
|
||||
}
|
||||
let Some(weight) = weight else { return };
|
||||
|
||||
for (image, _) in results {
|
||||
let faded = self.run("blend_if_fade", WORKING_FORMAT, self.size, image, Some(&weight), None, Parameters::default());
|
||||
self.replace(image, faded);
|
||||
}
|
||||
self.textures.release(weight);
|
||||
}
|
||||
}
|
||||
@@ -9,11 +9,11 @@ impl PassRecorder<'_> {
|
||||
/// How much the `mask` graphic's texture shows the content at each pixel, from 0 to 1, matching the CPU's `mask_strength`.
|
||||
/// Its coverage is softened by a Gaussian of standard deviation `sigma` in pixels, then mapped through its `density` percentage, flipped if `invert`.
|
||||
pub(super) fn mask_strength(&mut self, mask: &wgpu::Texture, mode: MaskMode, density: f64, sigma: f64, invert: bool) -> wgpu::Texture {
|
||||
let mode = Parameters {
|
||||
values: [if mode == MaskMode::Alpha { 1. } else { 0. }, 0., 0., 0.],
|
||||
let weights = Parameters {
|
||||
values: mode.channel_weights(),
|
||||
..Default::default()
|
||||
};
|
||||
let mut coverage = self.run("mask_coverage", COVERAGE_FORMAT, self.size, mask, None, None, mode);
|
||||
let mut coverage = self.run("mask_coverage", COVERAGE_FORMAT, self.size, mask, None, None, weights);
|
||||
|
||||
if sigma >= NEGLIGIBLE_LENGTH {
|
||||
coverage = self.blur(coverage, BlurKernel::Gaussian { sigma }, false);
|
||||
@@ -86,7 +86,7 @@ impl PassRecorder<'_> {
|
||||
})
|
||||
.map(half::f16::from_f32)
|
||||
.collect();
|
||||
let table = self.row_texture("vello_effects_masked_radius_blur", wgpu::TextureFormat::Rgba16Float, 256, bytemuck::cast_slice(&blends));
|
||||
let table = self.row_texture(wgpu::TextureFormat::Rgba16Float, 256, bytemuck::cast_slice(&blends));
|
||||
let interpolation = self.run("masked_radius_blur_interpolation", WORKING_FORMAT, self.size, luminance, Some(&table), None, Parameters::default());
|
||||
|
||||
if full_is_read && let Some(blurred) = self.masked_radius_blur_image(full.as_ref().unwrap_or(content), &interpolation, levels, linear) {
|
||||
|
||||
@@ -74,7 +74,7 @@ impl PassRecorder<'_> {
|
||||
return band;
|
||||
};
|
||||
let samples: Vec<half::f16> = samples.into_iter().flatten().map(half::f16::from_f32).collect();
|
||||
let samples = self.row_texture("vello_effects_gradient", wgpu::TextureFormat::Rgba16Float, GRADIENT_SAMPLES, bytemuck::cast_slice(&samples));
|
||||
let samples = self.row_texture(wgpu::TextureFormat::Rgba16Float, GRADIENT_SAMPLES, bytemuck::cast_slice(&samples));
|
||||
|
||||
let parameters = Parameters {
|
||||
amount: opacity,
|
||||
|
||||
@@ -40,7 +40,7 @@ impl PassRecorder<'_> {
|
||||
let vertices = 12 * (columns + rows) + 24 + 6 * columns * rows;
|
||||
|
||||
let format = texture.format();
|
||||
let warped = self.textures.acquire(self.device, self.size, format);
|
||||
let warped = self.textures.acquire(self.executor, self.size, format);
|
||||
let view = |texture: &wgpu::Texture| texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let reading = self.passes.bind_group(self.device, self.size, &view(&texture), None, None, parameters);
|
||||
let mesh = (self.passes).pipeline_with(self.device, "warp_vertex", "warp_effect", format, Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING));
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
//! The GPU pass that renders tiles of generators' patterns, matching the CPU's renders of them.
|
||||
|
||||
use crate::WgpuExecutor;
|
||||
use crate::vello_render::TEXTURE_FORMAT;
|
||||
use bytemuck::{Pod, Zeroable};
|
||||
use glam::DVec2;
|
||||
use glam::{DVec2, UVec2};
|
||||
use graphic_types::generator::{
|
||||
CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, GeneratorPattern, MandelbrotExterior, MandelbrotFractal, MandelbrotInterior, NoiseSettings, NoiseType,
|
||||
};
|
||||
use raster_kernels::mandelbrot::{MandelbrotSetup, ReferenceOrbit, resolves_in_32_bits};
|
||||
use raster_types::Texture;
|
||||
use std::iter::zip;
|
||||
use std::sync::OnceLock;
|
||||
use wgpu::util::DeviceExt;
|
||||
@@ -270,7 +272,7 @@ impl Tile {
|
||||
}
|
||||
|
||||
/// The texture holding a reference orbit's values and their raisings for the Mandelbrot shader, in rows of `REFERENCE_ROW_LENGTH`, or one empty texel without one.
|
||||
fn reference_texture(device: &wgpu::Device, queue: &wgpu::Queue, reference: Option<&ReferenceOrbit>) -> wgpu::Texture {
|
||||
fn reference_texture(executor: &WgpuExecutor, queue: &wgpu::Queue, reference: Option<&ReferenceOrbit>) -> Texture {
|
||||
let (values, raised_values) = reference.map_or((&[][..], &[][..]), |reference| (&reference.values[..], &reference.raised_values[..]));
|
||||
let (width, height) = (values.len().clamp(1, REFERENCE_ROW_LENGTH), values.len().div_ceil(REFERENCE_ROW_LENGTH).max(1));
|
||||
|
||||
@@ -279,25 +281,18 @@ fn reference_texture(device: &wgpu::Device, queue: &wgpu::Queue, reference: Opti
|
||||
*texel = [value.x, value.y, raised.x, raised.y];
|
||||
}
|
||||
|
||||
device.create_texture_with_data(
|
||||
queue,
|
||||
&wgpu::TextureDescriptor {
|
||||
label: Some("vello_generator_reference_orbit"),
|
||||
size: wgpu::Extent3d {
|
||||
width: width as u32,
|
||||
height: height as u32,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu::TextureFormat::Rgba32Float,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING,
|
||||
view_formats: &[],
|
||||
},
|
||||
wgpu::util::TextureDataOrder::LayerMajor,
|
||||
let texture = executor.request_texture_with_format(UVec2::new(width as u32, height as u32), wgpu::TextureFormat::Rgba32Float);
|
||||
queue.write_texture(
|
||||
texture.as_image_copy(),
|
||||
bytemuck::cast_slice(&texels),
|
||||
)
|
||||
wgpu::TexelCopyBufferLayout {
|
||||
offset: 0,
|
||||
bytes_per_row: Some(width as u32 * size_of::<[f32; 4]>() as u32),
|
||||
rows_per_image: Some(height as u32),
|
||||
},
|
||||
texture.size(),
|
||||
);
|
||||
texture
|
||||
}
|
||||
|
||||
/// The pipelines of the pass, one for each shader.
|
||||
@@ -386,26 +381,24 @@ impl GeneratorPasses {
|
||||
}
|
||||
|
||||
/// A texture for square tiles `pixels` across to be rendered into, with the mip levels they're drawn from.
|
||||
pub(crate) fn tile_texture(device: &wgpu::Device, pixels: u32) -> wgpu::Texture {
|
||||
device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("vello_generator_tile"),
|
||||
size: wgpu::Extent3d {
|
||||
width: pixels,
|
||||
height: pixels,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: TILE_MIP_LEVELS,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: TEXTURE_FORMAT,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[],
|
||||
})
|
||||
pub(crate) fn tile_texture(executor: &WgpuExecutor, pixels: u32) -> Texture {
|
||||
executor.request_texture_with_mips(UVec2::splat(pixels), TEXTURE_FORMAT, TILE_MIP_LEVELS)
|
||||
}
|
||||
|
||||
/// Records the rendering of a square tile of `pattern` into the top mip level of `texture`, with its top left corner at `corner` of the pattern's space and pixels `texel` units across.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn render_tile(&self, device: &wgpu::Device, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, texture: &wgpu::Texture, pattern: &GeneratorPattern, corner: DVec2, texel: f64) {
|
||||
pub(crate) fn render_tile(
|
||||
&self,
|
||||
executor: &WgpuExecutor,
|
||||
queue: &wgpu::Queue,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
held: &mut Vec<Texture>,
|
||||
texture: &wgpu::Texture,
|
||||
pattern: &GeneratorPattern,
|
||||
corner: DVec2,
|
||||
texel: f64,
|
||||
) {
|
||||
let device = &executor.context().device;
|
||||
let tile = Tile::new(pattern, corner, texel, texture.width());
|
||||
let (pipeline, bind_group_layout) = self.pipeline(device, tile.shader);
|
||||
|
||||
@@ -414,7 +407,12 @@ impl GeneratorPasses {
|
||||
contents: &tile.parameters,
|
||||
usage: wgpu::BufferUsages::UNIFORM,
|
||||
});
|
||||
let reference_view = (tile.shader == Shader::Mandelbrot).then(|| reference_texture(device, queue, tile.reference.as_ref()).create_view(&wgpu::TextureViewDescriptor::default()));
|
||||
let reference_view = (tile.shader == Shader::Mandelbrot).then(|| {
|
||||
let reference = reference_texture(executor, queue, tile.reference.as_ref());
|
||||
let view = reference.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
held.push(reference);
|
||||
view
|
||||
});
|
||||
let mut entries = vec![wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: buffer.as_entire_binding(),
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
// The passes that mask, feather, and blur content by a radius mask, appended to `vello_effects.wgsl` and sharing its bindings and parameters
|
||||
|
||||
// SVG's `luminanceToAlpha` weights, taken on gamma-encoded channels, matching `MASK_LUMINANCE_WEIGHTS`
|
||||
const MASK_LUMINANCE_WEIGHTS: vec3<f32> = vec3<f32>(0.2125, 0.7154, 0.0721);
|
||||
// SVG's `luminanceToAlpha` weights, taken on gamma-encoded channels, by which the maps varying other effects are read, matching `SVG_LUMINANCE_WEIGHTS`
|
||||
const SVG_LUMINANCE_WEIGHTS: vec3<f32> = vec3<f32>(0.2125, 0.7154, 0.0721);
|
||||
|
||||
// How much the mask graphic in `source`, premultiplied, shows the content: its luminance (times its alpha) with `values.x` 0, or its alpha with 1
|
||||
// How much the mask graphic in `source`, premultiplied, shows the content: its channels weighed by the mask mode's `values`, matching `MaskMode::channel_weights`
|
||||
@fragment
|
||||
fn mask_coverage(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let mask = textureLoad(source, vec2<i32>(position.xy), 0);
|
||||
let coverage = select(dot(mask.rgb, MASK_LUMINANCE_WEIGHTS), mask.a, parameters.values.x > 0.5);
|
||||
return vec4<f32>(clamp(coverage, 0., 1.), 0., 0., 0.);
|
||||
return vec4<f32>(clamp(dot(mask, parameters.values), 0., 1.), 0., 0., 0.);
|
||||
}
|
||||
|
||||
// The mask's feathered coverage in `source` mapped through its density line, of slope `values.x` and intercept `values.y`
|
||||
@@ -75,7 +74,7 @@ fn feather_erode(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f3
|
||||
@fragment
|
||||
fn masked_radius_blur_luminance(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let map = textureLoad(source, vec2<i32>(position.xy), 0);
|
||||
let luminance = clamp(dot(map.rgb, MASK_LUMINANCE_WEIGHTS), 0., 1.);
|
||||
let luminance = clamp(dot(map.rgb, SVG_LUMINANCE_WEIGHTS), 0., 1.);
|
||||
if parameters.values.x > 0.5 {
|
||||
return vec4<f32>(luminance);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use crate::WgpuExecutor;
|
||||
use crate::vello_adjustments::adjustment_run_hash;
|
||||
use crate::vello_effects::{EffectPasses, EffectTextures};
|
||||
use crate::vello_generators::GeneratorPasses;
|
||||
@@ -5,7 +6,7 @@ use core_types::blending::BlendMode;
|
||||
use glam::{DAffine2, UVec2};
|
||||
use graphic_types::effect_layers::EffectLayers;
|
||||
use graphic_types::effects::EffectCapture;
|
||||
use graphic_types::raster_types::{CPU, Image, Raster, WeakCPU};
|
||||
use graphic_types::raster_types::{CPU, Image, Raster, Texture, TextureWeakRef, WeakCPU};
|
||||
use graphic_types::{Adjustment, Effects};
|
||||
use rendering::vello_scene_builder::{EffectsRenderer, GeneratorTile, SceneImage, VelloSceneBuilder, image_downscale_factor, image_texture_size};
|
||||
use std::collections::HashMap;
|
||||
@@ -25,12 +26,6 @@ pub(crate) const TEXTURE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba
|
||||
/// 16-bit unorm comes first for holding every 8-bit level exactly, unlike half floats.
|
||||
const PRECISE_FORMATS: &[wgpu::TextureFormat] = &[wgpu::TextureFormat::Rgba16Unorm, wgpu::TextureFormat::Rgba16Float];
|
||||
|
||||
/// How many renders a GPU texture's premultiplied copy survives without being drawn before it is freed.
|
||||
const UNUSED_IMAGE_RENDER_LIMIT: u64 = 60;
|
||||
|
||||
/// About the most tiles of generators kept between renders, past which the least recently drawn are freed. Tiles drawn in the same render are kept or freed together.
|
||||
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;
|
||||
|
||||
@@ -54,8 +49,6 @@ pub(crate) struct VelloRenderer {
|
||||
pub struct VelloCanvas {
|
||||
/// Scenes to draw into, one for each depth of effects groups nested in a render, reused between renders to keep their allocations.
|
||||
spare_scenes: Vec<vello_gpu::Scene>,
|
||||
/// The premultiplied texture Vello GPU renders into before conversion to straight alpha, kept while the render size stays the same.
|
||||
premultiplied_target: Option<wgpu::Texture>,
|
||||
images: ImageTextures,
|
||||
effect_textures: EffectTextures,
|
||||
}
|
||||
@@ -71,8 +64,7 @@ enum TargetAlpha {
|
||||
struct RenderContext<'a> {
|
||||
renderer: &'a VelloRenderer,
|
||||
canvas: &'a mut VelloCanvas,
|
||||
device: &'a wgpu::Device,
|
||||
queue: &'a Queue,
|
||||
executor: &'a WgpuExecutor,
|
||||
}
|
||||
|
||||
impl VelloRenderer {
|
||||
@@ -121,12 +113,10 @@ impl VelloRenderer {
|
||||
|
||||
/// Renders the scene `draw` draws on `canvas`, with its content placed by `view`, into `target` (an `Rgba8Unorm` texture of `size` with straight alpha).
|
||||
/// A render with more content than Vello GPU can hold calls `draw` again for each part it splits into.
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
pub(crate) fn render(
|
||||
&self,
|
||||
executor: &WgpuExecutor,
|
||||
canvas: &mut VelloCanvas,
|
||||
device: &wgpu::Device,
|
||||
queue: &Queue,
|
||||
draw: &mut dyn FnMut(&mut VelloSceneBuilder),
|
||||
view: Affine,
|
||||
size: UVec2,
|
||||
@@ -137,12 +127,7 @@ impl VelloRenderer {
|
||||
}
|
||||
|
||||
canvas.images.render_count += 1;
|
||||
let mut context = RenderContext {
|
||||
renderer: self,
|
||||
canvas,
|
||||
device,
|
||||
queue,
|
||||
};
|
||||
let mut context = RenderContext { renderer: self, canvas, executor };
|
||||
context.render_area(draw, view, size, target, TargetAlpha::Straight);
|
||||
canvas.images.free_unused();
|
||||
canvas.effect_textures.finish_render();
|
||||
@@ -152,25 +137,30 @@ impl VelloRenderer {
|
||||
|
||||
/// Renders a `scene` drawn beforehand on `canvas` into `target` (an `Rgba8Unorm` texture of the scene's size with straight alpha).
|
||||
/// Unlike [`Self::render`], it can't split the scene, so one with more content than Vello GPU can hold renders transparent.
|
||||
pub(crate) fn render_scene(&self, canvas: &mut VelloCanvas, device: &wgpu::Device, queue: &Queue, scene: VelloSceneBuilder, target: &wgpu::Texture) {
|
||||
pub(crate) fn render_scene(&self, executor: &WgpuExecutor, canvas: &mut VelloCanvas, scene: VelloSceneBuilder, target: &wgpu::Texture) {
|
||||
canvas.images.render_count += 1;
|
||||
let max_texture_size = scene.max_texture_size();
|
||||
let mut context = RenderContext {
|
||||
renderer: self,
|
||||
canvas,
|
||||
device,
|
||||
queue,
|
||||
};
|
||||
let mut context = RenderContext { renderer: self, canvas, executor };
|
||||
let (scene, images) = scene.finish();
|
||||
if let Err(error) = context.submit(&scene, images, max_texture_size, target, TargetAlpha::Straight) {
|
||||
if let Err(error) = context.submit(&scene, images, max_texture_size, target, TargetAlpha::Straight, true) {
|
||||
log::error!("Vello GPU failed to render: {error}");
|
||||
clear(device, queue, target);
|
||||
clear(&executor.context().device, &executor.context().queue, target);
|
||||
}
|
||||
canvas.images.free_unused();
|
||||
canvas.effect_textures.finish_render();
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> RenderContext<'a> {
|
||||
fn device(&self) -> &'a wgpu::Device {
|
||||
&self.executor.context().device
|
||||
}
|
||||
|
||||
fn queue(&self) -> &'a Queue {
|
||||
&self.executor.context().queue
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderContext<'_> {
|
||||
/// Renders the scene `draw` draws into `target`, a texture of `size`, splitting its area into halves while it holds more content than one render can.
|
||||
fn render_area(&mut self, draw: &mut dyn FnMut(&mut VelloSceneBuilder), view: Affine, size: UVec2, target: &wgpu::Texture, target_alpha: TargetAlpha) {
|
||||
@@ -182,7 +172,7 @@ impl RenderContext<'_> {
|
||||
/// Renders each half of the area of `target`, a texture of `size`, after rendering it whole failed with `error`, splitting again each half that still holds too much.
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
fn render_halves(&mut self, draw: &mut dyn FnMut(&mut VelloSceneBuilder), view: Affine, size: UVec2, target: &wgpu::Texture, target_alpha: TargetAlpha, error: RenderError, split_depth: u32) {
|
||||
let (device, queue) = (self.device, self.queue);
|
||||
let (device, queue) = (self.device(), self.queue());
|
||||
|
||||
// Each half covers less of the scene, so it has less content and smaller layers to hold
|
||||
let too_much_to_hold = matches!(
|
||||
@@ -203,14 +193,9 @@ impl RenderContext<'_> {
|
||||
let top = size.y / 2;
|
||||
[(UVec2::ZERO, UVec2::new(size.x, top)), (UVec2::new(0, top), UVec2::new(size.x, size.y - top))]
|
||||
};
|
||||
let executor = self.executor;
|
||||
let halves = halves.map(|(offset, half_size)| {
|
||||
let half_target = create_texture(
|
||||
device,
|
||||
"vello_gpu_split_target",
|
||||
half_size,
|
||||
target.format(),
|
||||
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST,
|
||||
);
|
||||
let half_target = executor.request_texture_with_format(half_size, target.format());
|
||||
let half_view = Affine::translate((-(offset.x as f64), -(offset.y as f64))) * view;
|
||||
let rendered = self.render_once(draw, half_view, half_size, &half_target, target_alpha);
|
||||
(offset, half_size, half_view, half_target, rendered)
|
||||
@@ -254,41 +239,108 @@ impl RenderContext<'_> {
|
||||
|
||||
/// Renders the scene `draw` draws into `target`, a texture of `size`, in a single Vello GPU render.
|
||||
fn render_once(&mut self, draw: &mut dyn FnMut(&mut VelloSceneBuilder), view: Affine, size: UVec2, target: &wgpu::Texture, target_alpha: TargetAlpha) -> Result<(), RenderError> {
|
||||
let (width, height) = (size.x as u16, size.y as u16);
|
||||
let max_texture_size = self.device.limits().max_texture_dimension_2d;
|
||||
let max_texture_size = self.device().limits().max_texture_dimension_2d;
|
||||
let max_size = max_texture_size.min(u16::MAX as u32);
|
||||
let (mut scene, mut images, apron) = self.draw_scene(draw, view, size, max_texture_size, largest_apron(size, max_size));
|
||||
|
||||
// Draw the scene for this render's size and placement, which renders its effects groups as they're drawn
|
||||
let mut scene = self.canvas.spare_scenes.pop().unwrap_or_else(|| vello_gpu::Scene::new(width, height));
|
||||
scene.reset_and_resize(width, height);
|
||||
let mut builder = VelloSceneBuilder::from_vello(scene, view, max_texture_size).with_effects_renderer(self);
|
||||
draw(&mut builder);
|
||||
let (scene, images) = builder.finish();
|
||||
// Content reading what lies beneath it past the scene's edges stops its drawing for one grown by as much, of which the target takes the middle
|
||||
if let Some(apron) = apron
|
||||
&& let Some(grown_size) = grown_render_size(size, apron, max_size)
|
||||
{
|
||||
self.discard_scene(scene, images);
|
||||
let grown_view = Affine::translate((apron as f64, apron as f64)) * view;
|
||||
let (scene, images, _) = self.draw_scene(draw, grown_view, grown_size, max_texture_size, 0);
|
||||
|
||||
let rendered = self.submit(&scene, images, max_texture_size, target, target_alpha);
|
||||
let grown_target = self.executor.request_texture_with_format(grown_size, target.format());
|
||||
let rendered = self.submit(&scene, images, max_texture_size, &grown_target, target_alpha, true);
|
||||
self.canvas.spare_scenes.push(scene);
|
||||
|
||||
let mut encoder = self.device().create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("vello_gpu_grown_copy") });
|
||||
encoder.copy_texture_to_texture(
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
origin: wgpu::Origin3d { x: apron, y: apron, z: 0 },
|
||||
..grown_target.as_image_copy()
|
||||
},
|
||||
target.as_image_copy(),
|
||||
wgpu::Extent3d {
|
||||
width: size.x,
|
||||
height: size.y,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
);
|
||||
self.queue().submit([encoder.finish()]);
|
||||
return rendered;
|
||||
}
|
||||
|
||||
// Later content reading farther past the edges than a grown render holds leaves the scene to draw again, reading only what it holds
|
||||
if apron.is_some() {
|
||||
self.discard_scene(scene, images);
|
||||
(scene, images, _) = self.draw_scene(draw, view, size, max_texture_size, 0);
|
||||
}
|
||||
|
||||
let rendered = self.submit(&scene, images, max_texture_size, target, target_alpha, true);
|
||||
// Once the render that draws it is submitted, the scene is free to reuse
|
||||
self.canvas.spare_scenes.push(scene);
|
||||
rendered
|
||||
}
|
||||
|
||||
/// Draws the scene `draw` draws for a render of `size` placed by `view`, which renders its effects groups as they're drawn.
|
||||
/// It stops at the first content reading what lies beneath it past its edges by at most `largest_apron` pixels, then returns how far past them all of it reads.
|
||||
fn draw_scene(&mut self, draw: &mut dyn FnMut(&mut VelloSceneBuilder), view: Affine, size: UVec2, max_texture_size: u32, largest_apron: u32) -> (vello_gpu::Scene, Vec<SceneImage>, Option<u32>) {
|
||||
let (width, height) = (size.x as u16, size.y as u16);
|
||||
let mut scene = self.canvas.spare_scenes.pop().unwrap_or_else(|| vello_gpu::Scene::new(width, height));
|
||||
scene.reset_and_resize(width, height);
|
||||
|
||||
let mut builder = VelloSceneBuilder::from_vello(scene, view, max_texture_size)
|
||||
.with_effects_renderer(self)
|
||||
.stopping_for_an_apron_up_to(largest_apron);
|
||||
draw(&mut builder);
|
||||
let apron = (!builder.drew_everything()).then(|| builder.backdrop_apron());
|
||||
let (scene, images) = builder.finish();
|
||||
(scene, images, apron)
|
||||
}
|
||||
|
||||
/// Sets aside a drawn scene without rendering it, freeing the effects results it draws for reuse.
|
||||
fn discard_scene(&mut self, scene: vello_gpu::Scene, images: Vec<SceneImage>) {
|
||||
for image in images {
|
||||
if let SceneImage::Rendered(texture) = image {
|
||||
self.canvas.effect_textures.release(texture);
|
||||
}
|
||||
}
|
||||
self.canvas.spare_scenes.push(scene);
|
||||
}
|
||||
|
||||
/// Renders a drawn scene, with the images it draws, into `target`, a texture of the scene's size, in a single Vello GPU render.
|
||||
fn submit(&mut self, scene: &vello_gpu::Scene, images: Vec<SceneImage>, max_texture_size: u32, target: &wgpu::Texture, target_alpha: TargetAlpha) -> Result<(), RenderError> {
|
||||
let device = self.device;
|
||||
/// The effects results it draws are freed for reuse after it, even if it fails when `release_failed`.
|
||||
fn submit(&mut self, scene: &vello_gpu::Scene, images: Vec<SceneImage>, max_texture_size: u32, target: &wgpu::Texture, target_alpha: TargetAlpha, release_failed: bool) -> Result<(), RenderError> {
|
||||
let device = self.device();
|
||||
let (width, height) = (scene.width(), scene.height());
|
||||
let size = UVec2::new(width as u32, height as u32);
|
||||
|
||||
// Locked from here to the submission, so drawing a scene doesn't hold up other uses of the queue
|
||||
let queue = self.queue.lock();
|
||||
let queue = self.queue().lock();
|
||||
|
||||
// Each render submits its own encoder, since Vello GPU stages its uploads for the next submission
|
||||
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("vello_gpu_render") });
|
||||
|
||||
// Supply the textures of the images the scene draws, under the IDs it drew them with
|
||||
let mut texture_bindings = TextureBindings::new();
|
||||
let mut held = Vec::new();
|
||||
for (id, image) in images.iter().enumerate() {
|
||||
let view = self
|
||||
.canvas
|
||||
.images
|
||||
.prepare(device, &queue, &mut encoder, &mut self.canvas.effect_textures, self.renderer, image, max_texture_size);
|
||||
let view = match image {
|
||||
SceneImage::Texture(source) => {
|
||||
let premultiplied = self.executor.request_texture(UVec2::new(source.width(), source.height()));
|
||||
let view = premultiplied.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let source_view = source.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
self.renderer.alpha_conversion.premultiply(device, &mut encoder, &source_view, source.format().is_srgb(), &view);
|
||||
held.push(premultiplied);
|
||||
Some(view)
|
||||
}
|
||||
_ => self
|
||||
.canvas
|
||||
.images
|
||||
.prepare(self.executor, &queue, &mut encoder, &mut self.canvas.effect_textures, self.renderer, image, max_texture_size, &mut held),
|
||||
};
|
||||
|
||||
// Adjustments draw a copy of the texture they're carried out on
|
||||
let view = match image {
|
||||
@@ -296,7 +348,7 @@ impl RenderContext<'_> {
|
||||
let effects = (&self.renderer.effect_passes, &mut self.canvas.effect_textures);
|
||||
self.canvas
|
||||
.images
|
||||
.prepare_adjusted(device, &queue, effects, raster, adjustments, max_texture_size, self.renderer.precise_format)
|
||||
.prepare_adjusted(self.executor, &queue, effects, raster, adjustments, max_texture_size, self.renderer.precise_format, &mut held)
|
||||
}),
|
||||
_ => view,
|
||||
};
|
||||
@@ -308,21 +360,10 @@ impl RenderContext<'_> {
|
||||
|
||||
// Vello GPU renders premultiplied, which is converted to straight alpha unless the target wants it premultiplied
|
||||
let target_view = target.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let premultiplied_view = match (target_alpha, &self.canvas.premultiplied_target) {
|
||||
(TargetAlpha::Premultiplied, _) => target_view.clone(),
|
||||
(TargetAlpha::Straight, Some(texture)) if texture.width() == size.x && texture.height() == size.y => texture.create_view(&wgpu::TextureViewDescriptor::default()),
|
||||
(TargetAlpha::Straight, _) => {
|
||||
let texture = create_texture(
|
||||
device,
|
||||
"vello_gpu_premultiplied_target",
|
||||
size,
|
||||
TEXTURE_FORMAT,
|
||||
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
|
||||
);
|
||||
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
self.canvas.premultiplied_target = Some(texture);
|
||||
view
|
||||
}
|
||||
let premultiplied_target = (target_alpha == TargetAlpha::Straight).then(|| self.executor.request_texture(size));
|
||||
let premultiplied_view = match &premultiplied_target {
|
||||
Some(texture) => texture.create_view(&wgpu::TextureViewDescriptor::default()),
|
||||
None => target_view.clone(),
|
||||
};
|
||||
let target_init = TargetInit::Clear(ClearSettings::Viewport { color: peniko::Color::TRANSPARENT });
|
||||
|
||||
@@ -350,10 +391,12 @@ impl RenderContext<'_> {
|
||||
queue.submit([encoder.finish()]);
|
||||
drop((gpu, queue));
|
||||
|
||||
// Once the render that draws them is submitted, its effects results are free to reuse
|
||||
for image in images {
|
||||
if let SceneImage::Rendered(texture) = image {
|
||||
self.canvas.effect_textures.release(texture);
|
||||
// Once the render that draws them is submitted, its effects results are free to reuse, unless a failed render leaves them still to draw
|
||||
if rendered.is_ok() || release_failed {
|
||||
for image in images {
|
||||
if let SceneImage::Rendered(texture) = image {
|
||||
self.canvas.effect_textures.release(texture);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -376,28 +419,29 @@ impl EffectsRenderer for RenderContext<'_> {
|
||||
opacity: f32,
|
||||
effect_to_pixels: DAffine2,
|
||||
frame: Option<graphic_types::resampling::EffectFrame>,
|
||||
backdrop: Option<(&wgpu::Texture, Affine)>,
|
||||
capture: Option<EffectCapture>,
|
||||
draw_paint: &mut dyn FnMut(usize, &mut VelloSceneBuilder),
|
||||
draw: &mut dyn FnMut(&mut VelloSceneBuilder),
|
||||
) -> Vec<(wgpu::Texture, BlendMode)> {
|
||||
let content_texture = self.canvas.effect_textures.acquire(self.device, size, self.renderer.precise_format);
|
||||
let content_texture = self.canvas.effect_textures.acquire(self.executor, size, self.renderer.precise_format);
|
||||
self.render_area(draw, view, size, &content_texture, TargetAlpha::Premultiplied);
|
||||
|
||||
// The effects' drawn paints, each rendered over the same pixels as the content
|
||||
let paint_count = effects.operations().map(|operation| operation.drawn_paints().count()).sum();
|
||||
let paint_textures: Vec<wgpu::Texture> = (0..paint_count)
|
||||
.map(|index| {
|
||||
let paint_texture = self.canvas.effect_textures.acquire(self.device, size, self.renderer.precise_format);
|
||||
let paint_texture = self.canvas.effect_textures.acquire(self.executor, size, self.renderer.precise_format);
|
||||
self.render_area(&mut |scene| draw_paint(index, scene), view, size, &paint_texture, TargetAlpha::Premultiplied);
|
||||
paint_texture
|
||||
})
|
||||
.collect();
|
||||
|
||||
let queue = self.queue().lock();
|
||||
let effect_textures = &mut self.canvas.effect_textures;
|
||||
let queue = self.queue.lock();
|
||||
let effect_passes = &self.renderer.effect_passes;
|
||||
let results = effect_passes.apply(
|
||||
self.device,
|
||||
self.executor,
|
||||
&queue,
|
||||
effect_textures,
|
||||
&content_texture,
|
||||
@@ -408,6 +452,7 @@ impl EffectsRenderer for RenderContext<'_> {
|
||||
effect_to_pixels,
|
||||
frame,
|
||||
&paint_textures,
|
||||
backdrop,
|
||||
capture,
|
||||
);
|
||||
effect_textures.release(content_texture);
|
||||
@@ -415,6 +460,31 @@ impl EffectsRenderer for RenderContext<'_> {
|
||||
|
||||
results
|
||||
}
|
||||
|
||||
fn render_backdrop(&mut self, scene: &vello_gpu::Scene, images: &[SceneImage], max_texture_size: u32) -> Option<wgpu::Texture> {
|
||||
let size = UVec2::new(scene.width() as u32, scene.height() as u32);
|
||||
let backdrop = self.canvas.effect_textures.acquire(self.executor, size, self.renderer.precise_format);
|
||||
|
||||
// A failed render leaves the scene to go on drawing what it drew, so the results it draws stay in use
|
||||
match self.submit(scene, images.to_vec(), max_texture_size, &backdrop, TargetAlpha::Premultiplied, false) {
|
||||
Ok(()) => Some(backdrop),
|
||||
Err(error) => {
|
||||
log::error!("Vello GPU failed to render what lies beneath content reading it: {error}");
|
||||
self.canvas.effect_textures.release(backdrop);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The widest apron of pixels past each edge that a render of `size` can grow by and still fit a texture of `max_size`.
|
||||
fn largest_apron(size: UVec2, max_size: u32) -> u32 {
|
||||
max_size.saturating_sub(size.max_element()) / 2
|
||||
}
|
||||
|
||||
/// The size of a render of `size` grown by an `apron` of pixels past each edge, or `None` without one or if it's too large for a texture of `max_size`.
|
||||
fn grown_render_size(size: UVec2, apron: u32, max_size: u32) -> Option<UVec2> {
|
||||
(apron > 0 && apron <= largest_apron(size, max_size)).then(|| size + UVec2::splat(2 * apron))
|
||||
}
|
||||
|
||||
/// Leaves `target` transparent.
|
||||
@@ -424,122 +494,117 @@ 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, a GPU texture, or a tile of a generator's pattern.
|
||||
/// Identifies the pixels behind an image texture: a blob of CPU pixels or a CPU raster.
|
||||
#[derive(Clone, PartialEq, Eq, Hash)]
|
||||
enum ImageKey {
|
||||
Blob(u64),
|
||||
Raster(u64),
|
||||
Texture(wgpu::Texture),
|
||||
GeneratorTile(GeneratorTile),
|
||||
}
|
||||
|
||||
/// A premultiplied copy of an image's pixels that Vello GPU samples as an external texture.
|
||||
struct ImageTexture {
|
||||
texture: wgpu::Texture,
|
||||
texture: TextureWeakRef,
|
||||
last_used: u64,
|
||||
/// The CPU raster pixels copied into the texture, which is freed once they're gone since they can't be drawn again.
|
||||
raster: Option<WeakCPU>,
|
||||
/// Copies with runs of adjustments carried out on them, one for each run the image is drawn with.
|
||||
adjusted: Vec<AdjustedTexture>,
|
||||
/// The raster's straight linear colors in 32-bit floats that adjustments are carried out from, kept while any adjusted copy is.
|
||||
adjustment_source: Option<wgpu::Texture>,
|
||||
adjustment_source: Option<TextureWeakRef>,
|
||||
}
|
||||
|
||||
/// A copy of an image's texture with a run of adjustments carried out on it, made over in place for another run.
|
||||
/// A copy of an image's texture with a run of adjustments carried out on it, made over for another run.
|
||||
struct AdjustedTexture {
|
||||
texture: wgpu::Texture,
|
||||
/// The hash of the run carried out on it, or `None` until one is.
|
||||
run_hash: Option<u64>,
|
||||
texture: TextureWeakRef,
|
||||
run_hash: u64,
|
||||
last_used: u64,
|
||||
}
|
||||
|
||||
/// The textures of the images recent renders drew, each freed once it goes unused for long enough.
|
||||
/// The textures of the images recent renders drew, parked in the texture pool between renders.
|
||||
#[derive(Default)]
|
||||
struct ImageTextures {
|
||||
textures: HashMap<ImageKey, ImageTexture>,
|
||||
/// The textures of the generator tiles the last render freed, for its next render's new tiles to take over, as when changing a generator's settings replaces every tile.
|
||||
spare_generator_tiles: Vec<wgpu::Texture>,
|
||||
generator_tiles: HashMap<GeneratorTile, TextureWeakRef>,
|
||||
render_count: u64,
|
||||
}
|
||||
|
||||
impl ImageTextures {
|
||||
/// A view of the premultiplied texture for `image`, uploading CPU pixels or rendering a generator's tile the first time they're drawn.
|
||||
/// GPU textures are converted again at every render since the texture cache hands their textures out again with new contents.
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
fn prepare(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
executor: &WgpuExecutor,
|
||||
queue: &wgpu::Queue,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
effect_textures: &mut EffectTextures,
|
||||
renderer: &VelloRenderer,
|
||||
image: &SceneImage,
|
||||
max_texture_size: u32,
|
||||
held: &mut Vec<Texture>,
|
||||
) -> Option<wgpu::TextureView> {
|
||||
let key = match image {
|
||||
SceneImage::Pixels(data) => ImageKey::Blob(data.data.id()),
|
||||
SceneImage::Raster { raster, .. } => ImageKey::Raster(raster.buffer_id()),
|
||||
SceneImage::Texture(texture) => ImageKey::Texture((**texture).clone()),
|
||||
SceneImage::GeneratorTile { tile, .. } => ImageKey::GeneratorTile(*tile),
|
||||
SceneImage::GeneratorTile { pattern, tile } => {
|
||||
let texture = match self.generator_tiles.get(tile).and_then(TextureWeakRef::upgrade) {
|
||||
Some(texture) => texture,
|
||||
None => {
|
||||
let texture = GeneratorPasses::tile_texture(executor, GeneratorTile::SAMPLES);
|
||||
let (corner, texel) = tile.corner_and_texel();
|
||||
renderer.generator_passes.render_tile(executor, queue, encoder, held, &texture, pattern, corner, texel);
|
||||
renderer.effect_passes.record_mipmaps(executor, encoder, effect_textures, &texture);
|
||||
self.generator_tiles.insert(*tile, texture.downgrade());
|
||||
texture
|
||||
}
|
||||
};
|
||||
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
held.push(texture);
|
||||
return Some(view);
|
||||
}
|
||||
// Effects results are premultiplied already
|
||||
SceneImage::Rendered(texture) => return Some(texture.create_view(&wgpu::TextureViewDescriptor::default())),
|
||||
SceneImage::Texture(_) => return None,
|
||||
};
|
||||
|
||||
if !self.textures.contains_key(&key) {
|
||||
let texture = match image {
|
||||
SceneImage::Pixels(data) => {
|
||||
if data.format != peniko::ImageFormat::Rgba8 {
|
||||
log::error!("Unsupported image format {:?}", data.format);
|
||||
return None;
|
||||
let texture = match self.textures.get(&key).and_then(|image_texture| image_texture.texture.upgrade()) {
|
||||
Some(texture) => texture,
|
||||
None => {
|
||||
let texture = match image {
|
||||
SceneImage::Pixels(data) => {
|
||||
if data.format != peniko::ImageFormat::Rgba8 {
|
||||
log::error!("Unsupported image format {:?}", data.format);
|
||||
return None;
|
||||
}
|
||||
|
||||
upload_pixels(executor, queue, data.data.data(), data.width, data.height, data.alpha_type, max_texture_size)?
|
||||
}
|
||||
SceneImage::Raster { raster, .. } => {
|
||||
let (pixels, width, height) = raster.to_flat_u8();
|
||||
upload_pixels(executor, queue, &pixels, width, height, peniko::ImageAlphaType::Alpha, max_texture_size)?
|
||||
}
|
||||
SceneImage::Rendered(_) | SceneImage::Texture(_) | SceneImage::GeneratorTile { .. } => return None,
|
||||
};
|
||||
let raster = match image {
|
||||
SceneImage::Raster { raster, .. } => Some(raster.downgrade()),
|
||||
SceneImage::Pixels(_) | SceneImage::Texture(_) | SceneImage::Rendered(_) | SceneImage::GeneratorTile { .. } => None,
|
||||
};
|
||||
self.textures.insert(
|
||||
key.clone(),
|
||||
ImageTexture {
|
||||
texture: texture.downgrade(),
|
||||
last_used: 0,
|
||||
raster,
|
||||
adjusted: Vec::new(),
|
||||
adjustment_source: None,
|
||||
},
|
||||
);
|
||||
texture
|
||||
}
|
||||
};
|
||||
|
||||
upload_pixels(device, queue, data.data.data(), data.width, data.height, data.alpha_type, max_texture_size)?
|
||||
}
|
||||
SceneImage::Raster { raster, .. } => {
|
||||
let (pixels, width, height) = raster.to_flat_u8();
|
||||
upload_pixels(device, queue, &pixels, width, height, peniko::ImageAlphaType::Alpha, max_texture_size)?
|
||||
}
|
||||
SceneImage::GeneratorTile { pattern, tile } => {
|
||||
let texture = (self.spare_generator_tiles.pop()).unwrap_or_else(|| GeneratorPasses::tile_texture(device, GeneratorTile::SAMPLES));
|
||||
let (corner, texel) = tile.corner_and_texel();
|
||||
renderer.generator_passes.render_tile(device, queue, encoder, &texture, pattern, corner, texel);
|
||||
renderer.effect_passes.record_mipmaps(device, encoder, effect_textures, &texture);
|
||||
texture
|
||||
}
|
||||
SceneImage::Rendered(_) => return None,
|
||||
SceneImage::Texture(texture) => create_texture(
|
||||
device,
|
||||
"vello_gpu_premultiplied_image",
|
||||
UVec2::new(texture.width(), texture.height()),
|
||||
TEXTURE_FORMAT,
|
||||
wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
),
|
||||
};
|
||||
let raster = match image {
|
||||
SceneImage::Raster { raster, .. } => Some(raster.downgrade()),
|
||||
SceneImage::Pixels(_) | SceneImage::Texture(_) | SceneImage::Rendered(_) | SceneImage::GeneratorTile { .. } => None,
|
||||
};
|
||||
self.textures.insert(
|
||||
key.clone(),
|
||||
ImageTexture {
|
||||
texture,
|
||||
last_used: 0,
|
||||
raster,
|
||||
adjusted: Vec::new(),
|
||||
adjustment_source: None,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
let image_texture = self.textures.get_mut(&key)?;
|
||||
image_texture.last_used = self.render_count;
|
||||
let view = image_texture.texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
|
||||
if let SceneImage::Texture(source) = image {
|
||||
let source_view = source.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
renderer.alpha_conversion.premultiply(device, encoder, &source_view, source.format().is_srgb(), &view);
|
||||
}
|
||||
|
||||
self.textures.get_mut(&key)?.last_used = self.render_count;
|
||||
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
held.push(texture);
|
||||
Some(view)
|
||||
}
|
||||
|
||||
@@ -547,30 +612,38 @@ impl ImageTextures {
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
fn prepare_adjusted(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
executor: &WgpuExecutor,
|
||||
queue: &wgpu::Queue,
|
||||
effects: (&EffectPasses, &mut EffectTextures),
|
||||
raster: &Raster<CPU>,
|
||||
run: &[Adjustment],
|
||||
max_texture_size: u32,
|
||||
precise_format: wgpu::TextureFormat,
|
||||
held: &mut Vec<Texture>,
|
||||
) -> Option<wgpu::TextureView> {
|
||||
let (effect_passes, effect_textures) = effects;
|
||||
let run: Vec<&Adjustment> = run.iter().collect();
|
||||
let run_hash = adjustment_run_hash(&run);
|
||||
let render_count = self.render_count;
|
||||
let image_texture = self.textures.get_mut(&ImageKey::Raster(raster.buffer_id()))?;
|
||||
let image = image_texture.texture.upgrade()?;
|
||||
|
||||
// A run seen before has its copy
|
||||
if let Some(copy) = image_texture.adjusted.iter_mut().find(|copy| copy.run_hash == Some(run_hash)) {
|
||||
let seen = (image_texture.adjusted.iter_mut()).find(|copy| copy.run_hash == run_hash).and_then(|copy| {
|
||||
copy.last_used = render_count;
|
||||
return Some(copy.texture.create_view(&wgpu::TextureViewDescriptor::default()));
|
||||
copy.texture.upgrade()
|
||||
});
|
||||
if let Some(copy) = seen {
|
||||
let view = copy.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
held.push(copy);
|
||||
return Some(view);
|
||||
}
|
||||
image_texture.adjusted.retain(|copy| copy.run_hash != run_hash);
|
||||
|
||||
// A run that changes no color draws the texture itself
|
||||
let prepared = effect_textures.prepare_adjustments(device, queue, &run);
|
||||
let prepared = effect_textures.prepare_adjustments(executor, queue, &run);
|
||||
if prepared.is_empty() {
|
||||
return Some(image_texture.texture.create_view(&wgpu::TextureViewDescriptor::default()));
|
||||
return Some(image.create_view(&wgpu::TextureViewDescriptor::default()));
|
||||
}
|
||||
|
||||
// A new run takes over the copy longest unused, as when dragging a slider makes a new run every render
|
||||
@@ -578,85 +651,59 @@ impl ImageTextures {
|
||||
.filter(|(_, copy)| copy.last_used < render_count)
|
||||
.min_by_key(|(_, copy)| copy.last_used)
|
||||
.map(|(index, _)| index);
|
||||
let index = match reusable {
|
||||
Some(index) => index,
|
||||
None => {
|
||||
let texture = device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("vello_gpu_adjusted_image"),
|
||||
size: image_texture.texture.size(),
|
||||
mip_level_count: image_texture.texture.mip_level_count(),
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: precise_format,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[],
|
||||
});
|
||||
image_texture.adjusted.push(AdjustedTexture {
|
||||
texture,
|
||||
run_hash: None,
|
||||
last_used: render_count,
|
||||
});
|
||||
image_texture.adjusted.len() - 1
|
||||
}
|
||||
};
|
||||
if let Some(index) = reusable {
|
||||
image_texture.adjusted.swap_remove(index);
|
||||
}
|
||||
let copy = executor.request_texture_with_mips(UVec2::new(image.width(), image.height()), precise_format, image.mip_level_count());
|
||||
|
||||
// Adjusting the raster's own colors, rather than its 8-bit premultiplied texture, keeps faint colors from banding and steps landing as on the CPU
|
||||
if image_texture.adjustment_source.is_none() {
|
||||
image_texture.adjustment_source = upload_adjustment_source(device, queue, raster.data(), max_texture_size);
|
||||
}
|
||||
let (source, straight_linear) = match &image_texture.adjustment_source {
|
||||
let source = match image_texture.adjustment_source.as_ref().and_then(TextureWeakRef::upgrade) {
|
||||
Some(source) => Some(source),
|
||||
None => {
|
||||
let source = upload_adjustment_source(executor, queue, raster.data(), max_texture_size);
|
||||
image_texture.adjustment_source = source.as_ref().map(Texture::downgrade);
|
||||
source
|
||||
}
|
||||
};
|
||||
let (source, straight_linear) = match &source {
|
||||
Some(source) => (source, true),
|
||||
None => (&image_texture.texture, false),
|
||||
None => (&image, false),
|
||||
};
|
||||
|
||||
let copy = &mut image_texture.adjusted[index];
|
||||
effect_passes.adjust_image(device, queue, effect_textures, source, straight_linear, &prepared, ©.texture);
|
||||
copy.run_hash = Some(run_hash);
|
||||
copy.last_used = render_count;
|
||||
effect_passes.adjust_image(executor, queue, effect_textures, source, straight_linear, &prepared, ©);
|
||||
image_texture.adjusted.push(AdjustedTexture {
|
||||
texture: copy.downgrade(),
|
||||
run_hash,
|
||||
last_used: render_count,
|
||||
});
|
||||
|
||||
Some(copy.texture.create_view(&wgpu::TextureViewDescriptor::default()))
|
||||
let view = copy.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
held.push(copy);
|
||||
Some(view)
|
||||
}
|
||||
|
||||
fn free_unused(&mut self) {
|
||||
let render_count = self.render_count;
|
||||
let in_use = |last_used: u64| render_count - last_used < UNUSED_IMAGE_RENDER_LIMIT;
|
||||
|
||||
let kept = |key: &ImageKey, image_texture: &ImageTexture| match key {
|
||||
// CPU pixels get a new blob ID at every render, so a blob this render didn't draw is unlikely to return
|
||||
ImageKey::Blob(_) => image_texture.last_used == render_count,
|
||||
ImageKey::Raster(_) => image_texture.last_used == render_count || (in_use(image_texture.last_used) && image_texture.raster.as_ref().is_some_and(WeakCPU::is_alive)),
|
||||
ImageKey::Texture(_) | ImageKey::GeneratorTile(_) => in_use(image_texture.last_used),
|
||||
ImageKey::Raster(_) => image_texture.last_used == render_count || image_texture.raster.as_ref().is_some_and(WeakCPU::is_alive),
|
||||
};
|
||||
|
||||
// Spares this render didn't take over are freed, and the tiles it freed become the next render's spares
|
||||
self.spare_generator_tiles.clear();
|
||||
let unused = self.textures.extract_if(|key, image_texture| !kept(key, image_texture));
|
||||
let unused_tiles = unused.filter(|(key, _)| matches!(key, ImageKey::GeneratorTile(_))).map(|(_, image_texture)| image_texture.texture);
|
||||
self.spare_generator_tiles.extend(unused_tiles);
|
||||
self.textures.retain(|key, image_texture| kept(key, image_texture) && image_texture.texture.upgrade().is_some());
|
||||
self.generator_tiles.retain(|_, texture| texture.upgrade().is_some());
|
||||
|
||||
self.textures.values_mut().for_each(|image_texture| {
|
||||
image_texture.adjusted.retain(|copy| in_use(copy.last_used));
|
||||
image_texture.adjusted.retain(|copy| copy.texture.upgrade().is_some());
|
||||
if image_texture.adjusted.is_empty() {
|
||||
image_texture.adjustment_source = None;
|
||||
}
|
||||
});
|
||||
|
||||
// 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);
|
||||
let least_recent = (self.textures).extract_if(|key, image_texture| matches!(key, ImageKey::GeneratorTile(_)) && image_texture.last_used < oldest_kept);
|
||||
self.spare_generator_tiles.extend(least_recent.map(|(_, image_texture)| image_texture.texture));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Uploads CPU pixels as a premultiplied texture, downscaling them by a whole factor if they exceed `max_texture_size`.
|
||||
fn upload_pixels(device: &wgpu::Device, queue: &wgpu::Queue, pixels: &[u8], width: u32, height: u32, alpha_type: peniko::ImageAlphaType, max_texture_size: u32) -> Option<wgpu::Texture> {
|
||||
fn upload_pixels(executor: &WgpuExecutor, queue: &wgpu::Queue, pixels: &[u8], width: u32, height: u32, alpha_type: peniko::ImageAlphaType, max_texture_size: u32) -> Option<Texture> {
|
||||
if width == 0 || height == 0 {
|
||||
return None;
|
||||
}
|
||||
@@ -685,20 +732,7 @@ fn upload_pixels(device: &wgpu::Device, queue: &wgpu::Queue, pixels: &[u8], widt
|
||||
|
||||
// Each mipmap level halves the one before it, so a minified image averages its pixels rather than skipping over them
|
||||
let level_count = texture_width.max(texture_height).ilog2() + 1;
|
||||
let texture = device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("vello_gpu_image"),
|
||||
size: wgpu::Extent3d {
|
||||
width: texture_width,
|
||||
height: texture_height,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: level_count,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: TEXTURE_FORMAT,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[],
|
||||
});
|
||||
let texture = executor.request_texture_with_mips(UVec2::new(texture_width, texture_height), TEXTURE_FORMAT, level_count);
|
||||
|
||||
let (mut level_pixels, mut level_width, mut level_height) = (pixels, texture_width, texture_height);
|
||||
for level in 0..level_count {
|
||||
@@ -789,7 +823,7 @@ fn box_downscale<Channel: Copy + Into<f32>>(pixels: &[Channel], width: u32, heig
|
||||
|
||||
/// Uploads a raster's straight linear colors as one level of 32-bit floats, the size [`upload_pixels`] makes them, so adjustments read the CPU's exact values.
|
||||
/// A raster too large for one texture is averaged down to fit on premultiplied gamma-encoded channels, as [`upload_pixels`] averages them.
|
||||
fn upload_adjustment_source(device: &wgpu::Device, queue: &wgpu::Queue, image: &Image<core_types::Color>, max_texture_size: u32) -> Option<wgpu::Texture> {
|
||||
fn upload_adjustment_source(executor: &WgpuExecutor, queue: &wgpu::Queue, image: &Image<core_types::Color>, max_texture_size: u32) -> Option<Texture> {
|
||||
let (width, height) = (image.width, image.height);
|
||||
if width == 0 || height == 0 {
|
||||
return None;
|
||||
@@ -826,16 +860,7 @@ fn upload_adjustment_source(device: &wgpu::Device, queue: &wgpu::Queue, image: &
|
||||
height: texture_height,
|
||||
depth_or_array_layers: 1,
|
||||
};
|
||||
let texture = device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("vello_gpu_adjustment_source"),
|
||||
size,
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[],
|
||||
});
|
||||
let texture = executor.request_texture_with_format(UVec2::new(texture_width, texture_height), format);
|
||||
queue.write_texture(
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
texture: &texture,
|
||||
@@ -874,23 +899,6 @@ fn clear_texture(encoder: &mut wgpu::CommandEncoder, view: &wgpu::TextureView) {
|
||||
});
|
||||
}
|
||||
|
||||
fn create_texture(device: &wgpu::Device, label: &str, size: UVec2, format: wgpu::TextureFormat, usage: wgpu::TextureUsages) -> wgpu::Texture {
|
||||
device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some(label),
|
||||
size: wgpu::Extent3d {
|
||||
width: size.x.max(1),
|
||||
height: size.y.max(1),
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format,
|
||||
usage,
|
||||
view_formats: &[],
|
||||
})
|
||||
}
|
||||
|
||||
/// Full-target passes converting between straight and premultiplied alpha.
|
||||
struct AlphaConversion {
|
||||
bind_group_layout: wgpu::BindGroupLayout,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -559,9 +559,9 @@ fn field_displacement(local: vec2<f32>) -> vec2<f32> {
|
||||
return moved * settings.xy;
|
||||
}
|
||||
|
||||
// How many levels past the neutral one a displacement map's premultiplied texel lies, by the luminance a mask reads, seen over the neutral level where it's translucent, matching the CPU's `displacement_amount`
|
||||
// How many levels past the neutral one a displacement map's premultiplied texel lies, by the luminance an SVG luminance mask reads, seen over the neutral level where it's translucent, matching the CPU's `displacement_amount`
|
||||
fn displacement_map_levels(map: vec4<f32>) -> f32 {
|
||||
let luminance = clamp(dot(map.rgb, MASK_LUMINANCE_WEIGHTS), 0., 1.);
|
||||
let luminance = clamp(dot(map.rgb, SVG_LUMINANCE_WEIGHTS), 0., 1.);
|
||||
return luminance * 255. + DISPLACEMENT_NEUTRAL_LEVEL * (1. - map.a) - DISPLACEMENT_NEUTRAL_LEVEL;
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@ use convert_case::{Case, Casing};
|
||||
use proc_macro2::TokenStream as TokenStream2;
|
||||
use quote::{ToTokens, format_ident, quote, quote_spanned};
|
||||
use std::sync::atomic::AtomicU64;
|
||||
use syn::ext::IdentExt;
|
||||
use syn::punctuated::Punctuated;
|
||||
use syn::spanned::Spanned;
|
||||
use syn::token::Comma;
|
||||
@@ -113,7 +112,15 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
let data_field_names: Vec<_> = data_fields.iter().map(|f| &f.pat_ident.ident).collect();
|
||||
|
||||
// Only regular fields have input names/descriptions (for UI)
|
||||
let input_names: Vec<_> = regular_fields.iter().map(|field| parameter_display_name(field)).collect();
|
||||
let input_names: Vec<_> = regular_fields
|
||||
.iter()
|
||||
.map(|f| &f.name)
|
||||
.zip(regular_field_names.iter())
|
||||
.map(|zipped| match zipped {
|
||||
(Some(name), _) => name.value(),
|
||||
(_, name) => name.to_string().to_case(Case::Title),
|
||||
})
|
||||
.collect();
|
||||
|
||||
// The primary input is not a parameter, so generators can name their unused one `_primary` without it becoming internal
|
||||
let input_internal = regular_field_names
|
||||
@@ -167,6 +174,56 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Only regular fields have UI metadata (data fields are internal state)
|
||||
let widget_override: Vec<_> = regular_fields
|
||||
.iter()
|
||||
.map(|field| match &field.widget_override {
|
||||
ParsedWidgetOverride::None => quote!(RegistryWidgetOverride::None),
|
||||
ParsedWidgetOverride::Hidden => quote!(RegistryWidgetOverride::Hidden),
|
||||
ParsedWidgetOverride::String(lit_str) => quote!(RegistryWidgetOverride::String(#lit_str)),
|
||||
ParsedWidgetOverride::Custom(lit_str) => quote!(RegistryWidgetOverride::Custom(#lit_str)),
|
||||
})
|
||||
.collect();
|
||||
|
||||
let value_sources: Vec<_> = regular_fields
|
||||
.iter()
|
||||
.map(|field| match field.ty.value_source() {
|
||||
ParsedValueSource::Default(data) => {
|
||||
// Check if the data is a string literal by parsing the token stream
|
||||
let data_str = data.to_string();
|
||||
if data_str.starts_with('"') && data_str.ends_with('"') && data_str.len() >= 2 {
|
||||
quote!(RegistryValueSource::Default(#data))
|
||||
} else {
|
||||
quote!(RegistryValueSource::Default(stringify!(#data)))
|
||||
}
|
||||
}
|
||||
ParsedValueSource::Scope(data) => {
|
||||
if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(_), .. }) = data.as_ref() {
|
||||
quote!(RegistryValueSource::Scope(#data))
|
||||
} else {
|
||||
quote!(RegistryValueSource::Scope(#data.as_static_str()))
|
||||
}
|
||||
}
|
||||
ParsedValueSource::SourceId => quote!(RegistryValueSource::SourceId),
|
||||
ParsedValueSource::NodePath => quote!(RegistryValueSource::NodePath),
|
||||
_ => quote!(RegistryValueSource::None),
|
||||
})
|
||||
.collect();
|
||||
|
||||
let default_colors: Vec<_> = regular_fields
|
||||
.iter()
|
||||
.map(|field| match field.ty.regular() {
|
||||
Some(RegularParsedField {
|
||||
value_source: ParsedValueSource::Default(data),
|
||||
..
|
||||
}) => match color_constant_paths(data) {
|
||||
Some(paths) => quote!(Some(&[#(#paths),*])),
|
||||
None => quote!(None),
|
||||
},
|
||||
_ => quote!(None),
|
||||
})
|
||||
.collect();
|
||||
|
||||
let default_types: Vec<_> = regular_fields
|
||||
.iter()
|
||||
.enumerate()
|
||||
@@ -213,12 +270,64 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Only regular fields have UI metadata (data fields are internal state)
|
||||
let field_metadata: Vec<_> = regular_fields
|
||||
let bound_values = |select: fn(&RegularParsedField) -> &Option<NumberBound>| -> Vec<_> {
|
||||
regular_fields
|
||||
.iter()
|
||||
.map(|field| match field.ty.regular() {
|
||||
Some(regular) => select(regular).as_ref().map_or(quote!(None), |bound| quote!(Some(#bound))),
|
||||
None => quote!(None),
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let number_soft_min_values = bound_values(|field| &field.number_soft_min);
|
||||
let number_soft_max_values = bound_values(|field| &field.number_soft_max);
|
||||
let number_hard_min_values = bound_values(|field| &field.number_hard_min);
|
||||
let number_hard_max_values = bound_values(|field| &field.number_hard_max);
|
||||
let number_mode_range_values: Vec<_> = regular_fields
|
||||
.iter()
|
||||
.zip(&input_internal)
|
||||
.zip(&default_types)
|
||||
.map(|((field, internal), default_type)| field_metadata_tokens(field, *internal, default_type, core_types))
|
||||
.map(|field| match field.ty.regular() {
|
||||
Some(RegularParsedField { number_mode_range, .. }) => quote!(#number_mode_range),
|
||||
None => quote!(false),
|
||||
})
|
||||
.collect();
|
||||
let number_display_decimal_places: Vec<_> = regular_fields
|
||||
.iter()
|
||||
.map(|field| field.number_display_decimal_places.as_ref().map_or(quote!(None), |i| quote!(Some(#i))))
|
||||
.collect();
|
||||
let number_step: Vec<_> = regular_fields.iter().map(|field| field.number_step.as_ref().map_or(quote!(None), |i| quote!(Some(#i)))).collect();
|
||||
|
||||
let unit_suffix: Vec<_> = regular_fields.iter().map(|field| field.unit.as_ref().map_or(quote!(None), |i| quote!(Some(#i)))).collect();
|
||||
let multiline: Vec<_> = regular_fields
|
||||
.iter()
|
||||
.map(|field| {
|
||||
let multiline = field.multiline;
|
||||
quote!(#multiline)
|
||||
})
|
||||
.collect();
|
||||
let progression: Vec<_> = regular_fields
|
||||
.iter()
|
||||
.map(|field| {
|
||||
let progression = field.progression;
|
||||
quote!(#progression)
|
||||
})
|
||||
.collect();
|
||||
let constant: Vec<_> = regular_fields
|
||||
.iter()
|
||||
.map(|field| {
|
||||
let constant = field.constant;
|
||||
quote!(#constant)
|
||||
})
|
||||
.collect();
|
||||
|
||||
let exposed: Vec<_> = regular_fields
|
||||
.iter()
|
||||
.map(|field| match field.ty.regular() {
|
||||
Some(RegularParsedField { exposed, .. }) => quote!(#exposed),
|
||||
None => {
|
||||
let exposed = !field.is_environment();
|
||||
quote!(#exposed)
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Only eval regular fields (data fields are accessed directly as self.field_name)
|
||||
@@ -749,8 +858,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
Some(cfg) => quote!(#[cfg(#cfg)]),
|
||||
None => quote!(),
|
||||
};
|
||||
let parameter_idents: Vec<_> = regular_fields.iter().filter(|field| !field.is_environment()).map(|field| &field.pat_ident).collect();
|
||||
let node_input_accessor = generate_node_input_references(parsed, ¶meter_idents, core_types, &identifier, &cfg);
|
||||
let node_input_accessor = generate_node_input_references(parsed, &field_idents, core_types, &identifier, &cfg);
|
||||
|
||||
let mapped_node_impl = match (&mapped_struct_where_clause, &mapped_eval_impl) {
|
||||
(Some(mapped_where_clause), Some(mapped_eval)) => quote! {
|
||||
@@ -901,7 +1009,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
use gcore::{Node, NodeIOTypes, concrete, fn_type, ProtoNodeIdentifier, WasmNotSync, NodeIO, ContextFeature};
|
||||
use gcore::value::ClonedNode;
|
||||
use gcore::ops::TypeNode;
|
||||
use gcore::registry::{NodeMetadata, NODE_REGISTRY, NODE_METADATA, DynAnyNode, DowncastBothNode, TypeErasedBox, PanicNode};
|
||||
use gcore::registry::{NodeMetadata, FieldMetadata, NODE_REGISTRY, NODE_METADATA, DynAnyNode, DowncastBothNode, TypeErasedBox, PanicNode, RegistryValueSource, RegistryWidgetOverride};
|
||||
use gcore::ctor::ctor;
|
||||
|
||||
// Use the types specified in the implementation
|
||||
@@ -948,7 +1056,31 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
},
|
||||
version: #version,
|
||||
output_fields: #output_fields,
|
||||
fields: vec![#(#field_metadata,)*],
|
||||
fields: vec![
|
||||
#(
|
||||
FieldMetadata {
|
||||
name: #input_names,
|
||||
widget_override: #widget_override,
|
||||
description: #input_descriptions,
|
||||
internal: #input_internal,
|
||||
exposed: #exposed,
|
||||
value_source: #value_sources,
|
||||
default_colors: #default_colors,
|
||||
default_type: #default_types,
|
||||
number_soft_min: #number_soft_min_values,
|
||||
number_soft_max: #number_soft_max_values,
|
||||
number_hard_min: #number_hard_min_values,
|
||||
number_hard_max: #number_hard_max_values,
|
||||
number_mode_range: #number_mode_range_values,
|
||||
number_display_decimal_places: #number_display_decimal_places,
|
||||
number_step: #number_step,
|
||||
unit: #unit_suffix,
|
||||
multiline: #multiline,
|
||||
progression: #progression,
|
||||
constant: #constant,
|
||||
},
|
||||
)*
|
||||
],
|
||||
};
|
||||
NODE_METADATA.lock().unwrap().insert(#identifier(), metadata);
|
||||
}
|
||||
@@ -956,131 +1088,6 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
})
|
||||
}
|
||||
|
||||
/// The display name an identifier derives, in Title Case.
|
||||
pub(crate) fn derived_display_name(ident: &Ident) -> String {
|
||||
// A lone `_` comes out of the case conversion as a space
|
||||
ident.unraw().to_string().to_case(Case::Title).trim().to_string()
|
||||
}
|
||||
|
||||
/// The name a parameter shows in the UI: its `#[name("…")]`, or else its identifier in Title Case.
|
||||
pub(crate) fn parameter_display_name(field: &ParsedField) -> String {
|
||||
match &field.name {
|
||||
Some(name) => name.value(),
|
||||
None => derived_display_name(&field.pat_ident.ident),
|
||||
}
|
||||
}
|
||||
|
||||
/// The symbol naming a parameter or output in a node's module, like `CountInput` for the `count` parameter.
|
||||
pub(crate) fn symbol_name(ident: &Ident, suffix: &str) -> Ident {
|
||||
format_ident!("{}{suffix}", ident.unraw().to_string().to_case(Case::Pascal), span = ident.span())
|
||||
}
|
||||
|
||||
/// Generated code for `Some(value)` or `None`, by full path so no name in the author's module can stand in for either.
|
||||
pub(crate) fn option_tokens(value: Option<TokenStream2>) -> TokenStream2 {
|
||||
match value {
|
||||
Some(value) => quote!(::core::option::Option::Some(#value)),
|
||||
None => quote!(::core::option::Option::None),
|
||||
}
|
||||
}
|
||||
|
||||
/// The registry's `FieldMetadata` for a parameter, shared by proto node fields and graph imports, which differ only in
|
||||
/// how they work out whether it's internal state and which type its default is built from.
|
||||
pub(crate) fn field_metadata_tokens(field: &ParsedField, internal: bool, default_type: &TokenStream2, core_types: &TokenStream2) -> TokenStream2 {
|
||||
let registry = quote!(#core_types::registry);
|
||||
|
||||
let name = parameter_display_name(field);
|
||||
let description = &field.description;
|
||||
let exposed = match field.ty.regular() {
|
||||
Some(regular) => regular.exposed,
|
||||
None => !field.is_environment(),
|
||||
};
|
||||
|
||||
let widget_override = match &field.widget_override {
|
||||
ParsedWidgetOverride::None => quote!(#registry::RegistryWidgetOverride::None),
|
||||
ParsedWidgetOverride::Hidden => quote!(#registry::RegistryWidgetOverride::Hidden),
|
||||
ParsedWidgetOverride::String(text) => quote!(#registry::RegistryWidgetOverride::String(#text)),
|
||||
ParsedWidgetOverride::Custom(key) => quote!(#registry::RegistryWidgetOverride::Custom(#key)),
|
||||
};
|
||||
|
||||
// A string literal default keeps its contents, and any other expression is stringified for the editor to parse by type
|
||||
let value_source = match field.ty.value_source() {
|
||||
ParsedValueSource::Default(data) => {
|
||||
let data_string = data.to_string();
|
||||
if data_string.starts_with('"') && data_string.ends_with('"') && data_string.len() >= 2 {
|
||||
quote!(#registry::RegistryValueSource::Default(#data))
|
||||
} else {
|
||||
quote!(#registry::RegistryValueSource::Default(::core::stringify!(#data)))
|
||||
}
|
||||
}
|
||||
ParsedValueSource::Scope(data) => {
|
||||
if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(_), .. }) = data.as_ref() {
|
||||
quote!(#registry::RegistryValueSource::Scope(#data))
|
||||
} else {
|
||||
quote!(#registry::RegistryValueSource::Scope(#data.as_static_str()))
|
||||
}
|
||||
}
|
||||
ParsedValueSource::SourceId => quote!(#registry::RegistryValueSource::SourceId),
|
||||
ParsedValueSource::NodePath => quote!(#registry::RegistryValueSource::NodePath),
|
||||
ParsedValueSource::None => quote!(#registry::RegistryValueSource::None),
|
||||
};
|
||||
|
||||
let default_colors = match field.ty.regular() {
|
||||
Some(RegularParsedField {
|
||||
value_source: ParsedValueSource::Default(data),
|
||||
..
|
||||
}) => option_tokens(color_constant_paths(data).map(|paths| quote!(&[#(#paths),*]))),
|
||||
_ => option_tokens(None),
|
||||
};
|
||||
|
||||
let regular = field.ty.regular();
|
||||
let bound = |select: fn(&RegularParsedField) -> &Option<NumberBound>| option_tokens(regular.and_then(|regular| select(regular).as_ref()).map(ToTokens::to_token_stream));
|
||||
let number_soft_min = bound(|regular| ®ular.number_soft_min);
|
||||
let number_soft_max = bound(|regular| ®ular.number_soft_max);
|
||||
let number_hard_min = bound(|regular| ®ular.number_hard_min);
|
||||
let number_hard_max = bound(|regular| ®ular.number_hard_max);
|
||||
let number_mode_range = regular.is_some_and(|regular| regular.number_mode_range);
|
||||
|
||||
let number_display_decimal_places = option_tokens(field.number_display_decimal_places.as_ref().map(ToTokens::to_token_stream));
|
||||
let number_step = option_tokens(field.number_step.as_ref().map(ToTokens::to_token_stream));
|
||||
let unit = option_tokens(field.unit.as_ref().map(ToTokens::to_token_stream));
|
||||
let labels = option_tokens(field.labels.as_ref().map(|(x, y)| quote!((#x, #y))));
|
||||
let ParsedField {
|
||||
multiline,
|
||||
progression,
|
||||
constant,
|
||||
integer,
|
||||
blank_assist,
|
||||
..
|
||||
} = field;
|
||||
|
||||
quote! {
|
||||
#registry::FieldMetadata {
|
||||
name: #name,
|
||||
description: #description,
|
||||
internal: #internal,
|
||||
exposed: #exposed,
|
||||
widget_override: #widget_override,
|
||||
value_source: #value_source,
|
||||
default_colors: #default_colors,
|
||||
default_type: #default_type,
|
||||
number_soft_min: #number_soft_min,
|
||||
number_soft_max: #number_soft_max,
|
||||
number_hard_min: #number_hard_min,
|
||||
number_hard_max: #number_hard_max,
|
||||
number_mode_range: #number_mode_range,
|
||||
number_display_decimal_places: #number_display_decimal_places,
|
||||
number_step: #number_step,
|
||||
unit: #unit,
|
||||
multiline: #multiline,
|
||||
progression: #progression,
|
||||
constant: #constant,
|
||||
labels: #labels,
|
||||
integer: #integer,
|
||||
blank_assist: #blank_assist,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The `Color::*` constant paths making up a default expression, when it consists solely of them (the form used by color and gradient parameter defaults).
|
||||
fn color_constant_paths(tokens: &TokenStream2) -> Option<Vec<ExprPath>> {
|
||||
use syn::parse::Parser;
|
||||
@@ -1101,25 +1108,26 @@ fn color_constant_paths(tokens: &TokenStream2) -> Option<Vec<ExprPath>> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Generates the module named after the node's function, holding its identifier, its parameter count, and a symbol for each parameter.
|
||||
/// The inputs the compiler fills in come after the parameters and get no symbol, so a graph can't name one.
|
||||
fn generate_node_input_references(parsed: &ParsedNodeFn, parameter_idents: &[&PatIdent], core_types: &TokenStream2, identifier: &Ident, cfg: &TokenStream2) -> TokenStream2 {
|
||||
let inputs_module_name = &parsed.fn_name;
|
||||
/// Generates the per-parameter symbol types used to reference this node's inputs.
|
||||
fn generate_node_input_references(parsed: &ParsedNodeFn, field_idents: &[&PatIdent], core_types: &TokenStream2, identifier: &Ident, cfg: &TokenStream2) -> TokenStream2 {
|
||||
let inputs_module_name = format_ident!("{}", parsed.struct_name.to_string().to_case(Case::Snake));
|
||||
|
||||
// Every parameter gets a plain unit struct: the symbol used across the codebase to name this input
|
||||
let generated_input_accessor = parameter_idents.iter().enumerate().map(|(input_index, input_ident)| {
|
||||
// TODO: figure out a better name that doesn't conflict with so many types
|
||||
let struct_name = symbol_name(&input_ident.ident, "Input");
|
||||
quote! {
|
||||
pub struct #struct_name;
|
||||
impl #core_types::NodeParameter for #struct_name {
|
||||
const NODE_IDENTIFIER: #core_types::ProtoNodeIdentifier = #inputs_module_name::IDENTIFIER;
|
||||
const INDEX: usize = #input_index;
|
||||
}
|
||||
let mut generated_input_accessor = Vec::new();
|
||||
if !parsed.attributes.flags.skip_impl {
|
||||
for (input_index, input_ident) in field_idents.iter().enumerate() {
|
||||
// TODO: figure out a better name that doesn't conflict with so many types
|
||||
let struct_name = format_ident!("{}Input", input_ident.ident.to_string().to_case(Case::Pascal));
|
||||
|
||||
// Every parameter gets a plain unit struct: the symbol used across the codebase to name this input
|
||||
generated_input_accessor.push(quote! {
|
||||
pub struct #struct_name;
|
||||
impl #core_types::NodeParameter for #struct_name {
|
||||
const NODE_IDENTIFIER: #core_types::ProtoNodeIdentifier = #inputs_module_name::IDENTIFIER;
|
||||
const INDEX: usize = #input_index;
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
let parameter_count = parameter_idents.len();
|
||||
}
|
||||
|
||||
quote! {
|
||||
#cfg
|
||||
@@ -1128,8 +1136,6 @@ fn generate_node_input_references(parsed: &ParsedNodeFn, parameter_idents: &[&Pa
|
||||
|
||||
/// The `ProtoNodeIdentifier` of this node without any generics attached to it
|
||||
pub const IDENTIFIER: #core_types::ProtoNodeIdentifier = #identifier();
|
||||
/// How many parameters this node has, which come before the inputs the compiler fills in.
|
||||
pub const PARAMETER_COUNT: usize = #parameter_count;
|
||||
#(#generated_input_accessor)*
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -5,7 +5,6 @@ mod codegen;
|
||||
mod crate_ident;
|
||||
mod derive_choice_type;
|
||||
mod destructure;
|
||||
mod graph;
|
||||
mod parsing;
|
||||
mod validation;
|
||||
|
||||
@@ -17,38 +16,6 @@ pub fn node(attr: TokenStream, item: TokenStream) -> TokenStream {
|
||||
parsing::new_node_fn(attr.into(), item.into()).unwrap_or_else(|err| err.to_compile_error()).into()
|
||||
}
|
||||
|
||||
/// Defines a node as a subgraph of other nodes, the way `#[node]` defines a proto node.
|
||||
///
|
||||
/// The function's parameters are the subgraph's imports, parsed like a proto node's parameters, so they take the same
|
||||
/// value and widget attributes. On an import, `#[hard]` bounds the widget without clamping a wired value.
|
||||
/// `out!(...)` names its exports. The body binds nodes with `let`, wires them with `>>` (which feeds its left side
|
||||
/// into the primary input of the node on its right), and ends with `return`, giving one value per export. Every
|
||||
/// parameter is named in a call, and a bare name feeds the binding or import of that name to the parameter of the same
|
||||
/// name. Node state goes in methods after the call, each written once: `.at(x, y)`, `.layer()`, `.hidden()`, `.locked()`,
|
||||
/// `.pinned()`, `.named("…")`, and `.call_argument::<Footprint>()`. After those, an output's name like `.captures` wires from that
|
||||
/// output of the node, which also works on a binding.
|
||||
///
|
||||
/// ```ignore
|
||||
/// /// Outlines its content.
|
||||
/// #[node_macro::graph(category("Vector: Style"))]
|
||||
/// pub fn outlined(
|
||||
/// content: List<Graphic>,
|
||||
/// /// Outline thickness.
|
||||
/// #[unit(" px")]
|
||||
/// width: Item<f64>,
|
||||
/// ) -> out!(
|
||||
/// /// The outlined content.
|
||||
/// out,
|
||||
/// ) {
|
||||
/// return content >> stroke(weight = width).at(7, 0);
|
||||
/// }
|
||||
/// ```
|
||||
#[proc_macro_error]
|
||||
#[proc_macro_attribute]
|
||||
pub fn graph(attr: TokenStream, item: TokenStream) -> TokenStream {
|
||||
graph::new_graph_fn(attr.into(), item.into()).unwrap_or_else(|err| err.to_compile_error()).into()
|
||||
}
|
||||
|
||||
/// Derives `Destructure` for a struct returned by a multi-output node, making each of its `Item<T>` or `List<T>` fields an output connector.
|
||||
///
|
||||
/// A node function returning such a struct (rather than an `Item` or `List`) becomes a multi-output node. The preprocessor
|
||||
|
||||
@@ -137,10 +137,6 @@ pub struct ParsedField {
|
||||
pub progression: bool,
|
||||
pub constant: bool,
|
||||
pub is_data_field: bool,
|
||||
/// The X and Y labels of a Vec2 widget, from `#[labels("W", "H")]`.
|
||||
pub labels: Option<(LitStr, LitStr)>,
|
||||
pub integer: bool,
|
||||
pub blank_assist: bool,
|
||||
}
|
||||
|
||||
impl ParsedField {
|
||||
@@ -174,9 +170,6 @@ impl ParsedField {
|
||||
progression: false,
|
||||
constant: false,
|
||||
is_data_field: false,
|
||||
labels: None,
|
||||
integer: false,
|
||||
blank_assist: true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -326,8 +319,8 @@ impl ToTokens for NumberBound {
|
||||
/// Unlike a Rust range there is no `..=` form, `..` is purely this attribute DSL's bounds operator.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct NumberRange {
|
||||
pub(crate) start: Option<NumberBound>,
|
||||
pub(crate) end: Option<NumberBound>,
|
||||
start: Option<NumberBound>,
|
||||
end: Option<NumberBound>,
|
||||
}
|
||||
|
||||
impl Parse for NumberRange {
|
||||
@@ -826,8 +819,7 @@ fn parse_node_implementations<T: Parse>(attr: &Attribute, name: &Ident) -> syn::
|
||||
})
|
||||
}
|
||||
|
||||
/// Parses a parameter and its attributes, for a proto node's field or a graph's import.
|
||||
pub(crate) fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Result<ParsedField> {
|
||||
fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Result<ParsedField> {
|
||||
let ident = &pat_ident.ident;
|
||||
|
||||
// Checks for the #[data] attribute, indicating that this is a data field rather than an input parameter to the node.
|
||||
@@ -1012,22 +1004,6 @@ pub(crate) fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) ->
|
||||
})
|
||||
.transpose()?;
|
||||
|
||||
// `#[labels("W", "H")]` names a Vec2 widget's two fields, and `#[integer]` makes a number or Vec2 widget take only integers
|
||||
let labels = extract_attribute(attrs, "labels")
|
||||
.map(|attr| {
|
||||
let labels: Vec<LitStr> = attr.parse_args_with(Punctuated::<LitStr, Comma>::parse_terminated)?.into_iter().collect();
|
||||
let [x, y] = <[LitStr; 2]>::try_from(labels).map_err(|_| Error::new_spanned(attr, "Give a Vec2 widget two labels, like `#[labels(\"W\", \"H\")]`"))?;
|
||||
Ok::<_, Error>((x, y))
|
||||
})
|
||||
.transpose()?;
|
||||
let integer = extract_attribute(attrs, "integer").is_some();
|
||||
|
||||
// `#[blank_assist(false)]` drops the space a widget leaves for the assist area beside it
|
||||
let blank_assist = extract_attribute(attrs, "blank_assist")
|
||||
.map(|attr| attr.parse_args::<syn::LitBool>().map(|enabled| enabled.value))
|
||||
.transpose()?
|
||||
.unwrap_or(true);
|
||||
|
||||
let (is_node, node_input_type, node_output_type) = parse_node_type(&ty);
|
||||
let description = attrs
|
||||
.iter()
|
||||
@@ -1086,9 +1062,6 @@ pub(crate) fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) ->
|
||||
progression,
|
||||
constant,
|
||||
is_data_field,
|
||||
labels,
|
||||
integer,
|
||||
blank_assist,
|
||||
})
|
||||
} else {
|
||||
let implementations = extract_attribute(attrs, "implementations")
|
||||
@@ -1141,9 +1114,6 @@ pub(crate) fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) ->
|
||||
progression,
|
||||
constant,
|
||||
is_data_field,
|
||||
labels,
|
||||
integer,
|
||||
blank_assist,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1443,9 +1413,6 @@ mod tests {
|
||||
progression: false,
|
||||
constant: false,
|
||||
is_data_field: false,
|
||||
labels: None,
|
||||
integer: false,
|
||||
blank_assist: true,
|
||||
}],
|
||||
body: TokenStream2::new(),
|
||||
description: String::from("Multi\nLine\n"),
|
||||
@@ -1508,9 +1475,6 @@ mod tests {
|
||||
progression: false,
|
||||
constant: false,
|
||||
is_data_field: false,
|
||||
labels: None,
|
||||
integer: false,
|
||||
blank_assist: true,
|
||||
},
|
||||
ParsedField {
|
||||
pat_ident: pat_ident("translate"),
|
||||
@@ -1535,9 +1499,6 @@ mod tests {
|
||||
progression: false,
|
||||
constant: false,
|
||||
is_data_field: false,
|
||||
labels: None,
|
||||
integer: false,
|
||||
blank_assist: true,
|
||||
},
|
||||
],
|
||||
body: TokenStream2::new(),
|
||||
@@ -1601,9 +1562,6 @@ mod tests {
|
||||
progression: false,
|
||||
constant: false,
|
||||
is_data_field: false,
|
||||
labels: None,
|
||||
integer: false,
|
||||
blank_assist: true,
|
||||
}],
|
||||
body: TokenStream2::new(),
|
||||
description: "Test\n".into(),
|
||||
@@ -1670,9 +1628,6 @@ mod tests {
|
||||
progression: false,
|
||||
constant: false,
|
||||
is_data_field: false,
|
||||
labels: None,
|
||||
integer: false,
|
||||
blank_assist: true,
|
||||
}],
|
||||
body: TokenStream2::new(),
|
||||
description: String::new(),
|
||||
@@ -1742,9 +1697,6 @@ mod tests {
|
||||
progression: false,
|
||||
constant: false,
|
||||
is_data_field: false,
|
||||
labels: None,
|
||||
integer: false,
|
||||
blank_assist: true,
|
||||
}],
|
||||
body: TokenStream2::new(),
|
||||
description: String::new(),
|
||||
@@ -1839,9 +1791,6 @@ mod tests {
|
||||
progression: false,
|
||||
constant: false,
|
||||
is_data_field: false,
|
||||
labels: None,
|
||||
integer: false,
|
||||
blank_assist: true,
|
||||
}],
|
||||
body: TokenStream2::new(),
|
||||
description: String::new(),
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
use crate::graph::VALUE_HELPERS;
|
||||
use crate::parsing::{Implementation, NodeOutputTier, NodeParsedField, ParsedField, ParsedFieldType, ParsedNodeFn, RegularParsedField, output_payload, output_tier};
|
||||
use crate::parsing::{Implementation, NodeOutputTier, NodeParsedField, ParsedFieldType, ParsedNodeFn, RegularParsedField, output_payload, output_tier};
|
||||
use proc_macro_error3::{abort_if_dirty, emit_error};
|
||||
use quote::quote;
|
||||
use syn::spanned::Spanned;
|
||||
use syn::{GenericParam, Ident, Type};
|
||||
use syn::{GenericParam, Type};
|
||||
|
||||
pub fn validate_node_fn(parsed: &ParsedNodeFn) -> syn::Result<()> {
|
||||
let validators: &[fn(&ParsedNodeFn)] = &[
|
||||
// Add more validators here as needed
|
||||
validate_implementations_for_generics,
|
||||
validate_implementations_row_counts,
|
||||
|parsed| validate_parameters(&parsed.fields),
|
||||
validate_primary_input_expose,
|
||||
validate_min_max,
|
||||
validate_range_slider_bounds,
|
||||
validate_no_item_parameters,
|
||||
validate_element_wise,
|
||||
validate_ranked_inputs,
|
||||
validate_async,
|
||||
validate_non_parameters_trail,
|
||||
|parsed| validate_name_isnt_a_value_helper(&parsed.fn_name),
|
||||
];
|
||||
|
||||
for validator in validators {
|
||||
@@ -28,20 +28,6 @@ pub fn validate_node_fn(parsed: &ParsedNodeFn) -> syn::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A graph body reads a call to a value helper like `rgb(...)` as a value, so a node or graph of that name couldn't be called there.
|
||||
pub(crate) fn validate_name_isnt_a_value_helper(name: &Ident) {
|
||||
if let Some(message) = value_helper_name_violation(name) {
|
||||
emit_error!(name.span(), "{}", message);
|
||||
}
|
||||
}
|
||||
|
||||
fn value_helper_name_violation(name: &Ident) -> Option<String> {
|
||||
let name = name.to_string();
|
||||
VALUE_HELPERS
|
||||
.contains(&name.as_str())
|
||||
.then(|| format!("A node can't be named `{name}`, since graphs use that name for a value helper"))
|
||||
}
|
||||
|
||||
fn validate_no_item_parameters(parsed: &ParsedNodeFn) {
|
||||
if parsed.attributes.flags.skip_impl {
|
||||
return;
|
||||
@@ -305,15 +291,8 @@ fn is_unit_type(ty: &Type) -> bool {
|
||||
matches!(ty, Type::Tuple(tuple) if tuple.elems.is_empty())
|
||||
}
|
||||
|
||||
/// The checks on a node's parameters, shared by proto node fields and graph imports, where the first is the primary input.
|
||||
pub(crate) fn validate_parameters(fields: &[ParsedField]) {
|
||||
validate_primary_input_expose(fields);
|
||||
validate_min_max(fields);
|
||||
validate_range_slider_bounds(fields);
|
||||
}
|
||||
|
||||
fn validate_min_max(fields: &[ParsedField]) {
|
||||
for field in fields {
|
||||
fn validate_min_max(parsed: &ParsedNodeFn) {
|
||||
for field in &parsed.fields {
|
||||
if let Some(RegularParsedField {
|
||||
number_hard_max,
|
||||
number_hard_min,
|
||||
@@ -372,8 +351,8 @@ fn validate_min_max(fields: &[ParsedField]) {
|
||||
|
||||
/// A `#[range]` slider needs a defined extent on both ends. The extent comes from `#[soft]` when present,
|
||||
/// otherwise it falls back to `#[hard]`, so each end must be covered by at least one of the two attributes.
|
||||
fn validate_range_slider_bounds(fields: &[ParsedField]) {
|
||||
for field in fields {
|
||||
fn validate_range_slider_bounds(parsed: &ParsedNodeFn) {
|
||||
for field in &parsed.fields {
|
||||
if let Some(RegularParsedField {
|
||||
number_mode_range: true,
|
||||
number_soft_min,
|
||||
@@ -405,8 +384,8 @@ fn validate_range_slider_bounds(fields: &[ParsedField]) {
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_primary_input_expose(fields: &[ParsedField]) {
|
||||
if let Some(field) = fields.first()
|
||||
fn validate_primary_input_expose(parsed: &ParsedNodeFn) {
|
||||
if let Some(field) = parsed.fields.first()
|
||||
&& let Some(RegularParsedField { exposed: true, .. }) = field.ty.regular()
|
||||
{
|
||||
let pat_ident = &field.pat_ident;
|
||||
@@ -415,7 +394,7 @@ fn validate_primary_input_expose(fields: &[ParsedField]) {
|
||||
"Unnecessary #[expose] attribute on primary input `{}`. Primary inputs are always exposed.",
|
||||
pat_ident.ident;
|
||||
help = "You can safely remove the #[expose] attribute from this field.";
|
||||
note = "`{}` is the node's primary input, which is always exposed by default", pat_ident.ident
|
||||
note = "The function's second argument, `{}`, is the node's primary input and it's always exposed by default", pat_ident.ident
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -483,7 +462,7 @@ fn validate_async(parsed: &ParsedNodeFn) {
|
||||
}
|
||||
|
||||
/// The arguments that aren't parameters, which are `#[data]` state and the inputs the compiler fills in, go after the parameters.
|
||||
/// That keeps the primary input at index 0, where the editor's chain flow and a graph's `>>` expect it.
|
||||
/// That keeps the primary input at index 0, where the editor's chain flow and other nodes feeding the primary input expect it.
|
||||
fn validate_non_parameters_trail(parsed: &ParsedNodeFn) {
|
||||
if let Some((span, message)) = non_parameter_order_violation(parsed) {
|
||||
emit_error!(span, "{}", message);
|
||||
@@ -496,7 +475,7 @@ fn non_parameter_order_violation(parsed: &ParsedNodeFn) -> Option<(proc_macro2::
|
||||
|
||||
let (parameter, non_parameter) = (¶meter.pat_ident, &non_parameter.pat_ident.ident);
|
||||
let message = format!(
|
||||
"The parameter `{}` comes after `{non_parameter}`, which isn't a parameter. Move `{non_parameter}` after the parameters: `#[data]` state and the inputs the compiler fills in (`#[scope]`, `#[source_id]`, and `#[node_path]`) go last, so the primary input is always the node's first input, which is the one the editor's chain flow and a graph's `>>` feed.",
|
||||
"The parameter `{}` comes after `{non_parameter}`, which isn't a parameter. Move `{non_parameter}` after the parameters: `#[data]` state and the inputs the compiler fills in (`#[scope]`, `#[source_id]`, and `#[node_path]`) go last, so the primary input is always the node's first input, which is the one the editor's chain flow feeds.",
|
||||
parameter.ident
|
||||
);
|
||||
Some((parameter.span(), message))
|
||||
@@ -748,25 +727,6 @@ mod tests {
|
||||
assert_eq!(only_non_parameters, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_node_named_like_a_value_helper_is_rejected() {
|
||||
let named = |input: TokenStream| value_helper_name_violation(&parse_node_fn(quote::quote!(category("Test")), input).expect("The test node fn should parse").fn_name);
|
||||
|
||||
let message = named(quote::quote!(
|
||||
fn rgb(_: impl Ctx, value: Item<f64>) -> Item<f64> {
|
||||
value
|
||||
}
|
||||
));
|
||||
assert!(message.is_some_and(|message| message.contains("can't be named `rgb`")));
|
||||
|
||||
let other = named(quote::quote!(
|
||||
fn tint(_: impl Ctx, value: Item<f64>) -> Item<f64> {
|
||||
value
|
||||
}
|
||||
));
|
||||
assert_eq!(other, None);
|
||||
}
|
||||
|
||||
fn row_count_violations(input: TokenStream) -> Vec<String> {
|
||||
let parsed = parse_node_fn(quote::quote!(category("Test")), input).expect("The test node fn should parse");
|
||||
implementations_row_count_violations(&parsed).into_iter().map(|(_, message)| message).collect()
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
use core_types::list::Item;
|
||||
use core_types::{Color, Ctx};
|
||||
use graphic_types::raster_types::{CPU, GPU, Raster};
|
||||
use graphic_types::{Effect, EffectOperation, Generator, Graphic, Vector, stamp_effect};
|
||||
use vector_types::Gradient;
|
||||
|
||||
/// Blurs what lies beneath the input graphics within their shape, like frosted glass seen through them.
|
||||
///
|
||||
/// The content draws over the blur, hiding it where opaque. Lowering the content's fill reveals the blur at full strength, while a translucent paint shows it only as strongly as the paint covers.
|
||||
#[node_macro::node(category("Raster: Effect"))]
|
||||
fn background_blur<T>(
|
||||
_: impl Ctx,
|
||||
/// The content to see the blurred backdrop through.
|
||||
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// How far the blur spreads each point of what lies beneath.
|
||||
#[unit(" px")]
|
||||
#[range]
|
||||
#[hard(0..)]
|
||||
#[soft(..100)]
|
||||
#[default(10.)]
|
||||
radius: Item<f64>,
|
||||
/// Use a box kernel instead of a circular Gaussian kernel, which averages evenly and leaves boxy artifacts.
|
||||
box_blur: Item<bool>,
|
||||
/// Opt to incorrectly blend the colors in gamma space for compatibility with the results from other software.
|
||||
gamma: Item<bool>,
|
||||
) -> Item<T> {
|
||||
let mut content = content;
|
||||
stamp_effect(
|
||||
&mut content,
|
||||
Effect::new(&EffectOperation::BackgroundBlur {
|
||||
radius: radius.into_element(),
|
||||
box_blur: box_blur.into_element(),
|
||||
gamma: gamma.into_element(),
|
||||
}),
|
||||
);
|
||||
content
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
use core_types::list::Item;
|
||||
use core_types::{Color, Ctx};
|
||||
use graphic_types::blend_if::{BlendIfRanges, BlendRange, ChannelRanges};
|
||||
use graphic_types::raster_types::{CPU, GPU, Raster};
|
||||
use graphic_types::{BlendIfChannel, Effect, EffectOperation, Generator, Graphic, Vector, stamp_effect};
|
||||
use vector_types::Gradient;
|
||||
|
||||
/// Shows the content only where the levels of its own colors, and those of what lies beneath it, fall within ranges, fading it out across each range's falloffs.
|
||||
/// The content's own ranges fade it like its fill does, leaving the shadows and glows cast from it, while the ranges beneath fade everything it draws like its opacity does. The gray, red, green, and blue channels' ranges all apply together.
|
||||
#[node_macro::node(category("Graphic"), inspector("blend_if_inspector"))]
|
||||
fn blend_if<T>(
|
||||
_: impl Ctx,
|
||||
/// The content that will be composited when rendering.
|
||||
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// Hides the content where its gray level falls below this, fading it in from here to the range start.
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(0.)]
|
||||
content_falloff_start: Item<f64>,
|
||||
/// Shows the content fully where its gray level is at least this, up to the range end.
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(0.)]
|
||||
content_range_start: Item<f64>,
|
||||
/// Shows the content fully where its gray level is at most this, down to the range start.
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(100.)]
|
||||
content_range_end: Item<f64>,
|
||||
/// Hides the content where its gray level rises above this, fading it in from here to the range end.
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(100.)]
|
||||
content_falloff_end: Item<f64>,
|
||||
/// Hides the content and its effects where the gray level of what lies beneath it falls below this, fading it in from here to the range start.
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(0.)]
|
||||
underlying_falloff_start: Item<f64>,
|
||||
/// Shows the content and its effects fully where the gray level of what lies beneath it is at least this, up to the range end.
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(0.)]
|
||||
underlying_range_start: Item<f64>,
|
||||
/// Shows the content and its effects fully where the gray level of what lies beneath it is at most this, down to the range start.
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(100.)]
|
||||
underlying_range_end: Item<f64>,
|
||||
/// Hides the content and its effects where the gray level of what lies beneath it rises above this, fading it in from here to the range end.
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(100.)]
|
||||
underlying_falloff_end: Item<f64>,
|
||||
/// Hides the content where its red level falls below this, fading it in from here to the range start.
|
||||
#[name("(Red) Content Falloff Start")]
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(0.)]
|
||||
red_content_falloff_start: Item<f64>,
|
||||
/// Shows the content fully where its red level is at least this, up to the range end.
|
||||
#[name("(Red) Content Range Start")]
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(0.)]
|
||||
red_content_range_start: Item<f64>,
|
||||
/// Shows the content fully where its red level is at most this, down to the range start.
|
||||
#[name("(Red) Content Range End")]
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(100.)]
|
||||
red_content_range_end: Item<f64>,
|
||||
/// Hides the content where its red level rises above this, fading it in from here to the range end.
|
||||
#[name("(Red) Content Falloff End")]
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(100.)]
|
||||
red_content_falloff_end: Item<f64>,
|
||||
/// Hides the content and its effects where the red level of what lies beneath it falls below this, fading it in from here to the range start.
|
||||
#[name("(Red) Underlying Falloff Start")]
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(0.)]
|
||||
red_underlying_falloff_start: Item<f64>,
|
||||
/// Shows the content and its effects fully where the red level of what lies beneath it is at least this, up to the range end.
|
||||
#[name("(Red) Underlying Range Start")]
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(0.)]
|
||||
red_underlying_range_start: Item<f64>,
|
||||
/// Shows the content and its effects fully where the red level of what lies beneath it is at most this, down to the range start.
|
||||
#[name("(Red) Underlying Range End")]
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(100.)]
|
||||
red_underlying_range_end: Item<f64>,
|
||||
/// Hides the content and its effects where the red level of what lies beneath it rises above this, fading it in from here to the range end.
|
||||
#[name("(Red) Underlying Falloff End")]
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(100.)]
|
||||
red_underlying_falloff_end: Item<f64>,
|
||||
/// Hides the content where its green level falls below this, fading it in from here to the range start.
|
||||
#[name("(Green) Content Falloff Start")]
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(0.)]
|
||||
green_content_falloff_start: Item<f64>,
|
||||
/// Shows the content fully where its green level is at least this, up to the range end.
|
||||
#[name("(Green) Content Range Start")]
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(0.)]
|
||||
green_content_range_start: Item<f64>,
|
||||
/// Shows the content fully where its green level is at most this, down to the range start.
|
||||
#[name("(Green) Content Range End")]
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(100.)]
|
||||
green_content_range_end: Item<f64>,
|
||||
/// Hides the content where its green level rises above this, fading it in from here to the range end.
|
||||
#[name("(Green) Content Falloff End")]
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(100.)]
|
||||
green_content_falloff_end: Item<f64>,
|
||||
/// Hides the content and its effects where the green level of what lies beneath it falls below this, fading it in from here to the range start.
|
||||
#[name("(Green) Underlying Falloff Start")]
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(0.)]
|
||||
green_underlying_falloff_start: Item<f64>,
|
||||
/// Shows the content and its effects fully where the green level of what lies beneath it is at least this, up to the range end.
|
||||
#[name("(Green) Underlying Range Start")]
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(0.)]
|
||||
green_underlying_range_start: Item<f64>,
|
||||
/// Shows the content and its effects fully where the green level of what lies beneath it is at most this, down to the range start.
|
||||
#[name("(Green) Underlying Range End")]
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(100.)]
|
||||
green_underlying_range_end: Item<f64>,
|
||||
/// Hides the content and its effects where the green level of what lies beneath it rises above this, fading it in from here to the range end.
|
||||
#[name("(Green) Underlying Falloff End")]
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(100.)]
|
||||
green_underlying_falloff_end: Item<f64>,
|
||||
/// Hides the content where its blue level falls below this, fading it in from here to the range start.
|
||||
#[name("(Blue) Content Falloff Start")]
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(0.)]
|
||||
blue_content_falloff_start: Item<f64>,
|
||||
/// Shows the content fully where its blue level is at least this, up to the range end.
|
||||
#[name("(Blue) Content Range Start")]
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(0.)]
|
||||
blue_content_range_start: Item<f64>,
|
||||
/// Shows the content fully where its blue level is at most this, down to the range start.
|
||||
#[name("(Blue) Content Range End")]
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(100.)]
|
||||
blue_content_range_end: Item<f64>,
|
||||
/// Hides the content where its blue level rises above this, fading it in from here to the range end.
|
||||
#[name("(Blue) Content Falloff End")]
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(100.)]
|
||||
blue_content_falloff_end: Item<f64>,
|
||||
/// Hides the content and its effects where the blue level of what lies beneath it falls below this, fading it in from here to the range start.
|
||||
#[name("(Blue) Underlying Falloff Start")]
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(0.)]
|
||||
blue_underlying_falloff_start: Item<f64>,
|
||||
/// Shows the content and its effects fully where the blue level of what lies beneath it is at least this, up to the range end.
|
||||
#[name("(Blue) Underlying Range Start")]
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(0.)]
|
||||
blue_underlying_range_start: Item<f64>,
|
||||
/// Shows the content and its effects fully where the blue level of what lies beneath it is at most this, down to the range start.
|
||||
#[name("(Blue) Underlying Range End")]
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(100.)]
|
||||
blue_underlying_range_end: Item<f64>,
|
||||
/// Hides the content and its effects where the blue level of what lies beneath it rises above this, fading it in from here to the range end.
|
||||
#[name("(Blue) Underlying Falloff End")]
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(100.)]
|
||||
blue_underlying_falloff_end: Item<f64>,
|
||||
/// Which channel's ranges are shown for editing.
|
||||
_channel: Item<BlendIfChannel>,
|
||||
) -> Item<T> {
|
||||
let range = |falloff_start: Item<f64>, range_start: Item<f64>, range_end: Item<f64>, falloff_end: Item<f64>| BlendRange {
|
||||
falloff_start: falloff_start.into_element(),
|
||||
range_start: range_start.into_element(),
|
||||
range_end: range_end.into_element(),
|
||||
falloff_end: falloff_end.into_element(),
|
||||
};
|
||||
let ranges = BlendIfRanges {
|
||||
content: ChannelRanges {
|
||||
gray: range(content_falloff_start, content_range_start, content_range_end, content_falloff_end),
|
||||
red: range(red_content_falloff_start, red_content_range_start, red_content_range_end, red_content_falloff_end),
|
||||
green: range(green_content_falloff_start, green_content_range_start, green_content_range_end, green_content_falloff_end),
|
||||
blue: range(blue_content_falloff_start, blue_content_range_start, blue_content_range_end, blue_content_falloff_end),
|
||||
},
|
||||
underlying: ChannelRanges {
|
||||
gray: range(underlying_falloff_start, underlying_range_start, underlying_range_end, underlying_falloff_end),
|
||||
red: range(red_underlying_falloff_start, red_underlying_range_start, red_underlying_range_end, red_underlying_falloff_end),
|
||||
green: range(green_underlying_falloff_start, green_underlying_range_start, green_underlying_range_end, green_underlying_falloff_end),
|
||||
blue: range(blue_underlying_falloff_start, blue_underlying_range_start, blue_underlying_range_end, blue_underlying_falloff_end),
|
||||
},
|
||||
};
|
||||
|
||||
let mut content = content;
|
||||
stamp_effect(&mut content, Effect::new(&EffectOperation::BlendIf(Box::new(ranges))));
|
||||
content
|
||||
}
|
||||
@@ -971,4 +971,30 @@ mod test {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paint_overlay_fades_a_color_paint_by_its_own_blend_ifs() {
|
||||
use graphic_types::blend_if::BlendIfRanges;
|
||||
use graphic_types::{Effect, EffectOperation, stamp_effect};
|
||||
|
||||
// A black paint shown only where its gray is at least half, so it paints nothing
|
||||
let mut hides_darks = BlendIfRanges::default();
|
||||
hides_darks.content.gray.falloff_start = 50.;
|
||||
hides_darks.content.gray.range_start = 50.;
|
||||
let mut paint = Item::new_from_element(Color::BLACK);
|
||||
stamp_effect(&mut paint, Effect::new(&EffectOperation::BlendIf(Box::new(hides_darks))));
|
||||
|
||||
let result = super::paint_overlay(
|
||||
(),
|
||||
Item::new_from_element(Raster::new_cpu(Image::new(1, 1, Color::WHITE))),
|
||||
Item::new_from_element(Graphic::from(paint)),
|
||||
BlendMode::Normal.into(),
|
||||
100_f64.into(),
|
||||
false.into(),
|
||||
DAffine2::IDENTITY.into(),
|
||||
);
|
||||
let color = raster_kernels::evaluate_raster_effects(result).into_element().data[0];
|
||||
|
||||
assert!(color.r() > 0.99, "the hidden black paint leaves {color:?}");
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
pub mod backdrop;
|
||||
pub mod blend_if;
|
||||
pub mod distortions;
|
||||
pub mod effects;
|
||||
pub mod filters;
|
||||
|
||||
@@ -9,7 +9,6 @@ use graphic_types::graphic::{Graphic, IntoGraphicList, is_lone_anonymous_leaf};
|
||||
use graphic_types::{Artboard, Effects, Generator, Vector};
|
||||
use rand::SeedableRng;
|
||||
use rand::seq::SliceRandom;
|
||||
use raster_kernels::adjustments::PreparedAdjustment;
|
||||
use raster_kernels::value_effects;
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
use std::cmp::Ordering;
|
||||
@@ -1168,13 +1167,14 @@ fn colors_to_gradient(_: impl Ctx, colors: List<Graphic>) -> Item<Gradient> {
|
||||
/// Unwraps a gradient into a `Color[]` of its stops, keeping any `position` and `midpoint` attributes that place them along the ramp. Attributes belonging to the gradient as a whole (like spread and interpolation), rather than its individual color stops, are not preserved.
|
||||
#[node_macro::node(category("Gradient"), icon("NodeGradientToColors"), name("Gradient to Colors"))]
|
||||
fn gradient_to_colors(_: impl Ctx, gradient: Item<Gradient>) -> List<Color> {
|
||||
// The adjustments the gradient carries change each stop's color
|
||||
let adjustments = gradient.attribute::<Effects>(ATTR_EFFECTS).map(value_effects::adjustments).unwrap_or_default();
|
||||
let adjustments: Vec<PreparedAdjustment> = adjustments.iter().map(PreparedAdjustment::new).collect();
|
||||
// The effects the gradient carries, like adjustments and Blend Ifs, change each stop's color
|
||||
let after_effects = gradient.attribute::<Effects>(ATTR_EFFECTS).map(value_effects::prepared_color_after_effects);
|
||||
|
||||
let mut colors = gradient.into_element().into_color_list();
|
||||
for color in colors.iter_element_values_mut() {
|
||||
*color = adjustments.iter().fold(*color, |color, adjustment| adjustment.adjust(color));
|
||||
if let Some(after_effects) = after_effects {
|
||||
for color in colors.iter_element_values_mut() {
|
||||
*color = after_effects(*color);
|
||||
}
|
||||
}
|
||||
colors
|
||||
}
|
||||
@@ -1421,4 +1421,25 @@ mod test {
|
||||
let restored = colors_to_gradient((), embed_colors(gradient_to_colors((), Item::new_from_element(gradient.clone()))));
|
||||
assert_eq!(restored.element(), &gradient, "a default ramp should round trip without gaining attributes it never had");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_to_colors_fades_each_stop_by_the_blend_ifs_the_gradient_carries() {
|
||||
use graphic_types::EffectOperation;
|
||||
use graphic_types::blend_if::BlendIfRanges;
|
||||
|
||||
// Shown only where the gray is at least half
|
||||
let mut hides_darks = BlendIfRanges::default();
|
||||
hides_darks.content.gray.falloff_start = 50.;
|
||||
hides_darks.content.gray.range_start = 50.;
|
||||
let effects = Effects::from_operations([EffectOperation::BlendIf(Box::new(hides_darks))]);
|
||||
|
||||
let mut gradient = Gradient::from(vec![Color::BLACK, Color::WHITE]);
|
||||
gradient.set_positions(&[0.25, 0.75]);
|
||||
let colors = gradient_to_colors((), Item::new_from_element(gradient).with_attribute(ATTR_EFFECTS, effects));
|
||||
assert_eq!(elements(&colors), [Color::BLACK.with_alpha(0.), Color::WHITE], "the dark stop should be hidden and the light one shown");
|
||||
|
||||
let mut expected = Gradient::from(vec![Color::BLACK.with_alpha(0.), Color::WHITE]);
|
||||
expected.set_positions(&[0.25, 0.75]);
|
||||
assert_eq!(colors_to_gradient((), embed_colors(colors)).element(), &expected, "each stop should keep its place");
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,6 @@ pub mod render_background;
|
||||
pub mod render_cache;
|
||||
pub mod render_node;
|
||||
pub mod render_pixel_preview;
|
||||
pub mod subgraphs;
|
||||
pub mod text;
|
||||
pub use blending_nodes;
|
||||
pub use brush_nodes as brush;
|
||||
@@ -15,8 +14,8 @@ pub use graphene_core;
|
||||
pub use graphene_core::debug;
|
||||
pub use graphic_nodes;
|
||||
pub use graphic_types::{
|
||||
Appearance, Artboard, BevelDirection, BevelStyle, BevelTechnique, Cover, CoverPlacement, Coverage, Effect, EffectKind, EffectOperation, Effects, GlowSource, GlowTechnique, Graphic, MaskMode,
|
||||
MinimumMaximumMode, NoiseDistribution, Vector, stamp_coverage,
|
||||
Appearance, Artboard, BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, Cover, CoverPlacement, Coverage, Effect, EffectKind, EffectOperation, Effects, GlowSource, GlowTechnique,
|
||||
Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution, Vector, stamp_coverage,
|
||||
};
|
||||
pub use graphic_types::{DisplaceMode, RadialBlurMethod, WarpStyle, WaveType};
|
||||
pub use math_nodes;
|
||||
|
||||
@@ -6,6 +6,7 @@ use core_types::transform::{Footprint, RenderQuality, Transform};
|
||||
use core_types::{CloneVarArgs, Context, Ctx, ExtractAll, ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime, Generations, NodeError, OwnedContextImpl, Poll};
|
||||
use glam::{DAffine2, DVec2, I64Vec2, UVec2};
|
||||
use graph_craft::document::value::{RenderOutput, RenderOutputType};
|
||||
use graphic_types::raster_types::{Texture, TextureWeakRef};
|
||||
use rendering::{RenderOutputType as RenderOutputTypeRequest, RenderParams};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::hash::Hash;
|
||||
@@ -14,7 +15,7 @@ use vector_types::vector::style::RenderMode;
|
||||
use wgpu_executor::WgpuExecutor;
|
||||
|
||||
pub const TILE_SIZE: u32 = 256;
|
||||
pub const MAX_CACHE_MEMORY_BYTES: usize = 512 * 1024 * 1024;
|
||||
const MAX_CACHE_KEYS: usize = 8;
|
||||
const BYTES_PER_PIXEL: usize = 4;
|
||||
|
||||
/// A tile in the grid laid out in device pixels from the document's origin, which deep zoom puts too far away to count in 32 bits.
|
||||
@@ -29,8 +30,14 @@ pub struct CachedRegion {
|
||||
pub output: Poll<RenderOutput>,
|
||||
pub size: UVec2,
|
||||
pub tiles: Vec<TileCoord>,
|
||||
last_access: u64,
|
||||
memory_size: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ParkedRegion {
|
||||
metadata: Poll<rendering::RenderMetadata>,
|
||||
texture: TextureWeakRef,
|
||||
size: UVec2,
|
||||
tiles: Vec<TileCoord>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
|
||||
@@ -108,10 +115,8 @@ impl TileCache {
|
||||
|
||||
#[derive(Default, Debug)]
|
||||
struct TileCacheImpl {
|
||||
regions: Vec<CachedRegion>,
|
||||
timestamp: u64,
|
||||
total_memory: usize,
|
||||
cache_key: CacheKey,
|
||||
keys: Vec<(CacheKey, Vec<ParkedRegion>)>,
|
||||
view: Vec<Texture>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -163,25 +168,37 @@ fn tiles_bounds(tiles: &[TileCoord]) -> AxisAlignedBbox {
|
||||
|
||||
impl TileCacheImpl {
|
||||
fn query(&mut self, viewport_bounds: &AxisAlignedBbox, cache_key: &CacheKey, max_region_size: u32) -> CacheQuery {
|
||||
if &self.cache_key != cache_key {
|
||||
self.invalidate_all();
|
||||
self.cache_key = cache_key.clone();
|
||||
}
|
||||
let regions = match self.keys.iter().position(|(key, _)| key == cache_key) {
|
||||
Some(index) => self.keys.remove(index).1,
|
||||
None => Vec::new(),
|
||||
};
|
||||
self.keys.insert(0, (cache_key.clone(), regions));
|
||||
self.keys.truncate(MAX_CACHE_KEYS);
|
||||
|
||||
let required_tiles = bounds_to_tiles(viewport_bounds);
|
||||
let required_tile_set: HashSet<_> = required_tiles.iter().cloned().collect();
|
||||
let mut cached_regions = Vec::new();
|
||||
let mut covered_tiles = HashSet::new();
|
||||
let mut view = Vec::new();
|
||||
|
||||
for region in &mut self.regions {
|
||||
self.keys[0].1.retain(|region| {
|
||||
let Some(texture) = region.texture.upgrade() else { return false };
|
||||
let region_tiles: HashSet<_> = region.tiles.iter().cloned().collect();
|
||||
if region_tiles.iter().any(|t| required_tile_set.contains(t)) {
|
||||
region.last_access = self.timestamp;
|
||||
self.timestamp += 1;
|
||||
cached_regions.push(region.clone());
|
||||
view.push(texture.clone());
|
||||
cached_regions.push(CachedRegion {
|
||||
output: region.metadata.clone().map(|metadata| RenderOutput {
|
||||
data: RenderOutputType::Texture(texture),
|
||||
metadata,
|
||||
}),
|
||||
size: region.size,
|
||||
tiles: region.tiles.clone(),
|
||||
});
|
||||
covered_tiles.extend(region_tiles);
|
||||
}
|
||||
}
|
||||
true
|
||||
});
|
||||
self.view = view;
|
||||
|
||||
let missing_tiles: Vec<_> = required_tiles.into_iter().filter(|t| !covered_tiles.contains(t)).collect();
|
||||
let missing_regions = group_into_regions(&missing_tiles, max_region_size);
|
||||
@@ -189,30 +206,25 @@ impl TileCacheImpl {
|
||||
}
|
||||
|
||||
fn store_regions(&mut self, new_regions: Vec<CachedRegion>) {
|
||||
for mut region in new_regions {
|
||||
region.last_access = self.timestamp;
|
||||
self.timestamp += 1;
|
||||
self.total_memory += region.memory_size;
|
||||
self.regions.push(region);
|
||||
}
|
||||
self.evict_until_under_budget();
|
||||
}
|
||||
let Some((_, regions)) = self.keys.first_mut() else { return };
|
||||
for region in new_regions {
|
||||
let output = match ®ion.output {
|
||||
Poll::Final(output) | Poll::Partial(output) => output,
|
||||
Poll::Fallback(boxed) => &boxed.0,
|
||||
Poll::Pending | Poll::Error(_) => continue,
|
||||
};
|
||||
let RenderOutputType::Texture(texture) = &output.data else { continue };
|
||||
let texture = texture.clone();
|
||||
|
||||
fn evict_until_under_budget(&mut self) {
|
||||
while self.total_memory > MAX_CACHE_MEMORY_BYTES && !self.regions.is_empty() {
|
||||
if let Some((oldest_idx, _)) = self.regions.iter().enumerate().min_by_key(|(_, r)| r.last_access) {
|
||||
let removed = self.regions.remove(oldest_idx);
|
||||
self.total_memory = self.total_memory.saturating_sub(removed.memory_size);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
regions.push(ParkedRegion {
|
||||
metadata: region.output.map(|output| output.metadata),
|
||||
texture: texture.downgrade(),
|
||||
size: region.size,
|
||||
tiles: region.tiles,
|
||||
});
|
||||
self.view.push(texture);
|
||||
}
|
||||
}
|
||||
|
||||
fn invalidate_all(&mut self) {
|
||||
self.regions.clear();
|
||||
self.total_memory = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// Groups tiles into rectangular regions no wider or taller than `max_region_size` pixels.
|
||||
@@ -490,8 +502,6 @@ where
|
||||
output,
|
||||
size: region_pixel_size,
|
||||
tiles: region.tiles.clone(),
|
||||
last_access: 0,
|
||||
memory_size: (region_pixel_size.x * region_pixel_size.y) as usize * BYTES_PER_PIXEL,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -717,8 +727,6 @@ mod tests {
|
||||
output: Poll::Pending,
|
||||
size: tiles_bounds(®ion.tiles).size().as_uvec2(),
|
||||
tiles: region.tiles,
|
||||
last_access: 0,
|
||||
memory_size: 0,
|
||||
};
|
||||
if let Some(placement) = region_placement(®ion, &device_origin_offset, resolution) {
|
||||
covered += placement.size.x as u64 * placement.size.y as u64;
|
||||
@@ -727,4 +735,129 @@ mod tests {
|
||||
assert_eq!(covered, resolution.x as u64 * resolution.y as u64, "with the document's origin offset by {device_origin_offset}");
|
||||
}
|
||||
}
|
||||
|
||||
fn texture(device: &wgpu::Device) -> Texture {
|
||||
device
|
||||
.create_texture(&wgpu::TextureDescriptor {
|
||||
label: None,
|
||||
size: wgpu::Extent3d {
|
||||
width: 1,
|
||||
height: 1,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu::TextureFormat::Rgba8Unorm,
|
||||
usage: wgpu::TextureUsages::COPY_SRC,
|
||||
view_formats: &[],
|
||||
})
|
||||
.into()
|
||||
}
|
||||
|
||||
fn view(column: i64) -> AxisAlignedBbox {
|
||||
let start = DVec2::new(column as f64, 0.) * TILE_SIZE as f64;
|
||||
AxisAlignedBbox {
|
||||
start,
|
||||
end: start + DVec2::splat(2. * TILE_SIZE as f64),
|
||||
}
|
||||
}
|
||||
|
||||
fn zoom(zoom: u64) -> CacheKey {
|
||||
CacheKey { zoom, ..Default::default() }
|
||||
}
|
||||
|
||||
fn show(cache: &TileCache, device: &wgpu::Device, view: &AxisAlignedBbox, key: &CacheKey) -> (Vec<Texture>, Vec<Texture>) {
|
||||
let query = cache.query(view, key, 4096);
|
||||
let reused = query
|
||||
.cached_regions
|
||||
.iter()
|
||||
.filter_map(|region| match ®ion.output {
|
||||
Poll::Final(RenderOutput {
|
||||
data: RenderOutputType::Texture(texture),
|
||||
..
|
||||
}) => Some(texture.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
|
||||
let rendered: Vec<_> = query.missing_regions.iter().map(|_| texture(device)).collect();
|
||||
let regions = query.missing_regions.into_iter().zip(&rendered).map(|(region, texture)| CachedRegion {
|
||||
output: Poll::Final(RenderOutput {
|
||||
data: RenderOutputType::Texture(texture.clone()),
|
||||
metadata: Default::default(),
|
||||
}),
|
||||
size: tiles_bounds(®ion.tiles).size().as_uvec2(),
|
||||
tiles: region.tiles,
|
||||
});
|
||||
cache.store_regions(regions.collect());
|
||||
|
||||
(reused, rendered)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn regions_out_of_view_are_held_weakly_and_those_in_view_strongly() {
|
||||
let Some(context) = futures::executor::block_on(wgpu_executor::WgpuContext::new()) else { return };
|
||||
let cache = TileCache::default();
|
||||
|
||||
let mut pool = Vec::new();
|
||||
for column in [0, 4, 8, 12] {
|
||||
pool.extend(show(&cache, &context.device, &view(column), &zoom(1)).1);
|
||||
|
||||
let (in_view, out_of_view) = pool.split_last().unwrap();
|
||||
assert!(in_view.is_shared());
|
||||
assert!(out_of_view.iter().all(|texture| !texture.is_shared() && texture.is_weakly_shared()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_parked_region_back_in_view_is_reused() {
|
||||
let Some(context) = futures::executor::block_on(wgpu_executor::WgpuContext::new()) else { return };
|
||||
let cache = TileCache::default();
|
||||
|
||||
let (_, parked) = show(&cache, &context.device, &view(0), &zoom(1));
|
||||
show(&cache, &context.device, &view(4), &zoom(1));
|
||||
|
||||
assert_eq!(show(&cache, &context.device, &view(0), &zoom(1)), (parked, Vec::new()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_parked_region_the_pool_evicted_is_rendered_again() {
|
||||
let Some(context) = futures::executor::block_on(wgpu_executor::WgpuContext::new()) else { return };
|
||||
let cache = TileCache::default();
|
||||
|
||||
let (_, evicted) = show(&cache, &context.device, &view(0), &zoom(1));
|
||||
show(&cache, &context.device, &view(4), &zoom(1));
|
||||
drop(evicted);
|
||||
|
||||
let (reused, rendered) = show(&cache, &context.device, &view(0), &zoom(1));
|
||||
assert!(reused.is_empty());
|
||||
assert_eq!(rendered.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_regions_of_an_earlier_cache_key_are_reused_on_returning_to_it() {
|
||||
let Some(context) = futures::executor::block_on(wgpu_executor::WgpuContext::new()) else { return };
|
||||
let cache = TileCache::default();
|
||||
|
||||
let (_, parked) = show(&cache, &context.device, &view(0), &zoom(1));
|
||||
show(&cache, &context.device, &view(0), &zoom(2));
|
||||
|
||||
assert_eq!(show(&cache, &context.device, &view(0), &zoom(1)), (parked, Vec::new()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_regions_of_cache_keys_older_than_the_most_recent_ones_are_released() {
|
||||
let Some(context) = futures::executor::block_on(wgpu_executor::WgpuContext::new()) else { return };
|
||||
let cache = TileCache::default();
|
||||
|
||||
let (_, oldest) = show(&cache, &context.device, &view(0), &zoom(0));
|
||||
for key in 1..MAX_CACHE_KEYS as u64 {
|
||||
show(&cache, &context.device, &view(0), &zoom(key));
|
||||
}
|
||||
assert!(oldest[0].is_weakly_shared());
|
||||
|
||||
show(&cache, &context.device, &view(0), &zoom(MAX_CACHE_KEYS as u64));
|
||||
assert!(!oldest[0].is_weakly_shared());
|
||||
}
|
||||
}
|
||||
@@ -1,218 +0,0 @@
|
||||
use crate::artboard::create_artboard;
|
||||
use crate::context::{read_index, read_vector};
|
||||
use crate::graphic::{as_graphic, extend, flatten_vector, into_group, item_at_index, map, remove_at_index};
|
||||
use crate::platform_application_io::{bytes_to_image, load_resource};
|
||||
use crate::vector::misc::InterpolationDistribution;
|
||||
use crate::vector::{as_vector, combine_paths, count, morph, path_is_closed, points_to_polyline, separate_paths};
|
||||
use crate::{Artboard, Color, Graphic, Vector};
|
||||
use glam::DVec2;
|
||||
use math_nodes::{add, as_number, divide, floor, max, modulo, multiply, subtract, switch};
|
||||
use repeat_nodes::repeat;
|
||||
use transform_nodes::{decompose_translation, extract_transform};
|
||||
|
||||
/// Merges the provided content as a new item in the layer's compositing stack.
|
||||
#[node_macro::graph(category("Graphic"), icon("NodeMerge"), layer)]
|
||||
pub fn merge(
|
||||
/// The stack of layers below this one, which the content is placed above.
|
||||
base: List<Graphic>,
|
||||
/// The artwork this layer adds to the stack as a single item.
|
||||
#[expose]
|
||||
content: List<Graphic>,
|
||||
) -> out!(
|
||||
/// The stack of layers with this layer's content placed on top.
|
||||
out,
|
||||
) {
|
||||
let grouped = content >> into_group().at(-7, -1);
|
||||
base >> as_graphic().at(-7, -2) >> extend(new = grouped).at(0, -2)
|
||||
}
|
||||
|
||||
/// Creates a new Artboard which can be used as a working surface.
|
||||
#[node_macro::graph(category("Graphic"), icon("NodeArtboard"), layer)]
|
||||
pub fn artboard(
|
||||
/// The stack of artboards below this one, which this artboard is placed above.
|
||||
base: List<Artboard>,
|
||||
/// Graphics to include within the artboard.
|
||||
#[expose]
|
||||
content: List<Graphic>,
|
||||
/// Coordinate of the top-left corner of the artboard within the document.
|
||||
#[labels("X", "Y")]
|
||||
#[unit(" px")]
|
||||
#[integer]
|
||||
location: Item<DVec2>,
|
||||
/// Width and height of the artboard within the document.
|
||||
#[labels("W", "H")]
|
||||
#[unit(" px")]
|
||||
#[integer]
|
||||
#[default(1920., 1080.)]
|
||||
dimensions: Item<DVec2>,
|
||||
/// Color of the artboard background.
|
||||
#[widget(ParsedWidgetOverride::Custom = "artboard_background")]
|
||||
#[default(Color::WHITE)]
|
||||
background: Item<Color>,
|
||||
/// Whether to cut off the contained content that extends outside the artboard, or keep it visible.
|
||||
#[default(true)]
|
||||
clip: Item<bool>,
|
||||
) -> out!(
|
||||
/// The stack of artboards with this artboard placed on top.
|
||||
out,
|
||||
) {
|
||||
let board = create_artboard(content, location, dimensions, background, clip).at(-7, -3);
|
||||
base >> extend(new = board).at(0, -4)
|
||||
}
|
||||
|
||||
/// Creates a series of intermediate shapes that gradually transition between vector objects, optionally along a control path.
|
||||
#[node_macro::graph(category("Vector: Deform"), icon("NodeBlend"))]
|
||||
pub fn blend(
|
||||
/// The vector objects to create intermediate shapes between.
|
||||
content: List<Vector>,
|
||||
/// The number of shapes spanning from the first object to the last, repeated for each subpath of the control path.
|
||||
#[default(10)]
|
||||
count: Item<i64>,
|
||||
/// Flip the stacking order of the shapes, so the ones nearest the first object are on top.
|
||||
reverse: Item<bool>,
|
||||
/// What changes evenly from one shape to the next, which sets how the intermediate shapes are spaced.
|
||||
distribution: Item<InterpolationDistribution>,
|
||||
/// An optional control path with one anchor point per object. Curved segments shape the trajectory of the blend instead of traveling straight.
|
||||
path: Item<Vector>,
|
||||
) -> out!(
|
||||
/// The blended shapes, from the first object to the last.
|
||||
out,
|
||||
) {
|
||||
// Each clamps to at least 1, which also covers an empty control path
|
||||
let shapes_per_path = count >> as_number().at(2, 13) >> max(other_value = 1).at(9, 13);
|
||||
let path_count = path >> separate_paths().at(2, 0) >> count().at(2, 2) >> max(other_value = 1).at(9, 2);
|
||||
|
||||
// Split the repetition index into which subpath it's on and where along that subpath
|
||||
let index = read_index().at(2, 7);
|
||||
let path_index = index >> divide(denominator = shapes_per_path).at(16, 10) >> floor().at(23, 4);
|
||||
let local_index = index >> modulo(modulus = shapes_per_path).at(16, 7);
|
||||
|
||||
// A closed subpath spaces its shapes by the count, and an open one by one fewer (at least 1) so its last shape lands on the end
|
||||
let open_spacing = shapes_per_path >> subtract(subtrahend = 1).at(16, 14) >> max(other_value = 1).at(23, 14);
|
||||
let spacing = path >> path_is_closed(index = path_index).at(30, 2) >> switch(if_true = shapes_per_path, if_false = open_spacing).at(30, 12);
|
||||
|
||||
// Scaling just below 1 keeps the last shape from overflowing into the next subpath
|
||||
let fraction = local_index >> divide(denominator = spacing).at(23, 7) >> multiply(multiplicand = 0.9999999999).at(30, 7);
|
||||
let progression = path_index >> add(addend = fraction).at(37, 4);
|
||||
|
||||
let total = shapes_per_path >> multiply(multiplicand = path_count).at(16, 1);
|
||||
content >> morph(progression, distribution, path).at(44, 3) >> repeat(count = total, reverse).at(51, 0)
|
||||
}
|
||||
|
||||
/// Connects the origins of vector objects in order with an open polyline, such as to make a control path for the **Blend** and **Morph** nodes.
|
||||
#[node_macro::graph(category("Vector: Path"), icon("NodeOriginsToPolyline"), name("Origins to Polyline"))]
|
||||
pub fn origins_to_polyline(
|
||||
/// The vector objects to connect in order by their origins.
|
||||
vector: List<Vector>,
|
||||
) -> out!(
|
||||
/// An open polyline with an anchor point at the origin of each object.
|
||||
vector,
|
||||
) {
|
||||
// Each object's origin, read from the item being mapped, as a single-anchor vector
|
||||
let origin = read_vector().at(0, 1) >> extract_transform().at(7, 1) >> decompose_translation().at(14, 1) >> as_vector().at(21, 1);
|
||||
|
||||
vector >> flatten_vector().at(21, 0) >> map(mapped = origin).at(28, 0) >> combine_paths().at(35, 0) >> points_to_polyline(closed = false).at(42, 0)
|
||||
}
|
||||
|
||||
/// Loads an image from a given URL.
|
||||
#[node_macro::graph(category("Data: I/O"), icon("NodeLoadImage"))]
|
||||
pub fn load_image(
|
||||
_: (),
|
||||
/// The web address or local asset path of the image to load.
|
||||
#[name("URL")]
|
||||
url: Item<String>,
|
||||
) -> out!(
|
||||
/// The loaded image.
|
||||
image,
|
||||
) {
|
||||
load_resource(url).at(0, 0) >> bytes_to_image().at(7, 0)
|
||||
}
|
||||
|
||||
/// Finds a portion of the string matching a regular expression pattern. With "Match Index" at its default 0, it selects the first non-overlapping occurrence, but others may be selected. Capture groups, if any, are produced as a list in the "Captures" output.
|
||||
#[node_macro::graph(category("String: Regex"), icon("NodeRegexFind"))]
|
||||
pub fn regex_find(
|
||||
/// The string to search within.
|
||||
string: Item<String>,
|
||||
/// The regular expression pattern to search for.
|
||||
pattern: Item<String>,
|
||||
/// Which non-overlapping occurrence of the pattern to return, starting from 0 for the first match. Negative indices count backwards from the last match.
|
||||
match_index: Item<i64>,
|
||||
/// Match letters regardless of case.
|
||||
case_insensitive: Item<bool>,
|
||||
/// Make `^` and `$` match the start and end of each line, not just the whole string.
|
||||
multiline: Item<bool>,
|
||||
) -> out!(
|
||||
/// The whole portion of the string matching the pattern, or empty if there is no match.
|
||||
r#match,
|
||||
/// The text matched by each capture group in the pattern, in order.
|
||||
captures,
|
||||
) {
|
||||
// The whole match, then each capture group, where each item carries `start`, `end`, and `name` attributes
|
||||
let found = string >> text_nodes::regex::regex_find(pattern, match_index, case_insensitive, multiline).at(0, 0);
|
||||
|
||||
let whole_match = found >> item_at_index(index = 0).at(8, 0);
|
||||
let capture_groups = found >> remove_at_index(index = 0).at(8, 2);
|
||||
|
||||
(whole_match, capture_groups)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use core_types::registry::GraphInputSource;
|
||||
|
||||
/// Finds the capture groups of a pattern.
|
||||
#[node_macro::graph(category("Test"))]
|
||||
fn regex_captures(string: Item<String>, pattern: Item<String>) -> out!(captures) {
|
||||
return string >> regex_find(pattern).captures;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_output_chosen_by_name_wires_from_that_output() {
|
||||
let graph = _regex_captures_graph_metadata();
|
||||
assert!(matches!(graph.exports[0].source, GraphInputSource::Node { node: 0, output: 1 }));
|
||||
}
|
||||
|
||||
/// Puts its content on a board, setting every piece of node state.
|
||||
#[node_macro::graph(category("Test"))]
|
||||
fn boarded(content: List<Graphic>) -> out!(out) {
|
||||
return create_artboard(content, background = rgb(0x102030), clip = exposed(false))
|
||||
.named("Board")
|
||||
.hidden()
|
||||
.locked()
|
||||
.pinned()
|
||||
.layer()
|
||||
.call_argument::<impl Any>()
|
||||
.at(3, -4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn node_state_and_values_reach_the_metadata() {
|
||||
use core_types::NodeParameter;
|
||||
use core_types::registry::GraphValue;
|
||||
|
||||
let graph = _boarded_graph_metadata();
|
||||
let node = &graph.nodes[0];
|
||||
assert_eq!(node.display_name, Some("Board"));
|
||||
assert!(node.hidden && node.locked && node.pinned && node.layer);
|
||||
assert_eq!(node.position, Some((3, -4)));
|
||||
assert!(matches!(node.call_argument, Some(core_types::Type::Generic(_))));
|
||||
|
||||
let source = |index: usize| &node.inputs.iter().find(|(input_index, _)| *input_index == index).expect("the input should be set").1;
|
||||
assert!(matches!(source(create_artboard::ContentInput::INDEX), GraphInputSource::Import { index: 0, .. }));
|
||||
assert!(matches!(
|
||||
source(create_artboard::BackgroundInput::INDEX),
|
||||
GraphInputSource::Value {
|
||||
value: GraphValue::Color(_),
|
||||
exposed: None
|
||||
}
|
||||
));
|
||||
assert!(matches!(
|
||||
source(create_artboard::ClipInput::INDEX),
|
||||
GraphInputSource::Value {
|
||||
value: GraphValue::Bool(false),
|
||||
exposed: Some(true)
|
||||
}
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -416,8 +416,7 @@ pub fn node_inputs(fields: &[registry::FieldMetadata], first_node_io: &NodeIOTyp
|
||||
return NodeInput::value(TaggedValue::None, true);
|
||||
};
|
||||
let ty = ty.clone().normalize_rank();
|
||||
// A `()` primary has nothing to connect, whether it's a proto node's lazy input or a graph's import
|
||||
let exposed = if index == 0 { ty != fn_type!(Context, ()) && ty != concrete!(()) } else { field.exposed };
|
||||
let exposed = if index == 0 { ty != fn_type!(Context, ()) } else { field.exposed };
|
||||
|
||||
match &field.value_source {
|
||||
RegistryValueSource::None => {}
|
||||
@@ -544,7 +543,7 @@ mod destructure_tests {
|
||||
fn vec2_to_numbers_network() -> NodeNetwork {
|
||||
let vec2_to_numbers = DocumentNode {
|
||||
inputs: vec![NodeInput::value(TaggedValue::DVec2(DVec2::new(3., 5.)), false)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::math_nodes::vec2_to_numbers::IDENTIFIER),
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
|
||||
..Default::default()
|
||||
};
|
||||
multi_output_into_add_network(vec2_to_numbers, [1, 2])
|
||||
@@ -562,7 +561,7 @@ mod destructure_tests {
|
||||
|
||||
#[test]
|
||||
fn multi_output_node_expands_into_generated_destructure_network() {
|
||||
let vec2_to_numbers_identifier = graphene_std::math_nodes::vec2_to_numbers::IDENTIFIER;
|
||||
let vec2_to_numbers_identifier = graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER;
|
||||
let destructure = registry::MULTI_OUTPUT_NODES
|
||||
.get(&vec2_to_numbers_identifier)
|
||||
.expect("Vec2 to Numbers should be registered as a multi-output node");
|
||||
|
||||
@@ -219,7 +219,7 @@ Writing to any other node fails, since another anchor's run may be editing it.
|
||||
|
||||
### Network definitions
|
||||
|
||||
Some built-in nodes, like Merge and Artboard, are subgraphs. Each is defined by a `#[graph]` function in `node-graph/nodes/gstd/src/subgraphs.rs`, and instances store the definition's identifier and `version` next to their copy of its network. Bump the version with `#[graph(..., version(N))]` when instances saved before your change would load wrongly, and register a migration from the old version with the `network` prefix:
|
||||
Some built-in nodes, like Merge and Artboard, are subgraphs. Each instance holds its own copy of a network defined in `document_node_definitions.rs`, and stores the definition's identifier and `version` next to it. Bump `version` on the `DocumentNodeDefinition` when instances saved before your change would load wrongly, and register a migration from the old version with the `network` prefix:
|
||||
|
||||
```rust
|
||||
rename!(network "Artboard"@1 => @2);
|
||||
|
||||
Reference in new issue
Block a user