mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-05 19:12:08 -10:00
Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
865b6be603 | ||
|
|
de786aa381 | ||
|
|
e773fff9e3 | ||
|
|
1b6df61bc4 | ||
|
|
3c69b1d930 | ||
|
|
5418fcbf7b | ||
|
|
98d636c1e5 | ||
|
|
6fb9f26e99 |
No files matched your search
@@ -176,6 +176,8 @@ jobs:
|
|||||||
env:
|
env:
|
||||||
# `--cfg=web_sys_unstable_apis` mirrors the `[build]` section of `.cargo/config.toml`
|
# `--cfg=web_sys_unstable_apis` mirrors the `[build]` section of `.cargo/config.toml`
|
||||||
RUSTFLAGS: "-Dwarnings --cfg=web_sys_unstable_apis"
|
RUSTFLAGS: "-Dwarnings --cfg=web_sys_unstable_apis"
|
||||||
|
# GPU tests made through `for_tests()` fail rather than skip when the software Vulkan driver above can't make a device
|
||||||
|
WGPU_BACKEND: vulkan
|
||||||
# The desktop crates need CEF, and `third-party-licenses` only pulls it in through its `desktop` feature, so it runs on its own without `--all-features`
|
# The desktop crates need CEF, and `third-party-licenses` only pulls it in through its `desktop` feature, so it runs on its own without `--all-features`
|
||||||
run: >-
|
run: >-
|
||||||
cargo test --workspace --all-features
|
cargo test --workspace --all-features
|
||||||
|
|||||||
Generated
+3
-2
@@ -585,6 +585,7 @@ name = "blending-nodes"
|
|||||||
version = "0.0.0"
|
version = "0.0.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"core-types",
|
"core-types",
|
||||||
|
"futures",
|
||||||
"glam",
|
"glam",
|
||||||
"graphic-types",
|
"graphic-types",
|
||||||
"node-macro",
|
"node-macro",
|
||||||
@@ -592,6 +593,7 @@ dependencies = [
|
|||||||
"serde",
|
"serde",
|
||||||
"text-nodes",
|
"text-nodes",
|
||||||
"vector-types",
|
"vector-types",
|
||||||
|
"wgpu-executor",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -5747,8 +5749,6 @@ dependencies = [
|
|||||||
"glam",
|
"glam",
|
||||||
"graphene-resource",
|
"graphene-resource",
|
||||||
"graphic-types",
|
"graphic-types",
|
||||||
"half",
|
|
||||||
"log",
|
|
||||||
"raster-types",
|
"raster-types",
|
||||||
"thiserror 2.0.21",
|
"thiserror 2.0.21",
|
||||||
"vector-types",
|
"vector-types",
|
||||||
@@ -8586,6 +8586,7 @@ dependencies = [
|
|||||||
"raster-kernels",
|
"raster-kernels",
|
||||||
"raster-types",
|
"raster-types",
|
||||||
"rendering",
|
"rendering",
|
||||||
|
"svg-convert",
|
||||||
"thiserror 2.0.21",
|
"thiserror 2.0.21",
|
||||||
"vello_gpu",
|
"vello_gpu",
|
||||||
"web-sys",
|
"web-sys",
|
||||||
|
|||||||
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
mod fill_v1;
|
mod fill_v1;
|
||||||
mod passthrough_from_read_attribute_gradient_form_node;
|
mod passthrough_from_read_attribute_gradient_form_node;
|
||||||
|
mod passthrough_from_footprint_value;
|
||||||
mod passthrough_from_upload_texture_node;
|
mod passthrough_from_upload_texture_node;
|
||||||
mod renames;
|
mod renames;
|
||||||
|
mod stroke_v1;
|
||||||
mod vary_colors_from_assign_colors;
|
mod vary_colors_from_assign_colors;
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
use migration_core::{Inputs, migration};
|
||||||
|
|
||||||
|
/// 'Footprint Value' is gone with the footprint input of 'Rasterize', whose migration takes over the inputs of one feeding it. One read
|
||||||
|
/// elsewhere passes on its empty primary input instead, since nothing else takes a footprint.
|
||||||
|
#[migration("math_nodes::FootprintValueNode"@1 => "graphene_core::ops::PassthroughNode"@2)]
|
||||||
|
pub fn passthrough_from_footprint_value(inputs: &mut Inputs) {
|
||||||
|
inputs.truncate(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::{decl, literal};
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(3, |random, _slot| literal(random.below(10) as f64))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&PassthroughFromFootprintValue, &contract());
|
||||||
|
check_undo(&PassthroughFromFootprintValue, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn keeps_the_primary_input_and_drops_the_transform_and_resolution() {
|
||||||
|
let (primary, transform, resolution) = (literal(()), literal(1.), literal(2.));
|
||||||
|
|
||||||
|
let mut fixture = Fixture::new(&PassthroughFromFootprintValue);
|
||||||
|
let footprint_value = fixture.add(decl!("math_nodes::FootprintValueNode"@1), vec![primary.clone(), transform, resolution]);
|
||||||
|
let migrated = fixture.migrate(&PassthroughFromFootprintValue).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(fixture.declaration_of(&migrated, footprint_value), Some(decl!("graphene_core::ops::PassthroughNode"@2)));
|
||||||
|
assert_eq!(fixture.inputs(&migrated, footprint_value), [primary]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
use migration_core::{Inputs, literal, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
PaintMapping(PaintMapping),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum PaintMapping {
|
||||||
|
Plane,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 'Stroke' gained Paint Mapping after its dash offset, set to Plane to keep placing the paint in the canvas as it was.
|
||||||
|
#[migration("graphene_core::vector::StrokeNode"@1 => @2)]
|
||||||
|
pub fn stroke_v1(inputs: &mut Inputs) {
|
||||||
|
inputs.push(literal(Tagged::PaintMapping(PaintMapping::Plane)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::decl;
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(9, |random, _slot| literal(random.below(10) as f64))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&StrokeV1, &contract());
|
||||||
|
check_undo(&StrokeV1, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn keeps_the_inputs_and_appends_the_plane_paint_mapping() {
|
||||||
|
let inputs: Vec<_> = (0..9).map(|index| literal(index as f64)).collect();
|
||||||
|
|
||||||
|
let mut fixture = Fixture::new(&StrokeV1);
|
||||||
|
let stroke = fixture.add(decl!("graphene_core::vector::StrokeNode"@1), inputs.clone());
|
||||||
|
let migrated = fixture.migrate(&StrokeV1).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(fixture.declaration_of(&migrated, stroke), Some(decl!("graphene_core::vector::StrokeNode"@2)));
|
||||||
|
assert_eq!(fixture.inputs(&migrated, stroke), [inputs, vec![literal(Tagged::PaintMapping(PaintMapping::Plane))]].concat());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
//! Migrations of the nodes in `graphene_std`.
|
//! Migrations of the nodes in `graphene_std`.
|
||||||
|
|
||||||
|
mod rasterize_v1;
|
||||||
mod renames;
|
mod renames;
|
||||||
@@ -0,0 +1,276 @@
|
|||||||
|
use migration_core::{Declaration, Graph, InputConnector, Inputs, MigrationError, NewNode, Node, NodeInput, OutputConnector, Upstream, decl, encode, literal, literal_of, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::collections::HashSet;
|
||||||
|
|
||||||
|
const FOOTPRINT: u32 = 1;
|
||||||
|
const RASTERIZE: Declaration = decl!("graphene_std::platform_application_io::RasterizeNode"@1);
|
||||||
|
|
||||||
|
/// Matched at any version, since naming one would order this migration after the one turning 'Footprint Value' into it, which must come after.
|
||||||
|
const PASSTHROUGH: &str = "graphene_core::ops::PassthroughNode";
|
||||||
|
|
||||||
|
/// The default area, a square 1000 px across centered at (500, 500), and its resolution of one pixel per px.
|
||||||
|
const DEFAULT_TRANSFORM: [f64; 6] = [1000., 0., 0., 1000., 500., 500.];
|
||||||
|
const DEFAULT_RESOLUTION: [f64; 2] = [1000., 1000.];
|
||||||
|
|
||||||
|
/// A translation by half a unit, which moves a unit square anchored at its corner to one centered on the origin.
|
||||||
|
const CORNER_TO_CENTER: [f64; 6] = [1., 0., 0., 1., 0.5, 0.5];
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
DVec2([f64; 2]),
|
||||||
|
DAffine2([f64; 6]),
|
||||||
|
Footprint(Footprint),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Frozen mirror of the removed `Footprint` value, leaving out the render quality 'Rasterize' ignored.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct Footprint {
|
||||||
|
transform: [f64; 6],
|
||||||
|
resolution: [u32; 2],
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 'Rasterize' takes its footprint's area as a transform placing a unit square centered on its origin, rather than anchored at its corner,
|
||||||
|
/// then its resolution. A 'Footprint Value' node feeding it, directly or through reroutes, hands over its own inputs and goes once nothing
|
||||||
|
/// else reads it. Any other wire can't be read before it runs, so it leaves the defaults, shown in the graph.
|
||||||
|
#[migration("graphene_std::platform_application_io::RasterizeNode"@1 => @2)]
|
||||||
|
pub fn rasterize_v1(node: &Node, graph: &Graph, inputs: &mut Inputs, upstream: &mut Upstream) -> Result<(), MigrationError> {
|
||||||
|
let Some(footprint) = node.inputs().get(FOOTPRINT as usize) else {
|
||||||
|
return Err(MigrationError::invariant("Rasterize has a Footprint input"));
|
||||||
|
};
|
||||||
|
let footprint = through_reroutes(*graph, &footprint.input);
|
||||||
|
|
||||||
|
let (transform, resolution) = match footprint {
|
||||||
|
NodeInput::Value { exposed, .. } => match literal_of::<Tagged>(footprint) {
|
||||||
|
Some(Tagged::Footprint(footprint)) => (
|
||||||
|
value(Tagged::DAffine2(centered(footprint.transform)), *exposed),
|
||||||
|
value(Tagged::DVec2(footprint.resolution.map(f64::from)), *exposed),
|
||||||
|
),
|
||||||
|
_ => defaults(*exposed),
|
||||||
|
},
|
||||||
|
NodeInput::Node { id, index: 0 } if graph.declaration(*id) == Some(decl!("math_nodes::FootprintValueNode"@1)) => {
|
||||||
|
let parameters = graph.node(*id).map(|footprint_value| footprint_value.inputs()).and_then(|slots| Some((slots.get(1)?, slots.get(2)?)));
|
||||||
|
let Some((transform, resolution)) = parameters else {
|
||||||
|
return Err(MigrationError::invariant("Footprint Value has Transform and Resolution inputs"));
|
||||||
|
};
|
||||||
|
|
||||||
|
// Each Rasterize node it feeds takes over its inputs, so it's only needed by whatever else reads it
|
||||||
|
let readers = graph.consumers(OutputConnector { node: *id, output: 0 });
|
||||||
|
let only_feeds_rasterize = readers
|
||||||
|
.iter()
|
||||||
|
.all(|reader| matches!(reader, InputConnector::Node { node, input: FOOTPRINT } if graph.declaration(*node) == Some(RASTERIZE)));
|
||||||
|
if only_feeds_rasterize {
|
||||||
|
upstream.remove_node(*id);
|
||||||
|
}
|
||||||
|
|
||||||
|
let multiply = decl!("math_nodes::MultiplyNode"@1);
|
||||||
|
(centered_transform_input(&transform.input, multiply, upstream), resolution.input.clone())
|
||||||
|
}
|
||||||
|
_ => defaults(true),
|
||||||
|
};
|
||||||
|
|
||||||
|
inputs.set(FOOTPRINT, transform);
|
||||||
|
inputs.insert(FOOTPRINT + 1, resolution);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where `input` reads from past any 'Passthrough' nodes rerouting it, which pass their content along unchanged.
|
||||||
|
fn through_reroutes<'a>(graph: Graph<'a>, mut input: &'a NodeInput) -> &'a NodeInput {
|
||||||
|
let mut visited = HashSet::new();
|
||||||
|
|
||||||
|
// A cycle of reroutes leads nowhere else, so revisiting one ends the walk
|
||||||
|
while let NodeInput::Node { id, index: 0 } = input
|
||||||
|
&& visited.insert(*id)
|
||||||
|
&& graph.declaration(*id).is_some_and(|declaration| declaration.identifier == PASSTHROUGH)
|
||||||
|
&& let Some(content) = graph.node(*id).and_then(|node| node.inputs().first())
|
||||||
|
{
|
||||||
|
input = &content.input;
|
||||||
|
}
|
||||||
|
|
||||||
|
input
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The area transform from a 'Footprint Value' node's transform input, through a `multiply` node centering its unit square if it's wired.
|
||||||
|
fn centered_transform_input(transform: &NodeInput, multiply: Declaration, upstream: &mut Upstream) -> NodeInput {
|
||||||
|
match transform {
|
||||||
|
NodeInput::Value { exposed, .. } => match literal_of::<Tagged>(transform) {
|
||||||
|
Some(Tagged::DAffine2(transform)) => value(Tagged::DAffine2(centered(transform)), *exposed),
|
||||||
|
_ => value(Tagged::DAffine2(DEFAULT_TRANSFORM), *exposed),
|
||||||
|
},
|
||||||
|
wire => {
|
||||||
|
let multiply = upstream.add_node(NewNode {
|
||||||
|
declaration: multiply,
|
||||||
|
inputs: vec![wire.clone(), literal(Tagged::DAffine2(CORNER_TO_CENTER))],
|
||||||
|
});
|
||||||
|
NodeInput::Node { id: multiply, index: 0 }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The transform placing a unit square centered on its origin over the one `transform` places anchored at its corner, which is `transform`
|
||||||
|
/// followed by a translation of half a unit, computed in the order a `DAffine2` product computes it.
|
||||||
|
fn centered([x_axis_x, x_axis_y, y_axis_x, y_axis_y, translation_x, translation_y]: [f64; 6]) -> [f64; 6] {
|
||||||
|
[
|
||||||
|
x_axis_x,
|
||||||
|
x_axis_y,
|
||||||
|
y_axis_x,
|
||||||
|
y_axis_y,
|
||||||
|
x_axis_x * 0.5 + y_axis_x * 0.5 + translation_x,
|
||||||
|
x_axis_y * 0.5 + y_axis_y * 0.5 + translation_y,
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn defaults(exposed: bool) -> (NodeInput, NodeInput) {
|
||||||
|
(value(Tagged::DAffine2(DEFAULT_TRANSFORM), exposed), value(Tagged::DVec2(DEFAULT_RESOLUTION), exposed))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn value(value: Tagged, exposed: bool) -> NodeInput {
|
||||||
|
NodeInput::Value { value: encode(&value), exposed }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
const FOOTPRINT_VALUE: Declaration = decl!("math_nodes::FootprintValueNode"@1);
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(3, |random, slot| match slot {
|
||||||
|
1 => literal(Tagged::Footprint(Footprint {
|
||||||
|
transform: [random.below(10) as f64, 0., 0., random.below(10) as f64, random.below(10) as f64, random.below(10) as f64],
|
||||||
|
resolution: [random.below(10) as u32, random.below(10) as u32],
|
||||||
|
})),
|
||||||
|
_ => literal(random.below(10) as f64),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Rasterize's inputs with `footprint` between its artwork and its executor.
|
||||||
|
fn rasterize_inputs(footprint: NodeInput) -> Vec<NodeInput> {
|
||||||
|
vec![literal(0.), footprint, NodeInput::Scope("wgpu-executor".into())]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Rasterize's migrated inputs with `transform` and `resolution` between its artwork and its executor.
|
||||||
|
fn migrated_inputs(transform: NodeInput, resolution: NodeInput) -> Vec<NodeInput> {
|
||||||
|
vec![literal(0.), transform, resolution, NodeInput::Scope("wgpu-executor".into())]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn footprint_value_inputs(transform: NodeInput, resolution: NodeInput) -> Vec<NodeInput> {
|
||||||
|
vec![literal(()), transform, resolution]
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&RasterizeV1, &contract());
|
||||||
|
check_undo(&RasterizeV1, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_footprint_becomes_the_transform_centered_on_its_area_and_its_resolution() {
|
||||||
|
// The 64 by 32 pixel footprint over the 500 by 250 px rectangle from (-20, 40)
|
||||||
|
let footprint = Footprint {
|
||||||
|
transform: [500., 0., 0., 250., -20., 40.],
|
||||||
|
resolution: [64, 32],
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut fixture = Fixture::new(&RasterizeV1);
|
||||||
|
let rasterize = fixture.add(RASTERIZE, rasterize_inputs(literal(Tagged::Footprint(footprint))));
|
||||||
|
let migrated = fixture.migrate(&RasterizeV1).unwrap();
|
||||||
|
|
||||||
|
let expected = migrated_inputs(literal(Tagged::DAffine2([500., 0., 0., 250., 230., 165.])), literal(Tagged::DVec2([64., 32.])));
|
||||||
|
assert_eq!(fixture.declaration_of(&migrated, rasterize), Some(decl!("graphene_std::platform_application_io::RasterizeNode"@2)));
|
||||||
|
assert_eq!(fixture.inputs(&migrated, rasterize), expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_default_footprint_becomes_the_default_area_and_resolution() {
|
||||||
|
let footprint = Footprint {
|
||||||
|
transform: [1000., 0., 0., 1000., 0., 0.],
|
||||||
|
resolution: [1000, 1000],
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut fixture = Fixture::new(&RasterizeV1);
|
||||||
|
let rasterize = fixture.add(RASTERIZE, rasterize_inputs(literal(Tagged::Footprint(footprint))));
|
||||||
|
let migrated = fixture.migrate(&RasterizeV1).unwrap();
|
||||||
|
|
||||||
|
let (transform, resolution) = defaults(false);
|
||||||
|
assert_eq!(fixture.inputs(&migrated, rasterize), migrated_inputs(transform, resolution));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_footprint_value_node_hands_over_its_inputs_and_goes() {
|
||||||
|
let transform = literal(Tagged::DAffine2([300., 0., 0., 200., 10., 20.]));
|
||||||
|
let mut fixture = Fixture::new(&RasterizeV1);
|
||||||
|
let resolution_source = fixture.add(decl!("migration_testing::consumer"@1), Vec::new());
|
||||||
|
let resolution = NodeInput::Node { id: resolution_source, index: 0 };
|
||||||
|
let footprint_value = fixture.add(FOOTPRINT_VALUE, footprint_value_inputs(transform, resolution.clone()));
|
||||||
|
let first = fixture.add(RASTERIZE, rasterize_inputs(NodeInput::Node { id: footprint_value, index: 0 }));
|
||||||
|
let second = fixture.add(RASTERIZE, rasterize_inputs(NodeInput::Node { id: footprint_value, index: 0 }));
|
||||||
|
let migrated = fixture.migrate(&RasterizeV1).unwrap();
|
||||||
|
|
||||||
|
let expected = migrated_inputs(literal(Tagged::DAffine2([300., 0., 0., 200., 160., 120.])), resolution);
|
||||||
|
assert_eq!(fixture.inputs(&migrated, first), expected);
|
||||||
|
assert_eq!(fixture.inputs(&migrated, second), expected);
|
||||||
|
assert_eq!(fixture.declaration_of(&migrated, footprint_value), None, "nothing else reads the Footprint Value node");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_footprint_value_node_hands_over_its_inputs_through_reroutes() {
|
||||||
|
let transform = literal(Tagged::DAffine2([300., 0., 0., 200., 10., 20.]));
|
||||||
|
let resolution = literal(Tagged::DVec2([30., 20.]));
|
||||||
|
let mut fixture = Fixture::new(&RasterizeV1);
|
||||||
|
let footprint_value = fixture.add(FOOTPRINT_VALUE, footprint_value_inputs(transform, resolution.clone()));
|
||||||
|
let first_reroute = fixture.add(decl!("graphene_core::ops::PassthroughNode"@1), vec![NodeInput::Node { id: footprint_value, index: 0 }]);
|
||||||
|
let second_reroute = fixture.add(decl!("graphene_core::ops::PassthroughNode"@2), vec![NodeInput::Node { id: first_reroute, index: 0 }]);
|
||||||
|
let rasterize = fixture.add(RASTERIZE, rasterize_inputs(NodeInput::Node { id: second_reroute, index: 0 }));
|
||||||
|
let migrated = fixture.migrate(&RasterizeV1).unwrap();
|
||||||
|
|
||||||
|
let expected = migrated_inputs(literal(Tagged::DAffine2([300., 0., 0., 200., 160., 120.])), resolution);
|
||||||
|
assert_eq!(fixture.inputs(&migrated, rasterize), expected);
|
||||||
|
assert_eq!(
|
||||||
|
fixture.declaration_of(&migrated, footprint_value),
|
||||||
|
Some(FOOTPRINT_VALUE),
|
||||||
|
"the reroute still reads the Footprint Value node"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_wired_footprint_value_transform_reaches_the_area_through_a_multiply_node() {
|
||||||
|
let mut fixture = Fixture::new(&RasterizeV1);
|
||||||
|
let transform_source = fixture.add(decl!("migration_testing::consumer"@1), Vec::new());
|
||||||
|
let wire = NodeInput::Node { id: transform_source, index: 0 };
|
||||||
|
let footprint_value = fixture.add(FOOTPRINT_VALUE, footprint_value_inputs(wire.clone(), literal(Tagged::DVec2([30., 20.]))));
|
||||||
|
let rasterize = fixture.add(RASTERIZE, rasterize_inputs(NodeInput::Node { id: footprint_value, index: 0 }));
|
||||||
|
let migrated = fixture.migrate(&RasterizeV1).unwrap();
|
||||||
|
|
||||||
|
let inputs = fixture.inputs(&migrated, rasterize);
|
||||||
|
let NodeInput::Node { id: multiply, index: 0 } = inputs[1] else {
|
||||||
|
panic!("the area should be wired from a Multiply node");
|
||||||
|
};
|
||||||
|
assert_eq!(inputs, migrated_inputs(NodeInput::Node { id: multiply, index: 0 }, literal(Tagged::DVec2([30., 20.]))));
|
||||||
|
assert_eq!(fixture.declaration_of(&migrated, multiply), Some(decl!("math_nodes::MultiplyNode"@1)));
|
||||||
|
assert_eq!(fixture.inputs(&migrated, multiply), [wire, literal(Tagged::DAffine2(CORNER_TO_CENTER))]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_footprint_value_node_read_elsewhere_stays() {
|
||||||
|
let mut fixture = Fixture::new(&RasterizeV1);
|
||||||
|
let footprint_value = fixture.add(FOOTPRINT_VALUE, footprint_value_inputs(literal(Tagged::DAffine2(CORNER_TO_CENTER)), literal(Tagged::DVec2([1., 1.]))));
|
||||||
|
fixture.add(RASTERIZE, rasterize_inputs(NodeInput::Node { id: footprint_value, index: 0 }));
|
||||||
|
fixture.export(NodeInput::Node { id: footprint_value, index: 0 });
|
||||||
|
let migrated = fixture.migrate(&RasterizeV1).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(fixture.declaration_of(&migrated, footprint_value), Some(FOOTPRINT_VALUE));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn any_other_wire_leaves_the_defaults_shown_in_the_graph() {
|
||||||
|
let mut fixture = Fixture::new(&RasterizeV1);
|
||||||
|
let source = fixture.add(decl!("migration_testing::consumer"@1), Vec::new());
|
||||||
|
let rasterize = fixture.add(RASTERIZE, rasterize_inputs(NodeInput::Node { id: source, index: 0 }));
|
||||||
|
let migrated = fixture.migrate(&RasterizeV1).unwrap();
|
||||||
|
|
||||||
|
let (transform, resolution) = defaults(true);
|
||||||
|
assert_eq!(fixture.inputs(&migrated, rasterize), migrated_inputs(transform, resolution));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -13,7 +13,7 @@ pub enum ClipboardMessage {
|
|||||||
CopyLayers,
|
CopyLayers,
|
||||||
CutLayers,
|
CutLayers,
|
||||||
WriteItems { items: Vec<ApplicationDataItem> },
|
WriteItems { items: Vec<ApplicationDataItem> },
|
||||||
Rendered { id: u64, svg: Option<String> },
|
Rendered { id: u64, svg: Result<Option<String>, String> },
|
||||||
Loaded { id: u64, content: DataTransfer },
|
Loaded { id: u64, content: DataTransfer },
|
||||||
PasteItems { items: Vec<ApplicationDataItem> },
|
PasteItems { items: Vec<ApplicationDataItem> },
|
||||||
PasteLayers { entries: Vec<ApplicationDataLayer> },
|
PasteLayers { entries: Vec<ApplicationDataLayer> },
|
||||||
|
|||||||
@@ -246,6 +246,15 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
|||||||
let Some(PendingCopy::Rendering { items, loads, .. }) = self.pending_copy.take_if(|pending| pending.id() == id) else {
|
let Some(PendingCopy::Rendering { items, loads, .. }) = self.pending_copy.take_if(|pending| pending.id() == id) else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// The layers still copy, without an SVG
|
||||||
|
let svg = svg.unwrap_or_else(|error| {
|
||||||
|
responses.add(DialogMessage::DisplayDialogError {
|
||||||
|
title: "Unable to copy as SVG".to_string(),
|
||||||
|
description: error,
|
||||||
|
});
|
||||||
|
None
|
||||||
|
});
|
||||||
self.finish_copy(items, loads, svg, resource_storage, responses);
|
self.finish_copy(items, loads, svg, resource_storage, responses);
|
||||||
}
|
}
|
||||||
ClipboardMessage::Loaded { id, content } => {
|
ClipboardMessage::Loaded { id, content } => {
|
||||||
@@ -665,6 +674,212 @@ mod test {
|
|||||||
assert!(rectangle < polygon && polygon < ellipse, "The first drawn layer should be painted first: {svg}");
|
assert!(rectangle < polygon && polygon < ellipse, "The first drawn layer should be painted first: {svg}");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The bounds of what the SVG draws, strokes included, and the size of its frame.
|
||||||
|
fn drawn_bounds_and_frame(svg: &str) -> (usvg::Rect, usvg::Size) {
|
||||||
|
let tree = usvg::Tree::from_str(svg, &usvg::Options::default()).unwrap_or_else(|error| panic!("the SVG should parse ({error}): {svg}"));
|
||||||
|
(tree.root().abs_stroke_bounding_box(), tree.size())
|
||||||
|
}
|
||||||
|
|
||||||
|
// A layer is copied as what it adds to the group holding it, so the group's move is left out of both its frame and what it draws
|
||||||
|
#[cfg_attr(miri, ignore)]
|
||||||
|
#[tokio::test]
|
||||||
|
async fn copied_svg_frames_a_grouped_layer_without_its_groups_transform() {
|
||||||
|
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||||
|
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
||||||
|
use glam::DAffine2;
|
||||||
|
|
||||||
|
let mut editor = EditorTestUtils::create();
|
||||||
|
editor.new_document().await;
|
||||||
|
editor.draw_rect(0., 0., 100., 50.).await;
|
||||||
|
let rectangle = editor.active_document().metadata().all_layers().next().expect("the drawn rectangle");
|
||||||
|
editor
|
||||||
|
.handle_message(DocumentMessage::GroupSelectedLayers {
|
||||||
|
group_folder_type: GroupFolderType::Layer,
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
let group = rectangle.parent(editor.active_document().metadata()).expect("the rectangle should be grouped");
|
||||||
|
editor
|
||||||
|
.handle_message(GraphOperationMessage::TransformChange {
|
||||||
|
layer: group,
|
||||||
|
transform: DAffine2::from_translation(DVec2::new(500., 300.)),
|
||||||
|
transform_in: TransformIn::Local,
|
||||||
|
skip_rerender: false,
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
|
||||||
|
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![rectangle.to_node()] }).await;
|
||||||
|
let clipboard = copy_layers_to_clipboard(&mut editor).await;
|
||||||
|
let svg = copied_svg(&clipboard).expect("the grouped rectangle should render an SVG");
|
||||||
|
|
||||||
|
// The frame grows past the stroke by as far as its miter joins could reach
|
||||||
|
let (drawn, frame) = drawn_bounds_and_frame(svg);
|
||||||
|
let within_frame = drawn.left() >= 0. && drawn.top() >= 0. && drawn.right() <= frame.width() && drawn.bottom() <= frame.height();
|
||||||
|
assert!(within_frame, "the rectangle should be drawn within the frame, at {drawn:?} in {frame:?}: {svg}");
|
||||||
|
assert!(frame.width() < 120. && frame.height() < 70., "the frame should hold only the rectangle: {svg}");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Any node can be shown as a layer, which adds everything it outputs
|
||||||
|
#[cfg_attr(miri, ignore)]
|
||||||
|
#[tokio::test]
|
||||||
|
async fn copied_svg_draws_a_layer_that_is_not_a_merge() {
|
||||||
|
use crate::messages::portfolio::document::utility_types::network_interface::FlowType;
|
||||||
|
|
||||||
|
let mut editor = EditorTestUtils::create();
|
||||||
|
editor.new_document().await;
|
||||||
|
editor.draw_rect(0., 0., 100., 50.).await;
|
||||||
|
let rectangle = editor.active_document().metadata().all_layers().next().expect("the drawn rectangle").to_node();
|
||||||
|
|
||||||
|
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||||
|
let content_node = network_interface
|
||||||
|
.upstream_flow_back_from_nodes(vec![rectangle], &[], FlowType::HorizontalFlow)
|
||||||
|
.nth(1)
|
||||||
|
.expect("the layer should have a content chain");
|
||||||
|
network_interface.set_to_node_or_layer(&content_node, &[], true);
|
||||||
|
|
||||||
|
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![content_node] }).await;
|
||||||
|
let clipboard = copy_layers_to_clipboard(&mut editor).await;
|
||||||
|
let svg = copied_svg(&clipboard).expect("the layer should render an SVG");
|
||||||
|
assert!(svg.contains("<path"), "the SVG should draw the rectangle: {svg}");
|
||||||
|
}
|
||||||
|
|
||||||
|
// An artboard holds its own content, so the other layers copied with it are left out of the SVG
|
||||||
|
#[cfg_attr(miri, ignore)]
|
||||||
|
#[tokio::test]
|
||||||
|
async fn copied_svg_of_artboards_and_other_layers_draws_only_the_artboards() {
|
||||||
|
let mut editor = EditorTestUtils::create();
|
||||||
|
editor.new_document().await;
|
||||||
|
editor.drag_tool(ToolType::Artboard, 0., 0., 200., 100., ModifierKeys::empty()).await;
|
||||||
|
editor.draw_rect(500., 500., 600., 600.).await;
|
||||||
|
|
||||||
|
let layers = editor.active_document().metadata().all_layers().map(|layer| layer.to_node()).collect();
|
||||||
|
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: layers }).await;
|
||||||
|
let clipboard = copy_layers_to_clipboard(&mut editor).await;
|
||||||
|
let svg = copied_svg(&clipboard).expect("the artboard should render an SVG");
|
||||||
|
|
||||||
|
let (_, frame) = drawn_bounds_and_frame(svg);
|
||||||
|
assert!(
|
||||||
|
(frame.width() - 200.).abs() < 1. && (frame.height() - 100.).abs() < 1.,
|
||||||
|
"the SVG should be framed to the artboard alone: {svg}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The frame keeps the content's exact size, rather than whole pixels that would round a fifth of a unit away to nothing
|
||||||
|
#[cfg_attr(miri, ignore)]
|
||||||
|
#[tokio::test]
|
||||||
|
async fn copied_svg_keeps_a_fractional_frame() {
|
||||||
|
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||||
|
use glam::DAffine2;
|
||||||
|
use graphene_std::vector::style::Stroke;
|
||||||
|
|
||||||
|
// A square shrunk to a fifth of a unit across, with only a fill
|
||||||
|
let mut editor = EditorTestUtils::create();
|
||||||
|
editor.new_document().await;
|
||||||
|
editor.draw_rect(0., 0., 100., 100.).await;
|
||||||
|
let layer = editor.active_document().metadata().all_layers().next().expect("the drawn rectangle");
|
||||||
|
editor
|
||||||
|
.handle_message(GraphOperationMessage::StrokeSet {
|
||||||
|
layer,
|
||||||
|
color: None,
|
||||||
|
stroke: Stroke::default(),
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
editor
|
||||||
|
.handle_message(GraphOperationMessage::TransformSet {
|
||||||
|
layer,
|
||||||
|
transform: DAffine2::from_scale(DVec2::splat(0.002)),
|
||||||
|
transform_in: TransformIn::Local,
|
||||||
|
skip_rerender: false,
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
|
||||||
|
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
|
||||||
|
let clipboard = copy_layers_to_clipboard(&mut editor).await;
|
||||||
|
let svg = copied_svg(&clipboard).expect("the square should render an SVG");
|
||||||
|
|
||||||
|
let (drawn, frame) = drawn_bounds_and_frame(svg);
|
||||||
|
assert!(
|
||||||
|
(frame.width() - 0.2).abs() < 1e-4 && (frame.height() - 0.2).abs() < 1e-4,
|
||||||
|
"the frame should be the square's size: {svg}"
|
||||||
|
);
|
||||||
|
assert!((drawn.width() - 0.2).abs() < 1e-4 && drawn.left().abs() < 1e-4, "the square should fill the frame: {svg}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sets the viewport to `size` pixels and gives back the size of the part of the document it shows.
|
||||||
|
async fn view_of_size(editor: &mut EditorTestUtils, size: DVec2) -> DVec2 {
|
||||||
|
use graphene_std::math::quad::Quad;
|
||||||
|
|
||||||
|
editor.set_viewport_size(DVec2::ZERO, size).await;
|
||||||
|
let viewport_to_document = editor.active_document().metadata().document_to_viewport.inverse();
|
||||||
|
let [min, max] = (viewport_to_document * Quad::from_box([DVec2::ZERO, size])).bounding_box();
|
||||||
|
max - min
|
||||||
|
}
|
||||||
|
|
||||||
|
// Content drawn for its view, like a brush stroke's image or tiles covering the view, is framed to the view it was copied in
|
||||||
|
#[cfg_attr(miri, ignore)]
|
||||||
|
#[tokio::test]
|
||||||
|
async fn copied_svg_frames_content_drawn_for_its_view_to_that_view() {
|
||||||
|
let mut editor = EditorTestUtils::create();
|
||||||
|
editor.new_document().await;
|
||||||
|
let view = view_of_size(&mut editor, DVec2::new(400., 300.)).await;
|
||||||
|
let framed_to_view = |svg: &str| {
|
||||||
|
let (_, frame) = drawn_bounds_and_frame(svg);
|
||||||
|
(frame.width() as f64 - view.x).abs() < 1e-3 && (frame.height() as f64 - view.y).abs() < 1e-3
|
||||||
|
};
|
||||||
|
|
||||||
|
// A brush stroke
|
||||||
|
editor.handle_message(PreferencesMessage::BrushTool { enabled: true }).await;
|
||||||
|
editor.drag_tool(ToolType::Brush, 50., 50., 150., 100., ModifierKeys::empty()).await;
|
||||||
|
let brush = editor.active_document().metadata().all_layers().next().expect("the brush layer");
|
||||||
|
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![brush.to_node()] }).await;
|
||||||
|
let clipboard = copy_layers_to_clipboard(&mut editor).await;
|
||||||
|
let svg = copied_svg(&clipboard).expect("the brush layer should render an SVG");
|
||||||
|
assert!(framed_to_view(svg), "the brush layer should be framed to the {view} view: {svg}");
|
||||||
|
assert!(svg.contains("data:image/png;base64,") && !svg.contains("deferred-image"), "the stroke should be the GPU's image: {svg}");
|
||||||
|
|
||||||
|
// A rectangle tiled across the view
|
||||||
|
editor.draw_rect(0., 0., 20., 20.).await;
|
||||||
|
let tiled = editor.active_document().metadata().all_layers().next().expect("the rectangle");
|
||||||
|
let tile = DefinitionIdentifier::ProtoNode(graphene_std::repeat::tile::IDENTIFIER);
|
||||||
|
editor.handle_message(NodeGraphMessage::CreateNodeInLayerWithTransaction { node_type: tile, layer: tiled }).await;
|
||||||
|
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![tiled.to_node()] }).await;
|
||||||
|
let clipboard = copy_layers_to_clipboard(&mut editor).await;
|
||||||
|
let svg = copied_svg(&clipboard).expect("the tiled layer should render an SVG");
|
||||||
|
assert!(framed_to_view(svg), "the tiled layer should be framed to the {view} view: {svg}");
|
||||||
|
assert!(svg.matches("<path").count() > 1, "the view should hold several tiles: {svg}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg_attr(miri, ignore)]
|
||||||
|
#[tokio::test]
|
||||||
|
async fn copied_svg_draws_generators_as_the_gpus_render() {
|
||||||
|
use crate::messages::portfolio::document::utility_types::network_interface::OutputConnector;
|
||||||
|
use graph_craft::document::NodeId;
|
||||||
|
|
||||||
|
// A Mandelbrot layer, made from an image layer by feeding the fractal into its content instead
|
||||||
|
let mut editor = EditorTestUtils::create();
|
||||||
|
editor.new_document().await;
|
||||||
|
editor.create_raster_image(graphene_std::raster::Image::new(1, 1, Color::BLACK), None).await;
|
||||||
|
let layer = editor.active_document().metadata().all_layers().next().expect("the image layer").to_node();
|
||||||
|
let mandelbrot = NodeId::new();
|
||||||
|
editor.dispatch(NodeGraphMessage::CreateNodeFromContextMenu {
|
||||||
|
node_id: Some(mandelbrot),
|
||||||
|
node_type: DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER),
|
||||||
|
xy: None,
|
||||||
|
add_transaction: true,
|
||||||
|
});
|
||||||
|
editor.dispatch(NodeGraphMessage::CreateWire {
|
||||||
|
output_connector: OutputConnector::primary_output(mandelbrot),
|
||||||
|
input_connector: InputConnector::node_at_index(layer, 1),
|
||||||
|
});
|
||||||
|
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer] }).await;
|
||||||
|
|
||||||
|
// The SVG frames the fractal's body, hundreds of units across rather than the image's one, and embeds the GPU's image of it where its placeholder stood
|
||||||
|
let clipboard = copy_layers_to_clipboard(&mut editor).await;
|
||||||
|
let svg = copied_svg(&clipboard).expect("the Mandelbrot layer should render an SVG");
|
||||||
|
let (_, frame) = drawn_bounds_and_frame(svg);
|
||||||
|
assert!(frame.width() > 100., "{svg}");
|
||||||
|
assert!(svg.matches("data:image/png;base64,").count() == 1 && !svg.contains("deferred-image"), "{svg}");
|
||||||
|
}
|
||||||
|
|
||||||
/// - paste
|
/// - paste
|
||||||
/// - assert that ellipse was copied
|
/// - assert that ellipse was copied
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
|
|||||||
@@ -31,8 +31,8 @@ use graphene_std::vector::misc::{
|
|||||||
WeldMethod,
|
WeldMethod,
|
||||||
};
|
};
|
||||||
use graphene_std::vector::style::{
|
use graphene_std::vector::style::{
|
||||||
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap,
|
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, PaintMapping, StrokeAlign,
|
||||||
StrokeJoin,
|
StrokeCap, StrokeJoin,
|
||||||
};
|
};
|
||||||
use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector};
|
use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector};
|
||||||
use graphene_std::{
|
use graphene_std::{
|
||||||
@@ -419,6 +419,7 @@ macro_rules! inspectable_types {
|
|||||||
List<StrokeJoin>,
|
List<StrokeJoin>,
|
||||||
List<StrokeAlign>,
|
List<StrokeAlign>,
|
||||||
List<StrokeCap>,
|
List<StrokeCap>,
|
||||||
|
List<PaintMapping>,
|
||||||
List<WeldMethod>,
|
List<WeldMethod>,
|
||||||
List<UnweldMethod>,
|
List<UnweldMethod>,
|
||||||
List<ExtrudeJoiningAlgorithm>,
|
List<ExtrudeJoiningAlgorithm>,
|
||||||
@@ -480,6 +481,7 @@ macro_rules! inspectable_types {
|
|||||||
Item<StrokeJoin>,
|
Item<StrokeJoin>,
|
||||||
Item<StrokeAlign>,
|
Item<StrokeAlign>,
|
||||||
Item<StrokeCap>,
|
Item<StrokeCap>,
|
||||||
|
Item<PaintMapping>,
|
||||||
Item<WeldMethod>,
|
Item<WeldMethod>,
|
||||||
Item<UnweldMethod>,
|
Item<UnweldMethod>,
|
||||||
Item<ExtrudeJoiningAlgorithm>,
|
Item<ExtrudeJoiningAlgorithm>,
|
||||||
@@ -1295,6 +1297,7 @@ impl_table_item_layout_for_choice_enum!(
|
|||||||
StrokeJoin,
|
StrokeJoin,
|
||||||
StrokeAlign,
|
StrokeAlign,
|
||||||
StrokeCap,
|
StrokeCap,
|
||||||
|
PaintMapping,
|
||||||
WeldMethod,
|
WeldMethod,
|
||||||
UnweldMethod,
|
UnweldMethod,
|
||||||
ExtrudeJoiningAlgorithm,
|
ExtrudeJoiningAlgorithm,
|
||||||
@@ -1491,6 +1494,7 @@ macro_rules! known_item_types {
|
|||||||
StrokeJoin,
|
StrokeJoin,
|
||||||
StrokeAlign,
|
StrokeAlign,
|
||||||
StrokeCap,
|
StrokeCap,
|
||||||
|
PaintMapping,
|
||||||
WeldMethod,
|
WeldMethod,
|
||||||
UnweldMethod,
|
UnweldMethod,
|
||||||
ExtrudeJoiningAlgorithm,
|
ExtrudeJoiningAlgorithm,
|
||||||
|
|||||||
+2
-1
@@ -14,7 +14,7 @@ use graph_craft::document::{NodeId, NodeInput};
|
|||||||
use graph_craft::list;
|
use graph_craft::list;
|
||||||
use graphene_std::renderer::convert_usvg_path::convert_usvg_path;
|
use graphene_std::renderer::convert_usvg_path::convert_usvg_path;
|
||||||
use graphene_std::text::{Font, TypesettingConfig};
|
use graphene_std::text::{Font, TypesettingConfig};
|
||||||
use graphene_std::vector::style::{Gradient, GradientForm, GradientSettings, GradientSpace, GradientSpread, GradientStop, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
|
use graphene_std::vector::style::{Gradient, GradientForm, GradientSettings, GradientSpace, GradientSpread, GradientStop, PaintMapping, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
|
||||||
use graphene_std::{Artboard, Color};
|
use graphene_std::{Artboard, Color};
|
||||||
|
|
||||||
#[derive(ExtractField)]
|
#[derive(ExtractField)]
|
||||||
@@ -991,6 +991,7 @@ fn apply_usvg_stroke(stroke: &usvg::Stroke, modify_inputs: &mut ModifyInputsCont
|
|||||||
},
|
},
|
||||||
join_miter_limit: stroke.miterlimit().get() as f64,
|
join_miter_limit: stroke.miterlimit().get() as f64,
|
||||||
align: StrokeAlign::Center,
|
align: StrokeAlign::Center,
|
||||||
|
paint_mapping: PaintMapping::Plane,
|
||||||
transform,
|
transform,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -904,6 +904,8 @@ impl<'a> ModifyInputsContext<'a> {
|
|||||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::DashPattern(stroke.dash_lengths), false), true);
|
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::DashPattern(stroke.dash_lengths), false), true);
|
||||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashOffsetInput);
|
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashOffsetInput);
|
||||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Number(stroke.dash_offset), false), true);
|
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Number(stroke.dash_offset), false), true);
|
||||||
|
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintMappingInput);
|
||||||
|
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::PaintMapping(stroke.paint_mapping), false), true);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Update the transform value of the upstream Transform node based a change to its existing value and the given parent transform.
|
/// Update the transform value of the upstream Transform node based a change to its existing value and the given parent transform.
|
||||||
|
|||||||
@@ -1684,19 +1684,18 @@ mod test {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn rasterize_defaults_to_a_1000_px_square_at_full_resolution() {
|
fn rasterize_defaults_to_a_1000_px_square_at_full_resolution() {
|
||||||
use glam::{DAffine2, UVec2};
|
use glam::DAffine2;
|
||||||
use graph_craft::document::value::TaggedValue;
|
use graph_craft::document::value::TaggedValue;
|
||||||
use graphene_std::platform_application_io::rasterize;
|
use graphene_std::platform_application_io::rasterize;
|
||||||
|
|
||||||
let definition = super::resolve_proto_node_definition(&rasterize::IDENTIFIER).expect("Rasterize should have a definition");
|
let definition = super::resolve_proto_node_definition(&rasterize::IDENTIFIER).expect("Rasterize should have a definition");
|
||||||
let footprint = definition.node_template.input(rasterize::FootprintInput).and_then(|input| input.as_value());
|
let transform = definition.node_template.input(rasterize::TransformInput).and_then(|input| input.as_value());
|
||||||
|
let resolution = definition.node_template.input(rasterize::ResolutionInput).and_then(|input| input.as_value());
|
||||||
|
|
||||||
let expected = Footprint {
|
// The square from (0, 0) to (1000, 1000)
|
||||||
transform: DAffine2::from_scale(DVec2::splat(1000.)),
|
let expected_transform = DAffine2::from_scale_angle_translation(DVec2::splat(1000.), 0., DVec2::splat(500.));
|
||||||
resolution: UVec2::splat(1000),
|
assert_eq!(transform, Some(&TaggedValue::DAffine2(expected_transform)));
|
||||||
..Default::default()
|
assert_eq!(resolution, Some(&TaggedValue::DVec2(DVec2::splat(1000.))));
|
||||||
};
|
|
||||||
assert_eq!(footprint, Some(&TaggedValue::Footprint(expected)));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// The executor input the compiler fills in has no type yet, which mustn't rule out every implementation
|
// The executor input the compiler fills in has no type yet, which mustn't rule out every implementation
|
||||||
|
|||||||
@@ -31,14 +31,14 @@ use graphene_std::raster_types::{CPU, GPU, Image, Raster};
|
|||||||
use graphene_std::text::{Font, TextAlign};
|
use graphene_std::text::{Font, TextAlign};
|
||||||
use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
|
use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
|
||||||
use graphene_std::transfer_curve::TransferCurve;
|
use graphene_std::transfer_curve::TransferCurve;
|
||||||
use graphene_std::transform::{Footprint, ReferencePoint, ScaleType, Transform};
|
use graphene_std::transform::{ReferencePoint, ScaleType, Transform};
|
||||||
use graphene_std::vector::misc::BooleanOperation;
|
use graphene_std::vector::misc::BooleanOperation;
|
||||||
use graphene_std::vector::misc::{
|
use graphene_std::vector::misc::{
|
||||||
ArcType, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod, WeldMethod,
|
ArcType, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod, WeldMethod,
|
||||||
};
|
};
|
||||||
use graphene_std::vector::style::{
|
use graphene_std::vector::style::{
|
||||||
FillChoice, Gradient, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStops, StrokeAlign,
|
FillChoice, Gradient, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStops, PaintMapping,
|
||||||
StrokeCap, StrokeJoin, build_transform_with_y_preservation,
|
StrokeAlign, StrokeCap, StrokeJoin, build_transform_with_y_preservation,
|
||||||
};
|
};
|
||||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
|
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
|
||||||
use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, GlowSource, GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution, Vector};
|
use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, GlowSource, GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution, Vector};
|
||||||
@@ -421,7 +421,6 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
|||||||
// ============
|
// ============
|
||||||
Some(x) if id_is::<Font>(x) => font_widget(default_info),
|
Some(x) if id_is::<Font>(x) => font_widget(default_info),
|
||||||
Some(x) if id_is::<TransferCurve>(x) => transfer_curve_widget(default_info),
|
Some(x) if id_is::<TransferCurve>(x) => transfer_curve_widget(default_info),
|
||||||
Some(x) if id_is::<Footprint>(x) => footprint_widget(default_info, &mut extra_widgets),
|
|
||||||
Some(x) if id_is::<Box<VectorModification>>(x) => vector_modification_widget(default_info).into(),
|
Some(x) if id_is::<Box<VectorModification>>(x) => vector_modification_widget(default_info).into(),
|
||||||
Some(x) if id_is::<Image<Color>>(x) => image_data_widget(default_info).into(),
|
Some(x) if id_is::<Image<Color>>(x) => image_data_widget(default_info).into(),
|
||||||
Some(x) if id_is::<Resource>(x) => resource_widget(default_info, Vec::new()).into(),
|
Some(x) if id_is::<Resource>(x) => resource_widget(default_info, Vec::new()).into(),
|
||||||
@@ -460,6 +459,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
|||||||
Some(x) if id_is::<StrokeCap>(x) => enum_choice::<StrokeCap>().for_socket(default_info).inspector_row(),
|
Some(x) if id_is::<StrokeCap>(x) => enum_choice::<StrokeCap>().for_socket(default_info).inspector_row(),
|
||||||
Some(x) if id_is::<StrokeJoin>(x) => enum_choice::<StrokeJoin>().for_socket(default_info).inspector_row(),
|
Some(x) if id_is::<StrokeJoin>(x) => enum_choice::<StrokeJoin>().for_socket(default_info).inspector_row(),
|
||||||
Some(x) if id_is::<StrokeAlign>(x) => enum_choice::<StrokeAlign>().for_socket(default_info).inspector_row(),
|
Some(x) if id_is::<StrokeAlign>(x) => enum_choice::<StrokeAlign>().for_socket(default_info).inspector_row(),
|
||||||
|
Some(x) if id_is::<PaintMapping>(x) => enum_choice::<PaintMapping>().for_socket(default_info).inspector_row(),
|
||||||
Some(x) if id_is::<ArcType>(x) => enum_choice::<ArcType>().for_socket(default_info).inspector_row(),
|
Some(x) if id_is::<ArcType>(x) => enum_choice::<ArcType>().for_socket(default_info).inspector_row(),
|
||||||
Some(x) if id_is::<RowsOrColumns>(x) => enum_choice::<RowsOrColumns>().for_socket(default_info).inspector_row(),
|
Some(x) if id_is::<RowsOrColumns>(x) => enum_choice::<RowsOrColumns>().for_socket(default_info).inspector_row(),
|
||||||
Some(x) if id_is::<TextAlign>(x) => enum_choice::<TextAlign>().for_socket(default_info).inspector_row(),
|
Some(x) if id_is::<TextAlign>(x) => enum_choice::<TextAlign>().for_socket(default_info).inspector_row(),
|
||||||
@@ -677,142 +677,6 @@ pub fn image_data_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Vec<Wi
|
|||||||
widgets
|
widgets
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn footprint_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widgets: &mut Vec<LayoutGroup>) -> LayoutGroup {
|
|
||||||
let ParameterWidgetsInfo { document_node, node_id, index, .. } = parameter_widgets_info;
|
|
||||||
|
|
||||||
let mut location_widgets = start_widgets(¶meter_widgets_info);
|
|
||||||
location_widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
|
||||||
|
|
||||||
let mut scale_widgets = vec![TextLabel::new("").widget_instance()];
|
|
||||||
add_blank_assist(&mut scale_widgets);
|
|
||||||
scale_widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
|
||||||
|
|
||||||
let mut resolution_widgets = vec![TextLabel::new("").widget_instance()];
|
|
||||||
add_blank_assist(&mut resolution_widgets);
|
|
||||||
resolution_widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
|
||||||
|
|
||||||
let Some(document_node) = document_node else { return LayoutGroup::default() };
|
|
||||||
let Some(input) = document_node.inputs.get(index) else {
|
|
||||||
log::warn!("A widget failed to be built because its node's input index is invalid.");
|
|
||||||
return Vec::new().into();
|
|
||||||
};
|
|
||||||
|
|
||||||
if let Some(&TaggedValue::Footprint(footprint)) = input.as_non_exposed_value() {
|
|
||||||
let top_left = footprint.transform.transform_point2(DVec2::ZERO);
|
|
||||||
let bounds = footprint.scale();
|
|
||||||
let oversample = footprint.resolution.as_dvec2() / bounds;
|
|
||||||
|
|
||||||
location_widgets.extend_from_slice(&[
|
|
||||||
NumberInput::new(Some(top_left.x))
|
|
||||||
.label("X")
|
|
||||||
.unit(" px")
|
|
||||||
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| {
|
|
||||||
let (offset, scale) = {
|
|
||||||
let diff = DVec2::new(top_left.x - x.value.unwrap_or_default(), 0.);
|
|
||||||
(top_left - diff, bounds)
|
|
||||||
};
|
|
||||||
|
|
||||||
let footprint = Footprint {
|
|
||||||
transform: DAffine2::from_scale_angle_translation(scale, 0., offset),
|
|
||||||
resolution: (oversample * scale).as_uvec2(),
|
|
||||||
..footprint
|
|
||||||
};
|
|
||||||
|
|
||||||
TaggedValue::Footprint(footprint)
|
|
||||||
}))
|
|
||||||
.on_commit(commit_value)
|
|
||||||
.widget_instance(),
|
|
||||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
|
||||||
NumberInput::new(Some(top_left.y))
|
|
||||||
.label("Y")
|
|
||||||
.unit(" px")
|
|
||||||
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| {
|
|
||||||
let (offset, scale) = {
|
|
||||||
let diff = DVec2::new(0., top_left.y - x.value.unwrap_or_default());
|
|
||||||
(top_left - diff, bounds)
|
|
||||||
};
|
|
||||||
|
|
||||||
let footprint = Footprint {
|
|
||||||
transform: DAffine2::from_scale_angle_translation(scale, 0., offset),
|
|
||||||
resolution: (oversample * scale).as_uvec2(),
|
|
||||||
..footprint
|
|
||||||
};
|
|
||||||
|
|
||||||
TaggedValue::Footprint(footprint)
|
|
||||||
}))
|
|
||||||
.on_commit(commit_value)
|
|
||||||
.widget_instance(),
|
|
||||||
]);
|
|
||||||
|
|
||||||
scale_widgets.extend_from_slice(&[
|
|
||||||
NumberInput::new(Some(bounds.x))
|
|
||||||
.label("W")
|
|
||||||
.unit(" px")
|
|
||||||
.on_update(update_value_at_index(
|
|
||||||
move |x: &NumberInput| {
|
|
||||||
let (offset, scale) = (top_left, DVec2::new(x.value.unwrap_or_default(), bounds.y));
|
|
||||||
|
|
||||||
let footprint = Footprint {
|
|
||||||
transform: DAffine2::from_scale_angle_translation(scale, 0., offset),
|
|
||||||
resolution: (oversample * scale).as_uvec2(),
|
|
||||||
..footprint
|
|
||||||
};
|
|
||||||
|
|
||||||
TaggedValue::Footprint(footprint)
|
|
||||||
},
|
|
||||||
node_id,
|
|
||||||
index,
|
|
||||||
))
|
|
||||||
.on_commit(commit_value)
|
|
||||||
.widget_instance(),
|
|
||||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
|
||||||
NumberInput::new(Some(bounds.y))
|
|
||||||
.label("H")
|
|
||||||
.unit(" px")
|
|
||||||
.on_update(update_value_at_index(
|
|
||||||
move |x: &NumberInput| {
|
|
||||||
let (offset, scale) = (top_left, DVec2::new(bounds.x, x.value.unwrap_or_default()));
|
|
||||||
|
|
||||||
let footprint = Footprint {
|
|
||||||
transform: DAffine2::from_scale_angle_translation(scale, 0., offset),
|
|
||||||
resolution: (oversample * scale).as_uvec2(),
|
|
||||||
..footprint
|
|
||||||
};
|
|
||||||
|
|
||||||
TaggedValue::Footprint(footprint)
|
|
||||||
},
|
|
||||||
node_id,
|
|
||||||
index,
|
|
||||||
))
|
|
||||||
.on_commit(commit_value)
|
|
||||||
.widget_instance(),
|
|
||||||
]);
|
|
||||||
|
|
||||||
resolution_widgets.push(
|
|
||||||
NumberInput::new(Some((footprint.resolution.as_dvec2() / bounds).x * 100.))
|
|
||||||
.label("Resolution")
|
|
||||||
.mode_range()
|
|
||||||
.min(0.)
|
|
||||||
.range_min(Some(1.))
|
|
||||||
.range_max(Some(100.))
|
|
||||||
.unit("%")
|
|
||||||
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| {
|
|
||||||
let resolution = (bounds * x.value.unwrap_or(100.) / 100.).as_uvec2().max((1, 1).into()).min((4000, 4000).into());
|
|
||||||
|
|
||||||
let footprint = Footprint { resolution, ..footprint };
|
|
||||||
TaggedValue::Footprint(footprint)
|
|
||||||
}))
|
|
||||||
.on_commit(commit_value)
|
|
||||||
.widget_instance(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
let widgets = [LayoutGroup::row(location_widgets), LayoutGroup::row(scale_widgets), LayoutGroup::row(resolution_widgets)];
|
|
||||||
let (last, rest) = widgets.split_last().expect("Footprint widget should return multiple rows");
|
|
||||||
*extra_widgets = rest.to_vec();
|
|
||||||
last.clone()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The X, Y, rotation, W, and H of a transform input. W and H show as a multiplier, or with the parameter's `size_unit` (like " px") where it declares one, for a transform scaling a shape of unit size.
|
/// The X, Y, rotation, W, and H of a transform input. W and H show as a multiplier, or with the parameter's `size_unit` (like " px") where it declares one, for a transform scaling a shape of unit size.
|
||||||
pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, size_unit: Option<&str>, extra_widgets: &mut Vec<LayoutGroup>) -> LayoutGroup {
|
pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, size_unit: Option<&str>, extra_widgets: &mut Vec<LayoutGroup>) -> LayoutGroup {
|
||||||
let ParameterWidgetsInfo { document_node, node_id, index, .. } = parameter_widgets_info;
|
let ParameterWidgetsInfo { document_node, node_id, index, .. } = parameter_widgets_info;
|
||||||
@@ -3996,6 +3860,9 @@ pub fn stroke_inspector(node_id: NodeId, context: &mut NodeInspectorContext) ->
|
|||||||
let dash_lengths = dash_pattern_widget(ParameterWidgetsInfo::new(node_id, DashPatternInput, true, context), TextInput::default().centered(true));
|
let dash_lengths = dash_pattern_widget(ParameterWidgetsInfo::new(node_id, DashPatternInput, true, context), TextInput::default().centered(true));
|
||||||
let number_input = disabled_number_input;
|
let number_input = disabled_number_input;
|
||||||
let dash_offset = number_widget(ParameterWidgetsInfo::new(node_id, DashOffsetInput, true, context), number_input);
|
let dash_offset = number_widget(ParameterWidgetsInfo::new(node_id, DashOffsetInput, true, context), number_input);
|
||||||
|
let paint_mapping = enum_choice::<PaintMapping>()
|
||||||
|
.for_socket(ParameterWidgetsInfo::new(node_id, PaintMappingInput, true, context))
|
||||||
|
.inspector_row();
|
||||||
|
|
||||||
vec![
|
vec![
|
||||||
color,
|
color,
|
||||||
@@ -4006,6 +3873,7 @@ pub fn stroke_inspector(node_id: NodeId, context: &mut NodeInspectorContext) ->
|
|||||||
LayoutGroup::row(miter_limit),
|
LayoutGroup::row(miter_limit),
|
||||||
LayoutGroup::row(dash_lengths),
|
LayoutGroup::row(dash_lengths),
|
||||||
LayoutGroup::row(dash_offset),
|
LayoutGroup::row(dash_offset),
|
||||||
|
paint_mapping,
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ use crate::messages::portfolio::document::node_graph::document_node_definitions:
|
|||||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||||
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, NodeTemplate, NodeTemplateImplementation, OutputConnector};
|
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, NodeTemplate, NodeTemplateImplementation, OutputConnector};
|
||||||
use crate::messages::prelude::DocumentMessageHandler;
|
use crate::messages::prelude::DocumentMessageHandler;
|
||||||
use glam::{DVec2, IVec2};
|
use glam::{DAffine2, DVec2, IVec2};
|
||||||
use graph_craft::application_io::resource::{DataSource, Resource, ResourceHash, ResourceId};
|
use graph_craft::application_io::resource::{DataSource, Resource, ResourceHash, ResourceId};
|
||||||
use graph_craft::document::DocumentNode;
|
use graph_craft::document::DocumentNode;
|
||||||
use graph_craft::document::{DocumentNodeImplementation, NodeInput, value::TaggedValue};
|
use graph_craft::document::{DocumentNodeImplementation, NodeInput, value::TaggedValue};
|
||||||
@@ -297,10 +297,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
|||||||
node: graphene_std::math_nodes::floor::IDENTIFIER,
|
node: graphene_std::math_nodes::floor::IDENTIFIER,
|
||||||
aliases: &["graphene_math_nodes::FloorNode", "graphene_core::ops::FloorNode"],
|
aliases: &["graphene_math_nodes::FloorNode", "graphene_core::ops::FloorNode"],
|
||||||
},
|
},
|
||||||
NodeReplacement {
|
|
||||||
node: graphene_std::math_nodes::footprint_value::IDENTIFIER,
|
|
||||||
aliases: &["graphene_math_nodes::FootprintValueNode", "graphene_core::ops::FootprintValueNode"],
|
|
||||||
},
|
|
||||||
NodeReplacement {
|
NodeReplacement {
|
||||||
node: graphene_std::math_nodes::gradient_spread::IDENTIFIER,
|
node: graphene_std::math_nodes::gradient_spread::IDENTIFIER,
|
||||||
aliases: &["math_nodes::SpreadMethodNode"],
|
aliases: &["math_nodes::SpreadMethodNode"],
|
||||||
@@ -1827,6 +1823,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
|||||||
for (node_id, node, network_path) in &nodes {
|
for (node_id, node, network_path) in &nodes {
|
||||||
migrate_node(node_id, node, network_path, document, reset_node_definitions_on_open);
|
migrate_node(node_id, node, network_path, document, reset_node_definitions_on_open);
|
||||||
}
|
}
|
||||||
|
remove_footprint_value_nodes(document);
|
||||||
create_layer_stacks(document);
|
create_layer_stacks(document);
|
||||||
follow_segments_turned_on_load(document);
|
follow_segments_turned_on_load(document);
|
||||||
|
|
||||||
@@ -2185,6 +2182,100 @@ fn read_noise_through_gamma_correction(document: &mut DocumentMessageHandler, no
|
|||||||
Some(())
|
Some(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Whether a node is a removed 'Footprint Value' node, under any identifier it had.
|
||||||
|
fn is_footprint_value(node: &DocumentNode) -> bool {
|
||||||
|
matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if identifier.as_str().ends_with("::FootprintValueNode"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sets an upgraded Rasterize node's area transform and resolution from the footprint it took, stored or from a 'Footprint Value' node (even
|
||||||
|
/// through reroutes) whose inputs it takes over. Any other wire can't be read before it runs, so it leaves the defaults, shown in the graph.
|
||||||
|
fn set_rasterize_area_from_footprint(document: &mut DocumentMessageHandler, node_id: &NodeId, network_path: &[NodeId], footprint: &NodeInput) -> Option<()> {
|
||||||
|
use graphene_std::math_nodes::multiply;
|
||||||
|
|
||||||
|
// A footprint's transform placed a unit square anchored at its corner, where the area's is centered on its origin
|
||||||
|
let corner_to_center = DAffine2::from_translation(DVec2::splat(0.5));
|
||||||
|
let (transform_connector, resolution_connector) = (InputConnector::node_at_index(*node_id, 1), InputConnector::node_at_index(*node_id, 2));
|
||||||
|
|
||||||
|
// Reroutes pass the footprint along unchanged, and a cycle of them leads nowhere else
|
||||||
|
let mut footprint = footprint.clone();
|
||||||
|
let mut visited = HashSet::new();
|
||||||
|
while let NodeInput::Node { node_id: source, output_index: 0 } = footprint
|
||||||
|
&& visited.insert(source)
|
||||||
|
&& let Some(reroute) = document.network_interface.document_node(&source, network_path)
|
||||||
|
&& matches!(&reroute.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::ops::passthrough::IDENTIFIER)
|
||||||
|
&& let Some(content) = reroute.inputs.first()
|
||||||
|
{
|
||||||
|
footprint = content.clone();
|
||||||
|
}
|
||||||
|
|
||||||
|
match &footprint {
|
||||||
|
// A stored footprint loads as its transform's six numbers then its resolution's two
|
||||||
|
NodeInput::Value { tagged_value, exposed } => {
|
||||||
|
let TaggedValue::Numbers(numbers) = &**tagged_value else { return None };
|
||||||
|
let &[x_axis_x, x_axis_y, y_axis_x, y_axis_y, translation_x, translation_y, width, height] = numbers.as_slice() else {
|
||||||
|
return None;
|
||||||
|
};
|
||||||
|
|
||||||
|
let transform = DAffine2::from_cols_array(&[x_axis_x, x_axis_y, y_axis_x, y_axis_y, translation_x, translation_y]) * corner_to_center;
|
||||||
|
let resolution = DVec2::new(width, height);
|
||||||
|
document
|
||||||
|
.network_interface
|
||||||
|
.set_input(&transform_connector, NodeInput::value(TaggedValue::DAffine2(transform), *exposed), network_path);
|
||||||
|
document
|
||||||
|
.network_interface
|
||||||
|
.set_input(&resolution_connector, NodeInput::value(TaggedValue::DVec2(resolution), *exposed), network_path);
|
||||||
|
}
|
||||||
|
NodeInput::Node { node_id: source, output_index: 0 } if document.network_interface.document_node(source, network_path).is_some_and(is_footprint_value) => {
|
||||||
|
let footprint_value = document.network_interface.document_node(source, network_path)?;
|
||||||
|
let (transform, resolution) = (footprint_value.inputs.get(1)?.clone(), footprint_value.inputs.get(2)?.clone());
|
||||||
|
document.network_interface.set_input(&resolution_connector, resolution, network_path);
|
||||||
|
|
||||||
|
match transform {
|
||||||
|
NodeInput::Value { tagged_value, exposed } => {
|
||||||
|
let &TaggedValue::DAffine2(transform) = &*tagged_value else { return None };
|
||||||
|
let transform = NodeInput::value(TaggedValue::DAffine2(transform * corner_to_center), exposed);
|
||||||
|
document.network_interface.set_input(&transform_connector, transform, network_path);
|
||||||
|
}
|
||||||
|
// A wired transform goes through a Multiply node moving its unit square's anchor to the center
|
||||||
|
wire => {
|
||||||
|
document.network_interface.set_input(&transform_connector, wire, network_path);
|
||||||
|
|
||||||
|
let multiply_id = NodeId::new();
|
||||||
|
document
|
||||||
|
.network_interface
|
||||||
|
.insert_node(multiply_id, resolve_proto_node_type(multiply::IDENTIFIER)?.default_node_template(), network_path);
|
||||||
|
let multiplicand = NodeInput::value(TaggedValue::DAffine2(corner_to_center), false);
|
||||||
|
document.network_interface.set_input(&InputConnector::node_at_index(multiply_id, 1), multiplicand, network_path);
|
||||||
|
document.network_interface.insert_node_before_input(&multiply_id, &transform_connector, network_path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
for connector in [transform_connector, resolution_connector] {
|
||||||
|
let default = document.network_interface.input_from_connector(&connector, network_path)?.as_value()?.clone();
|
||||||
|
document.network_interface.set_input(&connector, NodeInput::value(default, true), network_path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Some(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Deletes every 'Footprint Value' node once the Rasterize nodes it fed have taken over its inputs, disconnecting whatever else it fed.
|
||||||
|
fn remove_footprint_value_nodes(document: &mut DocumentMessageHandler) {
|
||||||
|
let footprint_value_nodes: Vec<(NodeId, Vec<NodeId>)> = document
|
||||||
|
.network_interface
|
||||||
|
.document_network()
|
||||||
|
.recursive_nodes()
|
||||||
|
.filter(|(_, node, _)| is_footprint_value(node))
|
||||||
|
.map(|(node_id, _, path)| (*node_id, path))
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
for (node_id, network_path) in footprint_value_nodes {
|
||||||
|
document.network_interface.delete_nodes(vec![node_id], false, &network_path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Converts a legacy stroke dash input (a `List<f64>`, single `f64`, or comma/space separated `String`) to the `DashPattern` value type.
|
/// Converts a legacy stroke dash input (a `List<f64>`, single `f64`, or comma/space separated `String`) to the `DashPattern` value type.
|
||||||
fn migrate_dash_input(input: &NodeInput) -> Option<NodeInput> {
|
fn migrate_dash_input(input: &NodeInput) -> Option<NodeInput> {
|
||||||
let NodeInput::Value { tagged_value, exposed } = input else { return None };
|
let NodeInput::Value { tagged_value, exposed } = input else { return None };
|
||||||
@@ -2770,9 +2861,14 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
|||||||
inputs_count = 9;
|
inputs_count = 9;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The modern Stroke also has 10 inputs, so the Paint Order era is told apart by its paint order at 7 or its dash offset at 9,
|
||||||
|
// either of which may be wired, where the modern shape holds its dash pattern and paint mapping
|
||||||
|
let value_at = |index: usize| node.inputs.get(index).and_then(|input| input.as_value());
|
||||||
|
let is_paint_order_stroke = inputs_count == 10 && (matches!(value_at(7), Some(TaggedValue::PaintOrder(_))) || matches!(value_at(9), Some(TaggedValue::Number(_))));
|
||||||
|
|
||||||
// The Stroke node's "Paint Order" input was retired in favor of the relative order of the Fill and Stroke
|
// The Stroke node's "Paint Order" input was retired in favor of the relative order of the Fill and Stroke
|
||||||
// nodes in the chain, so the stored value becomes a topology rewrite that reorders the two nodes.
|
// nodes in the chain, so the stored value becomes a topology rewrite that reorders the two nodes.
|
||||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER) && inputs_count == 10 {
|
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER) && is_paint_order_stroke {
|
||||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||||
|
|
||||||
@@ -3165,6 +3261,16 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
|||||||
inputs_count = 2;
|
inputs_count = 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Rasterize, like the wrapper network collapsed into it above, took a footprint where it now takes an area transform and a resolution
|
||||||
|
if reference == DefinitionIdentifier::ProtoNode(graphene_std::platform_application_io::rasterize::IDENTIFIER) && matches!(inputs_count, 2 | 3) {
|
||||||
|
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||||
|
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||||
|
document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||||
|
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), node.inputs[0].clone(), network_path);
|
||||||
|
set_rasterize_area_from_footprint(document, node_id, network_path, &node.inputs[1]);
|
||||||
|
inputs_count = 4;
|
||||||
|
}
|
||||||
|
|
||||||
// The removed "Brightness/Contrast Classic" node had no Use Classic input, so its three inputs become the unified node with the toggle on
|
// The removed "Brightness/Contrast Classic" node had no Use Classic input, so its three inputs become the unified node with the toggle on
|
||||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster::brightness_contrast::IDENTIFIER) && inputs_count == 3 {
|
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster::brightness_contrast::IDENTIFIER) && inputs_count == 3 {
|
||||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||||
@@ -4697,6 +4803,7 @@ mod tests {
|
|||||||
.find(|node_id| document.network_interface.reference(node_id, &[]).as_ref() == Some(&stroke_reference))
|
.find(|node_id| document.network_interface.reference(node_id, &[]).as_ref() == Some(&stroke_reference))
|
||||||
.expect("a fresh shape should have a Stroke node in its chain");
|
.expect("a fresh shape should have a Stroke node in its chain");
|
||||||
let mut inputs = document.network_interface.document_node(&stroke_node_id, &[]).unwrap().inputs.clone();
|
let mut inputs = document.network_interface.document_node(&stroke_node_id, &[]).unwrap().inputs.clone();
|
||||||
|
inputs.truncate(graphene_std::vector::stroke::PaintMappingInput::INDEX);
|
||||||
inputs.insert(7, NodeInput::value(TaggedValue::PaintOrder(PaintOrder::StrokeBelow), false));
|
inputs.insert(7, NodeInput::value(TaggedValue::PaintOrder(PaintOrder::StrokeBelow), false));
|
||||||
let mut legacy_stroke = NodeTemplate { inputs, ..Default::default() };
|
let mut legacy_stroke = NodeTemplate { inputs, ..Default::default() };
|
||||||
legacy_stroke.normalize_input_metadata();
|
legacy_stroke.normalize_input_metadata();
|
||||||
@@ -4718,6 +4825,50 @@ mod tests {
|
|||||||
assert_eq!(chain_layout(&opened, layer), expected, "the migration should leave the layer's chain intact");
|
assert_eq!(chain_layout(&opened, layer), expected, "the migration should leave the layer's chain intact");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The modern Stroke also has 10 inputs, which must not be mistaken for the retired "Paint Order" layout
|
||||||
|
#[tokio::test]
|
||||||
|
async fn opening_a_ten_input_stroke_keeps_its_inputs_and_paint_order() {
|
||||||
|
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||||
|
use crate::messages::tool::common_functionality::graph_modification_utils::get_stroke_paint_order;
|
||||||
|
use crate::test_utils::test_prelude::*;
|
||||||
|
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||||
|
use graphene_std::vector::stroke::{DashPatternInput, PaintMappingInput};
|
||||||
|
use graphene_std::vector::style::PaintMapping;
|
||||||
|
|
||||||
|
let mut editor = EditorTestUtils::create();
|
||||||
|
editor.new_document().await;
|
||||||
|
editor.drag_tool(ToolType::Rectangle, 0., 0., 100., 100., ModifierKeys::empty()).await;
|
||||||
|
let document = editor.active_document_mut();
|
||||||
|
let layer = document.metadata().all_layers().next().unwrap().to_node();
|
||||||
|
|
||||||
|
let stroke_reference = DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER);
|
||||||
|
let stroke_node_id = document
|
||||||
|
.network_interface
|
||||||
|
.layer_chain_nodes(layer, &[])
|
||||||
|
.into_iter()
|
||||||
|
.find(|node_id| document.network_interface.reference(node_id, &[]).as_ref() == Some(&stroke_reference))
|
||||||
|
.expect("a fresh shape should have a Stroke node in its chain");
|
||||||
|
|
||||||
|
// A dashed stroke mapped along its path, whose dash pattern and paint mapping sit where the retired layout kept its paint order and dash offset
|
||||||
|
let dashed_along_path = [
|
||||||
|
(DashPatternInput::INDEX, TaggedValue::DashPattern(vec![4., 2.])),
|
||||||
|
(PaintMappingInput::INDEX, TaggedValue::PaintMapping(PaintMapping::Path)),
|
||||||
|
];
|
||||||
|
for (index, value) in dashed_along_path {
|
||||||
|
document
|
||||||
|
.network_interface
|
||||||
|
.set_input(&InputConnector::node_at_index(stroke_node_id, index), NodeInput::value(value, false), &[]);
|
||||||
|
}
|
||||||
|
let inputs = document.network_interface.document_node(&stroke_node_id, &[]).unwrap().inputs.clone();
|
||||||
|
assert_eq!(inputs.len(), 10, "the modern Stroke should have 10 inputs");
|
||||||
|
|
||||||
|
let opened = load_legacy_document(document.serialize_document(), &HashMapResourceStorage::new(), false).expect("the document should open");
|
||||||
|
|
||||||
|
let reopened = opened.network_interface.document_node(&stroke_node_id, &[]).expect("the Stroke node should still exist");
|
||||||
|
assert_eq!(reopened.inputs, inputs, "the Stroke node should keep its inputs");
|
||||||
|
assert_eq!(get_stroke_paint_order(LayerNodeIdentifier::new_unchecked(layer), &opened.network_interface), PaintOrder::StrokeAbove);
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn opening_a_canvas_rasterize_network_upgrades_it_to_the_vello_node() {
|
async fn opening_a_canvas_rasterize_network_upgrades_it_to_the_vello_node() {
|
||||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkTemplate;
|
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkTemplate;
|
||||||
@@ -4732,11 +4883,8 @@ mod tests {
|
|||||||
let node_id = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(rasterize::IDENTIFIER), 0, 0).await;
|
let node_id = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(rasterize::IDENTIFIER), 0, 0).await;
|
||||||
let document = editor.active_document_mut();
|
let document = editor.active_document_mut();
|
||||||
|
|
||||||
let footprint = Footprint {
|
// A footprint can't be written any more, so a placeholder value stands in for it until the document is serialized
|
||||||
resolution: glam::UVec2::new(64, 32),
|
let placeholder = NodeInput::value(TaggedValue::String("footprint placeholder".into()), false);
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
let footprint_input = NodeInput::value(TaggedValue::Footprint(footprint), false);
|
|
||||||
|
|
||||||
// Save the node as the network that drew into a browser canvas, which took only the artwork and footprint
|
// Save the node as the network that drew into a browser canvas, which took only the artwork and footprint
|
||||||
let canvas_network = NodeNetworkTemplate {
|
let canvas_network = NodeNetworkTemplate {
|
||||||
@@ -4754,27 +4902,111 @@ mod tests {
|
|||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
let mut legacy = NodeTemplate {
|
let mut legacy = NodeTemplate {
|
||||||
inputs: vec![NodeInput::type_default(list!(graphic_types::Graphic), true), footprint_input.clone()],
|
inputs: vec![NodeInput::type_default(list!(graphic_types::Graphic), true), placeholder],
|
||||||
implementation: NodeTemplateImplementation::Network(canvas_network),
|
implementation: NodeTemplateImplementation::Network(canvas_network),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
document.network_interface.replace_implementation(&node_id, &[], &mut legacy);
|
document.network_interface.replace_implementation(&node_id, &[], &mut legacy);
|
||||||
document.network_interface.replace_inputs(&node_id, &[], &mut legacy);
|
document.network_interface.replace_inputs(&node_id, &[], &mut legacy);
|
||||||
document.network_interface.set_reference(&node_id, &[], Some("Rasterize".into()));
|
document.network_interface.set_reference(&node_id, &[], Some("Rasterize".into()));
|
||||||
|
|
||||||
|
// A 64 by 32 pixel footprint over the 500 by 250 px rectangle from (-20, 40)
|
||||||
|
let placeholder = r#"{"String":"footprint placeholder"}"#;
|
||||||
|
let footprint = r#"{"Footprint":{"transform":[500.0,0.0,0.0,250.0,-20.0,40.0],"resolution":[64,32],"quality":"Full"}}"#;
|
||||||
let serialized = document.serialize_document();
|
let serialized = document.serialize_document();
|
||||||
|
assert!(serialized.contains(placeholder), "the placeholder should be serialized as expected");
|
||||||
|
let serialized = serialized.replace(placeholder, footprint);
|
||||||
|
|
||||||
let opened = load_legacy_document(serialized, &HashMapResourceStorage::new(), false).expect("the document should open");
|
let opened = load_legacy_document(serialized, &HashMapResourceStorage::new(), false).expect("the document should open");
|
||||||
let interface = &opened.network_interface;
|
let interface = &opened.network_interface;
|
||||||
assert_eq!(interface.reference(&node_id, &[]), Some(DefinitionIdentifier::ProtoNode(rasterize::IDENTIFIER)));
|
assert_eq!(interface.reference(&node_id, &[]), Some(DefinitionIdentifier::ProtoNode(rasterize::IDENTIFIER)));
|
||||||
|
|
||||||
|
// The area's unit square is centered on its origin, so its translation is the rectangle's center
|
||||||
|
let area = DAffine2::from_scale_angle_translation(DVec2::new(500., 250.), 0., DVec2::new(230., 165.));
|
||||||
|
let input = |index| interface.input_from_connector(&InputConnector::node_at_index(node_id, index), &[]).cloned();
|
||||||
|
assert_eq!(input(1), Some(NodeInput::value(TaggedValue::DAffine2(area), false)), "the footprint should cover the same area");
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
interface.input_from_connector(&InputConnector::node_at_index(node_id, 1), &[]),
|
input(2),
|
||||||
Some(&footprint_input),
|
Some(NodeInput::value(TaggedValue::DVec2(DVec2::new(64., 32.)), false)),
|
||||||
"the footprint should carry over"
|
"the footprint should keep its resolution"
|
||||||
);
|
);
|
||||||
|
|
||||||
let definition_inputs = resolve_proto_node_type(rasterize::IDENTIFIER).expect("Rasterize should have a definition").node_template.inputs.len();
|
let definition_inputs = resolve_proto_node_type(rasterize::IDENTIFIER).expect("Rasterize should have a definition").node_template.inputs.len();
|
||||||
assert_eq!(interface.number_of_inputs(&node_id, &[]), definition_inputs, "the node should gain the inputs the compiler fills in");
|
assert_eq!(interface.number_of_inputs(&node_id, &[]), definition_inputs, "the node should gain the inputs the compiler fills in");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn opening_footprint_value_nodes_folds_them_into_the_rasterize_nodes_they_fed() {
|
||||||
|
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||||
|
use crate::test_utils::test_prelude::*;
|
||||||
|
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||||
|
use graphene_std::platform_application_io::rasterize;
|
||||||
|
|
||||||
|
let mut editor = EditorTestUtils::create();
|
||||||
|
editor.new_document().await;
|
||||||
|
let literal_rasterize = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(rasterize::IDENTIFIER), 0, 0).await;
|
||||||
|
let wired_rasterize = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(rasterize::IDENTIFIER), 0, 10).await;
|
||||||
|
let transform_source = editor
|
||||||
|
.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER), -20, 10)
|
||||||
|
.await;
|
||||||
|
let reroute = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER), -5, 10).await;
|
||||||
|
let document = editor.active_document_mut();
|
||||||
|
|
||||||
|
let footprint_transform = DAffine2::from_scale_angle_translation(DVec2::new(300., 200.), 0., DVec2::new(10., 20.));
|
||||||
|
let footprint_value = NodeTemplate {
|
||||||
|
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new("math_nodes::FootprintValueNode")),
|
||||||
|
inputs: vec![
|
||||||
|
NodeInput::value(TaggedValue::None, false),
|
||||||
|
NodeInput::value(TaggedValue::DAffine2(footprint_transform), false),
|
||||||
|
NodeInput::value(TaggedValue::DVec2(DVec2::new(30., 20.)), false),
|
||||||
|
],
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let (literal_footprint, wired_footprint) = (NodeId(1), NodeId(2));
|
||||||
|
document.network_interface.insert_node(literal_footprint, footprint_value.clone(), &[]);
|
||||||
|
document.network_interface.insert_node(wired_footprint, footprint_value, &[]);
|
||||||
|
document
|
||||||
|
.network_interface
|
||||||
|
.set_input(&InputConnector::node_at_index(wired_footprint, 1), NodeInput::node(transform_source, 0), &[]);
|
||||||
|
document
|
||||||
|
.network_interface
|
||||||
|
.set_input(&InputConnector::node_at_index(reroute, 0), NodeInput::node(wired_footprint, 0), &[]);
|
||||||
|
|
||||||
|
// Each Rasterize node as saved before its area and resolution, taking the artwork, the footprint, and the executor
|
||||||
|
let definition = resolve_proto_node_type(rasterize::IDENTIFIER).expect("Rasterize should have a definition");
|
||||||
|
let executor = definition.node_template.inputs.last().cloned().expect("Rasterize should take the executor");
|
||||||
|
for (rasterize_node, footprint_node) in [(literal_rasterize, literal_footprint), (wired_rasterize, reroute)] {
|
||||||
|
let mut old_inputs = NodeTemplate {
|
||||||
|
inputs: vec![NodeInput::type_default(list!(graphic_types::Graphic), true), NodeInput::node(footprint_node, 0), executor.clone()],
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
document.network_interface.replace_inputs(&rasterize_node, &[], &mut old_inputs);
|
||||||
|
}
|
||||||
|
|
||||||
|
let opened = load_legacy_document(document.serialize_document(), &HashMapResourceStorage::new(), false).expect("the document should open");
|
||||||
|
let interface = &opened.network_interface;
|
||||||
|
let input = |node, index| interface.input_from_connector(&InputConnector::node_at_index(node, index), &[]).cloned();
|
||||||
|
|
||||||
|
assert!(interface.document_node(&literal_footprint, &[]).is_none(), "the Footprint Value node should be removed");
|
||||||
|
assert!(interface.document_node(&wired_footprint, &[]).is_none(), "the Footprint Value node should be removed");
|
||||||
|
|
||||||
|
let corner_to_center = DAffine2::from_translation(DVec2::splat(0.5));
|
||||||
|
let resolution = Some(NodeInput::value(TaggedValue::DVec2(DVec2::new(30., 20.)), false));
|
||||||
|
assert_eq!(
|
||||||
|
input(literal_rasterize, 1),
|
||||||
|
Some(NodeInput::value(TaggedValue::DAffine2(footprint_transform * corner_to_center), false))
|
||||||
|
);
|
||||||
|
assert_eq!(input(literal_rasterize, 2), resolution);
|
||||||
|
|
||||||
|
// The wired transform reaches the area through a Multiply node centering its unit square
|
||||||
|
let Some(NodeInput::Node { node_id: multiply, output_index: 0 }) = input(wired_rasterize, 1) else {
|
||||||
|
panic!("the wired transform should reach the area through a node");
|
||||||
|
};
|
||||||
|
assert_eq!(input(multiply, 0), Some(NodeInput::node(transform_source, 0)));
|
||||||
|
assert_eq!(input(multiply, 1), Some(NodeInput::value(TaggedValue::DAffine2(corner_to_center), false)));
|
||||||
|
assert_eq!(input(wired_rasterize, 2), resolution);
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn opening_a_document_with_the_removed_extract_node_turns_it_into_a_passthrough() {
|
async fn opening_a_document_with_the_removed_extract_node_turns_it_into_a_passthrough() {
|
||||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||||
|
|||||||
@@ -1123,20 +1123,10 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
|||||||
self.executor.submit_thumbnails_in_view(document, document_id);
|
self.executor.submit_thumbnails_in_view(document, document_id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
PortfolioMessage::SubmitClipboardSvg { id } => {
|
PortfolioMessage::SubmitClipboardSvg { id } => match self.active_document_id.and_then(|document_id| self.documents.get(&document_id)) {
|
||||||
let layers = self.active_document().map(|document| {
|
Some(document) => self.executor.submit_clipboard_svg(document, viewport.size().into_dvec2(), id),
|
||||||
let selected = document.partition_selection().layers;
|
None => responses.add(ClipboardMessage::Rendered { id, svg: Ok(None) }),
|
||||||
let mut layers = document
|
},
|
||||||
.metadata()
|
|
||||||
.all_layers()
|
|
||||||
.filter(|layer| selected.contains(layer))
|
|
||||||
.map(|layer| layer.to_node())
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
layers.reverse();
|
|
||||||
layers
|
|
||||||
});
|
|
||||||
responses.add(self.executor.submit_clipboard_svg(self.active_document_id, id, layers.unwrap_or_default()));
|
|
||||||
}
|
|
||||||
PortfolioMessage::ToggleResetNodesToDefinitionsOnOpen => {
|
PortfolioMessage::ToggleResetNodesToDefinitionsOnOpen => {
|
||||||
self.reset_node_definitions_on_open = !self.reset_node_definitions_on_open;
|
self.reset_node_definitions_on_open = !self.reset_node_definitions_on_open;
|
||||||
responses.add(MenuBarMessage::SendLayout);
|
responses.add(MenuBarMessage::SendLayout);
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ use crate::messages::tool::common_functionality::graph_modification_utils;
|
|||||||
use crate::messages::tool::utility_types::DocumentToolData;
|
use crate::messages::tool::utility_types::DocumentToolData;
|
||||||
use graphene_std::Color;
|
use graphene_std::Color;
|
||||||
use graphene_std::color::SRGBA8;
|
use graphene_std::color::SRGBA8;
|
||||||
use graphene_std::vector::style::{FillChoice, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin};
|
use graphene_std::vector::style::{FillChoice, PaintMapping, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin};
|
||||||
|
|
||||||
/// Color selector widgets seen in [`LayoutTarget::ToolOptions`] bar.
|
/// Color selector widgets seen in [`LayoutTarget::ToolOptions`] bar.
|
||||||
pub struct ToolColorOptions {
|
pub struct ToolColorOptions {
|
||||||
@@ -242,6 +242,7 @@ impl DrawingToolState {
|
|||||||
join_miter_limit: self.miter_limit.unwrap_or(defaults.miter_limit),
|
join_miter_limit: self.miter_limit.unwrap_or(defaults.miter_limit),
|
||||||
dash_lengths: self.dash_lengths.clone().unwrap_or_else(|| defaults.dash_lengths.clone()),
|
dash_lengths: self.dash_lengths.clone().unwrap_or_else(|| defaults.dash_lengths.clone()),
|
||||||
dash_offset: self.dash_offset.unwrap_or(defaults.dash_offset),
|
dash_offset: self.dash_offset.unwrap_or(defaults.dash_offset),
|
||||||
|
paint_mapping: PaintMapping::default(),
|
||||||
transform: glam::DAffine2::IDENTITY,
|
transform: glam::DAffine2::IDENTITY,
|
||||||
};
|
};
|
||||||
responses.add(GraphOperationMessage::StrokeSet { layer, color: Some(color), stroke });
|
responses.add(GraphOperationMessage::StrokeSet { layer, color: Some(color), stroke });
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation
|
|||||||
use graphene_std::bounds::RenderBoundingBox;
|
use graphene_std::bounds::RenderBoundingBox;
|
||||||
use graphene_std::color::SRGBA8;
|
use graphene_std::color::SRGBA8;
|
||||||
use graphene_std::list::{Item, List};
|
use graphene_std::list::{Item, List};
|
||||||
|
use graphene_std::math::quad::Quad;
|
||||||
use graphene_std::raster::{CPU, Raster};
|
use graphene_std::raster::{CPU, Raster};
|
||||||
use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box};
|
use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box};
|
||||||
use graphene_std::transform::Footprint;
|
use graphene_std::transform::Footprint;
|
||||||
@@ -114,7 +115,8 @@ pub enum NodeGraphUpdate {
|
|||||||
Observations(HashMap<ObservationKey, InspectResult>),
|
Observations(HashMap<ObservationKey, InspectResult>),
|
||||||
ClipboardSvg {
|
ClipboardSvg {
|
||||||
id: u64,
|
id: u64,
|
||||||
svg: Option<String>,
|
/// The SVG, `None` if the layers add nothing, or why it couldn't be rendered.
|
||||||
|
svg: Result<Option<String>, String>,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -229,13 +231,28 @@ impl NodeGraphExecutor {
|
|||||||
.expect("Failed to send the context overrides");
|
.expect("Failed to send the context overrides");
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn submit_clipboard_svg(&self, document_id: Option<DocumentId>, id: u64, layers: Vec<NodeId>) -> Message {
|
/// Has the runtime render what the selected layers add as an SVG, which it sends back once their content is final.
|
||||||
if document_id.is_none() || self.node_graph_document != document_id {
|
/// The `viewport_size` is in viewport pixels.
|
||||||
return ClipboardMessage::Rendered { id, svg: None }.into();
|
pub fn submit_clipboard_svg(&self, document: &DocumentMessageHandler, viewport_size: DVec2, id: u64) {
|
||||||
}
|
let network_interface = &document.network_interface;
|
||||||
|
let view = (document.metadata().document_to_viewport.inverse() * Quad::from_box([DVec2::ZERO, viewport_size])).bounding_box();
|
||||||
|
|
||||||
self.sender.send(GraphRuntimeRequest::ClipboardSvg { id, layers }).expect("Failed to send runtime request");
|
// Painted from the bottom up
|
||||||
Message::NoOp
|
let selected = document.partition_selection().layers;
|
||||||
|
let mut layers: Vec<_> = document.metadata().all_layers().filter(|layer| selected.contains(layer)).map(|layer| layer.to_node()).collect();
|
||||||
|
layers.reverse();
|
||||||
|
|
||||||
|
// The network as it is now, since the runtime applies a graph update sent before this one only after it reads this
|
||||||
|
let request = ClipboardSvgRequest {
|
||||||
|
id,
|
||||||
|
network: network_interface.document_network().clone(),
|
||||||
|
resources: document.resources.registry.clone(),
|
||||||
|
previewed: network_interface.previewed_nodes(),
|
||||||
|
layer_paths: network_interface.layer_paths(),
|
||||||
|
layers,
|
||||||
|
view,
|
||||||
|
};
|
||||||
|
self.sender.send(GraphRuntimeRequest::ClipboardSvg(request)).expect("Failed to send runtime request");
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn submit_thumbnails_in_view(&self, document: &DocumentMessageHandler, document_id: DocumentId) {
|
pub fn submit_thumbnails_in_view(&self, document: &DocumentMessageHandler, document_id: DocumentId) {
|
||||||
@@ -435,28 +452,7 @@ impl NodeGraphExecutor {
|
|||||||
ExportBounds::Artboard(id) => document.metadata().bounding_box_document(id),
|
ExportBounds::Artboard(id) => document.metadata().bounding_box_document(id),
|
||||||
}
|
}
|
||||||
.ok_or_else(|| "No bounding box".to_string())?;
|
.ok_or_else(|| "No bounding box".to_string())?;
|
||||||
|
let render_config = export_render_config(bounds, export_config.scale_factor, export_format);
|
||||||
let resolution_in_document_space = bounds[1] - bounds[0];
|
|
||||||
let export_resolution = resolution_in_document_space * export_config.scale_factor;
|
|
||||||
let resolution = export_resolution.round().as_uvec2();
|
|
||||||
let transform = DAffine2::from_translation(bounds[0]).inverse();
|
|
||||||
let viewport = Footprint {
|
|
||||||
resolution,
|
|
||||||
transform,
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
|
|
||||||
let render_config = RenderConfig {
|
|
||||||
viewport,
|
|
||||||
scale: export_config.scale_factor,
|
|
||||||
time: Default::default(),
|
|
||||||
pointer: DVec2::ZERO,
|
|
||||||
export_format,
|
|
||||||
// The viewport's render mode is only a way of viewing the artwork, which exports show as it is
|
|
||||||
render_mode: graphene_std::vector::style::RenderMode::Normal,
|
|
||||||
for_export: true,
|
|
||||||
for_eyedropper: false,
|
|
||||||
};
|
|
||||||
|
|
||||||
// Execute the node graph
|
// Execute the node graph
|
||||||
self.sender
|
self.sender
|
||||||
@@ -474,7 +470,7 @@ impl NodeGraphExecutor {
|
|||||||
ExecutionContext {
|
ExecutionContext {
|
||||||
export_config: Some(export_config),
|
export_config: Some(export_config),
|
||||||
document_id,
|
document_id,
|
||||||
document_to_viewport: viewport.transform,
|
document_to_viewport: render_config.viewport.transform,
|
||||||
measure_fill: None,
|
measure_fill: None,
|
||||||
},
|
},
|
||||||
));
|
));
|
||||||
@@ -1200,6 +1196,28 @@ fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2,
|
|||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The render of an export framed to these bounds in document space, drawn at `scale` pixels per unit.
|
||||||
|
fn export_render_config(bounds: [DVec2; 2], scale: f64, export_format: ExportFormat) -> RenderConfig {
|
||||||
|
let resolution = ((bounds[1] - bounds[0]) * scale).round().as_uvec2();
|
||||||
|
let viewport = Footprint {
|
||||||
|
resolution,
|
||||||
|
transform: DAffine2::from_translation(bounds[0]).inverse(),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
RenderConfig {
|
||||||
|
viewport,
|
||||||
|
scale,
|
||||||
|
time: Default::default(),
|
||||||
|
pointer: DVec2::ZERO,
|
||||||
|
export_format,
|
||||||
|
// The viewport's render mode is only a way of viewing the artwork, which exports show as it is
|
||||||
|
render_mode: graphene_std::vector::style::RenderMode::Normal,
|
||||||
|
for_export: true,
|
||||||
|
for_eyedropper: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Says why an export saved nothing, given the evaluation's error, or else the graph's failure to compile.
|
/// Says why an export saved nothing, given the evaluation's error, or else the graph's failure to compile.
|
||||||
fn export_failure_dialog(evaluation_error: Option<String>) -> DialogMessage {
|
fn export_failure_dialog(evaluation_error: Option<String>) -> DialogMessage {
|
||||||
DialogMessage::DisplayDialogError {
|
DialogMessage::DisplayDialogError {
|
||||||
|
|||||||
@@ -17,9 +17,9 @@ use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasSurface,
|
|||||||
use graphene_std::raster_types::Raster;
|
use graphene_std::raster_types::Raster;
|
||||||
use graphene_std::runtime::AsyncRuntime;
|
use graphene_std::runtime::AsyncRuntime;
|
||||||
use graphene_std::vector::style::RenderMode;
|
use graphene_std::vector::style::RenderMode;
|
||||||
use graphene_std::{Context, NodeError, Poll};
|
use graphene_std::{Artboard, Context, ContextFeatures, Generations, NodeError, OwnedContextImpl, Poll};
|
||||||
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle, ResolvedDocumentNodeTypesDelta};
|
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle, ResolvedDocumentNodeTypesDelta};
|
||||||
use interpreted_executor::layer_paths::write_layer_paths;
|
use interpreted_executor::layer_paths::{export_layers, write_layer_paths};
|
||||||
use interpreted_executor::util::wrap_network_with_render_node_in_scope;
|
use interpreted_executor::util::wrap_network_with_render_node_in_scope;
|
||||||
use observer::Observer;
|
use observer::Observer;
|
||||||
pub use observer::{InspectResult, InspectedContext, Observation, ObservedConnector, ObservedValue};
|
pub use observer::{InspectResult, InspectedContext, Observation, ObservedConnector, ObservedValue};
|
||||||
@@ -52,6 +52,8 @@ pub struct NodeRuntime {
|
|||||||
pending_export: Option<ExecutionRequest>,
|
pending_export: Option<ExecutionRequest>,
|
||||||
pending_eyedropper: Option<ExecutionRequest>,
|
pending_eyedropper: Option<ExecutionRequest>,
|
||||||
pending_thumbnails: Option<DocumentId>,
|
pending_thumbnails: Option<DocumentId>,
|
||||||
|
/// The latest copy's SVG, evaluated from its own network until its content is final.
|
||||||
|
pending_clipboard: Option<PendingClipboard>,
|
||||||
/// The network the executor last compiled successfully, with previews applied.
|
/// The network the executor last compiled successfully, with previews applied.
|
||||||
old_graph: Option<NodeNetwork>,
|
old_graph: Option<NodeNetwork>,
|
||||||
/// Whether the latest network failed to compile, leaving the executor with an older one that mustn't be shown in its place.
|
/// Whether the latest network failed to compile, leaving the executor with an older one that mustn't be shown in its place.
|
||||||
@@ -59,7 +61,6 @@ pub struct NodeRuntime {
|
|||||||
async_runtime: Option<AsyncRuntime>,
|
async_runtime: Option<AsyncRuntime>,
|
||||||
|
|
||||||
editor_api: Arc<PlatformEditorApi>,
|
editor_api: Arc<PlatformEditorApi>,
|
||||||
resources: ResourceRegistry,
|
|
||||||
node_graph_errors: GraphErrors,
|
node_graph_errors: GraphErrors,
|
||||||
node_graph_warnings: GraphErrors,
|
node_graph_warnings: GraphErrors,
|
||||||
thumbnails: Thumbnails,
|
thumbnails: Thumbnails,
|
||||||
@@ -107,13 +108,39 @@ pub enum GraphRuntimeRequest {
|
|||||||
key: ObservationKey,
|
key: ObservationKey,
|
||||||
observation: Option<Observation>,
|
observation: Option<Observation>,
|
||||||
},
|
},
|
||||||
ClipboardSvg {
|
ClipboardSvg(ClipboardSvgRequest),
|
||||||
id: u64,
|
|
||||||
layers: Vec<NodeId>,
|
|
||||||
},
|
|
||||||
RenderOverlays(OverlayContext),
|
RenderOverlays(OverlayContext),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The layers a copy renders as an SVG, with the document network as it was when they were copied.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct ClipboardSvgRequest {
|
||||||
|
pub(super) id: u64,
|
||||||
|
pub(super) network: NodeNetwork,
|
||||||
|
pub(super) resources: ResourceRegistry,
|
||||||
|
/// The node each network renders in place of its export, paired with that network's path.
|
||||||
|
pub(super) previewed: Vec<(Vec<NodeId>, RootNode)>,
|
||||||
|
/// Full path from the root network to every layer.
|
||||||
|
pub(super) layer_paths: Vec<Vec<NodeId>>,
|
||||||
|
/// The copied layers, in the order they're painted.
|
||||||
|
pub(super) layers: Vec<NodeId>,
|
||||||
|
/// The part of the document in view, which frames content drawn for its view.
|
||||||
|
pub(super) view: [DVec2; 2],
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A copy's SVG, held until its content is final.
|
||||||
|
struct PendingClipboard {
|
||||||
|
id: u64,
|
||||||
|
/// The output of the network made for the copy, which keeps its nodes compiled through a cut that removes the layers from the document's.
|
||||||
|
output: OutputHandle,
|
||||||
|
/// The compiled node giving what the copied layers add, whose bounds frame the SVG.
|
||||||
|
content: NodeId,
|
||||||
|
/// The part of the document in view when they were copied.
|
||||||
|
view: [DVec2; 2],
|
||||||
|
/// The SVG's frame, once it's known.
|
||||||
|
frame: Option<[DVec2; 2]>,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct GraphUpdate {
|
pub struct GraphUpdate {
|
||||||
pub(super) network: NodeNetwork,
|
pub(super) network: NodeNetwork,
|
||||||
@@ -158,9 +185,9 @@ impl NodeRuntime {
|
|||||||
pending_export: None,
|
pending_export: None,
|
||||||
pending_eyedropper: None,
|
pending_eyedropper: None,
|
||||||
pending_thumbnails: None,
|
pending_thumbnails: None,
|
||||||
|
pending_clipboard: None,
|
||||||
old_graph: None,
|
old_graph: None,
|
||||||
compile_failed: false,
|
compile_failed: false,
|
||||||
resources: ResourceRegistry::default(),
|
|
||||||
async_runtime: None,
|
async_runtime: None,
|
||||||
|
|
||||||
editor_api: PlatformEditorApi {
|
editor_api: PlatformEditorApi {
|
||||||
@@ -197,6 +224,7 @@ impl NodeRuntime {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let mut graph = None;
|
let mut graph = None;
|
||||||
|
let mut clipboard = None;
|
||||||
for request in self.receiver.try_iter() {
|
for request in self.receiver.try_iter() {
|
||||||
match request {
|
match request {
|
||||||
GraphRuntimeRequest::GraphUpdate(update) => graph = Some(update),
|
GraphRuntimeRequest::GraphUpdate(update) => graph = Some(update),
|
||||||
@@ -223,10 +251,8 @@ impl NodeRuntime {
|
|||||||
self.observations_changed = true;
|
self.observations_changed = true;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
GraphRuntimeRequest::ClipboardSvg { id, layers } => {
|
// The clipboard waits only for its latest copy
|
||||||
let svg = self.old_graph.as_ref().and_then(|network| thumbnails::layers_svg(&layers, network, &self.executor));
|
GraphRuntimeRequest::ClipboardSvg(request) => clipboard = Some(request),
|
||||||
self.sender.send(NodeGraphUpdate::ClipboardSvg { id, svg }).expect("Failed to send response");
|
|
||||||
}
|
|
||||||
GraphRuntimeRequest::RenderOverlays(context) => {
|
GraphRuntimeRequest::RenderOverlays(context) => {
|
||||||
self.overlays = Some(context);
|
self.overlays = Some(context);
|
||||||
self.overlays_stale = true;
|
self.overlays_stale = true;
|
||||||
@@ -234,6 +260,11 @@ impl NodeRuntime {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Compiled before a graph update that cuts the copied layers lets their nodes go
|
||||||
|
if let Some(request) = clipboard {
|
||||||
|
self.compile_clipboard_svg(request);
|
||||||
|
}
|
||||||
|
|
||||||
let Some(GraphUpdate {
|
let Some(GraphUpdate {
|
||||||
mut network,
|
mut network,
|
||||||
resources,
|
resources,
|
||||||
@@ -248,11 +279,8 @@ impl NodeRuntime {
|
|||||||
apply_previews(&mut network, &previewed);
|
apply_previews(&mut network, &previewed);
|
||||||
write_layer_paths(&mut network, &layers);
|
write_layer_paths(&mut network, &layers);
|
||||||
self.observer.replace_all(observations);
|
self.observer.replace_all(observations);
|
||||||
self.resources = resources;
|
|
||||||
|
|
||||||
self.node_graph_errors.clear();
|
let result = self.update_network(network.clone(), &resources);
|
||||||
self.node_graph_warnings.clear();
|
|
||||||
let result = self.update_network(network.clone());
|
|
||||||
self.compile_failed = result.is_err();
|
self.compile_failed = result.is_err();
|
||||||
if result.is_ok() {
|
if result.is_ok() {
|
||||||
self.thumbnails.update_sources(&layers, &network, &self.executor);
|
self.thumbnails.update_sources(&layers, &network, &self.executor);
|
||||||
@@ -305,6 +333,10 @@ impl NodeRuntime {
|
|||||||
self.run_viewport(viewport).await;
|
self.run_viewport(viewport).await;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if dirty && let Some(clipboard) = self.pending_clipboard.take() {
|
||||||
|
self.run_clipboard(clipboard);
|
||||||
|
}
|
||||||
|
|
||||||
// Overlays that changed without new artwork are drawn over the artwork already shown
|
// Overlays that changed without new artwork are drawn over the artwork already shown
|
||||||
if self.overlays_stale {
|
if self.overlays_stale {
|
||||||
texture = self.composite_viewport_frame();
|
texture = self.composite_viewport_frame();
|
||||||
@@ -398,6 +430,70 @@ impl NodeRuntime {
|
|||||||
self.respond(request, result, observations).await;
|
self.respond(request, result, observations).await;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Evaluates the copy's network as an export framed to its content, sending its SVG once that's final, and otherwise keeping it to evaluate again when a task lands.
|
||||||
|
fn run_clipboard(&mut self, mut clipboard: PendingClipboard) {
|
||||||
|
let generations = self.async_runtime().snapshot();
|
||||||
|
|
||||||
|
let frame = match clipboard.frame {
|
||||||
|
Some(frame) => frame,
|
||||||
|
None => {
|
||||||
|
let Some(frame) = self.clipboard_frame(&clipboard, &generations) else {
|
||||||
|
self.pending_clipboard = Some(clipboard);
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
match frame {
|
||||||
|
Ok(Some(frame)) => *clipboard.frame.insert(frame),
|
||||||
|
Ok(None) => return self.send_clipboard_svg(clipboard.id, Ok(None)),
|
||||||
|
Err(message) => return self.send_clipboard_svg(clipboard.id, Err(message)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// The render covers whole pixels, rounded outward, while the SVG's frame keeps the content's exact size
|
||||||
|
let size = frame[1] - frame[0];
|
||||||
|
let covered = size.ceil();
|
||||||
|
let context = export_render_config([frame[0], frame[0] + covered], 1., ExportFormat::Svg).into_context_with_generations(generations);
|
||||||
|
match self.settled(clipboard.output.node(), || self.executor.execute(&clipboard.output, context).map_err(|error| error.to_string())) {
|
||||||
|
Some(output) => self.send_clipboard_svg(clipboard.id, output.and_then(svg_text).map(|svg| svg.map(|svg| with_frame_size(svg, covered, size)))),
|
||||||
|
None => self.pending_clipboard = Some(clipboard),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The frame of the copy's SVG once it's known, unless it has no area.
|
||||||
|
/// Content drawn for its view is framed to the view it was copied in, while other content is framed to its bounds, which are the same in any view.
|
||||||
|
fn clipboard_frame(&self, clipboard: &PendingClipboard, generations: &Generations) -> Option<Result<Option<[DVec2; 2]>, String>> {
|
||||||
|
let has_area = |[min, max]: &[DVec2; 2]| (*max - *min).cmpgt(DVec2::ZERO).all();
|
||||||
|
|
||||||
|
if self.executor.tree().context_features(clipboard.content).contains(ContextFeatures::FOOTPRINT) {
|
||||||
|
return Some(Ok(Some(clipboard.view).filter(has_area)));
|
||||||
|
}
|
||||||
|
|
||||||
|
let context = OwnedContextImpl::default()
|
||||||
|
.with_footprint(export_render_config(clipboard.view, 1., ExportFormat::Svg).viewport)
|
||||||
|
.with_real_time(0.)
|
||||||
|
.with_animation_time(0.)
|
||||||
|
.with_generations(generations.clone())
|
||||||
|
.into_context();
|
||||||
|
let content = self.settled(clipboard.content, || self.executor.tree().evaluate(clipboard.content, &context).map_err(|error| error.to_string()))?;
|
||||||
|
Some(content.map(|content| exported_bounds(content).filter(has_area)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The value an evaluation of the node gives once it's final, `None` while it's pending or partial, or else what went wrong.
|
||||||
|
fn settled<T>(&self, node: NodeId, evaluate: impl FnOnce() -> Result<Poll<T>, String>) -> Option<Result<T, String>> {
|
||||||
|
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(evaluate)).unwrap_or_else(|payload| {
|
||||||
|
let message = payload.downcast_ref::<&str>().copied().or_else(|| payload.downcast_ref::<String>().map(String::as_str));
|
||||||
|
Err(format!("Panicked: {}", message.unwrap_or("no message")))
|
||||||
|
});
|
||||||
|
|
||||||
|
match result {
|
||||||
|
Ok(Poll::Pending | Poll::Partial(_)) => None,
|
||||||
|
Ok(Poll::Final(value)) => Some(Ok(value)),
|
||||||
|
Ok(Poll::Fallback(boxed)) => Some(Ok(boxed.0)),
|
||||||
|
Ok(Poll::Error(error)) => Some(Err(self.resolve_errors(node, &error).to_string())),
|
||||||
|
Err(message) => Some(Err(message)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async fn run_eyedropper(&mut self, mut request: ExecutionRequest) {
|
async fn run_eyedropper(&mut self, mut request: ExecutionRequest) {
|
||||||
// Eyedropper should use the same time and pointer to not invalidate the cache
|
// Eyedropper should use the same time and pointer to not invalidate the cache
|
||||||
if let Some(viewport) = self.pending {
|
if let Some(viewport) = self.pending {
|
||||||
@@ -436,9 +532,9 @@ impl NodeRuntime {
|
|||||||
Ok(Ok(Poll::Final(value))) => ExecutionResult::Value(value),
|
Ok(Ok(Poll::Final(value))) => ExecutionResult::Value(value),
|
||||||
Ok(Ok(Poll::Fallback(boxed))) => {
|
Ok(Ok(Poll::Fallback(boxed))) => {
|
||||||
let (value, error) = *boxed;
|
let (value, error) = *boxed;
|
||||||
ExecutionResult::Fallback(value, self.resolve_errors(&error))
|
ExecutionResult::Fallback(value, self.resolve_errors(self.output.node(), &error))
|
||||||
}
|
}
|
||||||
Ok(Ok(Poll::Error(error))) => ExecutionResult::Error(self.resolve_errors(&error)),
|
Ok(Ok(Poll::Error(error))) => ExecutionResult::Error(self.resolve_errors(self.output.node(), &error)),
|
||||||
Ok(Err(error)) => ExecutionResult::Error(EvaluationErrors(Box::new([(Arc::clone(NodeError::new(error.to_string()).error()), NodeErrorTrace::default())]))),
|
Ok(Err(error)) => ExecutionResult::Error(EvaluationErrors(Box::new([(Arc::clone(NodeError::new(error.to_string()).error()), NodeErrorTrace::default())]))),
|
||||||
Err(payload) => {
|
Err(payload) => {
|
||||||
let response = ExecutionResponse {
|
let response = ExecutionResponse {
|
||||||
@@ -506,42 +602,121 @@ impl NodeRuntime {
|
|||||||
Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor.clone()).await
|
Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor.clone()).await
|
||||||
}
|
}
|
||||||
|
|
||||||
fn update_network(&mut self, graph: NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
|
fn update_network(&mut self, graph: NodeNetwork, resources: &ResourceRegistry) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
|
||||||
|
self.node_graph_errors.clear();
|
||||||
|
self.node_graph_warnings.clear();
|
||||||
|
|
||||||
|
let CompiledNetwork { network: proto_network, warnings } = match self.compile_network(graph, resources) {
|
||||||
|
Ok(compiled_network) => compiled_network,
|
||||||
|
Err((message, errors)) => {
|
||||||
|
self.node_graph_errors = errors;
|
||||||
|
return Err((ResolvedDocumentNodeTypesDelta::default(), message));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
self.node_graph_warnings = warnings;
|
||||||
|
|
||||||
|
let result = match self.executor.update(proto_network) {
|
||||||
|
Ok((output, types)) => {
|
||||||
|
self.output = output;
|
||||||
|
Ok(types)
|
||||||
|
}
|
||||||
|
Err((types, errors)) => {
|
||||||
|
let message = format!("{errors:?}");
|
||||||
|
self.node_graph_errors = errors;
|
||||||
|
Err((types, message))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Every held output's sources, so the tasks they spawn bump their generations when they land
|
||||||
|
self.async_runtime().update_sources(self.executor.sources());
|
||||||
|
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Compiles the network of the copied layers beside the document's, to be evaluated until its SVG is final.
|
||||||
|
fn compile_clipboard_svg(&mut self, request: ClipboardSvgRequest) {
|
||||||
|
let ClipboardSvgRequest {
|
||||||
|
id,
|
||||||
|
mut network,
|
||||||
|
resources,
|
||||||
|
previewed,
|
||||||
|
layer_paths,
|
||||||
|
layers,
|
||||||
|
view,
|
||||||
|
} = request;
|
||||||
|
self.pending_clipboard = None;
|
||||||
|
|
||||||
|
// Made as the document's network is, so it shares the document's compiled nodes
|
||||||
|
apply_previews(&mut network, &previewed);
|
||||||
|
write_layer_paths(&mut network, &layer_paths);
|
||||||
|
let Some(content_node) = export_layers(&mut network, &layers) else {
|
||||||
|
self.send_clipboard_svg(id, Ok(None));
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
let proto_network = match self.compile_network(network, &resources) {
|
||||||
|
Ok(compiled_network) => compiled_network.network,
|
||||||
|
Err((message, _)) => {
|
||||||
|
self.send_clipboard_svg(id, Err(message));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// The last of the proto nodes at the stack's path, which may wrap it, gives what the stack outputs
|
||||||
|
let content_path = Some(vec![content_node]);
|
||||||
|
let Some(&(content, _)) = proto_network.nodes.iter().rev().find(|(_, node)| node.original_location.path == content_path) else {
|
||||||
|
self.send_clipboard_svg(id, Err("The copied layers' content didn't compile".to_string()));
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
// The document's updates keep the source map, so the types they send the editor stay whole
|
||||||
|
let output = match self.executor.insert_beside(proto_network) {
|
||||||
|
Ok(output) => output,
|
||||||
|
Err(errors) => {
|
||||||
|
self.send_clipboard_svg(id, Err(format!("{errors:?}")));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
self.async_runtime().update_sources(self.executor.sources());
|
||||||
|
|
||||||
|
self.pending_clipboard = Some(PendingClipboard {
|
||||||
|
id,
|
||||||
|
output,
|
||||||
|
content,
|
||||||
|
view,
|
||||||
|
frame: None,
|
||||||
|
});
|
||||||
|
self.dirty.store(true, Ordering::Release);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn send_clipboard_svg(&self, id: u64, svg: Result<Option<String>, String>) {
|
||||||
|
self.sender.send(NodeGraphUpdate::ClipboardSvg { id, svg }).expect("Failed to send response");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wraps the network with the render node in its scope, then preprocesses and compiles it, or else gives back why it failed with the errors on its nodes.
|
||||||
|
fn compile_network(&self, graph: NodeNetwork, resources: &ResourceRegistry) -> Result<CompiledNetwork, (String, GraphErrors)> {
|
||||||
let mut scoped_network = wrap_network_with_render_node_in_scope(graph, self.editor_api.clone(), self.async_runtime().handle());
|
let mut scoped_network = wrap_network_with_render_node_in_scope(graph, self.editor_api.clone(), self.async_runtime().handle());
|
||||||
|
|
||||||
if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| self.resources.hash(&resource_id)) {
|
if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| resources.hash(&resource_id)) {
|
||||||
return Err((ResolvedDocumentNodeTypesDelta::default(), e.to_string()));
|
return Err((e.to_string(), Vec::new()));
|
||||||
}
|
}
|
||||||
|
|
||||||
// We assume only one output
|
// We assume only one output
|
||||||
assert_eq!(scoped_network.exports.len(), 1, "Graph with multiple outputs not yet handled");
|
assert_eq!(scoped_network.exports.len(), 1, "Graph with multiple outputs not yet handled");
|
||||||
|
|
||||||
let c = Compiler {};
|
let c = Compiler {};
|
||||||
let CompiledNetwork { network: proto_network, warnings } = match c.compile_single(scoped_network) {
|
let compiled_network = match c.compile_single(scoped_network) {
|
||||||
Ok(compiled_network) => compiled_network,
|
Ok(compiled_network) => compiled_network,
|
||||||
Err(CompileError::Graph(errors)) => {
|
Err(CompileError::Graph(errors)) => return Err((format!("{errors:?}"), errors)),
|
||||||
let message = format!("{errors:?}");
|
Err(CompileError::Message(message)) => return Err((message, Vec::new())),
|
||||||
self.node_graph_errors = errors;
|
|
||||||
return Err((ResolvedDocumentNodeTypesDelta::default(), message));
|
|
||||||
}
|
|
||||||
Err(CompileError::Message(message)) => return Err((ResolvedDocumentNodeTypesDelta::default(), message)),
|
|
||||||
};
|
};
|
||||||
self.node_graph_warnings = warnings;
|
|
||||||
|
|
||||||
assert_ne!(proto_network.nodes.len(), 0, "No proto nodes exist?");
|
assert_ne!(compiled_network.network.nodes.len(), 0, "No proto nodes exist?");
|
||||||
let updated = self.executor.update(proto_network).map(|(output, types)| {
|
Ok(compiled_network)
|
||||||
self.output = output;
|
|
||||||
types
|
|
||||||
});
|
|
||||||
let result = updated.map_err(|(types, e)| {
|
|
||||||
self.node_graph_errors.clone_from(&e);
|
|
||||||
(types, format!("{e:?}"))
|
|
||||||
});
|
|
||||||
self.async_runtime().update_sources(self.executor.sources());
|
|
||||||
result
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn resolve_errors(&self, error: &NodeError) -> EvaluationErrors {
|
/// The errors of an evaluation of the `output` node, each traced through the nodes it passed.
|
||||||
|
fn resolve_errors(&self, output: NodeId, error: &NodeError) -> EvaluationErrors {
|
||||||
let source_map = self.executor.tree().source_map();
|
let source_map = self.executor.tree().source_map();
|
||||||
let paths = |node: NodeId| -> NodePaths {
|
let paths = |node: NodeId| -> NodePaths {
|
||||||
let mut paths: Vec<_> = source_map.iter().filter(|(_, (id, _))| *id == node).map(|(path, _)| path.clone()).collect();
|
let mut paths: Vec<_> = source_map.iter().filter(|(_, (id, _))| *id == node).map(|(path, _)| path.clone()).collect();
|
||||||
@@ -549,7 +724,6 @@ impl NodeRuntime {
|
|||||||
paths.into()
|
paths.into()
|
||||||
};
|
};
|
||||||
let mut errors = Vec::new();
|
let mut errors = Vec::new();
|
||||||
let output = self.output.node();
|
|
||||||
let mut pending = vec![(vec![paths(output)], output, error)];
|
let mut pending = vec![(vec![paths(output)], output, error)];
|
||||||
while let Some((mut trace, node, error)) = pending.pop() {
|
while let Some((mut trace, node, error)) = pending.pop() {
|
||||||
let passed = self.executor.trace_error(node, error);
|
let passed = self.executor.trace_error(node, error);
|
||||||
@@ -580,6 +754,54 @@ impl ExecutionResult {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The area an export of the copied layers' content shows, unless it's endless, like a lone noise pattern, while a fractal's is the body a thumbnail shows.
|
||||||
|
fn exported_bounds(content: graphene_std::registry::Any) -> Option<[DVec2; 2]> {
|
||||||
|
let bounds = match content.downcast_ref::<List<Graphic>>() {
|
||||||
|
Some(graphics) => graphene_std::renderer::graphic_list_painted_bounds(graphics),
|
||||||
|
None => artboard_clip_bounds(content.downcast_ref::<List<Artboard>>()?),
|
||||||
|
};
|
||||||
|
|
||||||
|
match bounds {
|
||||||
|
RenderBoundingBox::Rectangle([min, max]) if min.is_finite() && max.is_finite() => Some([min, max]),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The SVG with its frame narrowed from the whole pixels its render `covered` to the content's exact `size`.
|
||||||
|
fn with_frame_size(svg: String, covered: DVec2, size: DVec2) -> String {
|
||||||
|
let frame = |size: DVec2| format!(r#"viewBox="0 0 {} {}" width="{}" height="{}""#, size.x, size.y, size.x, size.y);
|
||||||
|
svg.replacen(&frame(covered), &frame(size), 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The union of the artboards' clipping rectangles, which frames what's visible of them better than their unclipped content does.
|
||||||
|
fn artboard_clip_bounds(artboards: &List<Artboard>) -> RenderBoundingBox {
|
||||||
|
let mut combined: Option<[DVec2; 2]> = None;
|
||||||
|
for index in 0..artboards.len() {
|
||||||
|
let location: DVec2 = artboards.attribute_cloned_or_default(graphene_std::ATTR_LOCATION, index);
|
||||||
|
let dimensions: DVec2 = artboards.attribute_cloned_or_default(graphene_std::ATTR_DIMENSIONS, index);
|
||||||
|
let bounds = [location, location + dimensions];
|
||||||
|
combined = Some(match combined {
|
||||||
|
Some(existing) => [existing[0].min(bounds[0]), existing[1].max(bounds[1])],
|
||||||
|
None => bounds,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
match combined {
|
||||||
|
Some(bounds) => RenderBoundingBox::Rectangle(bounds),
|
||||||
|
None => RenderBoundingBox::None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The text of an SVG render's output.
|
||||||
|
fn svg_text(value: TaggedValue) -> Result<Option<String>, String> {
|
||||||
|
match value {
|
||||||
|
TaggedValue::RenderOutput(RenderOutput {
|
||||||
|
data: RenderOutputType::Svg { svg, .. },
|
||||||
|
..
|
||||||
|
}) => Ok(Some(svg)),
|
||||||
|
_ => Err("The render gave no SVG".to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn evaluated_output(poll: Poll<graphene_std::registry::Any>) -> Option<graphene_std::registry::Any> {
|
fn evaluated_output(poll: Poll<graphene_std::registry::Any>) -> Option<graphene_std::registry::Any> {
|
||||||
match poll {
|
match poll {
|
||||||
Poll::Final(output) | Poll::Partial(output) => Some(output),
|
Poll::Final(output) | Poll::Partial(output) => Some(output),
|
||||||
@@ -1018,6 +1240,232 @@ mod tests {
|
|||||||
assert!(!svg.contains("deferred-image"), "the markup standing in for the image should be replaced: {svg}");
|
assert!(!svg.contains("deferred-image"), "the markup standing in for the image should be replaced: {svg}");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn an_svg_export_of_a_generator_settles_once_its_image_is_read_back() {
|
||||||
|
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||||
|
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
|
||||||
|
use graphene_std::raster::Image;
|
||||||
|
use graphene_std::raster::color::Color;
|
||||||
|
|
||||||
|
// A Mandelbrot layer, made from an image layer by feeding the fractal into its content instead, over a rectangle framing the export
|
||||||
|
let mut editor = EditorTestUtils::create();
|
||||||
|
editor.new_document().await;
|
||||||
|
editor.draw_rect(0., 0., 64., 64.).await;
|
||||||
|
editor.create_raster_image(Image::new(1, 1, Color::BLACK), None).await;
|
||||||
|
let layer = editor.get_selected_layer().await.expect("the pasted image should be selected").to_node();
|
||||||
|
let mandelbrot = NodeId::new();
|
||||||
|
editor.dispatch(NodeGraphMessage::CreateNodeFromContextMenu {
|
||||||
|
node_id: Some(mandelbrot),
|
||||||
|
node_type: DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER),
|
||||||
|
xy: None,
|
||||||
|
add_transaction: true,
|
||||||
|
});
|
||||||
|
editor.dispatch(NodeGraphMessage::CreateWire {
|
||||||
|
output_connector: OutputConnector::primary_output(mandelbrot),
|
||||||
|
input_connector: InputConnector::node_at_index(layer, 1),
|
||||||
|
});
|
||||||
|
editor.eval_graph_until_finished().await.expect("the graph evaluates");
|
||||||
|
|
||||||
|
// The evaluation the readback wakes draws the same placeholders again, so the image it read back fills them and the export finishes
|
||||||
|
send_export(&mut editor, FileType::Svg);
|
||||||
|
let mut saved = None;
|
||||||
|
for _ in 0..100 {
|
||||||
|
editor.runtime.update();
|
||||||
|
editor.runtime.run().await;
|
||||||
|
saved = editor.dispatch(Message::Wake).into_iter().find_map(|message| match message {
|
||||||
|
FrontendMessage::TriggerSaveFile { content, .. } => Some(content),
|
||||||
|
_ => None,
|
||||||
|
});
|
||||||
|
if saved.is_some() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let Some(saved) = saved else { panic!("the export never finished") };
|
||||||
|
|
||||||
|
let svg = String::from_utf8(saved.into_vec()).expect("the export should be SVG text");
|
||||||
|
assert!(
|
||||||
|
svg.contains("data:image/png;base64,") && !svg.contains("deferred-image"),
|
||||||
|
"the fractal's image should fill its placeholder: {svg}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Lets the runtime handle what's queued until the clipboard is written, giving back the SVG written with the copied layers, if any.
|
||||||
|
async fn clipboard_svg_once_written(editor: &mut EditorTestUtils, mut messages: Vec<FrontendMessage>) -> Option<String> {
|
||||||
|
use crate::messages::portfolio::ingest::utility_types::TransferData;
|
||||||
|
|
||||||
|
for _ in 0..1000 {
|
||||||
|
let written = messages.iter().find_map(|message| match message {
|
||||||
|
FrontendMessage::TriggerClipboardWrite { content } => Some(content),
|
||||||
|
_ => None,
|
||||||
|
});
|
||||||
|
if let Some(content) = written {
|
||||||
|
return content.0.iter().find_map(|item| match &item.data {
|
||||||
|
TransferData::Svg(svg) => Some(svg.clone()),
|
||||||
|
_ => None,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
editor.runtime.update();
|
||||||
|
editor.runtime.run().await;
|
||||||
|
messages = editor.dispatch(Message::Wake);
|
||||||
|
}
|
||||||
|
panic!("the clipboard was never written");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_cut_waits_through_document_updates_for_its_outstanding_tasks_then_writes_once() {
|
||||||
|
use crate::messages::portfolio::ingest::utility_types::TransferData;
|
||||||
|
|
||||||
|
/// Runs each task at once, or holds it while `holding` until the test runs it.
|
||||||
|
#[derive(Default)]
|
||||||
|
struct HeldTasks {
|
||||||
|
holding: AtomicBool,
|
||||||
|
held: std::sync::Mutex<Vec<Task>>,
|
||||||
|
}
|
||||||
|
impl Spawn for HeldTasks {
|
||||||
|
fn spawn(&self, task: Task) {
|
||||||
|
match self.holding.load(Ordering::Relaxed) {
|
||||||
|
true => self.held.lock().unwrap().push(task),
|
||||||
|
false => futures::executor::block_on(task),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let svgs_written = |messages: &[FrontendMessage]| -> Vec<String> {
|
||||||
|
let written = messages.iter().filter_map(|message| match message {
|
||||||
|
FrontendMessage::TriggerClipboardWrite { content } => Some(content),
|
||||||
|
_ => None,
|
||||||
|
});
|
||||||
|
let svgs = written.flat_map(|content| &content.0).filter_map(|item| match &item.data {
|
||||||
|
TransferData::Svg(svg) => Some(svg.clone()),
|
||||||
|
_ => None,
|
||||||
|
});
|
||||||
|
svgs.collect()
|
||||||
|
};
|
||||||
|
|
||||||
|
let tasks = Arc::new(HeldTasks::default());
|
||||||
|
let mut editor = EditorTestUtils::create();
|
||||||
|
editor.runtime.replace_task_executor(tasks.clone(), Arc::new(|| {}));
|
||||||
|
editor.new_document().await;
|
||||||
|
editor.handle_message(DocumentMessage::SetRenderMode { render_mode: RenderMode::SvgPreview }).await;
|
||||||
|
|
||||||
|
// The traced layer's tasks are held from the start, so it's still unfinished when it's cut
|
||||||
|
tasks.holding.store(true, Ordering::Relaxed);
|
||||||
|
add_traced_noise_layer(&mut editor).await;
|
||||||
|
send_update(&mut editor);
|
||||||
|
editor.runtime.update();
|
||||||
|
editor.runtime.run().await;
|
||||||
|
editor.dispatch(Message::Wake);
|
||||||
|
assert!(!tasks.held.lock().unwrap().is_empty(), "the layer should have tasks out");
|
||||||
|
|
||||||
|
let layer = editor.active_document().metadata().all_layers().next().unwrap().to_node();
|
||||||
|
editor.dispatch(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer] });
|
||||||
|
let mut messages = editor.dispatch(ClipboardMessage::CutLayers);
|
||||||
|
assert_eq!(editor.active_document().metadata().all_layers().count(), 0, "the layer should be cut");
|
||||||
|
|
||||||
|
// Document updates after the cut leave the copy's network alone, outliving the executor's grace for orphaned nodes
|
||||||
|
for _ in 0..3 {
|
||||||
|
send_update(&mut editor);
|
||||||
|
editor.runtime.update();
|
||||||
|
editor.runtime.run().await;
|
||||||
|
messages.extend(editor.dispatch(Message::Wake));
|
||||||
|
}
|
||||||
|
assert!(svgs_written(&messages).is_empty(), "nothing should be written while the tasks are out");
|
||||||
|
assert!(editor.runtime.pending_clipboard.is_some(), "the copy should hold its network");
|
||||||
|
|
||||||
|
// Released, the tasks land and the trace runs to its end
|
||||||
|
tasks.holding.store(false, Ordering::Relaxed);
|
||||||
|
let held = std::mem::take(&mut *tasks.held.lock().unwrap());
|
||||||
|
held.into_iter().for_each(futures::executor::block_on);
|
||||||
|
for _ in 0..1000 {
|
||||||
|
editor.runtime.update();
|
||||||
|
editor.runtime.run().await;
|
||||||
|
messages.extend(editor.dispatch(Message::Wake));
|
||||||
|
}
|
||||||
|
|
||||||
|
let svgs = svgs_written(&messages);
|
||||||
|
assert_eq!(svgs.len(), 1, "the SVG should be written once");
|
||||||
|
assert!(svgs[0].contains("<path"), "the SVG should hold the traced shapes: {}", svgs[0]);
|
||||||
|
assert!(editor.runtime.pending_clipboard.is_none(), "the copy should let its network go");
|
||||||
|
}
|
||||||
|
|
||||||
|
// The copy's network is compiled ahead of the edit sent with it, so the edit's node is compiled before the document's update reaches it
|
||||||
|
#[tokio::test]
|
||||||
|
async fn the_types_of_an_edit_sent_with_a_copy_reach_the_editor() {
|
||||||
|
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||||
|
use graphene_std::blending_nodes::effects::drop_shadow;
|
||||||
|
|
||||||
|
let mut editor = editor().await;
|
||||||
|
send_update(&mut editor);
|
||||||
|
editor.runtime.update();
|
||||||
|
editor.runtime.run().await;
|
||||||
|
editor.dispatch(Message::Wake);
|
||||||
|
|
||||||
|
let layer = editor.active_document().metadata().all_layers().next().unwrap();
|
||||||
|
let shadow_type = DefinitionIdentifier::ProtoNode(drop_shadow::IDENTIFIER);
|
||||||
|
editor.dispatch(NodeGraphMessage::CreateNodeInLayerWithTransaction {
|
||||||
|
node_type: shadow_type.clone(),
|
||||||
|
layer,
|
||||||
|
});
|
||||||
|
let interface = &editor.active_document().network_interface;
|
||||||
|
let shadow = interface
|
||||||
|
.document_network()
|
||||||
|
.nodes
|
||||||
|
.keys()
|
||||||
|
.copied()
|
||||||
|
.find(|node_id| interface.reference(node_id, &[]) == Some(shadow_type.clone()));
|
||||||
|
let shadow = shadow.expect("the shadow should be added");
|
||||||
|
|
||||||
|
send_update(&mut editor);
|
||||||
|
editor.dispatch(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] });
|
||||||
|
let messages = editor.dispatch(ClipboardMessage::CopyLayers);
|
||||||
|
clipboard_svg_once_written(&mut editor, messages).await.expect("the layer should render an SVG");
|
||||||
|
|
||||||
|
let types = &editor.active_document().network_interface.resolved_types.types;
|
||||||
|
assert!(types.keys().any(|path| path.first() == Some(&shadow)), "the shadow's types should reach the editor");
|
||||||
|
}
|
||||||
|
|
||||||
|
// The edit, the copy, and the cut taking the edited layer away all reach the runtime in one queue
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_copy_renders_the_document_as_it_was_when_copied() {
|
||||||
|
use graphene_std::raster::color::Color;
|
||||||
|
|
||||||
|
let mut editor = editor().await;
|
||||||
|
send_update(&mut editor);
|
||||||
|
editor.runtime.update();
|
||||||
|
editor.runtime.run().await;
|
||||||
|
editor.dispatch(Message::Wake);
|
||||||
|
|
||||||
|
let layer = editor.active_document().metadata().all_layers().next().unwrap();
|
||||||
|
editor.dispatch(GraphOperationMessage::FillColorSet { layer, color: Some(Color::RED) });
|
||||||
|
send_update(&mut editor);
|
||||||
|
editor.dispatch(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] });
|
||||||
|
let mut messages = editor.dispatch(ClipboardMessage::CopyLayers);
|
||||||
|
messages.extend(editor.dispatch(ClipboardMessage::CutLayers));
|
||||||
|
|
||||||
|
let svg = clipboard_svg_once_written(&mut editor, messages).await.expect("the cut layer should render an SVG");
|
||||||
|
assert!(svg.to_lowercase().contains("#ff0000"), "the SVG should show the edited fill: {svg}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_copy_renders_while_another_layer_fails_to_compile() {
|
||||||
|
let mut editor = editor().await;
|
||||||
|
editor.draw_rect(200., 0., 300., 100.).await;
|
||||||
|
let copied = editor.active_document().metadata().all_layers().nth(1).expect("the first rectangle drawn").to_node();
|
||||||
|
|
||||||
|
// The top layer fails to compile
|
||||||
|
break_compile(&mut editor);
|
||||||
|
send_update(&mut editor);
|
||||||
|
editor.runtime.update();
|
||||||
|
editor.runtime.run().await;
|
||||||
|
editor.dispatch(Message::Wake);
|
||||||
|
assert!(editor.runtime.compile_failed, "the document should fail to compile");
|
||||||
|
|
||||||
|
editor.dispatch(NodeGraphMessage::SelectedNodesSet { nodes: vec![copied] });
|
||||||
|
let messages = editor.dispatch(ClipboardMessage::CopyLayers);
|
||||||
|
let svg = clipboard_svg_once_written(&mut editor, messages).await.expect("the copied layer should render an SVG");
|
||||||
|
assert!(svg.contains("<path"), "the SVG should draw the rectangle: {svg}");
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn exporting_a_graph_that_fails_to_compile_says_it_failed() {
|
async fn exporting_a_graph_that_fails_to_compile_says_it_failed() {
|
||||||
let mut editor = editor().await;
|
let mut editor = editor().await;
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use super::evaluated_output;
|
use super::{artboard_clip_bounds, evaluated_output};
|
||||||
use crate::messages::frontend::FrontendMessage;
|
use crate::messages::frontend::FrontendMessage;
|
||||||
use atlas::ThumbnailAtlasLayout;
|
use atlas::ThumbnailAtlasLayout;
|
||||||
use glam::{DAffine2, DVec2, UVec2};
|
use glam::{DAffine2, DVec2, UVec2};
|
||||||
@@ -12,8 +12,8 @@ use graphene_std::ops::ConvertAsync;
|
|||||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||||
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasHandle};
|
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasHandle};
|
||||||
use graphene_std::raster_types::{CPU, GPU, Raster};
|
use graphene_std::raster_types::{CPU, GPU, Raster};
|
||||||
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
|
use graphene_std::renderer::Render;
|
||||||
use graphene_std::transform::{Footprint, RenderQuality};
|
use graphene_std::transform::Footprint;
|
||||||
use graphene_std::vector::Vector;
|
use graphene_std::vector::Vector;
|
||||||
use graphene_std::{Artboard, Color, Context, ContextFeatures, Graphic};
|
use graphene_std::{Artboard, Color, Context, ContextFeatures, Graphic};
|
||||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||||
@@ -276,11 +276,11 @@ impl ThumbnailContent {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The area the content covers once rendered, counting the effects drawn through maps and images only if they're `maps_resolved`, which the clipboard's SVG leaves out.
|
/// The area the content covers once rendered.
|
||||||
fn content_bounds(&self, maps_resolved: bool) -> RenderBoundingBox {
|
fn content_bounds(&self) -> RenderBoundingBox {
|
||||||
match self {
|
match self {
|
||||||
// Text-aware bounds, which the `BoundingBox` trait can't give `Graphic::TextList` content, with the effects' reach
|
// Text-aware bounds, which the `BoundingBox` trait can't give `Graphic::TextList` content, with the effects' reach
|
||||||
Self::Graphics(graphics) => graphene_std::renderer::graphic_list_painted_bounds(graphics, maps_resolved),
|
Self::Graphics(graphics) => graphene_std::renderer::graphic_list_painted_bounds(graphics),
|
||||||
// The clipping rectangles rather than the content, since the renderer clips content to them
|
// The clipping rectangles rather than the content, since the renderer clips content to them
|
||||||
Self::Artboards(artboards) => artboard_clip_bounds(artboards),
|
Self::Artboards(artboards) => artboard_clip_bounds(artboards),
|
||||||
Self::Text(text) => graphene_std::renderer::text_list_bounding_box(text, DAffine2::IDENTITY),
|
Self::Text(text) => graphene_std::renderer::text_list_bounding_box(text, DAffine2::IDENTITY),
|
||||||
@@ -289,7 +289,7 @@ impl ThumbnailContent {
|
|||||||
|
|
||||||
/// The area the thumbnail shows, centered on the content at the thumbnail's aspect ratio.
|
/// The area the thumbnail shows, centered on the content at the thumbnail's aspect ratio.
|
||||||
fn bounds(&self) -> [DVec2; 2] {
|
fn bounds(&self) -> [DVec2; 2] {
|
||||||
let bounds = match self.content_bounds(true) {
|
let bounds = match self.content_bounds() {
|
||||||
RenderBoundingBox::Rectangle(bounds) if (bounds[1] - bounds[0]) != DVec2::ZERO => bounds,
|
RenderBoundingBox::Rectangle(bounds) if (bounds[1] - bounds[0]) != DVec2::ZERO => bounds,
|
||||||
_ => [DVec2::ZERO, DVec2::ONE],
|
_ => [DVec2::ZERO, DVec2::ONE],
|
||||||
};
|
};
|
||||||
@@ -297,38 +297,6 @@ impl ThumbnailContent {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Renders what each of these document layers adds, painted in the given order, as one SVG framed to their combined bounds, or `None` if they render nothing.
|
|
||||||
pub fn layers_svg(layers: &[NodeId], network: &NodeNetwork, executor: &DynamicExecutor) -> Option<String> {
|
|
||||||
let contents: Vec<ThumbnailContent> = layers
|
|
||||||
.iter()
|
|
||||||
.filter_map(|&layer| ThumbnailContent::evaluate(executor, thumbnail_source(&[layer], network, executor)?))
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
let bounds = contents
|
|
||||||
.iter()
|
|
||||||
.filter_map(|content| match content.content_bounds(false) {
|
|
||||||
RenderBoundingBox::Rectangle(bounds) if (bounds[1] - bounds[0]) != DVec2::ZERO => Some(bounds),
|
|
||||||
_ => None,
|
|
||||||
})
|
|
||||||
.reduce(|[min, max], [other_min, other_max]| [min.min(other_min), max.max(other_max)])?;
|
|
||||||
|
|
||||||
let render_params = RenderParams {
|
|
||||||
footprint: Footprint::from_bounds(bounds, RenderQuality::Full),
|
|
||||||
thumbnail: true,
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
let mut render = SvgRender::new();
|
|
||||||
for content in &contents {
|
|
||||||
content.graphic().render_svg(&mut render, &render_params);
|
|
||||||
}
|
|
||||||
if render.svg.is_empty() {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
render.format_svg(bounds[0], bounds[1]);
|
|
||||||
|
|
||||||
Some(render.svg.to_svg_string())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The proto node giving the content a layer's thumbnail shows, which is only what the layer adds if it extends the stack below it.
|
/// The proto node giving the content a layer's thumbnail shows, which is only what the layer adds if it extends the stack below it.
|
||||||
fn thumbnail_source(layer_path: &[NodeId], network: &NodeNetwork, executor: &DynamicExecutor) -> Option<NodeId> {
|
fn thumbnail_source(layer_path: &[NodeId], network: &NodeNetwork, executor: &DynamicExecutor) -> Option<NodeId> {
|
||||||
let source = layer_content(layer_path, network)?.source(network)?;
|
let source = layer_content(layer_path, network)?.source(network)?;
|
||||||
@@ -361,25 +329,6 @@ fn into_graphic(output: graphene_std::registry::Any) -> Option<Graphic> {
|
|||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the union of the artboards' clipping rectangles, used as the thumbnail bounds for an artboard layer so the
|
|
||||||
/// framing matches what's actually visible after clipping rather than the unclipped content extents.
|
|
||||||
fn artboard_clip_bounds(artboards: &List<Artboard>) -> RenderBoundingBox {
|
|
||||||
let mut combined: Option<[DVec2; 2]> = None;
|
|
||||||
for index in 0..artboards.len() {
|
|
||||||
let location: DVec2 = artboards.attribute_cloned_or_default(graphene_std::ATTR_LOCATION, index);
|
|
||||||
let dimensions: DVec2 = artboards.attribute_cloned_or_default(graphene_std::ATTR_DIMENSIONS, index);
|
|
||||||
let bounds = [location, location + dimensions];
|
|
||||||
combined = Some(match combined {
|
|
||||||
Some(existing) => [existing[0].min(bounds[0]), existing[1].max(bounds[1])],
|
|
||||||
None => bounds,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
match combined {
|
|
||||||
Some(bounds) => RenderBoundingBox::Rectangle(bounds),
|
|
||||||
None => RenderBoundingBox::None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Expands an AABB outward (centered) to match the Layers panel thumbnail's 3:2 aspect ratio, padding the smaller axis
|
/// Expands an AABB outward (centered) to match the Layers panel thumbnail's 3:2 aspect ratio, padding the smaller axis
|
||||||
/// so the input's extent is always preserved.
|
/// so the input's extent is always preserved.
|
||||||
fn expand_to_thumbnail_aspect(bounds: [DVec2; 2]) -> [DVec2; 2] {
|
fn expand_to_thumbnail_aspect(bounds: [DVec2; 2]) -> [DVec2; 2] {
|
||||||
|
|||||||
@@ -63,7 +63,6 @@ pub fn draw_atlas(scene: &mut VelloSceneBuilder, layout: &ThumbnailAtlasLayout,
|
|||||||
let render_params = RenderParams {
|
let render_params = RenderParams {
|
||||||
footprint: Footprint::BOUNDLESS,
|
footprint: Footprint::BOUNDLESS,
|
||||||
render_output_type: RenderOutputType::Vello,
|
render_output_type: RenderOutputType::Vello,
|
||||||
thumbnail: true,
|
|
||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
let cell_size = layout.cell_size.as_dvec2();
|
let cell_size = layout.cell_size.as_dvec2();
|
||||||
|
|||||||
@@ -117,10 +117,17 @@ impl EditorTestUtils {
|
|||||||
panic!("Failed to evaluate graph: {e}");
|
panic!("Failed to evaluate graph: {e}");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The copied layers' SVG waits for the readbacks of the GPU images it holds, each landing before a later run
|
||||||
let mut frontend_messages = self.dispatch(message);
|
let mut frontend_messages = self.dispatch(message);
|
||||||
self.runtime.update();
|
for _ in 0..100 {
|
||||||
self.runtime.run().await;
|
self.runtime.update();
|
||||||
frontend_messages.extend(self.dispatch(Message::Wake));
|
self.runtime.run().await;
|
||||||
|
frontend_messages.extend(self.dispatch(Message::Wake));
|
||||||
|
|
||||||
|
if frontend_messages.iter().any(|message| matches!(message, FrontendMessage::TriggerClipboardWrite { .. })) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
frontend_messages
|
frontend_messages
|
||||||
.into_iter()
|
.into_iter()
|
||||||
|
|||||||
@@ -191,7 +191,6 @@ import NodeFlattenGradient from "/../branding/assets/16x16-nodes/node-flatten-gr
|
|||||||
import NodeFlattenRaster from "/../branding/assets/16x16-nodes/node-flatten-raster.svg";
|
import NodeFlattenRaster from "/../branding/assets/16x16-nodes/node-flatten-raster.svg";
|
||||||
import NodeFlattenVector from "/../branding/assets/16x16-nodes/node-flatten-vector.svg";
|
import NodeFlattenVector from "/../branding/assets/16x16-nodes/node-flatten-vector.svg";
|
||||||
import NodeFloor from "/../branding/assets/16x16-nodes/node-floor.svg";
|
import NodeFloor from "/../branding/assets/16x16-nodes/node-floor.svg";
|
||||||
import NodeFootprintValue from "/../branding/assets/16x16-nodes/node-footprint-value.svg";
|
|
||||||
import NodeFormatJson from "/../branding/assets/16x16-nodes/node-format-json.svg";
|
import NodeFormatJson from "/../branding/assets/16x16-nodes/node-format-json.svg";
|
||||||
import NodeFormatNumber from "/../branding/assets/16x16-nodes/node-format-number.svg";
|
import NodeFormatNumber from "/../branding/assets/16x16-nodes/node-format-number.svg";
|
||||||
import NodeGammaCorrection from "/../branding/assets/16x16-nodes/node-gamma-correction.svg";
|
import NodeGammaCorrection from "/../branding/assets/16x16-nodes/node-gamma-correction.svg";
|
||||||
@@ -485,7 +484,6 @@ export const ICON_16X16_NODES = {
|
|||||||
NodeFlattenRaster: { svg: NodeFlattenRaster, size: 16 },
|
NodeFlattenRaster: { svg: NodeFlattenRaster, size: 16 },
|
||||||
NodeFlattenVector: { svg: NodeFlattenVector, size: 16 },
|
NodeFlattenVector: { svg: NodeFlattenVector, size: 16 },
|
||||||
NodeFloor: { svg: NodeFloor, size: 16 },
|
NodeFloor: { svg: NodeFloor, size: 16 },
|
||||||
NodeFootprintValue: { svg: NodeFootprintValue, size: 16 },
|
|
||||||
NodeFormatJson: { svg: NodeFormatJson, size: 16 },
|
NodeFormatJson: { svg: NodeFormatJson, size: 16 },
|
||||||
NodeFormatNumber: { svg: NodeFormatNumber, size: 16 },
|
NodeFormatNumber: { svg: NodeFormatNumber, size: 16 },
|
||||||
NodeGammaCorrection: { svg: NodeGammaCorrection, size: 16 },
|
NodeGammaCorrection: { svg: NodeGammaCorrection, size: 16 },
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ use brush_nodes::{BrushCache, Stroke};
|
|||||||
use core_types::color::SRGBA8;
|
use core_types::color::SRGBA8;
|
||||||
use core_types::list::{Item, List, NodeIdPath};
|
use core_types::list::{Item, List, NodeIdPath};
|
||||||
use core_types::transfer_curve::TransferCurve;
|
use core_types::transfer_curve::TransferCurve;
|
||||||
use core_types::transform::Footprint;
|
|
||||||
use core_types::{CacheHash, Color, ContextModification, MemoHash, Node, Poll, RuntimeHandle, SourceId, Type, TypeDescriptor};
|
use core_types::{CacheHash, Color, ContextModification, MemoHash, Node, Poll, RuntimeHandle, SourceId, Type, TypeDescriptor};
|
||||||
pub use dyn_any::StaticType;
|
pub use dyn_any::StaticType;
|
||||||
pub use glam::{DAffine2, DVec2, IVec2, UVec2};
|
pub use glam::{DAffine2, DVec2, IVec2, UVec2};
|
||||||
@@ -75,7 +74,7 @@ macro_rules! tagged_value {
|
|||||||
TypeDefault(Type),
|
TypeDefault(Type),
|
||||||
/// Stored compactly as a `Vec<f64>`, materializes as `List<f64>` at runtime via `to_dynany`/`to_any`. Aliases recover legacy on-disk shapes.
|
/// Stored compactly as a `Vec<f64>`, materializes as `List<f64>` at runtime via `to_dynany`/`to_any`. Aliases recover legacy on-disk shapes.
|
||||||
#[serde(deserialize_with = "core_types::misc::migrate_to_numbers")] // TODO: Eventually remove this document upgrade code
|
#[serde(deserialize_with = "core_types::misc::migrate_to_numbers")] // TODO: Eventually remove this document upgrade code
|
||||||
#[serde(alias = "F64Array", alias = "F64Table", alias = "VecF64", alias = "VecF32", alias = "F64Array4")]
|
#[serde(alias = "F64Array", alias = "F64Table", alias = "VecF64", alias = "VecF32", alias = "F64Array4", alias = "Footprint")]
|
||||||
Numbers(Vec<f64>),
|
Numbers(Vec<f64>),
|
||||||
/// Stored compactly as a `Vec<f64>` of dash lengths, materializes as an `Item<DashPattern>` at runtime via `to_dynany`/`to_any`.
|
/// Stored compactly as a `Vec<f64>` of dash lengths, materializes as an `Item<DashPattern>` at runtime via `to_dynany`/`to_any`.
|
||||||
DashPattern(Vec<f64>),
|
DashPattern(Vec<f64>),
|
||||||
@@ -514,7 +513,6 @@ tagged_value! {
|
|||||||
#[serde(alias = "ColorTable", alias = "OptionalColor", alias = "ColorNotInTable")]
|
#[serde(alias = "ColorTable", alias = "OptionalColor", alias = "ColorNotInTable")]
|
||||||
Color(Color),
|
Color(Color),
|
||||||
Font(Font),
|
Font(Font),
|
||||||
Footprint(Footprint),
|
|
||||||
VectorModification(Box<VectorModification>),
|
VectorModification(Box<VectorModification>),
|
||||||
ImageData(Image<Color>),
|
ImageData(Image<Color>),
|
||||||
Resource(ResourceId),
|
Resource(ResourceId),
|
||||||
@@ -576,6 +574,7 @@ tagged_value! {
|
|||||||
#[serde(alias = "LineJoin")]
|
#[serde(alias = "LineJoin")]
|
||||||
StrokeJoin(vector::style::StrokeJoin),
|
StrokeJoin(vector::style::StrokeJoin),
|
||||||
StrokeAlign(vector::style::StrokeAlign),
|
StrokeAlign(vector::style::StrokeAlign),
|
||||||
|
PaintMapping(vector::style::PaintMapping),
|
||||||
#[serde(alias = "GradientType")] // TODO: Eventually remove this document upgrade code
|
#[serde(alias = "GradientType")] // TODO: Eventually remove this document upgrade code
|
||||||
GradientForm(vector::style::GradientForm),
|
GradientForm(vector::style::GradientForm),
|
||||||
GradientModel(vector::style::GradientModel),
|
GradientModel(vector::style::GradientModel),
|
||||||
@@ -706,17 +705,6 @@ impl TaggedValue {
|
|||||||
Some(DAffine2::from_scale_angle_translation(DVec2::new(width, height), 0., DVec2::new(x, y)))
|
Some(DAffine2::from_scale_angle_translation(DVec2::new(width, height), 0., DVec2::new(x, y)))
|
||||||
}
|
}
|
||||||
|
|
||||||
// The Inspector's X, Y, W, H, rendered at 100% resolution
|
|
||||||
fn to_footprint(input: &str) -> Option<Footprint> {
|
|
||||||
let transform = to_daffine2(input)?;
|
|
||||||
|
|
||||||
Some(Footprint {
|
|
||||||
transform,
|
|
||||||
resolution: transform.matrix2.diagonal().as_uvec2(),
|
|
||||||
..Default::default()
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn to_stroke_align(input: &str) -> Option<vector::style::StrokeAlign> {
|
fn to_stroke_align(input: &str) -> Option<vector::style::StrokeAlign> {
|
||||||
let mut choices = input.split("::");
|
let mut choices = input.split("::");
|
||||||
let (first, second) = (choices.next()?.trim(), choices.next()?.trim());
|
let (first, second) = (choices.next()?.trim(), choices.next()?.trim());
|
||||||
@@ -792,7 +780,6 @@ impl TaggedValue {
|
|||||||
() if ty == TypeId::of::<Graphic>() => to_color(string).map(TaggedValue::Color)?,
|
() if ty == TypeId::of::<Graphic>() => to_color(string).map(TaggedValue::Color)?,
|
||||||
() if ty == TypeId::of::<Gradient>() => to_gradient(string).map(|gradient| TaggedValue::GradientRamp(gradient.into()))?,
|
() if ty == TypeId::of::<Gradient>() => to_gradient(string).map(|gradient| TaggedValue::GradientRamp(gradient.into()))?,
|
||||||
() if ty == TypeId::of::<ReferencePoint>() => to_reference_point(string).map(TaggedValue::ReferencePoint)?,
|
() if ty == TypeId::of::<ReferencePoint>() => to_reference_point(string).map(TaggedValue::ReferencePoint)?,
|
||||||
() if ty == TypeId::of::<Footprint>() => to_footprint(string).map(TaggedValue::Footprint)?,
|
|
||||||
() if ty == TypeId::of::<vector::style::StrokeAlign>() => to_stroke_align(string).map(TaggedValue::StrokeAlign)?,
|
() if ty == TypeId::of::<vector::style::StrokeAlign>() => to_stroke_align(string).map(TaggedValue::StrokeAlign)?,
|
||||||
() if ty == TypeId::of::<core_types::blending::BlendMode>() => to_blend_mode(string).map(TaggedValue::BlendMode)?,
|
() if ty == TypeId::of::<core_types::blending::BlendMode>() => to_blend_mode(string).map(TaggedValue::BlendMode)?,
|
||||||
() if ty == TypeId::of::<vector::style::GradientSpread>() => to_gradient_spread(string).map(TaggedValue::GradientSpread)?,
|
() if ty == TypeId::of::<vector::style::GradientSpread>() => to_gradient_spread(string).map(TaggedValue::GradientSpread)?,
|
||||||
@@ -1148,20 +1135,6 @@ mod number_default_parsing {
|
|||||||
assert_eq!(TaggedValue::from_primitive_string("- 1., 2.", &item!(DVec2)), Some(TaggedValue::DVec2(DVec2::new(-1., 2.))));
|
assert_eq!(TaggedValue::from_primitive_string("- 1., 2.", &item!(DVec2)), Some(TaggedValue::DVec2(DVec2::new(-1., 2.))));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn footprint_defaults_parse_as_x_y_width_height() {
|
|
||||||
let expected = Footprint {
|
|
||||||
transform: DAffine2::from_scale_angle_translation(DVec2::new(10_000., 500.), 0., DVec2::new(-50., 20.)),
|
|
||||||
resolution: glam::UVec2::new(10_000, 500),
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
assert_eq!(
|
|
||||||
TaggedValue::from_primitive_string("- 50., 20., 10_000., 500.", &item!(Footprint)),
|
|
||||||
Some(TaggedValue::Footprint(expected))
|
|
||||||
);
|
|
||||||
assert_eq!(TaggedValue::from_primitive_string("1., 2., 3.", &item!(Footprint)), None);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn transform_defaults_parse_as_x_y_width_height() {
|
fn transform_defaults_parse_as_x_y_width_height() {
|
||||||
let expected = DAffine2::from_scale_angle_translation(DVec2::new(500., 400.), 0., DVec2::new(250., -20.));
|
let expected = DAffine2::from_scale_angle_translation(DVec2::new(500., 400.), 0., DVec2::new(250., -20.));
|
||||||
@@ -1303,3 +1276,29 @@ mod retired_numeric_variants {
|
|||||||
assert_ne!(load(serde_json::json!({ "F32": 2.2 })), TaggedValue::Number(2.2_f32 as f64));
|
assert_ne!(load(serde_json::json!({ "F32": 2.2 })), TaggedValue::Number(2.2_f32 as f64));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO: Eventually remove this document upgrade code
|
||||||
|
#[cfg(test)]
|
||||||
|
mod retired_footprint_variant {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_footprint_reads_as_its_transform_then_its_resolution() {
|
||||||
|
let payload = serde_json::json!({ "Footprint": { "transform": [500., 0., 0., 250., -20., 40.], "resolution": [64, 32], "quality": "Full" } });
|
||||||
|
let expected = TaggedValue::Numbers(vec![500., 0., 0., 250., -20., 40., 64., 32.]);
|
||||||
|
|
||||||
|
let legacy = deserialize_tagged_value_with_legacy_migration(payload.clone()).expect("The footprint payload should deserialize");
|
||||||
|
assert_eq!(*legacy.into_inner(), expected);
|
||||||
|
|
||||||
|
let stored: TaggedValue = serde_json::from_value(payload).expect("The footprint payload should deserialize");
|
||||||
|
assert_eq!(stored, expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_null_in_a_footprint_transform_reads_as_zero() {
|
||||||
|
let payload = serde_json::json!({ "Footprint": { "transform": [1., 0., 0., 1., null, 0.], "resolution": [64, 32], "quality": "Full" } });
|
||||||
|
let loaded: TaggedValue = serde_json::from_value(payload).expect("The footprint payload should deserialize");
|
||||||
|
|
||||||
|
assert_eq!(loaded, TaggedValue::Numbers(vec![1., 0., 0., 1., 0., 0., 64., 32.]));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -65,17 +65,23 @@ impl DynamicExecutor {
|
|||||||
/// Adds the [`ProtoNetwork`] to the existing [`BorrowTree`], reusing nodes where possible.
|
/// Adds the [`ProtoNetwork`] to the existing [`BorrowTree`], reusing nodes where possible.
|
||||||
#[cfg_attr(debug_assertions, inline(never))]
|
#[cfg_attr(debug_assertions, inline(never))]
|
||||||
pub fn update(&mut self, proto_network: ProtoNetwork) -> Result<(OutputHandle, ResolvedDocumentNodeTypesDelta), (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
|
pub fn update(&mut self, proto_network: ProtoNetwork) -> Result<(OutputHandle, ResolvedDocumentNodeTypesDelta), (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
|
||||||
let (output, add) = self.insert_nodes(proto_network)?;
|
let (output, add) = self.insert_nodes(proto_network, true)?;
|
||||||
let remove = self.free_orphaned_nodes();
|
let remove = self.free_orphaned_nodes();
|
||||||
Ok((output, ResolvedDocumentNodeTypesDelta { add, remove }))
|
Ok((output, ResolvedDocumentNodeTypesDelta { add, remove }))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn update_without_freeing(&mut self, proto_network: ProtoNetwork) -> Result<(OutputHandle, ResolvedDocumentNodeTypesDelta), (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
|
pub fn update_without_freeing(&mut self, proto_network: ProtoNetwork) -> Result<(OutputHandle, ResolvedDocumentNodeTypesDelta), (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
|
||||||
let (output, add) = self.insert_nodes(proto_network)?;
|
let (output, add) = self.insert_nodes(proto_network, true)?;
|
||||||
Ok((output, ResolvedDocumentNodeTypesDelta { add, remove: Vec::new() }))
|
Ok((output, ResolvedDocumentNodeTypesDelta { add, remove: Vec::new() }))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn insert_nodes(&mut self, proto_network: ProtoNetwork) -> Result<(OutputHandle, Vec<(Path, NodeTypes)>), (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
|
/// Adds the [`ProtoNetwork`] of an output held beside the one the editor shows, reusing nodes where possible.
|
||||||
|
/// The source map and the type deltas stay those of the networks given to [`Self::update`], so this records no document paths and frees nothing.
|
||||||
|
pub fn insert_beside(&mut self, proto_network: ProtoNetwork) -> Result<OutputHandle, GraphErrors> {
|
||||||
|
self.insert_nodes(proto_network, false).map(|(output, _)| output).map_err(|(_, errors)| errors)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn insert_nodes(&mut self, proto_network: ProtoNetwork, records_paths: bool) -> Result<(OutputHandle, Vec<(Path, NodeTypes)>), (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
|
||||||
self.typing_context.update(&proto_network).map_err(|e| {
|
self.typing_context.update(&proto_network).map_err(|e| {
|
||||||
// If there is an error then get types that have been resolved before the error
|
// If there is an error then get types that have been resolved before the error
|
||||||
let add = proto_network
|
let add = proto_network
|
||||||
@@ -98,7 +104,10 @@ impl DynamicExecutor {
|
|||||||
})?;
|
})?;
|
||||||
|
|
||||||
let output = proto_network.output;
|
let output = proto_network.output;
|
||||||
let add = self.tree.update(proto_network, &self.typing_context).map_err(|e| (ResolvedDocumentNodeTypesDelta::default(), e))?;
|
let add = self
|
||||||
|
.tree
|
||||||
|
.update(proto_network, &self.typing_context, records_paths)
|
||||||
|
.map_err(|e| (ResolvedDocumentNodeTypesDelta::default(), e))?;
|
||||||
self.outputs.retain(|output| output.strong_count() > 0);
|
self.outputs.retain(|output| output.strong_count() > 0);
|
||||||
let held = self.outputs.iter().filter_map(Weak::upgrade).find(|held| **held == output);
|
let held = self.outputs.iter().filter_map(Weak::upgrade).find(|held| **held == output);
|
||||||
let output = held.unwrap_or_else(|| {
|
let output = held.unwrap_or_else(|| {
|
||||||
@@ -292,20 +301,22 @@ impl BorrowTree {
|
|||||||
pub fn new(proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<BorrowTree, GraphErrors> {
|
pub fn new(proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<BorrowTree, GraphErrors> {
|
||||||
let mut nodes = BorrowTree::default();
|
let mut nodes = BorrowTree::default();
|
||||||
for (id, node) in proto_network.nodes {
|
for (id, node) in proto_network.nodes {
|
||||||
nodes.push_node(id, node, typing_context)?
|
nodes.push_node(id, node, typing_context, true)?
|
||||||
}
|
}
|
||||||
Ok(nodes)
|
Ok(nodes)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Pushes new nodes into the tree
|
/// Pushes new nodes into the tree, giving back the document paths whose entries in the source map changed, if it `records_paths`.
|
||||||
pub fn update(&mut self, proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<Vec<Path>, GraphErrors> {
|
pub fn update(&mut self, proto_network: ProtoNetwork, typing_context: &TypingContext, records_paths: bool) -> Result<Vec<Path>, GraphErrors> {
|
||||||
let mut new_nodes: Vec<_> = Vec::new();
|
let mut new_nodes: Vec<_> = Vec::new();
|
||||||
// TODO: Problem: When a passthrough node is connected directly to an export the first input to the passthrough node is not added to the proto network, while the second input is. This means the primary input does not have a type.
|
// TODO: Problem: When a passthrough node is connected directly to an export the first input to the passthrough node is not added to the proto network, while the second input is. This means the primary input does not have a type.
|
||||||
for (id, node) in proto_network.nodes {
|
for (id, node) in proto_network.nodes {
|
||||||
if !self.nodes.contains_key(&id) {
|
if !self.nodes.contains_key(&id) {
|
||||||
new_nodes.push(node.original_location.path.clone().unwrap_or_default().into());
|
if records_paths {
|
||||||
self.push_node(id, node, typing_context)?;
|
new_nodes.push(node.original_location.path.clone().unwrap_or_default().into());
|
||||||
} else if self.update_source_map(id, typing_context, &node) {
|
}
|
||||||
|
self.push_node(id, node, typing_context, records_paths)?;
|
||||||
|
} else if records_paths && self.update_source_map(id, typing_context, &node) {
|
||||||
new_nodes.push(node.original_location.path.clone().unwrap_or_default().into());
|
new_nodes.push(node.original_location.path.clone().unwrap_or_default().into());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -512,14 +523,16 @@ impl BorrowTree {
|
|||||||
///
|
///
|
||||||
/// # Notes
|
/// # Notes
|
||||||
///
|
///
|
||||||
/// - Updates the source map using [`update_source_map`](BorrowTree::update_source_map) before inserting the node.
|
/// - Updates the source map using [`update_source_map`](BorrowTree::update_source_map) before inserting the node, if it `records_path`.
|
||||||
/// - Handles different types of construction arguments:
|
/// - Handles different types of construction arguments:
|
||||||
/// - `Value`: Creates a node from a `TaggedValue`, with special handling for `EditorApi` values.
|
/// - `Value`: Creates a node from a `TaggedValue`, with special handling for `EditorApi` values.
|
||||||
/// - `Nodes`: Constructs a node using other nodes as dependencies.
|
/// - `Nodes`: Constructs a node using other nodes as dependencies.
|
||||||
/// - Uses the constructor function from the `typing_context` for `Nodes` construction arguments.
|
/// - Uses the constructor function from the `typing_context` for `Nodes` construction arguments.
|
||||||
/// - Returns an error if no constructor is found for the given node ID.
|
/// - Returns an error if no constructor is found for the given node ID.
|
||||||
fn push_node(&mut self, id: NodeId, proto_node: ProtoNode, typing_context: &TypingContext) -> Result<(), GraphErrors> {
|
fn push_node(&mut self, id: NodeId, proto_node: ProtoNode, typing_context: &TypingContext, records_path: bool) -> Result<(), GraphErrors> {
|
||||||
self.update_source_map(id, typing_context, &proto_node);
|
if records_path {
|
||||||
|
self.update_source_map(id, typing_context, &proto_node);
|
||||||
|
}
|
||||||
self.context_features.insert(id, proto_node.upstream_context_features);
|
self.context_features.insert(id, proto_node.upstream_context_features);
|
||||||
let path = proto_node.original_location.path.clone().unwrap_or_default();
|
let path = proto_node.original_location.path.clone().unwrap_or_default();
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ fn push_node_sync() {
|
|||||||
let mut tree = BorrowTree::default();
|
let mut tree = BorrowTree::default();
|
||||||
let val_1_protonode = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Integer(2_i64).into()), vec![]);
|
let val_1_protonode = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Integer(2_i64).into()), vec![]);
|
||||||
let context = TypingContext::default();
|
let context = TypingContext::default();
|
||||||
tree.push_node(NodeId(0), val_1_protonode, &context).unwrap();
|
tree.push_node(NodeId(0), val_1_protonode, &context, true).unwrap();
|
||||||
let _node = tree.get(NodeId(0)).unwrap();
|
let _node = tree.get(NodeId(0)).unwrap();
|
||||||
let result: Option<Item<i64>> = tree.eval(NodeId(0), &());
|
let result: Option<Item<i64>> = tree.eval(NodeId(0), &());
|
||||||
assert_eq!(result.map(|item| *item.element()), Some(2_i64));
|
assert_eq!(result.map(|item| *item.element()), Some(2_i64));
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
//! Writes each layer's path onto what it renders, so what's rendered can be traced back to its layer.
|
//! Writes each layer's path onto what it renders, so what's rendered can be traced back to its layer.
|
||||||
|
|
||||||
use crate::node_registry::NODE_REGISTRY;
|
use crate::node_registry::NODE_REGISTRY;
|
||||||
use graph_craft::ProtoNodeIdentifier;
|
|
||||||
use graph_craft::document::value::TaggedValue;
|
use graph_craft::document::value::TaggedValue;
|
||||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, DocumentNodeMetadata, NodeId, NodeInput, NodeNetwork};
|
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, DocumentNodeMetadata, NodeId, NodeInput, NodeNetwork};
|
||||||
use graphene_std::NodeParameter;
|
use graph_craft::{ProtoNodeIdentifier, Type, concrete, list};
|
||||||
use graphene_std::graphic::{extend, write_layer_path};
|
use graphene_std::graphic::{as_graphic, extend, write_layer_path};
|
||||||
use graphene_std::list::NodeIdPath;
|
use graphene_std::list::NodeIdPath;
|
||||||
|
use graphene_std::{Artboard, Graphic, NodeParameter};
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||||
|
|
||||||
@@ -108,6 +108,112 @@ pub fn write_layer_paths(network: &mut NodeNetwork, layer_paths: &[Vec<NodeId>])
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Replaces the network's export with the stack of what these layers add, in the given order, giving back the root node making it, or `None` if they add nothing.
|
||||||
|
/// An artboard holds its own content, so when any of the layers adds one, only the artboards are stacked.
|
||||||
|
pub fn export_layers(network: &mut NodeNetwork, layers: &[NodeId]) -> Option<NodeId> {
|
||||||
|
// O(layers * depth)
|
||||||
|
let mut added = Vec::new();
|
||||||
|
for &layer in layers {
|
||||||
|
let Some(content) = layer_content(&[layer], network) else { continue };
|
||||||
|
let Some(source) = content.source(network) else { continue };
|
||||||
|
let artboard = outputs_artboards(source, network);
|
||||||
|
|
||||||
|
let Some(root_input) = surface_layer_content(network, layer, content) else { continue };
|
||||||
|
added.push((layer, root_input, artboard));
|
||||||
|
}
|
||||||
|
|
||||||
|
let artboards = added.iter().any(|&(_, _, artboard)| artboard);
|
||||||
|
let seed = if artboards { list!(Artboard) } else { list!(Graphic) };
|
||||||
|
|
||||||
|
let mut stack = NodeInput::type_default(seed, false);
|
||||||
|
for (layer, root_input, _) in added.into_iter().filter(|&(_, _, artboard)| artboard == artboards) {
|
||||||
|
// Extend joins lists of one type, so what other layers add is converted to graphics as the base input of 'Merge' does
|
||||||
|
let content = if artboards {
|
||||||
|
root_input
|
||||||
|
} else {
|
||||||
|
let as_graphic_id = exported_layer_node_id("as graphic", layer);
|
||||||
|
network.nodes.insert(as_graphic_id, proto_node(as_graphic::IDENTIFIER, vec![root_input]));
|
||||||
|
NodeInput::node(as_graphic_id, 0)
|
||||||
|
};
|
||||||
|
|
||||||
|
let extend_id = exported_layer_node_id("extend", layer);
|
||||||
|
network.nodes.insert(extend_id, proto_node(extend::IDENTIFIER, vec![stack, content]));
|
||||||
|
stack = NodeInput::node(extend_id, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
let stack_node = stack.as_node();
|
||||||
|
network.exports = vec![stack];
|
||||||
|
stack_node
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Makes what the layer adds an output of the layer node at the root, giving back the input that refers to it there.
|
||||||
|
fn surface_layer_content(network: &mut NodeNetwork, layer: NodeId, content: LayerContent) -> Option<NodeInput> {
|
||||||
|
let LayerContent::Added { network_path, extend } = content else {
|
||||||
|
return Some(NodeInput::node(layer, 0));
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut passed_on = network.nested_network(&network_path)?.nodes.get(&extend)?.inputs.get(extend::NewInput::INDEX)?.clone();
|
||||||
|
|
||||||
|
// Each network from the Extend node's out to the layer's gives it as an extra export, which layers made from the same network share
|
||||||
|
for depth in (1..=network_path.len()).rev() {
|
||||||
|
let holder = network_mut(network, &network_path[..depth])?;
|
||||||
|
let output_index = match holder.exports.iter().position(|export| *export == passed_on) {
|
||||||
|
Some(index) => index,
|
||||||
|
None => {
|
||||||
|
holder.exports.push(passed_on);
|
||||||
|
holder.exports.len() - 1
|
||||||
|
}
|
||||||
|
};
|
||||||
|
passed_on = NodeInput::node(network_path[depth - 1], output_index);
|
||||||
|
}
|
||||||
|
|
||||||
|
Some(passed_on)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether every type the proto node at this path may output is an artboard type, looking through nodes that output what their first input is given.
|
||||||
|
fn outputs_artboards(mut source: Vec<NodeId>, network: &NodeNetwork) -> bool {
|
||||||
|
let is_artboard = |ty: &Type| matches!(ty.nested_type(), Type::Item(element) | Type::List(element) if **element == concrete!(Artboard));
|
||||||
|
|
||||||
|
loop {
|
||||||
|
let Some((node_id, network_path)) = source.split_last() else { return false };
|
||||||
|
let Some(node) = network.nested_network(network_path).and_then(|network| network.nodes.get(node_id)) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let DocumentNodeImplementation::ProtoNode(identifier) = &node.implementation else { return false };
|
||||||
|
let Some(implementations) = NODE_REGISTRY.get(identifier) else { return false };
|
||||||
|
|
||||||
|
if implementations.keys().all(|types| is_artboard(&types.return_value)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
let passes_first_input_on = |types: &graphene_std::NodeIOTypes| types.inputs.first().is_some_and(|input| input.nested_type() == types.return_value.nested_type());
|
||||||
|
if !implementations.keys().all(passes_first_input_on) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let Some(input_source) = node.inputs.first().and_then(|input| network.input_source(network_path, input)) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
source = input_source;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The ID of a node that `export_layers` adds at the root for the layer with this ID.
|
||||||
|
fn exported_layer_node_id(purpose: &str, layer: NodeId) -> NodeId {
|
||||||
|
let mut hasher = DefaultHasher::new();
|
||||||
|
"exported layer".hash(&mut hasher);
|
||||||
|
purpose.hash(&mut hasher);
|
||||||
|
layer.hash(&mut hasher);
|
||||||
|
NodeId(hasher.finish())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn proto_node(identifier: ProtoNodeIdentifier, inputs: Vec<NodeInput>) -> DocumentNode {
|
||||||
|
DocumentNode {
|
||||||
|
inputs,
|
||||||
|
implementation: DocumentNodeImplementation::ProtoNode(identifier),
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// How the layer path writer fares with what a proto node outputs.
|
/// How the layer path writer fares with what a proto node outputs.
|
||||||
#[derive(Clone, Copy)]
|
#[derive(Clone, Copy)]
|
||||||
enum CarriesLayerPath {
|
enum CarriesLayerPath {
|
||||||
@@ -236,14 +342,6 @@ mod tests {
|
|||||||
assert_eq!(network, unchanged);
|
assert_eq!(network, unchanged);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn proto_node(identifier: ProtoNodeIdentifier, inputs: Vec<NodeInput>) -> DocumentNode {
|
|
||||||
DocumentNode {
|
|
||||||
inputs,
|
|
||||||
implementation: DocumentNodeImplementation::ProtoNode(identifier),
|
|
||||||
..Default::default()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn definition_node(id: NetworkId) -> DocumentNode {
|
fn definition_node(id: NetworkId) -> DocumentNode {
|
||||||
DocumentNode {
|
DocumentNode {
|
||||||
implementation: DocumentNodeImplementation::Definition(id),
|
implementation: DocumentNodeImplementation::Definition(id),
|
||||||
@@ -321,4 +419,110 @@ mod tests {
|
|||||||
assert!(matches!(output_can_carry_layer_path(&identifier), CarriesLayerPath::Always), "{identifier:?} should carry a layer path");
|
assert!(matches!(output_can_carry_layer_path(&identifier), CarriesLayerPath::Always), "{identifier:?} should carry a layer path");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// What the exported stack's Extend nodes are given at the root, bottom up, each with whether it's converted to a graphic, and what the stack starts from.
|
||||||
|
fn exported_stack(network: &NodeNetwork) -> (Vec<(NodeInput, bool)>, NodeInput) {
|
||||||
|
let mut added = Vec::new();
|
||||||
|
let mut stack = network.exports[0].clone();
|
||||||
|
while let Some(extend_node) = stack.as_node().and_then(|node_id| network.nodes.get(&node_id)) {
|
||||||
|
assert_eq!(extend_node.implementation, DocumentNodeImplementation::ProtoNode(extend::IDENTIFIER));
|
||||||
|
|
||||||
|
let content = &extend_node.inputs[extend::NewInput::INDEX];
|
||||||
|
let as_graphic_node = content.as_node().map(|node_id| &network.nodes[&node_id]);
|
||||||
|
added.push(match as_graphic_node {
|
||||||
|
Some(node) if node.implementation == DocumentNodeImplementation::ProtoNode(as_graphic::IDENTIFIER) => (node.inputs[0].clone(), true),
|
||||||
|
_ => (content.clone(), false),
|
||||||
|
});
|
||||||
|
|
||||||
|
stack = extend_node.inputs[extend::BaseInput::INDEX].clone();
|
||||||
|
}
|
||||||
|
|
||||||
|
added.reverse();
|
||||||
|
(added, stack)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn exported_layers_stack_as_graphics_in_the_order_given() {
|
||||||
|
let merge = NetworkId(1);
|
||||||
|
let rectangle = || proto_node(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER, Vec::new());
|
||||||
|
let mut network = NodeNetwork {
|
||||||
|
exports: vec![NodeInput::node(NodeId(20), 0)],
|
||||||
|
nodes: [(NodeId(10), definition_node(merge)), (NodeId(20), definition_node(merge)), (NodeId(30), rectangle())]
|
||||||
|
.into_iter()
|
||||||
|
.collect(),
|
||||||
|
definitions: [(merge, merge_like(rectangle()))].into_iter().collect(),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
assert!(export_layers(&mut network, &[NodeId(20), NodeId(30), NodeId(10)]).is_some());
|
||||||
|
|
||||||
|
// The network both 'Merge' layers are made from gives what its Extend node adds as one extra export, while the plain node gives its output
|
||||||
|
assert_eq!(network.definitions[&merge].exports, vec![NodeInput::node(NodeId(1), 0), NodeInput::node(NodeId(2), 0)]);
|
||||||
|
let (added, start) = exported_stack(&network);
|
||||||
|
assert_eq!(start, NodeInput::type_default(list!(Graphic), false));
|
||||||
|
assert_eq!(
|
||||||
|
added,
|
||||||
|
[(NodeInput::node(NodeId(20), 1), true), (NodeInput::node(NodeId(30), 0), true), (NodeInput::node(NodeId(10), 1), true)]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A layer made from a network holding a 'Merge' node passes what that node's Extend node adds out through both networks
|
||||||
|
#[test]
|
||||||
|
fn a_nested_extend_nodes_content_is_exported_through_each_network_around_it() {
|
||||||
|
let (merge, outer) = (NetworkId(1), NetworkId(2));
|
||||||
|
let rectangle = proto_node(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER, Vec::new());
|
||||||
|
let outer_network = NodeNetwork {
|
||||||
|
exports: vec![NodeInput::node(NodeId(30), 0)],
|
||||||
|
nodes: [(NodeId(30), definition_node(merge))].into_iter().collect(),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let mut network = NodeNetwork {
|
||||||
|
exports: vec![NodeInput::node(NodeId(10), 0)],
|
||||||
|
nodes: [(NodeId(10), definition_node(outer))].into_iter().collect(),
|
||||||
|
definitions: [(merge, merge_like(rectangle)), (outer, outer_network)].into_iter().collect(),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
assert!(export_layers(&mut network, &[NodeId(10)]).is_some());
|
||||||
|
|
||||||
|
assert_eq!(network.definitions[&merge].exports[1], NodeInput::node(NodeId(2), 0));
|
||||||
|
assert_eq!(network.definitions[&outer].exports[1], NodeInput::node(NodeId(30), 1));
|
||||||
|
assert_eq!(exported_stack(&network).0, [(NodeInput::node(NodeId(10), 1), true)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// An artboard holds its own content, so the other layers copied with it are left out
|
||||||
|
#[test]
|
||||||
|
fn exported_artboards_leave_out_the_other_layers() {
|
||||||
|
let (merge, artboard) = (NetworkId(1), NetworkId(2));
|
||||||
|
let rectangle = proto_node(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER, Vec::new());
|
||||||
|
let create_artboard = proto_node(graphene_std::artboard::create_artboard::IDENTIFIER, Vec::new());
|
||||||
|
let mut network = NodeNetwork {
|
||||||
|
exports: vec![NodeInput::node(NodeId(20), 0)],
|
||||||
|
nodes: [(NodeId(10), definition_node(merge)), (NodeId(20), definition_node(artboard))].into_iter().collect(),
|
||||||
|
definitions: [(merge, merge_like(rectangle)), (artboard, merge_like(create_artboard))].into_iter().collect(),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
assert!(export_layers(&mut network, &[NodeId(10), NodeId(20)]).is_some());
|
||||||
|
|
||||||
|
let (added, start) = exported_stack(&network);
|
||||||
|
assert_eq!(start, NodeInput::type_default(list!(Artboard), false));
|
||||||
|
assert_eq!(added, [(NodeInput::node(NodeId(20), 1), false)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hidden_layers_export_nothing() {
|
||||||
|
let rectangle = DocumentNode {
|
||||||
|
visible: false,
|
||||||
|
..proto_node(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER, Vec::new())
|
||||||
|
};
|
||||||
|
let mut network = NodeNetwork {
|
||||||
|
exports: vec![NodeInput::node(NodeId(10), 0)],
|
||||||
|
nodes: [(NodeId(10), rectangle)].into_iter().collect(),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
assert_eq!(export_layers(&mut network, &[NodeId(10)]), None);
|
||||||
|
assert_eq!(exported_stack(&network), (Vec::new(), NodeInput::type_default(list!(Graphic), false)));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -21,12 +21,14 @@ use graphene_std::render_node::RenderIntermediate;
|
|||||||
use graphene_std::text::{Font, TextAlign};
|
use graphene_std::text::{Font, TextAlign};
|
||||||
use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
|
use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
|
||||||
use graphene_std::transfer_curve::TransferCurve;
|
use graphene_std::transfer_curve::TransferCurve;
|
||||||
use graphene_std::transform::{Footprint, ReferencePoint, ScaleType};
|
use graphene_std::transform::{ReferencePoint, ScaleType};
|
||||||
use graphene_std::vector::misc::{
|
use graphene_std::vector::misc::{
|
||||||
ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod,
|
ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod,
|
||||||
WeldMethod,
|
WeldMethod,
|
||||||
};
|
};
|
||||||
use graphene_std::vector::style::{DashPattern, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin};
|
use graphene_std::vector::style::{
|
||||||
|
DashPattern, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientSpace, GradientSpread, PaintMapping, StrokeAlign, StrokeCap, StrokeJoin,
|
||||||
|
};
|
||||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector, VectorModification};
|
use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector, VectorModification};
|
||||||
use graphene_std::{Artboard, Context, Graphic, NodeIO, NodeIOTypes, ProtoNodeIdentifier, concrete, fn_type};
|
use graphene_std::{Artboard, Context, Graphic, NodeIO, NodeIOTypes, ProtoNodeIdentifier, concrete, fn_type};
|
||||||
use graphene_std::{BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, GlowSource, GlowTechnique, MaskMode, MinimumMaximumMode, NoiseDistribution};
|
use graphene_std::{BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, GlowSource, GlowTechnique, MaskMode, MinimumMaximumMode, NoiseDistribution};
|
||||||
@@ -87,7 +89,6 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<String>]),
|
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<String>]),
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<f64>]),
|
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<f64>]),
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<DAffine2>]),
|
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<DAffine2>]),
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Footprint>]),
|
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<DVec2>]),
|
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<DVec2>]),
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<bool>]),
|
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<bool>]),
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<BlendMode>]),
|
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<BlendMode>]),
|
||||||
@@ -269,6 +270,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
StrokeJoin,
|
StrokeJoin,
|
||||||
StrokeAlign,
|
StrokeAlign,
|
||||||
StrokeCap,
|
StrokeCap,
|
||||||
|
PaintMapping,
|
||||||
GradientForm,
|
GradientForm,
|
||||||
GradientModel,
|
GradientModel,
|
||||||
GradientSpread,
|
GradientSpread,
|
||||||
@@ -347,7 +349,6 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
DAffine2,
|
DAffine2,
|
||||||
bool,
|
bool,
|
||||||
NodeIdPath,
|
NodeIdPath,
|
||||||
Footprint,
|
|
||||||
Artboard,
|
Artboard,
|
||||||
));
|
));
|
||||||
node_types.extend(ranked_value_types!(rank_adapter_nodes));
|
node_types.extend(ranked_value_types!(rank_adapter_nodes));
|
||||||
|
|||||||
@@ -107,6 +107,8 @@ pub const ATTR_JOIN: &str = "join";
|
|||||||
pub const ATTR_JOIN_MITER_LIMIT: &str = "join_miter_limit";
|
pub const ATTR_JOIN_MITER_LIMIT: &str = "join_miter_limit";
|
||||||
/// Stroke coverage's `StrokeAlign` (implicit default `Center`), on the `Item<Cover>` inside a `Coverage`.
|
/// Stroke coverage's `StrokeAlign` (implicit default `Center`), on the `Item<Cover>` inside a `Coverage`.
|
||||||
pub const ATTR_ALIGN: &str = "align";
|
pub const ATTR_ALIGN: &str = "align";
|
||||||
|
/// Stroke coverage's `PaintMapping` (implicit default `Plane`), on the `Item<Cover>` inside a `Coverage`.
|
||||||
|
pub const ATTR_PAINT_MAPPING: &str = "paint_mapping";
|
||||||
/// Brush stroke item's `Color` its strokes are painted with.
|
/// Brush stroke item's `Color` its strokes are painted with.
|
||||||
pub const ATTR_COLOR: &str = "color";
|
pub const ATTR_COLOR: &str = "color";
|
||||||
/// Brush stroke item's tip diameter in document-space units (`f64`).
|
/// Brush stroke item's tip diameter in document-space units (`f64`).
|
||||||
|
|||||||
@@ -116,11 +116,18 @@ pub fn migrate_to_numbers<'de, D: serde::Deserializer<'de>>(deserializer: D) ->
|
|||||||
enum NumbersFormat {
|
enum NumbersFormat {
|
||||||
Array(Vec<f64>),
|
Array(Vec<f64>),
|
||||||
List(LegacyTable<f64>),
|
List(LegacyTable<f64>),
|
||||||
|
/// The removed `Footprint` value, stored only by 'Rasterize', for its upgrade to split back into its transform's six numbers then its resolution's two.
|
||||||
|
Footprint {
|
||||||
|
transform: [Option<f64>; 6],
|
||||||
|
resolution: [f64; 2],
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(match NumbersFormat::deserialize(deserializer)? {
|
Ok(match NumbersFormat::deserialize(deserializer)? {
|
||||||
NumbersFormat::Array(values) => values,
|
NumbersFormat::Array(values) => values,
|
||||||
NumbersFormat::List(list) => list.element,
|
NumbersFormat::List(list) => list.element,
|
||||||
|
// A `null` saved in place of a NaN or infinite number loads as 0, like elsewhere
|
||||||
|
NumbersFormat::Footprint { transform, resolution } => transform.into_iter().map(Option::unwrap_or_default).chain(resolution).collect(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,9 @@
|
|||||||
use crate::effects::{rebased_stamped_transform, stamped_transform};
|
use crate::effects::{rebased_stamped_transform, stamped_transform};
|
||||||
use crate::graphic::Graphic;
|
use crate::graphic::Graphic;
|
||||||
use core_types::graphene_hash::CacheHash;
|
use core_types::graphene_hash::CacheHash;
|
||||||
use core_types::list::{ATTR_ALIGN, ATTR_APPEARANCE, ATTR_CAP, ATTR_DASH_OFFSET, ATTR_DASH_PATTERN, ATTR_JOIN, ATTR_JOIN_MITER_LIMIT, ATTR_PAINT, ATTR_TRANSFORM, ATTR_WEIGHT, Item, List};
|
use core_types::list::{
|
||||||
|
ATTR_ALIGN, ATTR_APPEARANCE, ATTR_CAP, ATTR_DASH_OFFSET, ATTR_DASH_PATTERN, ATTR_JOIN, ATTR_JOIN_MITER_LIMIT, ATTR_PAINT, ATTR_PAINT_MAPPING, ATTR_TRANSFORM, ATTR_WEIGHT, Item, List,
|
||||||
|
};
|
||||||
use glam::DAffine2;
|
use glam::DAffine2;
|
||||||
use vector_types::vector::style::{DashPattern, Stroke};
|
use vector_types::vector::style::{DashPattern, Stroke};
|
||||||
|
|
||||||
@@ -82,6 +84,9 @@ impl Coverage {
|
|||||||
if stroke.align != defaults.align {
|
if stroke.align != defaults.align {
|
||||||
item.set_attribute(ATTR_ALIGN, stroke.align);
|
item.set_attribute(ATTR_ALIGN, stroke.align);
|
||||||
}
|
}
|
||||||
|
if stroke.paint_mapping != defaults.paint_mapping {
|
||||||
|
item.set_attribute(ATTR_PAINT_MAPPING, stroke.paint_mapping);
|
||||||
|
}
|
||||||
|
|
||||||
Self(item)
|
Self(item)
|
||||||
}
|
}
|
||||||
@@ -105,6 +110,7 @@ impl Coverage {
|
|||||||
ATTR_JOIN => stroke.join = value.downcast_ref().copied().unwrap_or(stroke.join),
|
ATTR_JOIN => stroke.join = value.downcast_ref().copied().unwrap_or(stroke.join),
|
||||||
ATTR_JOIN_MITER_LIMIT => stroke.join_miter_limit = value.downcast_ref().copied().unwrap_or(stroke.join_miter_limit),
|
ATTR_JOIN_MITER_LIMIT => stroke.join_miter_limit = value.downcast_ref().copied().unwrap_or(stroke.join_miter_limit),
|
||||||
ATTR_ALIGN => stroke.align = value.downcast_ref().copied().unwrap_or(stroke.align),
|
ATTR_ALIGN => stroke.align = value.downcast_ref().copied().unwrap_or(stroke.align),
|
||||||
|
ATTR_PAINT_MAPPING => stroke.paint_mapping = value.downcast_ref().copied().unwrap_or(stroke.paint_mapping),
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -305,7 +311,7 @@ mod tests {
|
|||||||
use super::*;
|
use super::*;
|
||||||
use core_types::Color;
|
use core_types::Color;
|
||||||
use glam::{DAffine2, DVec2};
|
use glam::{DAffine2, DVec2};
|
||||||
use vector_types::vector::style::{StrokeAlign, StrokeCap, StrokeJoin};
|
use vector_types::vector::style::{PaintMapping, StrokeAlign, StrokeCap, StrokeJoin};
|
||||||
|
|
||||||
fn solid_paint(color: Color) -> Graphic {
|
fn solid_paint(color: Color) -> Graphic {
|
||||||
Graphic::ColorList(List::new_from_element(color))
|
Graphic::ColorList(List::new_from_element(color))
|
||||||
@@ -327,6 +333,7 @@ mod tests {
|
|||||||
join: StrokeJoin::Bevel,
|
join: StrokeJoin::Bevel,
|
||||||
join_miter_limit: 7.,
|
join_miter_limit: 7.,
|
||||||
align: StrokeAlign::Inside,
|
align: StrokeAlign::Inside,
|
||||||
|
paint_mapping: PaintMapping::Path,
|
||||||
transform: DAffine2::IDENTITY,
|
transform: DAffine2::IDENTITY,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -341,6 +348,7 @@ mod tests {
|
|||||||
assert_eq!(extracted.join, StrokeJoin::Bevel);
|
assert_eq!(extracted.join, StrokeJoin::Bevel);
|
||||||
assert_eq!(extracted.join_miter_limit, 7.);
|
assert_eq!(extracted.join_miter_limit, 7.);
|
||||||
assert_eq!(extracted.align, StrokeAlign::Inside);
|
assert_eq!(extracted.align, StrokeAlign::Inside);
|
||||||
|
assert_eq!(extracted.paint_mapping, PaintMapping::Path);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -404,6 +412,14 @@ mod tests {
|
|||||||
let keys: Vec<_> = coverage.0.attributes().keys().collect();
|
let keys: Vec<_> = coverage.0.attributes().keys().collect();
|
||||||
assert_eq!(keys, vec![ATTR_WEIGHT], "only the non-default weight should be stamped");
|
assert_eq!(keys, vec![ATTR_WEIGHT], "only the non-default weight should be stamped");
|
||||||
assert_eq!(coverage.stroke_params().weight, 2.);
|
assert_eq!(coverage.stroke_params().weight, 2.);
|
||||||
|
|
||||||
|
let coverage = Coverage::new_stroke(&Stroke {
|
||||||
|
paint_mapping: PaintMapping::Path,
|
||||||
|
..Stroke::default()
|
||||||
|
});
|
||||||
|
let keys: Vec<_> = coverage.0.attributes().keys().collect();
|
||||||
|
assert_eq!(keys, vec![ATTR_PAINT_MAPPING], "only the non-default paint mapping should be stamped");
|
||||||
|
assert_eq!(coverage.stroke_params().paint_mapping, PaintMapping::Path);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -240,6 +240,9 @@ impl EffectCapture {
|
|||||||
/// Not an effect's coverage but the share of each pixel within the content that its fill lets what lies beneath show through,
|
/// Not an effect's coverage but the share of each pixel within the content that its fill lets what lies beneath show through,
|
||||||
/// which the parts of interior pieces blending with what lies beneath are cut to (see [`crate::effect_layers::PiecePlace::Through`]).
|
/// which the parts of interior pieces blending with what lies beneath are cut to (see [`crate::effect_layers::PiecePlace::Through`]).
|
||||||
pub const THROUGH_MASK: Self = Self { index: usize::MAX, plane: 0 };
|
pub const THROUGH_MASK: Self = Self { index: usize::MAX, plane: 0 };
|
||||||
|
|
||||||
|
/// The plane of a paint overlay or outline holding its drawn paint as the GPU renders it, for an SVG that can't draw the paint whole as markup.
|
||||||
|
pub const DRAWN_PAINT_PLANE: usize = usize::MAX;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The offset a shadow cast by light from `angle` (in degrees counterclockwise from the right) falls at `distance` from the content, in the document's y-down space.
|
/// The offset a shadow cast by light from `angle` (in degrees counterclockwise from the right) falls at `distance` from the content, in the document's y-down space.
|
||||||
@@ -329,21 +332,10 @@ pub fn bevel_lit(gradient: DVec2, light: DVec3) -> f64 {
|
|||||||
(-gradient).extend(1.).normalize().dot(light).clamp(0., 1.)
|
(-gradient).extend(1.).normalize().dot(light).clamp(0., 1.)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A bevel's highlight and shadow from 0 to 1, from how much brighter its surface is lit (after its gloss contour) than a flat surface's brightness `light_z`, negative where it's darker.
|
|
||||||
/// For PSD interop, the flat brightness stays as it is under a gloss contour, so a curve that moves it shades even flat ground.
|
|
||||||
pub fn bevel_lighting(brighter: f64, light_z: f64) -> (f64, f64) {
|
|
||||||
let highlight = if light_z < 1. { brighter / (1. - light_z) } else { 0. };
|
|
||||||
let shadow = if light_z > 0. { -brighter / light_z } else { 0. };
|
|
||||||
(highlight.clamp(0., 1.), shadow.clamp(0., 1.))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// For PSD interop, under a gloss contour or a texture a bevel's highlight and shadow beneath the content reach no more than its height before its contour divided by this,
|
/// For PSD interop, under a gloss contour or a texture a bevel's highlight and shadow beneath the content reach no more than its height before its contour divided by this,
|
||||||
/// so the flat ground they shade ends at the slopes' foot. It's the same as [`GRADIENT_GLOW_FADE`].
|
/// so the flat ground they shade ends at the slopes' foot. It's the same as [`GRADIENT_GLOW_FADE`].
|
||||||
pub const BEVEL_FOOT_FADE: f64 = 0.12;
|
pub const BEVEL_FOOT_FADE: f64 = 0.12;
|
||||||
|
|
||||||
/// For PSD interop, the offsets from each pixel toward its right and lower neighbors at which an antialiased contour samples it, nine in all.
|
|
||||||
pub const ANTIALIASED_CONTOUR_OFFSETS: [f64; 3] = [0., 1. / 3., 2. / 3.];
|
|
||||||
|
|
||||||
/// Where a bevel's height `t` (0 at the foot of its slope and 1 on its top) falls along its contour, given the `range` percentage of the slope the contour spans.
|
/// Where a bevel's height `t` (0 at the foot of its slope and 1 on its top) falls along its contour, given the `range` percentage of the slope the contour spans.
|
||||||
/// For PSD interop, an inner bevel's contour spans the range down from the top, an outer bevel's spans it up from the foot, and an emboss's spans the whole slope.
|
/// For PSD interop, an inner bevel's contour spans the range down from the top, an outer bevel's spans it up from the foot, and an emboss's spans the whole slope.
|
||||||
pub fn slope_contour_input(t: f64, style: BevelStyle, range: f64) -> f64 {
|
pub fn slope_contour_input(t: f64, style: BevelStyle, range: f64) -> f64 {
|
||||||
@@ -376,11 +368,6 @@ pub fn extended_contour(contour: &TransferCurveEvaluator, (start_slope, end_slop
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// How much a texture's color sinks a bevel's surface, from its premultiplied gamma-encoded channels: their luma, so a transparent texture leaves it flat.
|
|
||||||
pub fn texture_gray([red, green, blue, _]: [f32; 4]) -> f32 {
|
|
||||||
0.299 * red + 0.587 * green + 0.114 * blue
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The `graphic` expressed in the own space of content placed by `placement`, for an effect with a drawn graphic that follows the content (see [`EffectOperation::drawn_paint_follows_content`]).
|
/// The `graphic` expressed in the own space of content placed by `placement`, for an effect with a drawn graphic that follows the content (see [`EffectOperation::drawn_paint_follows_content`]).
|
||||||
pub fn linked_to_content(graphic: Graphic, placement: DAffine2) -> Graphic {
|
pub fn linked_to_content(graphic: Graphic, placement: DAffine2) -> Graphic {
|
||||||
if placement == DAffine2::IDENTITY || !placement.matrix2.determinant().is_normal() {
|
if placement == DAffine2::IDENTITY || !placement.matrix2.determinant().is_normal() {
|
||||||
@@ -1138,7 +1125,7 @@ pub enum EffectOperation {
|
|||||||
radius: f64,
|
radius: f64,
|
||||||
/// On a scale of 0 to 255.
|
/// On a scale of 0 to 255.
|
||||||
threshold: f64,
|
threshold: f64,
|
||||||
/// Whether the content is compared against its four nearest neighbors only along edges, as [`crate::filters::edge_gain`] ramps it, rather than against the blur.
|
/// Whether the content is compared against its four nearest neighbors only along edges, by how steep the content's Sobel gradient is, rather than against the blur.
|
||||||
edges_only: bool,
|
edges_only: bool,
|
||||||
},
|
},
|
||||||
HighPass {
|
HighPass {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
//! The definitions the filter effects share across renderers: each pixel filter as weighted copies of the content shifted by document lengths, which the CPU, GPU, and SVG each carry out.
|
//! The definitions the filter effects share across renderers: each pixel filter as weighted copies of the content shifted by document lengths, which the GPU and SVG each carry out.
|
||||||
|
|
||||||
use crate::effects::EffectOperation;
|
use crate::effects::EffectOperation;
|
||||||
use core_types::graphene_hash::CacheHash;
|
use core_types::graphene_hash::CacheHash;
|
||||||
@@ -201,12 +201,6 @@ pub const AVERAGE_VISIBILITY_RAMP: [f32; 2] = [8. / 255., 24. / 255.];
|
|||||||
/// For PSD interop, the middle gray a high pass centers its differences on, as an 8-bit level.
|
/// For PSD interop, the middle gray a high pass centers its differences on, as an 8-bit level.
|
||||||
pub const HIGH_PASS_GRAY: f32 = 128. / 255.;
|
pub const HIGH_PASS_GRAY: f32 = 128. / 255.;
|
||||||
|
|
||||||
/// How much of the visible colors' average a pixel is compared against, the rest being its own color, given how much of the blur around it lands on visible pixels.
|
|
||||||
pub fn average_weight(visibility: f32) -> f32 {
|
|
||||||
let [start, end] = AVERAGE_VISIBILITY_RAMP;
|
|
||||||
((visibility - start) / (end - start)).clamp(0., 1.)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether the filter sharpens or otherwise weighs the content's coverage, so a fill must fade its result rather than its input.
|
/// Whether the filter sharpens or otherwise weighs the content's coverage, so a fill must fade its result rather than its input.
|
||||||
pub fn sharpens_coverage(operation: &EffectOperation) -> bool {
|
pub fn sharpens_coverage(operation: &EffectOperation) -> bool {
|
||||||
matches!(operation, EffectOperation::Sharpen { .. } | EffectOperation::ConvolutionKernel { apply_to_alpha: true, .. })
|
matches!(operation, EffectOperation::Sharpen { .. } | EffectOperation::ConvolutionKernel { apply_to_alpha: true, .. })
|
||||||
@@ -215,23 +209,13 @@ pub fn sharpens_coverage(operation: &EffectOperation) -> bool {
|
|||||||
/// For PSD interop, the shifts of the four nearest neighbors in document pixels, whose average Edges Only compares each pixel against.
|
/// For PSD interop, the shifts of the four nearest neighbors in document pixels, whose average Edges Only compares each pixel against.
|
||||||
pub const SHARPEN_NEIGHBORS: [DVec2; 4] = [DVec2::new(0., -1.), DVec2::new(-1., 0.), DVec2::new(1., 0.), DVec2::new(0., 1.)];
|
pub const SHARPEN_NEIGHBORS: [DVec2; 4] = [DVec2::new(0., -1.), DVec2::new(-1., 0.), DVec2::new(1., 0.), DVec2::new(0., 1.)];
|
||||||
|
|
||||||
/// For PSD interop, the Sobel gradient lengths (as Find Edges measures them, on values from 0 to 1) between which Edges Only ramps from no change to the whole of it.
|
|
||||||
/// A step between flat areas has a quarter of that length at a sixteenth of full contrast, and its whole length at a quarter.
|
|
||||||
pub const EDGE_GAIN_RAMP: [f32; 2] = [0.25, 1.];
|
|
||||||
|
|
||||||
/// For PSD interop, the share of its change that Edges Only makes in a channel whose Sobel gradient has the length `gradient`.
|
|
||||||
pub fn edge_gain(gradient: f32) -> f32 {
|
|
||||||
let [start, end] = EDGE_GAIN_RAMP;
|
|
||||||
((gradient - start) / (end - start)).clamp(0., 1.)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What unsharp masking or a high pass compares each pixel against.
|
/// What unsharp masking or a high pass compares each pixel against.
|
||||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||||
pub enum UnsharpBlur {
|
pub enum UnsharpBlur {
|
||||||
/// A Gaussian blur with this standard deviation in document pixels.
|
/// A Gaussian blur with this standard deviation in document pixels.
|
||||||
Gaussian(f64),
|
Gaussian(f64),
|
||||||
/// For Edges Only, the average of the four nearest neighbors, [`SHARPEN_NEIGHBORS`], read between pixels where they don't land on one.
|
/// For Edges Only, the average of the four nearest neighbors, [`SHARPEN_NEIGHBORS`], read between pixels where they don't land on one.
|
||||||
/// Each channel is moved only part of the way toward it, by its [`edge_gain`], so it changes only along edges.
|
/// Each channel is moved only part of the way toward it, by how steep its Sobel gradient is, so it changes only along edges.
|
||||||
EdgeNeighbors,
|
EdgeNeighbors,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -366,24 +350,6 @@ impl FieldSampling {
|
|||||||
deviation_scale: (counts / spans).min(DVec2::ONE).element_product().sqrt(),
|
deviation_scale: (counts / spans).min(DVec2::ONE).element_product().sqrt(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The cell under the point `offset` pixels from the middle of the pixel at `pixel` (its column and row).
|
|
||||||
fn cell_at(&self, pixel: [usize; 2], offset: DVec2) -> IVec2 {
|
|
||||||
let position = DVec2::new(pixel[0] as f64, pixel[1] as f64) + 0.5 + offset;
|
|
||||||
self.origin_cell.wrapping_add((self.origin_fraction + self.pixel_axes * position).floor().as_ivec2())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The cell under the middle of the pixel at `pixel`.
|
|
||||||
pub fn center_cell(&self, pixel: [usize; 2]) -> IVec2 {
|
|
||||||
self.cell_at(pixel, DVec2::ZERO)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The cells the pixel at `pixel` samples, row by row.
|
|
||||||
pub fn sample_cells(&self, pixel: [usize; 2]) -> impl Iterator<Item = IVec2> + '_ {
|
|
||||||
let place = |index: u32, count: u32, spread: f64| ((index as f64 + 0.5) / count as f64 - 0.5) * spread;
|
|
||||||
(0..self.counts.y)
|
|
||||||
.flat_map(move |row| (0..self.counts.x).map(move |column| self.cell_at(pixel, DVec2::new(place(column, self.counts.x, self.spreads.x), place(row, self.counts.y, self.spreads.y)))))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
//! Procedural patterns described by their settings, rendered at whatever resolution is needed of whatever part is seen by the kernels of the `raster-kernels` crate.
|
//! Procedural patterns described by their settings, rendered by the GPU at whatever resolution is needed of whatever part is seen, and sampled at points by the `raster-kernels` crate.
|
||||||
|
|
||||||
use crate::parameters::{ParameterVisitor, ReadParameters, StampParameters};
|
use crate::parameters::{ParameterVisitor, ReadParameters, StampParameters};
|
||||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||||
|
|||||||
@@ -65,12 +65,9 @@ pub fn mask_feather_sigma(feather: f64) -> f64 {
|
|||||||
feather.max(0.)
|
feather.max(0.)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The alpha at or below which a feather counts content as absent, half an 8-bit level, so the faint tail of a blur doesn't count as content, though an 8-bit image's faintest alpha does.
|
|
||||||
pub const FEATHER_FOOTPRINT_ALPHA: f32 = 0.5 / 255.;
|
|
||||||
|
|
||||||
/// How far a feather of `distance` erodes the content's footprint, and the standard deviation of the Gaussian softening the eroded footprint, in the same units.
|
/// How far a feather of `distance` erodes the content's footprint, and the standard deviation of the Gaussian softening the eroded footprint, in the same units.
|
||||||
///
|
///
|
||||||
/// A feather multiplies the content by a strength made this way. The footprint is where the content's alpha exceeds [`FEATHER_FOOTPRINT_ALPHA`].
|
/// A feather multiplies the content by a strength made this way. The footprint is where the content's alpha exceeds half an 8-bit level, so the faint tail of a blur doesn't count as content, though an 8-bit image's faintest alpha does.
|
||||||
/// Its edge falls within the pixels bordering the absent area by their alpha relative to the largest beside them, so translucent content places it as opaque content does.
|
/// Its edge falls within the pixels bordering the absent area by their alpha relative to the largest beside them, so translucent content places it as opaque content does.
|
||||||
/// It is eroded by half the distance, measured in straight lines, then blurred by a Gaussian reaching three standard deviations, which end at the footprint's edge.
|
/// It is eroded by half the distance, measured in straight lines, then blurred by a Gaussian reaching three standard deviations, which end at the footprint's edge.
|
||||||
/// Across a straight edge, the strength rises along the normal distribution's cumulative curve from nothing at the edge, through half at half the distance, to full at the distance. Parts thinner than the distance fade away entirely.
|
/// Across a straight edge, the strength rises along the normal distribution's cumulative curve from nothing at the edge, through half at half the distance, to full at the distance. Parts thinner than the distance fade away entirely.
|
||||||
@@ -106,11 +103,6 @@ pub fn masked_radius_blur_levels(radius: f64, pixels_per_length: f64) -> Vec<f64
|
|||||||
std::iter::once(0.).chain(blurred).collect()
|
std::iter::once(0.).chain(blurred).collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 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::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.
|
/// 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.
|
||||||
///
|
///
|
||||||
/// Each pixel of a Gaussian masked radius blur is the sum of its levels (its content blurred by Gaussians of their radii) weighed by their parts, on premultiplied gamma-encoded channels.
|
/// Each pixel of a Gaussian masked radius blur is the sum of its levels (its content blurred by Gaussians of their radii) weighed by their parts, on premultiplied gamma-encoded channels.
|
||||||
|
|||||||
@@ -1302,12 +1302,6 @@ pub fn source_within_frame(edge_mode: GradientSpread, source: DVec2, size: DVec2
|
|||||||
/// The most pixels a pixelation tests one by one for one of its cells or dots, past which it sums each row's run of them at once, so a vast cell at a deep zoom stays affordable.
|
/// The most pixels a pixelation tests one by one for one of its cells or dots, past which it sums each row's run of them at once, so a vast cell at a deep zoom stays affordable.
|
||||||
pub const MAX_AVERAGED_PIXELS: f64 = 65_536.;
|
pub const MAX_AVERAGED_PIXELS: f64 = 65_536.;
|
||||||
|
|
||||||
/// How many pixels from the image's origin a pixelation's averaging scans at most along each axis, past which single-precision pixel centers aren't exact, so a vast cell or dot ends its scan there.
|
|
||||||
pub const MAX_AVERAGED_PIXEL_COORDINATE: f64 = 16_777_216.;
|
|
||||||
|
|
||||||
/// How many rows past the image's top and bottom a pixelation counts for a cell or dot one by one, past which each it counts stands for those beside it, since they hold only transparency.
|
|
||||||
pub const MAX_COUNTED_ROWS: f64 = 4096.;
|
|
||||||
|
|
||||||
/// For PSD interop, the area of a disc of `radius` clipped to the square cell `side` across that it's centered in.
|
/// For PSD interop, the area of a disc of `radius` clipped to the square cell `side` across that it's centered in.
|
||||||
pub fn disc_in_cell_area(radius: f64, side: f64) -> f64 {
|
pub fn disc_in_cell_area(radius: f64, side: f64) -> f64 {
|
||||||
let half = side / 2.;
|
let half = side / 2.;
|
||||||
|
|||||||
@@ -25,6 +25,4 @@ vector-types = { workspace = true }
|
|||||||
# Workspace dependencies
|
# Workspace dependencies
|
||||||
fastnoise-lite = { workspace = true }
|
fastnoise-lite = { workspace = true }
|
||||||
glam = { workspace = true }
|
glam = { workspace = true }
|
||||||
half = { workspace = true }
|
|
||||||
log = { workspace = true }
|
|
||||||
thiserror = { workspace = true }
|
thiserror = { workspace = true }
|
||||||
@@ -11,6 +11,7 @@ use core_types::transfer_curve::TransferCurveEvaluator;
|
|||||||
use glam::Vec3;
|
use glam::Vec3;
|
||||||
use graphic_types::adjustment::{self as settings, Adjustment, DesaturateMethod, RelativeAbsolute};
|
use graphic_types::adjustment::{self as settings, Adjustment, DesaturateMethod, RelativeAbsolute};
|
||||||
use raster_types::parallel_rows::fill_rows;
|
use raster_types::parallel_rows::fill_rows;
|
||||||
|
use raster_types::{CPU, Raster};
|
||||||
use std::iter::once;
|
use std::iter::once;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use vector_types::gradient::{GradientEvaluator, SplineKnots, interpolation_endpoints};
|
use vector_types::gradient::{GradientEvaluator, SplineKnots, interpolation_endpoints};
|
||||||
@@ -36,6 +37,20 @@ pub fn adjust_colors(adjustment: &Adjustment, colors: &mut [Color]) {
|
|||||||
visit_kernel(adjustment, AdjustColors(colors));
|
visit_kernel(adjustment, AdjustColors(colors));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The raster with `adjustments` carried out on its colors, even those of transparent pixels, as for the adjustments leading its effects.
|
||||||
|
/// The result is kept with the raster's pixels, so adjusting them the same way again reuses it, ID and all.
|
||||||
|
pub fn adjusted_raster(raster: &Raster<CPU>, adjustments: &[Adjustment]) -> Raster<CPU> {
|
||||||
|
let mut hasher = std::hash::DefaultHasher::new();
|
||||||
|
adjustments.iter().for_each(|adjustment| core_types::graphene_hash::CacheHash::cache_hash(adjustment, &mut hasher));
|
||||||
|
let key = std::hash::Hasher::finish(&hasher);
|
||||||
|
|
||||||
|
raster.derived(key, |raster| {
|
||||||
|
let mut image = raster.data().clone();
|
||||||
|
adjustments.iter().for_each(|adjustment| adjust_colors(adjustment, &mut image.data));
|
||||||
|
Raster::new_cpu(image)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
/// The color with `adjustment` carried out on it. To adjust many colors one at a time, prepare a [`PreparedAdjustment`] once instead.
|
/// The color with `adjustment` carried out on it. To adjust many colors one at a time, prepare a [`PreparedAdjustment`] once instead.
|
||||||
pub fn adjust_color(adjustment: &Adjustment, color: Color) -> Color {
|
pub fn adjust_color(adjustment: &Adjustment, color: Color) -> Color {
|
||||||
struct AdjustColor(Color);
|
struct AdjustColor(Color);
|
||||||
|
|||||||
@@ -1,579 +0,0 @@
|
|||||||
//! The image operations that effects are built from, on the CPU: blurring, growing shapes, and shifting.
|
|
||||||
//! They mirror the renderer's GPU passes, so a raster's effects read the same in a node that needs its pixels as on the canvas.
|
|
||||||
|
|
||||||
use raster_types::parallel_rows::fill_rows;
|
|
||||||
|
|
||||||
/// Blurs and spreads shorter than this, in pixels, leave no visible trace.
|
|
||||||
pub const NEGLIGIBLE_LENGTH: f64 = 0.01;
|
|
||||||
|
|
||||||
/// The largest Gaussian standard deviation, in pixels, convolved on the image itself rather than a halved copy.
|
|
||||||
pub const MAX_DIRECT_GAUSSIAN_SIGMA: f64 = 8.;
|
|
||||||
|
|
||||||
/// The largest box or tent half width, in pixels, convolved on the image itself rather than a halved copy.
|
|
||||||
pub const MAX_DIRECT_BOX_RADIUS: f64 = 24.;
|
|
||||||
|
|
||||||
/// The farthest texel from the center a kernel weighs, which fits every direct limit.
|
|
||||||
pub const MAX_KERNEL_REACH: usize = 24;
|
|
||||||
|
|
||||||
/// The most times an image is halved for a blur, by which point it is one pixel across.
|
|
||||||
const MAX_LEVELS: u32 = 16;
|
|
||||||
|
|
||||||
/// How many passes after jump flooding to `reach` look for nearer seeds through the neighbors one chamfer step away, which settles the near misses within about 20 pixels.
|
|
||||||
/// Since a chamfer length is the shortest path of such steps, a pixel whose neighbor along that path found the nearest seed finds it too.
|
|
||||||
pub fn chamfer_passes(reach: f64) -> usize {
|
|
||||||
if reach > 16. { 4 } else { 2 }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The steps of a chamfer path (one pixel straight or diagonally, or a knight's move) by rows from the top, the order the GPU visits them in too.
|
|
||||||
const CHAMFER_STEPS: [[i32; 2]; 16] = [
|
|
||||||
[-1, -2],
|
|
||||||
[1, -2],
|
|
||||||
[-2, -1],
|
|
||||||
[-1, -1],
|
|
||||||
[0, -1],
|
|
||||||
[1, -1],
|
|
||||||
[2, -1],
|
|
||||||
[-1, 0],
|
|
||||||
[1, 0],
|
|
||||||
[-2, 1],
|
|
||||||
[-1, 1],
|
|
||||||
[0, 1],
|
|
||||||
[1, 1],
|
|
||||||
[2, 1],
|
|
||||||
[-1, 2],
|
|
||||||
[1, 2],
|
|
||||||
];
|
|
||||||
|
|
||||||
/// A blur's kernel along one axis, sized in pixels.
|
|
||||||
#[derive(Clone, Copy, Debug)]
|
|
||||||
pub enum BlurKernel {
|
|
||||||
Gaussian {
|
|
||||||
sigma: f64,
|
|
||||||
},
|
|
||||||
Box {
|
|
||||||
radius: f64,
|
|
||||||
},
|
|
||||||
/// Weighs each texel by how far short of `radius` it lies, the shape of two box blurs of that width in a row.
|
|
||||||
Tent {
|
|
||||||
radius: f64,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
impl BlurKernel {
|
|
||||||
/// How many times the image is halved before the kernel runs, so the kernel stays within [`MAX_KERNEL_REACH`].
|
|
||||||
pub fn levels(self) -> u32 {
|
|
||||||
let (length, direct_limit) = match self {
|
|
||||||
Self::Gaussian { sigma } => (sigma, MAX_DIRECT_GAUSSIAN_SIGMA),
|
|
||||||
Self::Box { radius } | Self::Tent { radius } => (radius, MAX_DIRECT_BOX_RADIUS),
|
|
||||||
};
|
|
||||||
|
|
||||||
(length / direct_limit).log2().ceil().clamp(0., MAX_LEVELS as f64) as u32
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The weights of the texels from the center outward for an image halved `levels` times, normalized so the symmetric kernel sums to 1.
|
|
||||||
pub fn weights(self, levels: u32) -> Vec<f64> {
|
|
||||||
let level_scale = (1 << levels) as f64;
|
|
||||||
|
|
||||||
let weights: Vec<f64> = match self {
|
|
||||||
Self::Gaussian { sigma } => {
|
|
||||||
// Halving the image and doubling it back blur it too, so the kernel makes up only the rest of the variance
|
|
||||||
let pyramid_variance = (4_f64.powi(levels as i32) - 1.) / 3.;
|
|
||||||
let sigma = (sigma * sigma - pyramid_variance).max(0.).sqrt() / level_scale;
|
|
||||||
if sigma < NEGLIGIBLE_LENGTH {
|
|
||||||
return vec![1.];
|
|
||||||
}
|
|
||||||
|
|
||||||
let reach = ((3. * sigma).ceil() as usize).min(MAX_KERNEL_REACH);
|
|
||||||
(0..=reach).map(|i| (-((i * i) as f64) / (2. * sigma * sigma)).exp()).collect()
|
|
||||||
}
|
|
||||||
Self::Box { radius } => {
|
|
||||||
let radius = radius / level_scale;
|
|
||||||
let reach = (radius.ceil() as usize).min(MAX_KERNEL_REACH);
|
|
||||||
(0..=reach).map(|i| box_weight(radius, i)).collect()
|
|
||||||
}
|
|
||||||
Self::Tent { radius } => {
|
|
||||||
let radius = radius / level_scale;
|
|
||||||
if radius <= 1. {
|
|
||||||
return vec![1.];
|
|
||||||
}
|
|
||||||
|
|
||||||
let reach = (radius.ceil() as usize).min(MAX_KERNEL_REACH);
|
|
||||||
(0..=reach).map(|i| (radius - i as f64).max(0.)).collect()
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let total = weights[0] + 2. * weights[1..].iter().sum::<f64>();
|
|
||||||
weights.into_iter().map(|weight| weight / total).collect()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// How much a box of half width `radius` weighs the texel `distance` from its center, before normalizing: all of it within the box,
|
|
||||||
/// and at each end the fraction of it the box covers, so the blur grows smoothly with its radius.
|
|
||||||
pub fn box_weight(radius: f64, distance: usize) -> f64 {
|
|
||||||
(radius + 1. - distance as f64).clamp(0., 1.)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The greatest channel value a variable box blur counts, past 1 to keep bright high dynamic range values, which `vello_masks.wgsl` matches.
|
|
||||||
pub const VARIABLE_BOX_MAX_VALUE: f32 = 16.;
|
|
||||||
|
|
||||||
/// How many steps from 0 to 1 a variable box blur counts each channel of an image of `pixels` in, up to [`VARIABLE_BOX_MAX_VALUE`].
|
|
||||||
/// The GPU's running sums of those counts then stay exact in f32 digits (see `RUNNING_SUM_DIGIT` in `vello_masks.wgsl`): 2^12 up to 8192 by 8192 pixels, halving for each doubling past it.
|
|
||||||
pub fn variable_box_scale(pixels: usize) -> f64 {
|
|
||||||
let pixel_bits = (pixels.max(1) as f64).log2().ceil();
|
|
||||||
2_f64.powf((38. - pixel_bits).clamp(0., 12.))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A pixel value the operations can weigh, sum, and compare: one coverage channel, or premultiplied color channels.
|
|
||||||
pub trait Sample: Copy + Default + Send + Sync {
|
|
||||||
fn scaled(self, factor: f32) -> Self;
|
|
||||||
fn plus(self, other: Self) -> Self;
|
|
||||||
fn max(self, other: Self) -> Self;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Sample for f32 {
|
|
||||||
fn scaled(self, factor: f32) -> Self {
|
|
||||||
self * factor
|
|
||||||
}
|
|
||||||
fn plus(self, other: Self) -> Self {
|
|
||||||
self + other
|
|
||||||
}
|
|
||||||
fn max(self, other: Self) -> Self {
|
|
||||||
f32::max(self, other)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Sample for [f32; 4] {
|
|
||||||
fn scaled(self, factor: f32) -> Self {
|
|
||||||
self.map(|channel| channel * factor)
|
|
||||||
}
|
|
||||||
fn plus(self, other: Self) -> Self {
|
|
||||||
std::array::from_fn(|channel| self[channel] + other[channel])
|
|
||||||
}
|
|
||||||
fn max(self, other: Self) -> Self {
|
|
||||||
std::array::from_fn(|channel| self[channel].max(other[channel]))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An image of [`Sample`]s in rows, which the operations read and write.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub struct Plane<T> {
|
|
||||||
pub width: usize,
|
|
||||||
pub height: usize,
|
|
||||||
pub data: Vec<T>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: Sample> Plane<T> {
|
|
||||||
pub fn new(width: usize, height: usize) -> Self {
|
|
||||||
Self {
|
|
||||||
width,
|
|
||||||
height,
|
|
||||||
data: vec![T::default(); width * height],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A plane of the same size whose pixels are `map` of this one's.
|
|
||||||
pub fn map<U: Sample>(&self, map: impl Fn(T) -> U + Sync) -> Plane<U> {
|
|
||||||
let mut mapped = Plane::new(self.width, self.height);
|
|
||||||
fill_rows(&mut mapped.data, self.width, |y, row| {
|
|
||||||
let source = &self.data[y * self.width..(y + 1) * self.width];
|
|
||||||
row.iter_mut().zip(source).for_each(|(target, &value)| *target = map(value));
|
|
||||||
});
|
|
||||||
mapped
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Combines this plane with `other`, of the same size, pixel by pixel.
|
|
||||||
pub fn zip<U: Sample, V: Sample>(&self, other: &Plane<U>, combine: impl Fn(T, U) -> V + Sync) -> Plane<V> {
|
|
||||||
let mut combined = Plane::new(self.width, self.height);
|
|
||||||
fill_rows(&mut combined.data, self.width, |y, row| {
|
|
||||||
let range = y * self.width..(y + 1) * self.width;
|
|
||||||
let pairs = self.data[range.clone()].iter().zip(&other.data[range]);
|
|
||||||
row.iter_mut().zip(pairs).for_each(|(target, (&a, &b))| *target = combine(a, b));
|
|
||||||
});
|
|
||||||
combined
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The plane with its rows and columns swapped, so a horizontal operation can work vertically. O(width × height).
|
|
||||||
pub(crate) fn transposed(&self) -> Self {
|
|
||||||
let mut transposed = Self::new(self.height, self.width);
|
|
||||||
fill_rows(&mut transposed.data, self.height, |x, row| {
|
|
||||||
row.iter_mut().enumerate().for_each(|(y, target)| *target = self.data[y * self.width + x]);
|
|
||||||
});
|
|
||||||
transposed
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Runs `operation` on each row, which it reads in full and writes as a new row of `width` pixels.
|
|
||||||
fn map_rows(&self, width: usize, operation: impl Fn(&[T], &mut [T]) + Sync) -> Self {
|
|
||||||
let mut result = Self::new(width, self.height);
|
|
||||||
fill_rows(&mut result.data, width, |y, row| operation(&self.data[y * self.width..(y + 1) * self.width], row));
|
|
||||||
result
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Runs `along_rows` on the plane's rows, then on its columns by way of one transpose there and back.
|
|
||||||
fn along_both_axes<P>(self, horizontal: P, vertical: P, along_rows: impl Fn(Self, P) -> Self) -> Self {
|
|
||||||
let plane = along_rows(self, horizontal);
|
|
||||||
along_rows(plane.transposed(), vertical).transposed()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Blurs the plane by a kernel along each axis. Kernels too wide to convolve directly run on a copy halved along their axis enough times
|
|
||||||
/// for them to fit, then doubled back. O(width × height) per pass, with a pass for each halving and doubling.
|
|
||||||
pub fn blurred(self, horizontal: BlurKernel, vertical: BlurKernel) -> Self {
|
|
||||||
self.along_both_axes(horizontal, vertical, |mut plane, kernel| {
|
|
||||||
let levels = kernel.levels();
|
|
||||||
let length = plane.width;
|
|
||||||
let level_length = |level: u32| length.div_ceil(1 << level);
|
|
||||||
|
|
||||||
for level in 1..=levels {
|
|
||||||
plane = plane.map_rows(level_length(level), halve_row);
|
|
||||||
}
|
|
||||||
|
|
||||||
let weights = kernel.weights(levels);
|
|
||||||
plane = plane.map_rows(level_length(levels), |source, target| convolve_row(source, target, &weights));
|
|
||||||
|
|
||||||
for level in (0..levels).rev() {
|
|
||||||
plane = plane.map_rows(level_length(level), double_row);
|
|
||||||
}
|
|
||||||
plane
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Moves the image by a fractional offset in pixels, interpolating between pixels and leaving transparency where it uncovers the edges.
|
|
||||||
pub fn shifted(self, offset_x: f64, offset_y: f64) -> Self {
|
|
||||||
self.along_both_axes(offset_x, offset_y, |plane, offset| plane.map_rows(plane.width, |source, target| shift_row(source, target, offset)))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The length of a whole-pixel offset along the shortest path of steps one pixel straight, one diagonally, or a knight's move away.
|
|
||||||
/// For PSD interop, layer styles measure distances this way, which rounds the corners they grow around into 16 sides rather than a circle.
|
|
||||||
pub fn chamfer_length([x, y]: [i32; 2]) -> f32 {
|
|
||||||
let (long, short) = (x.abs().max(y.abs()) as f32, x.abs().min(y.abs()) as f32);
|
|
||||||
match 2. * short <= long {
|
|
||||||
// Knight's moves and straight steps
|
|
||||||
true => (long - 2. * short) + 5_f32.sqrt() * short,
|
|
||||||
// Knight's moves and diagonal steps
|
|
||||||
false => 5_f32.sqrt() * (long - short) + std::f32::consts::SQRT_2 * (2. * short - long),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Plane<f32> {
|
|
||||||
/// Each pixel's distance to the silhouette's edge plus half a pixel, so a pixel beside a fully covered one lies one away and covered ones none, or infinity past `reach`.
|
|
||||||
/// Distances run by [`chamfer_length`] to the nearest covered pixel, then by its uncovered share within it, placing an antialiased edge between pixels.
|
|
||||||
pub fn distances_to_silhouette(&self, reach: f64) -> Self {
|
|
||||||
self.jump_flood(reach, |coverage| coverage > 0., |offset, coverage| chamfer_length(offset) + (0.5 - coverage) + 0.5)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Each pixel's least [`chamfer_length`] to a seed plus the seed's own value, where the seeds are the pixels with finite values, or infinity past `reach`.
|
|
||||||
pub fn distances_through_seeds(&self, reach: f64) -> Self {
|
|
||||||
self.jump_flood(reach, f32::is_finite, |offset, value| chamfer_length(offset) + value)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Each pixel's least `distance` to a seed, given its offset from the seed and the seed's value, or infinity past `reach`.
|
|
||||||
/// Jump flooding finds them in a pass for each halving of a step that starts past `reach`, so farther pixels may find none.
|
|
||||||
/// Seeds of differing values leave near misses, mostly settled by two more halving passes and then those of [`chamfer_passes`] along the chamfer steps. O(width × height × log(reach)).
|
|
||||||
pub(crate) fn jump_flood(&self, reach: f64, is_seed: impl Fn(f32) -> bool, distance: impl Fn([i32; 2], f32) -> f32 + Sync) -> Self {
|
|
||||||
let mut nearest: Vec<Option<[i32; 2]>> = self.data.iter().map(|&value| is_seed(value).then_some([0, 0])).collect();
|
|
||||||
|
|
||||||
let (columns, rows) = (self.width as i32, self.height as i32);
|
|
||||||
// The offset runs from the seed to the pixel
|
|
||||||
let distance = |x: i32, y: i32, offset: [i32; 2]| distance(offset, self.data[((y - offset[1]) * columns + x - offset[0]) as usize]);
|
|
||||||
|
|
||||||
// The neighbors each pass looks at in the GPU's order: the eight a step away, then those one chamfer step away
|
|
||||||
let first_step = (reach.clamp(0., (columns.max(rows)) as f64).ceil() as u32 + 1).next_power_of_two() as i32;
|
|
||||||
let halvings = std::iter::successors(Some(first_step), |&step| (step > 1).then_some(step / 2)).chain([2, 1]);
|
|
||||||
let adjacent = CHAMFER_STEPS.iter().filter(|[x, y]| x.abs().max(y.abs()) == 1);
|
|
||||||
let around = |step: i32| adjacent.clone().map(|&[x, y]| [x * step, y * step]).collect::<Vec<_>>();
|
|
||||||
let passes = halvings.map(around).chain(std::iter::repeat_n(CHAMFER_STEPS.to_vec(), chamfer_passes(reach)));
|
|
||||||
|
|
||||||
for neighbors in passes {
|
|
||||||
let previous = nearest.clone();
|
|
||||||
|
|
||||||
// Each pixel keeps the nearest of the seeds that it and its neighbors have found so far
|
|
||||||
fill_rows(&mut nearest, self.width, |y, row| {
|
|
||||||
let y = y as i32;
|
|
||||||
for (x, best) in row.iter_mut().enumerate() {
|
|
||||||
let x = x as i32;
|
|
||||||
let mut best_distance = best.map_or(f32::INFINITY, |offset| distance(x, y, offset));
|
|
||||||
|
|
||||||
for &[neighbor_x, neighbor_y] in &neighbors {
|
|
||||||
let (from_x, from_y) = (x + neighbor_x, y + neighbor_y);
|
|
||||||
if from_x < 0 || from_y < 0 || from_x >= columns || from_y >= rows {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let Some([offset_x, offset_y]) = previous[(from_y * columns + from_x) as usize] else { continue };
|
|
||||||
|
|
||||||
let candidate = [offset_x - neighbor_x, offset_y - neighbor_y];
|
|
||||||
let candidate_distance = distance(x, y, candidate);
|
|
||||||
if candidate_distance < best_distance {
|
|
||||||
*best = Some(candidate);
|
|
||||||
best_distance = candidate_distance;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
let data = nearest
|
|
||||||
.into_iter()
|
|
||||||
.enumerate()
|
|
||||||
.map(|(index, offset)| offset.map_or(f32::INFINITY, |offset| distance(index as i32 % columns, index as i32 / columns, offset).max(0.)))
|
|
||||||
.collect();
|
|
||||||
Self {
|
|
||||||
width: self.width,
|
|
||||||
height: self.height,
|
|
||||||
data,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The silhouette grown outward by `distance` pixels, measured by [`chamfer_length`] so it rounds the corners it grows around.
|
|
||||||
/// The grown edge lies half a pixel short of the farthest pixel center it reaches past, and fades out over one pixel.
|
|
||||||
pub fn grown(&self, distance: f64) -> Self {
|
|
||||||
let reach = distance as f32 + 1.;
|
|
||||||
self.distances_to_silhouette(distance + 1.).map(|nearest| (reach - nearest).clamp(0., 1.))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The row's value at a position measured in pixels from the first pixel's center, interpolating linearly and holding the end pixels beyond the ends.
|
|
||||||
fn sample_row<T: Sample>(row: &[T], position: f64) -> T {
|
|
||||||
let last = row.len() as f64 - 1.;
|
|
||||||
let position = position.clamp(0., last.max(0.));
|
|
||||||
let index = position.floor() as usize;
|
|
||||||
let fraction = (position - index as f64) as f32;
|
|
||||||
|
|
||||||
match row.get(index + 1) {
|
|
||||||
Some(&next) if fraction > 0. => row[index].scaled(1. - fraction).plus(next.scaled(fraction)),
|
|
||||||
_ => row[index],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Halves the row by averaging each pair of pixels, the last pixel of an odd row pairing with itself.
|
|
||||||
fn halve_row<T: Sample>(source: &[T], target: &mut [T]) {
|
|
||||||
for (index, value) in target.iter_mut().enumerate() {
|
|
||||||
let first = source[2 * index];
|
|
||||||
let second = source.get(2 * index + 1).copied().unwrap_or(first);
|
|
||||||
*value = first.plus(second).scaled(0.5);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Doubles a halved row back to its length, interpolating at each pixel's center within the pair it was averaged into.
|
|
||||||
fn double_row<T: Sample>(source: &[T], target: &mut [T]) {
|
|
||||||
for (index, value) in target.iter_mut().enumerate() {
|
|
||||||
*value = sample_row(source, index as f64 / 2. - 0.25);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Weighs each pixel's neighbors by the symmetric kernel `weights`, from the center outward, holding the end pixels beyond the ends.
|
|
||||||
fn convolve_row<T: Sample>(source: &[T], target: &mut [T], weights: &[f64]) {
|
|
||||||
let last = source.len() as isize - 1;
|
|
||||||
let at = |index: isize| source[index.clamp(0, last) as usize];
|
|
||||||
|
|
||||||
for (index, value) in target.iter_mut().enumerate() {
|
|
||||||
let index = index as isize;
|
|
||||||
let mut sum = at(index).scaled(weights[0] as f32);
|
|
||||||
for (distance, &weight) in weights.iter().enumerate().skip(1) {
|
|
||||||
let pair = at(index - distance as isize).plus(at(index + distance as isize));
|
|
||||||
sum = sum.plus(pair.scaled(weight as f32));
|
|
||||||
}
|
|
||||||
*value = sum;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Moves the row by `offset` pixels, with nothing beyond its ends.
|
|
||||||
fn shift_row<T: Sample>(source: &[T], target: &mut [T], offset: f64) {
|
|
||||||
let length = source.len() as f64;
|
|
||||||
for (index, value) in target.iter_mut().enumerate() {
|
|
||||||
let position = index as f64 - offset;
|
|
||||||
let floor = position.floor();
|
|
||||||
let fraction = (position - floor) as f32;
|
|
||||||
|
|
||||||
let at = |index: f64| if index >= 0. && index < length { source[index as usize] } else { T::default() };
|
|
||||||
*value = at(floor).scaled(1. - fraction).plus(at(floor + 1.).scaled(fraction));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn kernel_weights_sum_to_one() {
|
|
||||||
for kernel in [
|
|
||||||
BlurKernel::Gaussian { sigma: 3. },
|
|
||||||
BlurKernel::Gaussian { sigma: 40. },
|
|
||||||
BlurKernel::Box { radius: 5.5 },
|
|
||||||
BlurKernel::Box { radius: 100. },
|
|
||||||
] {
|
|
||||||
let levels = kernel.levels();
|
|
||||||
let weights = kernel.weights(levels);
|
|
||||||
let total = weights[0] + 2. * weights[1..].iter().sum::<f64>();
|
|
||||||
|
|
||||||
assert!((total - 1.).abs() < 1e-9, "{kernel:?} weights sum to {total}");
|
|
||||||
assert!(weights.len() <= MAX_KERNEL_REACH + 1, "{kernel:?} reaches {} texels", weights.len());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn small_kernels_run_without_halving() {
|
|
||||||
assert_eq!(BlurKernel::Gaussian { sigma: MAX_DIRECT_GAUSSIAN_SIGMA }.levels(), 0);
|
|
||||||
assert_eq!(
|
|
||||||
BlurKernel::Gaussian {
|
|
||||||
sigma: MAX_DIRECT_GAUSSIAN_SIGMA * 1.01
|
|
||||||
}
|
|
||||||
.levels(),
|
|
||||||
1
|
|
||||||
);
|
|
||||||
assert_eq!(BlurKernel::Box { radius: 1. }.levels(), 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn gaussian_blur_spreads_a_point_with_the_requested_deviation() {
|
|
||||||
// A single bright pixel blurs into the Gaussian itself, whose variance the pyramid must preserve at every level count
|
|
||||||
for sigma in [2., 20.] {
|
|
||||||
let size = 401;
|
|
||||||
let mut plane = Plane::<f32>::new(size, 1);
|
|
||||||
plane.data[size / 2] = 1.;
|
|
||||||
|
|
||||||
let blurred = plane.blurred(BlurKernel::Gaussian { sigma }, BlurKernel::Gaussian { sigma: 0. });
|
|
||||||
let total: f32 = blurred.data.iter().sum();
|
|
||||||
let variance: f64 = blurred.data.iter().enumerate().map(|(x, &value)| value as f64 * (x as f64 - (size / 2) as f64).powi(2)).sum::<f64>() / total as f64;
|
|
||||||
|
|
||||||
assert!((total - 1.).abs() < 1e-3, "sigma {sigma} keeps the total at {total}");
|
|
||||||
assert!((variance.sqrt() - sigma).abs() / sigma < 0.05, "sigma {sigma} spreads to a deviation of {}", variance.sqrt());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn tents_weigh_texels_by_how_far_short_of_the_radius_they_lie() {
|
|
||||||
// For PSD interop, a size of 16 weighs the texels 16, 15, ..., 1 from the center outward
|
|
||||||
let weights = BlurKernel::Tent { radius: 16. }.weights(0);
|
|
||||||
assert_eq!(weights.len(), 17);
|
|
||||||
for (distance, &weight) in weights.iter().enumerate() {
|
|
||||||
assert!((weight - (16 - distance) as f64 / 256.).abs() < 1e-12, "texel {distance} weighs {weight}");
|
|
||||||
}
|
|
||||||
|
|
||||||
// A straight edge blurred by it reaches (S - i)(S + 1 - i) / 2S² at the i-th pixel past the edge
|
|
||||||
let mut plane = Plane::<f32>::new(64, 1);
|
|
||||||
plane.data[..32].fill(1.);
|
|
||||||
let blurred = plane.blurred(BlurKernel::Tent { radius: 16. }, BlurKernel::Tent { radius: 0. });
|
|
||||||
for i in 1..17 {
|
|
||||||
let expected = ((16 - i) * (17 - i)) as f32 / 512.;
|
|
||||||
assert!((blurred.data[31 + i] - expected).abs() < 1e-6, "pixel {i} past the edge is {}", blurred.data[31 + i]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn growing_rounds_the_corners_it_grows_around() {
|
|
||||||
// A single pixel grows into a disk the distance across, rather than a square
|
|
||||||
let mut point = Plane::<f32>::new(21, 21);
|
|
||||||
point.data[10 * 21 + 10] = 1.;
|
|
||||||
let grown = point.grown(5.);
|
|
||||||
let at = |x: usize, y: usize| grown.data[y * 21 + x];
|
|
||||||
|
|
||||||
assert_eq!(at(15, 10), 1., "the full distance along an axis");
|
|
||||||
assert_eq!(at(16, 10), 0., "past the distance");
|
|
||||||
assert_eq!(at(15, 14), 0., "past the distance diagonally, where a square would still reach");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn chamfer_lengths_are_exact_along_their_steps() {
|
|
||||||
assert_eq!(chamfer_length([7, 0]), 7.);
|
|
||||||
assert!((chamfer_length([-4, 4]) - 4. * std::f32::consts::SQRT_2).abs() < 1e-5);
|
|
||||||
assert!((chamfer_length([2, -1]) - 5_f32.sqrt()).abs() < 1e-6);
|
|
||||||
// Between the steps, the path runs a little longer than a straight line
|
|
||||||
assert!((chamfer_length([3, 1]) - (1. + 5_f32.sqrt())).abs() < 1e-6);
|
|
||||||
assert!((chamfer_length([3, 2]) - (5_f32.sqrt() + std::f32::consts::SQRT_2)).abs() < 1e-6);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn distances_reach_no_farther_than_asked() {
|
|
||||||
let mut plane = Plane::<f32>::new(64, 1);
|
|
||||||
plane.data[0] = 1.;
|
|
||||||
let distances = plane.distances_to_silhouette(8.);
|
|
||||||
|
|
||||||
assert_eq!(distances.data[0], 0.);
|
|
||||||
assert_eq!(distances.data[5], 5.);
|
|
||||||
assert!(
|
|
||||||
distances.data[63].is_infinite() || distances.data[63] == 63.,
|
|
||||||
"a pixel far past the reach finds no seed or the true one"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn distances_from_seeds_of_differing_values_are_exact_within_their_reach() {
|
|
||||||
// An antialiased disk whose edge pixels seed with head starts set by their coverage away from half, as a Soft Chisel bevel's do
|
|
||||||
let side = 40;
|
|
||||||
let disk = Plane {
|
|
||||||
width: side,
|
|
||||||
height: side,
|
|
||||||
data: (0..side * side)
|
|
||||||
.map(|index| {
|
|
||||||
let (x, y) = ((index % side) as f64 + 0.5 - 20.3, (index / side) as f64 + 0.5 - 19.6);
|
|
||||||
(12.5 - (x * x + y * y).sqrt()).clamp(0., 1.) as f32
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
};
|
|
||||||
let head_starts = disk.map(|alpha| ((alpha - 0.5) * 22.).max(0.));
|
|
||||||
let reach = 11.;
|
|
||||||
|
|
||||||
// O(n²) over the pixel pairs, small enough here
|
|
||||||
let exactly = |values: &Plane<f32>, distance: &dyn Fn([i32; 2], f32) -> Option<f32>| {
|
|
||||||
(0..side * side)
|
|
||||||
.map(|index| {
|
|
||||||
let (x, y) = ((index % side) as i32, (index / side) as i32);
|
|
||||||
let candidates = (0..side * side).filter_map(|from| {
|
|
||||||
let offset = [x - (from % side) as i32, y - (from / side) as i32];
|
|
||||||
distance(offset, values.data[from])
|
|
||||||
});
|
|
||||||
candidates.fold(f32::INFINITY, f32::min)
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
};
|
|
||||||
|
|
||||||
let found = head_starts.distances_through_seeds(reach);
|
|
||||||
let exact = exactly(&head_starts, &|offset, value| Some(chamfer_length(offset) + value));
|
|
||||||
let found_edges = disk.distances_to_silhouette(reach);
|
|
||||||
let exact_edges = exactly(&disk, &|offset, coverage| (coverage > 0.).then(|| chamfer_length(offset) + 1. - coverage));
|
|
||||||
|
|
||||||
for index in 0..side * side {
|
|
||||||
if exact[index] <= reach as f32 {
|
|
||||||
assert!(
|
|
||||||
(found.data[index] - exact[index]).abs() < 1e-4,
|
|
||||||
"pixel {index} lies {} from the seeds, not {}",
|
|
||||||
found.data[index],
|
|
||||||
exact[index]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if exact_edges[index] <= reach as f32 {
|
|
||||||
assert!(
|
|
||||||
(found_edges.data[index] - exact_edges[index]).abs() < 1e-4,
|
|
||||||
"pixel {index} lies {} from the edge, not {}",
|
|
||||||
found_edges.data[index],
|
|
||||||
exact_edges[index]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn growing_the_outside_inward_covers_only_the_band_along_the_edges() {
|
|
||||||
let mut square = Plane::<f32>::new(21, 21);
|
|
||||||
for y in 2..19 {
|
|
||||||
square.data[y * 21 + 2..y * 21 + 19].fill(1.);
|
|
||||||
}
|
|
||||||
let inward = square.map(|coverage| 1. - coverage).grown(3.);
|
|
||||||
let at = |x: usize, y: usize| inward.data[y * 21 + x];
|
|
||||||
|
|
||||||
assert_eq!(at(2, 10), 1., "at the edge");
|
|
||||||
assert_eq!(at(4, 10), 1., "the band's full width in");
|
|
||||||
assert_eq!(at(5, 10), 0., "past the band's width");
|
|
||||||
assert_eq!(at(10, 10), 0., "deep inside");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn shifting_moves_by_fractions_of_a_pixel() {
|
|
||||||
let mut plane = Plane::<f32>::new(4, 1);
|
|
||||||
plane.data[1] = 1.;
|
|
||||||
|
|
||||||
let shifted = plane.shifted(0.25, 0.);
|
|
||||||
|
|
||||||
assert_eq!(shifted.data, vec![0., 0.75, 0.25, 0.]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,432 @@
|
|||||||
|
//! How the effects' GPU passes are planned from their settings: blur kernels and the halvings they run on, the limits of other passes, motion blur shears, and the cells of pixelations and halftones.
|
||||||
|
//! SVG's filters size their blurs by some of these too.
|
||||||
|
|
||||||
|
use glam::{DMat2, DVec2};
|
||||||
|
use graphic_types::filters::fill_shifts;
|
||||||
|
use graphic_types::resampling::{EffectFrame, HalftoneScreen, PIXELATE_TIE_NUDGE, tie_nudge};
|
||||||
|
|
||||||
|
/// Blurs and spreads shorter than this, in pixels, leave no visible trace.
|
||||||
|
pub const NEGLIGIBLE_LENGTH: f64 = 0.01;
|
||||||
|
|
||||||
|
/// The largest Gaussian standard deviation, in pixels, convolved on the image itself rather than a halved copy.
|
||||||
|
pub const MAX_DIRECT_GAUSSIAN_SIGMA: f64 = 8.;
|
||||||
|
|
||||||
|
/// The largest box or tent half width, in pixels, convolved on the image itself rather than a halved copy.
|
||||||
|
pub const MAX_DIRECT_BOX_RADIUS: f64 = 24.;
|
||||||
|
|
||||||
|
/// The farthest texel from the center a kernel weighs, which fits every direct limit.
|
||||||
|
pub const MAX_KERNEL_REACH: usize = 24;
|
||||||
|
|
||||||
|
/// The most times an image is halved for a blur, by which point it is one pixel across.
|
||||||
|
const MAX_LEVELS: u32 = 16;
|
||||||
|
|
||||||
|
/// How many passes after jump flooding to `reach` look for nearer seeds through the neighbors one chamfer step away, which settles the near misses within about 20 pixels.
|
||||||
|
/// Since a chamfer length is the shortest path of such steps, a pixel whose neighbor along that path found the nearest seed finds it too.
|
||||||
|
pub fn chamfer_passes(reach: f64) -> usize {
|
||||||
|
if reach > 16. { 4 } else { 2 }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A blur's kernel along one axis, sized in pixels.
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
pub enum BlurKernel {
|
||||||
|
Gaussian {
|
||||||
|
sigma: f64,
|
||||||
|
},
|
||||||
|
Box {
|
||||||
|
radius: f64,
|
||||||
|
},
|
||||||
|
/// Weighs each texel by how far short of `radius` it lies, the shape of two box blurs of that width in a row.
|
||||||
|
Tent {
|
||||||
|
radius: f64,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BlurKernel {
|
||||||
|
/// How many times the image is halved before the kernel runs, so the kernel stays within [`MAX_KERNEL_REACH`].
|
||||||
|
pub fn levels(self) -> u32 {
|
||||||
|
let (length, direct_limit) = match self {
|
||||||
|
Self::Gaussian { sigma } => (sigma, MAX_DIRECT_GAUSSIAN_SIGMA),
|
||||||
|
Self::Box { radius } | Self::Tent { radius } => (radius, MAX_DIRECT_BOX_RADIUS),
|
||||||
|
};
|
||||||
|
|
||||||
|
(length / direct_limit).log2().ceil().clamp(0., MAX_LEVELS as f64) as u32
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The weights of the texels from the center outward for an image halved `levels` times, normalized so the symmetric kernel sums to 1.
|
||||||
|
pub fn weights(self, levels: u32) -> Vec<f64> {
|
||||||
|
let level_scale = (1 << levels) as f64;
|
||||||
|
|
||||||
|
let weights: Vec<f64> = match self {
|
||||||
|
Self::Gaussian { sigma } => {
|
||||||
|
// Halving the image and doubling it back blur it too, so the kernel makes up only the rest of the variance
|
||||||
|
let pyramid_variance = (4_f64.powi(levels as i32) - 1.) / 3.;
|
||||||
|
let sigma = (sigma * sigma - pyramid_variance).max(0.).sqrt() / level_scale;
|
||||||
|
if sigma < NEGLIGIBLE_LENGTH {
|
||||||
|
return vec![1.];
|
||||||
|
}
|
||||||
|
|
||||||
|
let reach = ((3. * sigma).ceil() as usize).min(MAX_KERNEL_REACH);
|
||||||
|
(0..=reach).map(|i| (-((i * i) as f64) / (2. * sigma * sigma)).exp()).collect()
|
||||||
|
}
|
||||||
|
Self::Box { radius } => {
|
||||||
|
let radius = radius / level_scale;
|
||||||
|
let reach = (radius.ceil() as usize).min(MAX_KERNEL_REACH);
|
||||||
|
(0..=reach).map(|i| box_weight(radius, i)).collect()
|
||||||
|
}
|
||||||
|
Self::Tent { radius } => {
|
||||||
|
let radius = radius / level_scale;
|
||||||
|
if radius <= 1. {
|
||||||
|
return vec![1.];
|
||||||
|
}
|
||||||
|
|
||||||
|
let reach = (radius.ceil() as usize).min(MAX_KERNEL_REACH);
|
||||||
|
(0..=reach).map(|i| (radius - i as f64).max(0.)).collect()
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let total = weights[0] + 2. * weights[1..].iter().sum::<f64>();
|
||||||
|
weights.into_iter().map(|weight| weight / total).collect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How much a box of half width `radius` weighs the texel `distance` from its center, before normalizing: all of it within the box,
|
||||||
|
/// and at each end the fraction of it the box covers, so the blur grows smoothly with its radius.
|
||||||
|
pub fn box_weight(radius: f64, distance: usize) -> f64 {
|
||||||
|
(radius + 1. - distance as f64).clamp(0., 1.)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The greatest channel value a variable box blur counts, past 1 to keep bright high dynamic range values, which `vello_masks.wgsl` matches.
|
||||||
|
pub const VARIABLE_BOX_MAX_VALUE: f32 = 16.;
|
||||||
|
|
||||||
|
/// How many steps from 0 to 1 a variable box blur counts each channel of an image of `pixels` in, up to [`VARIABLE_BOX_MAX_VALUE`].
|
||||||
|
/// The GPU's running sums of those counts then stay exact in f32 digits (see `RUNNING_SUM_DIGIT` in `vello_masks.wgsl`): 2^12 up to 8192 by 8192 pixels, halving for each doubling past it.
|
||||||
|
pub fn variable_box_scale(pixels: usize) -> f64 {
|
||||||
|
let pixel_bits = (pixels.max(1) as f64).log2().ceil();
|
||||||
|
2_f64.powf((38. - pixel_bits).clamp(0., 12.))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The whole-pixel shifts, nearest first, that a faint pixel looks along for a visible one within `reach` document pixels, measured through `document_to_pixels`. O(reach² log reach).
|
||||||
|
pub fn pixel_fill_shifts(reach: f64, document_to_pixels: DMat2) -> Vec<[isize; 2]> {
|
||||||
|
let mut seen = std::collections::HashSet::new();
|
||||||
|
let pixel_shift = |[x, y]: [i32; 2]| (document_to_pixels * DVec2::new(x as f64, y as f64)).round();
|
||||||
|
(fill_shifts(reach.ceil() as i32).into_iter().map(pixel_shift))
|
||||||
|
.map(|shift| [shift.x as isize, shift.y as isize])
|
||||||
|
.filter(|&shift| seen.insert(shift))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The most samples a motion blur's box averages along its line at each pixel, past which its samples spread out evenly to cover it.
|
||||||
|
pub const MAX_MOTION_BLUR_SAMPLES: f64 = 1024.;
|
||||||
|
|
||||||
|
/// For PSD interop, a motion blur shears the image so its line runs along whichever axis it's closer to (the major axis), averages a box along that axis, and shears back.
|
||||||
|
/// Each shear interpolates across the minor axis with the Keys cubic kernel (a = -0.75), measured from the content's origin, which for an image is the corner PSD measures from.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||||
|
pub struct MotionBlurShear {
|
||||||
|
/// Whether the line is closer to vertical, so the shears move columns of pixels across rows rather than rows across columns.
|
||||||
|
pub vertical: bool,
|
||||||
|
/// How far the line moves across the minor axis for each pixel along the major axis.
|
||||||
|
pub slope: f64,
|
||||||
|
/// How many pixels the line spans along the major axis.
|
||||||
|
pub length: f64,
|
||||||
|
/// The fraction of a pixel the shears move the column (or row) at the start of the major axis back by, so they're measured from the anchor.
|
||||||
|
pub phase: f64,
|
||||||
|
/// Which way along the major axis the box leans at odd lengths: 1 toward its far end, or -1 toward its near end.
|
||||||
|
pub lean: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MotionBlurShear {
|
||||||
|
/// The shears of a line `distance` long (ignoring its sign) at `angle` (in degrees counterclockwise from the right), both in the effect space, given the map from its lengths into pixels, measured from `anchor` (in pixels).
|
||||||
|
pub fn new(angle: f64, distance: f64, lengths_to_pixels: DMat2, anchor: DVec2) -> Option<Self> {
|
||||||
|
let angle = angle.to_radians();
|
||||||
|
let line = DVec2::new(angle.cos(), -angle.sin()) * distance.abs();
|
||||||
|
let end = lengths_to_pixels * line;
|
||||||
|
|
||||||
|
// For PSD interop, a diagonal runs along the effect space's x axis, and in the pixels, along whichever axis that one lies nearer, so opposite and turned lines agree
|
||||||
|
let own_axis_vertical = nearer_y_axis(line).unwrap_or(false);
|
||||||
|
let own_axis = if own_axis_vertical { DVec2::Y } else { DVec2::X };
|
||||||
|
let vertical = nearer_y_axis(end).or_else(|| nearer_y_axis(lengths_to_pixels * own_axis)).unwrap_or(false);
|
||||||
|
let (major, minor, anchor) = if vertical { (end.y, end.x, anchor.y) } else { (end.x, end.y, anchor.x) };
|
||||||
|
if !(major.abs() >= 0.01 && major.is_finite() && minor.is_finite() && anchor.is_finite()) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A line shorter than a pixel slants in only as it lengthens, as PSD's whole-pixel line stays straight along an axis until it reaches across
|
||||||
|
let slope = minor / major * major.abs().min(1.);
|
||||||
|
|
||||||
|
// The box leans toward the end of the line farther along the effect space's axis nearest it, so it leans alike however the pixels lie in that space
|
||||||
|
let along_own_axis = if own_axis_vertical { line.y } else { line.x };
|
||||||
|
let lean = if (major > 0.) == (along_own_axis > 0.) { 1. } else { -1. };
|
||||||
|
|
||||||
|
Some(Self {
|
||||||
|
vertical,
|
||||||
|
slope,
|
||||||
|
length: major.abs(),
|
||||||
|
phase: (slope * anchor).rem_euclid(1.),
|
||||||
|
lean,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The span of the box along the major axis around each pixel: one pixel longer than the line, and for PSD interop, half a pixel toward the end of the axis it leans to at odd lengths.
|
||||||
|
pub fn box_span(&self) -> [f64; 2] {
|
||||||
|
let center = self.lean * (0.5 - (0.5 - (self.length / 2.).fract()).abs());
|
||||||
|
let half = (self.length + 1.) / 2.;
|
||||||
|
[center - half, center + half]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How many pixels apart the box's samples are, so it takes no more than [`MAX_MOTION_BLUR_SAMPLES`].
|
||||||
|
pub fn stride(&self) -> f64 {
|
||||||
|
((self.length + 2.) / MAX_MOTION_BLUR_SAMPLES).ceil().max(1.)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `vector` lies nearer the y axis than the x axis, or `None` along a diagonal, to within rounding.
|
||||||
|
fn nearer_y_axis(vector: DVec2) -> Option<bool> {
|
||||||
|
let (x, y) = (vector.x.abs(), vector.y.abs());
|
||||||
|
((x - y).abs() > x.max(y) * 1e-9).then_some(y > x)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How many cells a pixelation's tables hold at most for each pixel of the square on the region's longer side, past which its cells far outnumber the pixels, so most are slivers holding none.
|
||||||
|
/// A lattice turned from the region's axes spans about that square, rather than the region's area.
|
||||||
|
const TABLE_BUDGET_PER_SQUARE_PIXEL: usize = 4;
|
||||||
|
|
||||||
|
/// The most cells a pixelation's tables may hold however small the region is, so the margins around a small region's cells fit.
|
||||||
|
const MIN_TABLE_BUDGET: usize = 65_536;
|
||||||
|
|
||||||
|
/// The most cells a pixelation's table counts along each side, which the GPU's single-precision parameters hold exactly.
|
||||||
|
const MAX_TABLE_CELLS_ALONG_A_SIDE: usize = 16_777_216;
|
||||||
|
|
||||||
|
/// Whether a pixelation over a region `width` by `height` pixels makes its `tables` of cells `count` across and down.
|
||||||
|
/// Past this budget Pixelate leaves the content as it is and a halftone prints its tone, since the GPU would hold far more cells than pixels in its textures.
|
||||||
|
pub fn pixelation_table_fits(count: [usize; 2], tables: usize, width: usize, height: usize) -> bool {
|
||||||
|
let longest = width.max(height);
|
||||||
|
let budget = longest.saturating_mul(longest).saturating_mul(TABLE_BUDGET_PER_SQUARE_PIXEL).max(MIN_TABLE_BUDGET);
|
||||||
|
let cells = count[0].saturating_mul(count[1]).saturating_mul(tables);
|
||||||
|
cells <= budget && count.iter().all(|&count| count <= MAX_TABLE_CELLS_ALONG_A_SIDE)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pixelate's cells that a plane of pixels covers.
|
||||||
|
/// Columns and rows within the frame count from 0 at its near corner to its `last`, those before it count down from -1, and those past its far sides count on from one past its last.
|
||||||
|
pub struct PixelateCells {
|
||||||
|
/// How wide each cell is, in the effect space.
|
||||||
|
pub size: f64,
|
||||||
|
/// Where the cells within the frame start along each of its sides, in its local space: the last boundary between cells at or before its near corner.
|
||||||
|
pub start: DVec2,
|
||||||
|
/// How far a point nudges toward the frame's far corner before finding its cell, in the frame's local space, as [`tie_nudge`] gives it.
|
||||||
|
pub nudge: DVec2,
|
||||||
|
/// The column and row of the first cell the plane covers.
|
||||||
|
pub first: [i64; 2],
|
||||||
|
/// How many cells across and down the plane covers.
|
||||||
|
pub count: [usize; 2],
|
||||||
|
/// The column and row of the frame's last cell, at its far corner.
|
||||||
|
pub last: [i64; 2],
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PixelateCells {
|
||||||
|
/// The cells `size` across, with a corner at `offset` from the content's origin, that a plane `width` by `height` pixels covers in the `frame`.
|
||||||
|
pub fn new(size: f64, offset: DVec2, frame: &EffectFrame, width: usize, height: usize) -> Self {
|
||||||
|
let (to_local, half) = (frame.pixels_to_local(), frame.size / 2.);
|
||||||
|
let start = -half - (-half - (frame.origin + offset)).rem_euclid(DVec2::splat(size));
|
||||||
|
let last = (((half - start) / size).ceil() - 1.).max(DVec2::ZERO);
|
||||||
|
let mut cells = Self {
|
||||||
|
size,
|
||||||
|
start,
|
||||||
|
nudge: tie_nudge(size, PIXELATE_TIE_NUDGE, frame),
|
||||||
|
first: [0; 2],
|
||||||
|
count: [1; 2],
|
||||||
|
last: [last.x as i64, last.y as i64],
|
||||||
|
};
|
||||||
|
|
||||||
|
// Each axis numbers its cells in order, so the plane's corners hold the first and last it covers
|
||||||
|
let corners = [DVec2::ZERO, DVec2::new(width as f64, 0.), DVec2::new(0., height as f64), DVec2::new(width as f64, height as f64)];
|
||||||
|
let corner_cells = corners.map(|corner| cells.cell_at(to_local.transform_point2(corner), frame));
|
||||||
|
for axis in 0..2 {
|
||||||
|
let first = corner_cells.iter().map(|cell| cell[axis]).min().unwrap_or_default();
|
||||||
|
let end = corner_cells.iter().map(|cell| cell[axis]).max().unwrap_or_default();
|
||||||
|
cells.first[axis] = first;
|
||||||
|
cells.count[axis] = usize::try_from(end.saturating_sub(first).saturating_add(1)).unwrap_or(usize::MAX);
|
||||||
|
}
|
||||||
|
cells
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The column and row of the cell holding a point in the frame's local space, where the frame's sides belong to the cells within it.
|
||||||
|
pub fn cell_at(&self, local: DVec2, frame: &EffectFrame) -> [i64; 2] {
|
||||||
|
let (half, cuts) = (frame.size / 2., self.cuts_near_cells(frame));
|
||||||
|
let cell = ((local - self.start + self.nudge) / self.size).floor();
|
||||||
|
[0, 1].map(|axis| {
|
||||||
|
let cell = cell[axis] as i64;
|
||||||
|
match local[axis] {
|
||||||
|
coordinate if coordinate < -half[axis] => (cell - cuts[axis] as i64).min(-1),
|
||||||
|
coordinate if coordinate > half[axis] => cell.max(self.last[axis]) + 1,
|
||||||
|
_ => cell.clamp(0, self.last[axis]),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The boundary between cells nearest the frame's near corner along each of its sides, in its local space, and the column and row of the cell starting there.
|
||||||
|
/// Placed from there, the boundaries near the frame stay at the frame's own scale in single precision however wide the cells are.
|
||||||
|
pub fn boundary_near_frame(&self, frame: &EffectFrame) -> (DVec2, [i64; 2]) {
|
||||||
|
let past_start = (-frame.size / 2. - self.start).cmpgt(DVec2::splat(self.size / 2.));
|
||||||
|
(DVec2::select(past_start, self.start + self.size, self.start), [past_start.x as i64, past_start.y as i64])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the frame's near side cuts a cell along each of its sides, leaving its part before the side a cell of its own.
|
||||||
|
pub fn cuts_near_cells(&self, frame: &EffectFrame) -> [bool; 2] {
|
||||||
|
let cut = self.start.cmplt(-frame.size / 2.);
|
||||||
|
[cut.x, cut.y]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The first cell of a halftone `screen`'s table of dots that the pixels of an image `width` by `height` may lie nearest (see [`HalftoneScreen::table_cell_at`]), and how many cells across and down from it they span,
|
||||||
|
/// with one more around each side than a pixel looks through past its nearest (see [`HalftoneScreen::neighborhood`]).
|
||||||
|
pub fn halftone_cells(width: usize, height: usize, screen: &HalftoneScreen, frame: &EffectFrame) -> ([i64; 2], [usize; 2]) {
|
||||||
|
let to_local = frame.pixels_to_local();
|
||||||
|
let corners = [DVec2::ZERO, DVec2::new(width as f64, 0.), DVec2::new(0., height as f64), DVec2::new(width as f64, height as f64)];
|
||||||
|
let snaps_together = screen.snaps_together(frame);
|
||||||
|
let cells = corners.map(|corner| screen.table_cell_at(to_local.transform_point2(corner) - frame.origin, snaps_together));
|
||||||
|
let margin = screen.neighborhood(frame).saturating_add(1);
|
||||||
|
|
||||||
|
let first = [0, 1].map(|axis| cells.iter().map(|cell| cell[axis]).min().unwrap_or_default().saturating_sub(margin));
|
||||||
|
let last = [0, 1].map(|axis| cells.iter().map(|cell| cell[axis]).max().unwrap_or_default().saturating_add(margin));
|
||||||
|
(
|
||||||
|
first,
|
||||||
|
[0, 1].map(|axis| usize::try_from(last[axis].saturating_sub(first[axis]).saturating_add(1)).unwrap_or(usize::MAX)),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How many cells across and down a halftone's table holds for each channel, as many as the most that any channel's `cells` from [`halftone_cells`] span.
|
||||||
|
pub fn halftone_table_count(cells: &[([i64; 2], [usize; 2]); 3]) -> [usize; 2] {
|
||||||
|
[0, 1].map(|axis| cells.iter().map(|(_, count)| count[axis]).max().unwrap_or(1))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use glam::DAffine2;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn kernel_weights_sum_to_one() {
|
||||||
|
for kernel in [
|
||||||
|
BlurKernel::Gaussian { sigma: 3. },
|
||||||
|
BlurKernel::Gaussian { sigma: 40. },
|
||||||
|
BlurKernel::Box { radius: 5.5 },
|
||||||
|
BlurKernel::Box { radius: 100. },
|
||||||
|
] {
|
||||||
|
let levels = kernel.levels();
|
||||||
|
let weights = kernel.weights(levels);
|
||||||
|
let total = weights[0] + 2. * weights[1..].iter().sum::<f64>();
|
||||||
|
|
||||||
|
assert!((total - 1.).abs() < 1e-9, "{kernel:?} weights sum to {total}");
|
||||||
|
assert!(weights.len() <= MAX_KERNEL_REACH + 1, "{kernel:?} reaches {} texels", weights.len());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn small_kernels_run_without_halving() {
|
||||||
|
assert_eq!(BlurKernel::Gaussian { sigma: MAX_DIRECT_GAUSSIAN_SIGMA }.levels(), 0);
|
||||||
|
assert_eq!(
|
||||||
|
BlurKernel::Gaussian {
|
||||||
|
sigma: MAX_DIRECT_GAUSSIAN_SIGMA * 1.01
|
||||||
|
}
|
||||||
|
.levels(),
|
||||||
|
1
|
||||||
|
);
|
||||||
|
assert_eq!(BlurKernel::Box { radius: 1. }.levels(), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tents_weigh_texels_by_how_far_short_of_the_radius_they_lie() {
|
||||||
|
// For PSD interop, a size of 16 weighs the texels 16, 15, ..., 1 from the center outward
|
||||||
|
let weights = BlurKernel::Tent { radius: 16. }.weights(0);
|
||||||
|
assert_eq!(weights.len(), 17);
|
||||||
|
for (distance, &weight) in weights.iter().enumerate() {
|
||||||
|
assert!((weight - (16 - distance) as f64 / 256.).abs() < 1e-12, "texel {distance} weighs {weight}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn shear(angle: f64, distance: f64) -> MotionBlurShear {
|
||||||
|
MotionBlurShear::new(angle, distance, DMat2::IDENTITY, DVec2::ZERO).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn boxes_span_one_pixel_more_than_the_line_leaning_forward_at_odd_lengths() {
|
||||||
|
assert_eq!(shear(0., 10.).box_span(), [-5.5, 5.5]);
|
||||||
|
assert_eq!(shear(0., 11.).box_span(), [-5.5, 6.5]);
|
||||||
|
|
||||||
|
// The box leans toward the same end of the line in the effect space, which is the major axis's near end in flipped pixels
|
||||||
|
let flipped = MotionBlurShear::new(0., 11., DMat2::from_diagonal(DVec2::new(-1., 1.)), DVec2::ZERO).unwrap();
|
||||||
|
assert_eq!(flipped.box_span(), [-6.5, 5.5]);
|
||||||
|
assert_eq!(shear(180., 11.).box_span(), shear(0., 11.).box_span(), "opposite directions smear alike");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn opposite_directions_shear_alike_even_along_diagonals() {
|
||||||
|
for (angle, opposite) in [(0., 180.), (30., -150.), (45., -135.), (-45., 135.)] {
|
||||||
|
let (forward, backward) = (shear(angle, 10.), shear(opposite, 10.));
|
||||||
|
let boxes_match = forward.box_span().into_iter().zip(backward.box_span()).all(|(forward, backward)| (forward - backward).abs() < 1e-12);
|
||||||
|
assert_eq!(forward.vertical, backward.vertical, "lines at {angle} and {opposite} degrees run along different axes");
|
||||||
|
assert!((forward.slope - backward.slope).abs() < 1e-12, "lines at {angle} and {opposite} degrees slant differently");
|
||||||
|
assert!(boxes_match, "lines at {angle} and {opposite} degrees have different boxes");
|
||||||
|
}
|
||||||
|
|
||||||
|
// For PSD interop, whole-pixel diagonal lines run along x in either direction
|
||||||
|
for psd_angle in [45, -135] {
|
||||||
|
let (angle, distance) = graphic_types::resampling::motion_blur_from_psd(psd_angle, 11.);
|
||||||
|
assert!(!shear(angle, distance).vertical, "PSD's line at {psd_angle} degrees runs along y");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pixels turned a quarter, with or without rounding, put diagonals along the pixel axis the effect space's x turns onto
|
||||||
|
for turn in [DMat2::from_angle(std::f64::consts::FRAC_PI_2), DMat2::from_cols(DVec2::Y, -DVec2::X)] {
|
||||||
|
for angle in [45., -45., 135., -135.] {
|
||||||
|
let vertical = MotionBlurShear::new(angle, 10., turn, DVec2::ZERO).is_some_and(|turned| turned.vertical);
|
||||||
|
assert!(vertical, "a line at {angle} degrees through pixels turned by {turn} runs along x");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn huge_motion_blurs_spread_their_samples_out() {
|
||||||
|
let shear = shear(0., 5000.);
|
||||||
|
let [start, end] = shear.box_span();
|
||||||
|
assert!((end - start) / shear.stride() <= MAX_MOTION_BLUR_SAMPLES);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn negative_distances_smear_as_positive_ones_do() {
|
||||||
|
use graphic_types::EffectOperation;
|
||||||
|
|
||||||
|
// Through turned and unevenly scaled pixels, measured from an anchor off their corner
|
||||||
|
let lengths_to_pixels = DMat2::from_angle(0.3) * DMat2::from_diagonal(DVec2::new(1.5, 0.8));
|
||||||
|
let anchor = DVec2::new(3.2, -1.);
|
||||||
|
let blur = |angle, distance| EffectOperation::MotionBlur { angle, distance, gamma: false };
|
||||||
|
for (angle, distance) in [(0., 12.), (30., 7.5), (-70., 90.)] {
|
||||||
|
let shears = [distance, -distance].map(|distance| MotionBlurShear::new(angle, distance, lengths_to_pixels, anchor));
|
||||||
|
assert_eq!(shears[0], shears[1], "lines {distance} long at {angle} degrees shear differently");
|
||||||
|
|
||||||
|
assert!(!blur(angle, -distance).changes_nothing());
|
||||||
|
assert_eq!(blur(angle, -distance).reach(), blur(angle, distance).reach());
|
||||||
|
}
|
||||||
|
assert!(blur(0., 0.).changes_nothing());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn pixelation_tables_fit_the_cells_around_the_square_on_the_regions_longer_side() {
|
||||||
|
// A plane of 100 by 100 pixels in a frame stretched to 100 by 10^9 units, so cells 2 units across span 50 columns and 5 × 10^8 rows of cells, nearly all holding no pixel
|
||||||
|
let frame = EffectFrame::new(DAffine2::from_scale(DVec2::new(100., 1e9)), DAffine2::from_scale(DVec2::new(1., 1e-7))).unwrap();
|
||||||
|
let cells = PixelateCells::new(2., DVec2::ZERO, &frame, 100, 100);
|
||||||
|
assert!(!pixelation_table_fits(cells.count, 1, 100, 100), "the budget holds all {:?} cells around the plane", cells.count);
|
||||||
|
|
||||||
|
// A strip 4000 by 4 pixels within a frame turned an eighth, so cells 2 units across span about the square on its length
|
||||||
|
let (width, height) = (4000, 4);
|
||||||
|
let placement = DAffine2::from_translation(DVec2::new(2000., 2.))
|
||||||
|
* DAffine2::from_angle(std::f64::consts::FRAC_PI_4)
|
||||||
|
* DAffine2::from_translation(DVec2::splat(-3000.))
|
||||||
|
* DAffine2::from_scale(DVec2::splat(6000.));
|
||||||
|
let frame = EffectFrame::new(placement, DAffine2::IDENTITY).unwrap();
|
||||||
|
let cells = PixelateCells::new(2., DVec2::ZERO, &frame, width, height);
|
||||||
|
assert!(
|
||||||
|
pixelation_table_fits(cells.count, 1, width, height),
|
||||||
|
"the budget leaves out the {:?} cells around the strip",
|
||||||
|
cells.count
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -1,43 +1,9 @@
|
|||||||
//! The kernels rendering each [`GeneratorPattern`] across any area of its space at any resolution.
|
//! The point functions sampling each [`GeneratorPattern`] anywhere in its space, which the GPU's renders of it match.
|
||||||
|
|
||||||
use crate::mandelbrot::{MandelbrotSetup, resolves_in_32_bits};
|
use crate::mandelbrot::MandelbrotSetup;
|
||||||
use core_types::Color;
|
use core_types::Color;
|
||||||
use glam::{DVec2, IVec2};
|
use glam::{DVec2, IVec2};
|
||||||
use graphic_types::generator::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, GeneratorPattern, NoiseSettings, NoiseType, hash_fraction, pcg3d};
|
use graphic_types::generator::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, GeneratorPattern, NoiseSettings, NoiseType, hash_fraction, pcg3d};
|
||||||
use raster_types::parallel_rows::fill_rows;
|
|
||||||
use raster_types::{Image, ImageError};
|
|
||||||
|
|
||||||
/// The pattern across `area` of its own space, from its minimum to its maximum corner, sampled at the centers of a `width` by `height` grid of pixels.
|
|
||||||
/// Fails where an image of that size can't be allocated.
|
|
||||||
/// The rows are rendered in parallel on native targets.
|
|
||||||
pub fn render_pattern(pattern: &GeneratorPattern, area: [DVec2; 2], width: u32, height: u32) -> Result<Image<Color>, ImageError> {
|
|
||||||
let mut image = Image::try_new(width, height, Color::TRANSPARENT)?;
|
|
||||||
let pixel_size = (area[1] - area[0]) / DVec2::new(width as f64, height as f64);
|
|
||||||
let pixel_center = |x: usize, y: usize| area[0] + (DVec2::new(x as f64, y as f64) + 0.5) * pixel_size;
|
|
||||||
|
|
||||||
match pattern {
|
|
||||||
// Across a known area, a Mandelbrot pattern follows a reference orbit as the GPU does
|
|
||||||
GeneratorPattern::Mandelbrot(settings) => {
|
|
||||||
let setup = MandelbrotSetup::new(settings);
|
|
||||||
let (plane_area, plane_texel) = (area.map(|point| setup.plane_point(point)), (pixel_size / setup.scale).min_element());
|
|
||||||
let reference = setup.reference_orbit(plane_area, plane_texel);
|
|
||||||
let interior_test = setup.has_interior_test() && resolves_in_32_bits(plane_area, plane_texel);
|
|
||||||
fill_rows(&mut image.data, width as usize, |y, row| {
|
|
||||||
row.iter_mut().enumerate().for_each(|(x, pixel)| {
|
|
||||||
*pixel = pattern_gray(setup.sample(setup.plane_point(pixel_center(x, y)), reference.as_ref(), interior_test));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
_ => {
|
|
||||||
let sample = pattern_sampler(pattern);
|
|
||||||
fill_rows(&mut image.data, width as usize, |y, row| {
|
|
||||||
row.iter_mut().enumerate().for_each(|(x, pixel)| *pixel = sample(pixel_center(x, y)));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(image)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The area of the pattern's own space that a thumbnail frames, for a pattern with a part worth framing rather than one alike across the whole plane.
|
/// The area of the pattern's own space that a thumbnail frames, for a pattern with a part worth framing rather than one alike across the whole plane.
|
||||||
pub fn thumbnail_area(pattern: &GeneratorPattern) -> Option<[DVec2; 2]> {
|
pub fn thumbnail_area(pattern: &GeneratorPattern) -> Option<[DVec2; 2]> {
|
||||||
@@ -177,35 +143,6 @@ fn white_noise(seed: i32, cell: IVec2) -> f32 {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn renders_of_overlapping_areas_agree_where_they_overlap() {
|
|
||||||
let noise = GeneratorPattern::Noise(NoiseSettings {
|
|
||||||
seed: 7,
|
|
||||||
scale: 10.,
|
|
||||||
noise_type: NoiseType::OpenSimplex2,
|
|
||||||
domain_warp_type: DomainWarpType::None,
|
|
||||||
domain_warp_amplitude: 0.,
|
|
||||||
fractal_type: FractalType::FBm,
|
|
||||||
fractal_octaves: 3,
|
|
||||||
fractal_lacunarity: 2.,
|
|
||||||
fractal_gain: 0.5,
|
|
||||||
fractal_weighted_strength: 0.,
|
|
||||||
fractal_ping_pong_strength: 2.,
|
|
||||||
cellular_distance_function: CellularDistanceFunction::Euclidean,
|
|
||||||
cellular_return_type: CellularReturnType::Nearest,
|
|
||||||
cellular_jitter: 1.,
|
|
||||||
});
|
|
||||||
|
|
||||||
// One pixel per unit across 0 to 32, and again across 16 to 48, as two neighboring tiles of a render would sample it
|
|
||||||
let whole = render_pattern(&noise, [DVec2::ZERO, DVec2::splat(32.)], 32, 32).unwrap();
|
|
||||||
let shifted = render_pattern(&noise, [DVec2::splat(16.), DVec2::splat(48.)], 32, 32).unwrap();
|
|
||||||
for y in 0..16 {
|
|
||||||
for x in 0..16 {
|
|
||||||
assert_eq!(whole.data[(y + 16) * 32 + x + 16], shifted.data[y * 32 + x]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn pattern_values_show_as_the_gray_at_that_level() {
|
fn pattern_values_show_as_the_gray_at_that_level() {
|
||||||
for value in [0., 0.25, 0.5, 0.75, 1.] {
|
for value in [0., 0.25, 0.5, 0.75, 1.] {
|
||||||
@@ -239,18 +176,20 @@ mod tests {
|
|||||||
})
|
})
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// The centers of a grid of `cells` across the 4 by 4 units from the origin
|
||||||
|
let centers = |cells: usize| (0..cells * cells).map(move |index| (DVec2::new((index % cells) as f64, (index / cells) as f64) + 0.5) * 4. / cells as f64);
|
||||||
|
|
||||||
// Each unit cell keeps its value when sampled four times as finely
|
// Each unit cell keeps its value when sampled four times as finely
|
||||||
let coarse = render_pattern(&white_noise(3), [DVec2::ZERO, DVec2::splat(4.)], 4, 4).unwrap();
|
let sample = pattern_sampler(&white_noise(3));
|
||||||
let fine = render_pattern(&white_noise(3), [DVec2::ZERO, DVec2::splat(4.)], 16, 16).unwrap();
|
let coarse: Vec<Color> = centers(4).map(&sample).collect();
|
||||||
for y in 0..16 {
|
for (index, point) in centers(16).enumerate() {
|
||||||
for x in 0..16 {
|
let (x, y) = (index % 16, index / 16);
|
||||||
assert_eq!(fine.data[y * 16 + x], coarse.data[(y / 4) * 4 + x / 4]);
|
assert_eq!(sample(point), coarse[(y / 4) * 4 + x / 4]);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// The values spread across the whole range, and another seed gives others
|
// The values spread across the whole range, and another seed gives others
|
||||||
let luminances: Vec<f32> = coarse.data.iter().map(|color| color.r()).collect();
|
let luminances: Vec<f32> = coarse.iter().map(|color| color.r()).collect();
|
||||||
assert!(luminances.iter().any(|&value| value < 0.5) && luminances.iter().any(|&value| value > 0.5));
|
assert!(luminances.iter().any(|&value| value < 0.5) && luminances.iter().any(|&value| value > 0.5));
|
||||||
assert_ne!(render_pattern(&white_noise(4), [DVec2::ZERO, DVec2::splat(4.)], 4, 4).unwrap().data, coarse.data);
|
assert_ne!(centers(4).map(pattern_sampler(&white_noise(4))).collect::<Vec<_>>(), coarse);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,16 +1,10 @@
|
|||||||
//! Blends a layer onto those beneath it by a blend mode, with the W3C Compositing and Blending formulas on gamma-encoded colors, as SVG and the GPU's layers blend.
|
//! Blends a pixel of a layer onto those beneath it by a blend mode, with the W3C Compositing and Blending formulas on gamma-encoded colors, as SVG and the GPU's layers blend.
|
||||||
//! The modes CSS lacks, which layers read what lies beneath to blend by, take the formulas the effects share (see [`crate::blending::blend_gamma`]).
|
//! The modes CSS lacks, which layers read what lies beneath to blend by, take the formulas the effects share (see [`crate::blending::blend_gamma`]).
|
||||||
|
|
||||||
use crate::effect_kernels::Plane;
|
|
||||||
use core_types::Color;
|
use core_types::Color;
|
||||||
use core_types::blending::{BlendMode, apply_blend_mode_at_strength, layer_fill_shown};
|
use core_types::blending::{BlendMode, apply_blend_mode_at_strength, layer_fill_shown};
|
||||||
use core_types::color::BLEND_EDGE_TOLERANCE;
|
use core_types::color::BLEND_EDGE_TOLERANCE;
|
||||||
|
|
||||||
/// The premultiplied gamma-encoded `layer` blended by the mode onto the layers `below` it. O(width × height).
|
|
||||||
pub fn blend_layer(layer: &Plane<[f32; 4]>, below: &Plane<[f32; 4]>, blend_mode: BlendMode) -> Plane<[f32; 4]> {
|
|
||||||
layer.zip(below, |source, backdrop| blend_pixel(source, backdrop, blend_mode))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One premultiplied pixel blended onto another: its color mixes toward the blend of both as far as the backdrop covers it, and it then composites over the backdrop.
|
/// One premultiplied pixel blended onto another: its color mixes toward the blend of both as far as the backdrop covers it, and it then composites over the backdrop.
|
||||||
pub fn blend_pixel(source: [f32; 4], backdrop: [f32; 4], blend_mode: BlendMode) -> [f32; 4] {
|
pub fn blend_pixel(source: [f32; 4], backdrop: [f32; 4], blend_mode: BlendMode) -> [f32; 4] {
|
||||||
blend_pixel_at_strength(source, backdrop, blend_mode, 1.)
|
blend_pixel_at_strength(source, backdrop, blend_mode, 1.)
|
||||||
|
|||||||
@@ -4,18 +4,12 @@ pub mod adjustment_steps;
|
|||||||
pub mod adjustments;
|
pub mod adjustments;
|
||||||
mod blending;
|
mod blending;
|
||||||
pub mod color_lookup_table;
|
pub mod color_lookup_table;
|
||||||
pub mod effect_kernels;
|
pub mod effect_planning;
|
||||||
pub mod filter_kernels;
|
|
||||||
pub mod generators;
|
pub mod generators;
|
||||||
mod kernel;
|
mod kernel;
|
||||||
pub mod layer_blending;
|
pub mod layer_blending;
|
||||||
pub mod mandelbrot;
|
pub mod mandelbrot;
|
||||||
pub mod masks;
|
|
||||||
pub mod raster_effects;
|
|
||||||
pub mod resample_kernels;
|
|
||||||
pub mod value_effects;
|
pub mod value_effects;
|
||||||
pub mod warp_kernels;
|
|
||||||
|
|
||||||
pub use kernel::*;
|
pub use kernel::*;
|
||||||
pub use raster_effects::evaluate_raster_effects;
|
|
||||||
pub use value_effects::{evaluate_color_effects, evaluate_color_parameter, evaluate_gradient_effects};
|
pub use value_effects::{evaluate_color_effects, evaluate_color_parameter, evaluate_gradient_effects};
|
||||||
@@ -1,408 +0,0 @@
|
|||||||
//! The CPU twins of the GPU passes that mask, feather, and blur content by a radius mask.
|
|
||||||
|
|
||||||
use crate::effect_kernels::{BlurKernel, NEGLIGIBLE_LENGTH, Plane, VARIABLE_BOX_MAX_VALUE, variable_box_scale};
|
|
||||||
use crate::raster_effects::{blur, premultiplied_gamma_channels, transferred};
|
|
||||||
use core_types::Color;
|
|
||||||
use core_types::color::{linear_to_srgb, srgb_to_linear};
|
|
||||||
use glam::DVec2;
|
|
||||||
use graphic_types::masks::{FEATHER_FOOTPRINT_ALPHA, MaskMode, feather_parts, mask_coverage, mask_density_line, mask_feather_sigma, masked_radius_blur_code, masked_radius_blur_interpolation};
|
|
||||||
use raster_types::parallel_rows::fill_rows;
|
|
||||||
|
|
||||||
/// How much the mask shows the content at each pixel, from 0 to 1, given the `colors` its graphic draws over a plane of `width` by `height` pixels.
|
|
||||||
/// Its coverage is softened by the `feather` (in document pixels, `pixels_per_length` pixels each), then mapped through its `density` percentage, flipped if `invert`.
|
|
||||||
#[allow(clippy::too_many_arguments)]
|
|
||||||
pub(crate) fn mask_strength(colors: &[Color], width: usize, height: usize, mode: MaskMode, density: f64, feather: f64, invert: bool, pixels_per_length: DVec2) -> Plane<f32> {
|
|
||||||
let coverage = Plane {
|
|
||||||
width,
|
|
||||||
height,
|
|
||||||
data: colors.iter().map(|&color| mask_coverage(premultiplied_gamma_channels(color), mode)).collect(),
|
|
||||||
};
|
|
||||||
|
|
||||||
let sigma = mask_feather_sigma(feather) * pixels_per_length;
|
|
||||||
let coverage = match sigma.max_element() >= NEGLIGIBLE_LENGTH {
|
|
||||||
true => coverage.blurred(BlurKernel::Gaussian { sigma: sigma.x }, BlurKernel::Gaussian { sigma: sigma.y }),
|
|
||||||
false => coverage,
|
|
||||||
};
|
|
||||||
|
|
||||||
let (slope, intercept) = mask_density_line(density, invert);
|
|
||||||
coverage.map(|coverage| (slope * coverage + intercept).clamp(0., 1.))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The premultiplied image faded at each pixel by the mask's `strength` there.
|
|
||||||
pub(crate) fn masked(image: &Plane<[f32; 4]>, strength: &Plane<f32>) -> Plane<[f32; 4]> {
|
|
||||||
image.zip(strength, |pixel, strength| pixel.map(|channel| channel * strength))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// How much a footprint eroded by `erosion` pixels covers a pixel, given the pixel's distance to the area outside the footprint plus half a pixel and its share of that area, relative to its own coverage of the footprint.
|
|
||||||
fn erode(to_outside: f32, outside_coverage: f32, erosion: f32) -> f32 {
|
|
||||||
let coverage = 1. - outside_coverage;
|
|
||||||
let eroded = (to_outside - erosion).clamp(0., 1.);
|
|
||||||
if coverage > 0. { (eroded / coverage).min(1.) } else { eroded }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// How much a feather of `distance` pixels keeps of the `full`-strength content at each pixel, from 0 to 1, as [`feather_parts`] defines it, matching the GPU's `feather_strength`.
|
|
||||||
/// O(width × height × log(distance)).
|
|
||||||
pub(crate) fn feather_strength(full: &Plane<[f32; 4]>, distance: f64) -> Plane<f32> {
|
|
||||||
let (width, height) = (full.width, full.height);
|
|
||||||
let alpha_at = |x: usize, y: usize| full.data[y * width + x][3];
|
|
||||||
|
|
||||||
// The area outside the footprint, with its edge falling within the pixels bordering it by their alpha relative to the largest beside them
|
|
||||||
let mut outside = Plane::<f32>::new(width, height);
|
|
||||||
fill_rows(&mut outside.data, width, |y, row| {
|
|
||||||
for (x, outside_coverage) in row.iter_mut().enumerate() {
|
|
||||||
let alpha = alpha_at(x, y);
|
|
||||||
let neighbors = (y.saturating_sub(1)..(y + 2).min(height)).flat_map(|neighbor_y| (x.saturating_sub(1)..(x + 2).min(width)).map(move |neighbor_x| (neighbor_x, neighbor_y)));
|
|
||||||
let neighbor_alphas = neighbors.map(|(neighbor_x, neighbor_y)| alpha_at(neighbor_x, neighbor_y));
|
|
||||||
let (borders_absence, largest) = neighbor_alphas.fold((false, alpha), |(borders, largest), neighbor| (borders || neighbor <= FEATHER_FOOTPRINT_ALPHA, largest.max(neighbor)));
|
|
||||||
|
|
||||||
*outside_coverage = match (alpha <= FEATHER_FOOTPRINT_ALPHA, borders_absence) {
|
|
||||||
(true, _) => 1.,
|
|
||||||
(false, true) => 1. - (alpha / largest).min(1.),
|
|
||||||
(false, false) => 0.,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// The footprint eroded in straight lines, from each pixel's distance to the edge plus half a pixel, relative to the pixel's own coverage of the footprint so a feather of nothing keeps the content as it is
|
|
||||||
let (erosion, sigma) = feather_parts(distance);
|
|
||||||
let to_outside = outside.jump_flood(erosion + 2., |coverage| coverage > 0., |[x, y], coverage| (x as f32).hypot(y as f32) + (0.5 - coverage) + 0.5);
|
|
||||||
let eroded = to_outside.zip(&outside, |to_outside, outside_coverage| erode(to_outside, outside_coverage, erosion as f32));
|
|
||||||
|
|
||||||
match sigma >= NEGLIGIBLE_LENGTH {
|
|
||||||
true => eroded.blurred(BlurKernel::Gaussian { sigma }, BlurKernel::Gaussian { sigma }),
|
|
||||||
false => eroded,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A masked radius blur map's color in 8-bit channels as the GPU renders the map: straight, then premultiplied.
|
|
||||||
fn map_channels(color: Color) -> [f32; 4] {
|
|
||||||
let eight_bit = |channel: f32| (channel.clamp(0., 1.) * 255.).round() / 255.;
|
|
||||||
let [red, green, blue, alpha] = color.to_gamma_srgb_channels().map(eight_bit);
|
|
||||||
[eight_bit(red * alpha), eight_bit(green * alpha), eight_bit(blue * alpha), alpha]
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The 8-bit luminance code of each of a masked radius blur map's `colors` (see [`map_channels`]).
|
|
||||||
pub(crate) fn masked_radius_blur_codes(colors: &[Color]) -> Vec<u8> {
|
|
||||||
colors.iter().map(|&color| masked_radius_blur_code(map_channels(color))).collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The luminance from 0 to 1 of each of a masked box blur map's `colors`, unrounded like the GPU's precise map texture, in the half floats the GPU keeps it in, which size the boxes finer than 8-bit codes could.
|
|
||||||
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::LuminanceSvg).clamp(0., 1.)
|
|
||||||
};
|
|
||||||
colors.iter().map(|&color| half::f16::from_f32(luminance(color)).to_f32()).collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The premultiplied gamma-encoded `image` blurred by the interpolation between Gaussian `levels` (from `masked_radius_blur_levels`, here in pixels along each axis) each pixel's map luminance `codes` picks,
|
|
||||||
/// matching the GPU's `masked_radius_blur`, blurring in linear light if `linear`. O(width × height) for each of the levels.
|
|
||||||
pub(crate) fn masked_radius_blur(image: &Plane<[f32; 4]>, codes: &[u8], levels: &[DVec2], linear: bool) -> Plane<[f32; 4]> {
|
|
||||||
// Each code's level below and share of the level above, the same for every level and at any scale
|
|
||||||
let lengths: Vec<f64> = levels.iter().map(|level| level.max_element()).collect();
|
|
||||||
let interpolations: Vec<(usize, f32)> = (0..=255_u8)
|
|
||||||
.map(|code| {
|
|
||||||
let (below, above_parts) = masked_radius_blur_interpolation(code, &lengths);
|
|
||||||
(below, above_parts as f32 / 255.)
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
// Only the levels some pixel takes a share of are blurred, so a map of one luminance blurs once or twice
|
|
||||||
let mut weighed = vec![false; levels.len()];
|
|
||||||
for &code in codes {
|
|
||||||
let (below, above_share) = interpolations[code as usize];
|
|
||||||
weighed[below] |= above_share < 1.;
|
|
||||||
if let Some(above) = weighed.get_mut(below + 1) {
|
|
||||||
*above |= above_share > 0.;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut sum = Plane::<[f32; 4]>::new(image.width, image.height);
|
|
||||||
for (index, &length) in levels.iter().enumerate().filter(|&(index, _)| weighed[index]) {
|
|
||||||
let blurred = match length.max_element() >= NEGLIGIBLE_LENGTH {
|
|
||||||
true => blur(image.clone(), (BlurKernel::Gaussian { sigma: length.x }, BlurKernel::Gaussian { sigma: length.y }), linear),
|
|
||||||
false => image.clone(),
|
|
||||||
};
|
|
||||||
|
|
||||||
let weight = |(below, above_share): (usize, f32)| match index {
|
|
||||||
_ if index == below => 1. - above_share,
|
|
||||||
_ if index == below + 1 => above_share,
|
|
||||||
_ => 0.,
|
|
||||||
};
|
|
||||||
// Summed in gamma on purpose (see `masked_radius_blur_interpolation`)
|
|
||||||
for ((sum, pixel), &code) in sum.data.iter_mut().zip(&blurred.data).zip(codes) {
|
|
||||||
let weight = weight(interpolations[code as usize]);
|
|
||||||
*sum = std::array::from_fn(|channel| sum[channel] + pixel[channel] * weight);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
sum
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The premultiplied gamma-encoded `image` box blurred at each pixel by its own half width along each axis, the fraction of the `radius` in pixels its map's `luminances` give,
|
|
||||||
/// matching the GPU's `variable_box_blur`. Each box weighs pixels like [`BlurKernel::Box`], holding the edge pixels past the edges, in linear light if `linear`.
|
|
||||||
/// It sums each box from running sums (a summed-area table) of whole-number counts, exact at any size, so O(width × height) at any radius.
|
|
||||||
pub fn variable_box_blur(image: &Plane<[f32; 4]>, luminances: &[f32], radius: DVec2, linear: bool) -> Plane<[f32; 4]> {
|
|
||||||
let (width, height) = (image.width, image.height);
|
|
||||||
let summed = match linear {
|
|
||||||
true => std::borrow::Cow::Owned(image.map(transferred(srgb_to_linear))),
|
|
||||||
false => std::borrow::Cow::Borrowed(image),
|
|
||||||
};
|
|
||||||
let scale = variable_box_scale(width * height);
|
|
||||||
let count = |value: f32| (value.clamp(0., VARIABLE_BOX_MAX_VALUE) * scale as f32).round_ties_even() as u64;
|
|
||||||
|
|
||||||
// Two channels at a time, as the GPU sums them, keeping the running sums to 16 bytes a pixel
|
|
||||||
let mut averages = Plane::<[f32; 4]>::new(width, height);
|
|
||||||
for first in [0, 2] {
|
|
||||||
// Each channel counted in whole steps, summed over the pixels above and left of each corner between pixels, in rows of one more corner than pixels
|
|
||||||
let corners = width + 1;
|
|
||||||
let mut sums = vec![[0_u64; 2]; corners * (height + 1)];
|
|
||||||
for y in 0..height {
|
|
||||||
let mut row = [0_u64; 2];
|
|
||||||
for x in 0..width {
|
|
||||||
let pixel = summed.data[y * width + x];
|
|
||||||
row = [row[0] + count(pixel[first]), row[1] + count(pixel[first + 1])];
|
|
||||||
|
|
||||||
let above = sums[y * corners + x + 1];
|
|
||||||
sums[(y + 1) * corners + x + 1] = [above[0] + row[0], above[1] + row[1]];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let sum_at = |x: usize, y: usize| sums[y * corners + x];
|
|
||||||
|
|
||||||
// The counts over the pixels from `start` up to `end`, with those past the edges repeating the nearest edge pixel
|
|
||||||
let counts_continued = |start: [i64; 2], end: [i64; 2]| -> [f64; 2] {
|
|
||||||
let spans = |axis: usize, size: usize| {
|
|
||||||
let size = size as i64;
|
|
||||||
let (inner_start, inner_end) = (start[axis].clamp(0, size), end[axis].clamp(0, size));
|
|
||||||
[(0, 1, inner_start - start[axis]), (inner_start, inner_end, 1), (size - 1, size, end[axis] - inner_end)]
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut sum = [0.; 2];
|
|
||||||
for (start_x, end_x, count_x) in spans(0, width) {
|
|
||||||
for (start_y, end_y, count_y) in spans(1, height) {
|
|
||||||
if count_x <= 0 || count_y <= 0 {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
let [start_x, end_x, start_y, end_y] = [start_x, end_x, start_y, end_y].map(|corner| corner as usize);
|
|
||||||
let [top_left, top_right] = [sum_at(start_x, start_y), sum_at(end_x, start_y)];
|
|
||||||
let [bottom_left, bottom_right] = [sum_at(start_x, end_y), sum_at(end_x, end_y)];
|
|
||||||
let count = (count_x * count_y) as f64;
|
|
||||||
sum = std::array::from_fn(|channel| sum[channel] + count * ((bottom_right[channel] + top_left[channel]) - (bottom_left[channel] + top_right[channel])) as f64);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
sum
|
|
||||||
};
|
|
||||||
|
|
||||||
fill_rows(&mut averages.data, width, |y, row| {
|
|
||||||
for (x, target) in row.iter_mut().enumerate() {
|
|
||||||
let index = y * width + x;
|
|
||||||
if luminances[index] <= 0. {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// A box of a fractional half width is the mix of the boxes of the whole half widths either side, weighed by that fraction along each axis
|
|
||||||
let half_width = radius * luminances[index] as f64;
|
|
||||||
let (whole, fraction) = (half_width.floor(), half_width - half_width.floor());
|
|
||||||
let mut sum = [0.; 2];
|
|
||||||
for wider in [[false, false], [true, false], [false, true], [true, true]] {
|
|
||||||
let along = |axis: usize| if wider[axis] { fraction[axis] } else { 1. - fraction[axis] };
|
|
||||||
let weight = along(0) * along(1);
|
|
||||||
if weight <= 0. {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
let reach = [0, 1].map(|axis| whole[axis] as i64 + wider[axis] as i64);
|
|
||||||
let rectangle = counts_continued([x as i64 - reach[0], y as i64 - reach[1]], [x as i64 + reach[0] + 1, y as i64 + reach[1] + 1]);
|
|
||||||
sum = std::array::from_fn(|channel| sum[channel] + weight * rectangle[channel]);
|
|
||||||
}
|
|
||||||
|
|
||||||
let total = (2. * half_width.x + 1.) * (2. * half_width.y + 1.) * scale;
|
|
||||||
target[first..first + 2].copy_from_slice(&sum.map(|channel| (channel / total) as f32));
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Pixels not blurred keep their color, and the rest return to gamma from linear light
|
|
||||||
let encode = transferred(linear_to_srgb);
|
|
||||||
for ((average, &original), &luminance) in averages.data.iter_mut().zip(&image.data).zip(luminances) {
|
|
||||||
*average = match luminance > 0. {
|
|
||||||
false => original,
|
|
||||||
true if linear => encode(*average),
|
|
||||||
true => *average,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
averages
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use crate::effect_kernels::box_weight;
|
|
||||||
|
|
||||||
/// The standard normal cumulative distribution, from the Abramowitz and Stegun approximation of the error function, accurate to 1e-7.
|
|
||||||
fn normal_cdf(x: f64) -> f64 {
|
|
||||||
let z = x.abs() / std::f64::consts::SQRT_2;
|
|
||||||
let t = 1. / (1. + 0.327_591_1 * z);
|
|
||||||
let polynomial = t * (0.254_829_592 + t * (-0.284_496_736 + t * (1.421_413_741 + t * (-1.453_152_027 + t * 1.061_405_429))));
|
|
||||||
let erf = 1. - polynomial * (-z * z).exp();
|
|
||||||
if x >= 0. { 0.5 * (1. + erf) } else { 0.5 * (1. - erf) }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A plane of white content with the alpha `coverage` gives at each pixel's center.
|
|
||||||
fn content(size: usize, coverage: impl Fn(f64, f64) -> f32) -> Plane<[f32; 4]> {
|
|
||||||
let mut plane = Plane::<[f32; 4]>::new(size, size);
|
|
||||||
for (index, pixel) in plane.data.iter_mut().enumerate() {
|
|
||||||
let alpha = coverage((index % size) as f64 + 0.5, (index / size) as f64 + 0.5);
|
|
||||||
*pixel = [alpha; 4];
|
|
||||||
}
|
|
||||||
plane
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The feather's strength across a straight edge, as the definition gives it for a pixel center at `depth` within the edge.
|
|
||||||
fn expected(depth: f64, distance: f64) -> f64 {
|
|
||||||
normal_cdf((depth - distance / 2.) / (distance / 6.))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn feathers_follow_the_definition_across_straight_and_round_edges() {
|
|
||||||
let distance = 16.;
|
|
||||||
|
|
||||||
// A square from 8 to 56, measured across its left edge on its middle row
|
|
||||||
let square = content(64, |x, y| if (8. ..56.).contains(&x) && (8. ..56.).contains(&y) { 1. } else { 0. });
|
|
||||||
let strength = feather_strength(&square, distance);
|
|
||||||
for x in 8..30 {
|
|
||||||
let depth = x as f64 + 0.5 - 8.;
|
|
||||||
let actual = strength.data[32 * 64 + x] as f64;
|
|
||||||
assert!((actual - expected(depth, distance)).abs() < 0.03, "at depth {depth} the square keeps {actual}");
|
|
||||||
}
|
|
||||||
|
|
||||||
// A disk of radius 28 with an antialiased edge, measured along a diagonal, where distances by chamfer steps would stray from straight lines
|
|
||||||
let disk = content(80, |x, y| (28.5 - (x - 40.).hypot(y - 40.)).clamp(0., 1.) as f32);
|
|
||||||
let strength = feather_strength(&disk, distance);
|
|
||||||
for step in 0..14 {
|
|
||||||
let (x, y) = (40 + 19 - step, 40 + 19 - step);
|
|
||||||
let depth = 28. - (x as f64 + 0.5 - 40.).hypot(y as f64 + 0.5 - 40.);
|
|
||||||
let actual = strength.data[y * 80 + x] as f64;
|
|
||||||
assert!((actual - expected(depth, distance)).abs() < 0.04, "at depth {depth} on the diagonal the disk keeps {actual}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn feathers_fade_thin_parts_and_hole_edges_and_keep_translucent_edges_where_opaque_ones_are() {
|
|
||||||
let distance = 12.;
|
|
||||||
|
|
||||||
// A strip thinner than the distance fades away entirely
|
|
||||||
let strip = content(48, |x, _| if (20. ..26.).contains(&x) { 1. } else { 0. });
|
|
||||||
let strength = feather_strength(&strip, distance);
|
|
||||||
assert!(strength.data[24 * 48 + 23] < 0.01, "the strip's middle keeps {}", strength.data[24 * 48 + 23]);
|
|
||||||
|
|
||||||
// A hole's edge fades like the outline's
|
|
||||||
let holed = content(64, |x, y| if (x - 32.).hypot(y - 32.) < 4. { 0. } else { 1. });
|
|
||||||
let strength = feather_strength(&holed, distance);
|
|
||||||
assert!(strength.data[32 * 64 + 36] < 0.05, "beside the hole the content keeps {}", strength.data[32 * 64 + 36]);
|
|
||||||
|
|
||||||
// Content at 40% places its edge as opaque content does
|
|
||||||
let opaque = feather_strength(&content(48, |x, _| if x >= 16. { 1. } else { 0. }), distance);
|
|
||||||
let translucent = feather_strength(&content(48, |x, _| if x >= 16. { 0.4 } else { 0. }), distance);
|
|
||||||
for x in 16..32 {
|
|
||||||
assert!(
|
|
||||||
(opaque.data[24 * 48 + x] - translucent.data[24 * 48 + x]).abs() < 1e-4,
|
|
||||||
"at {x} the translucent content is feathered differently"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_feather_of_almost_nothing_keeps_the_content_as_it_is() {
|
|
||||||
let disk = content(32, |x, y| (10.5 - (x - 16.).hypot(y - 16.)).clamp(0., 1.) as f32);
|
|
||||||
let strength = feather_strength(&disk, 0.01);
|
|
||||||
for (pixel, strength) in disk.data.iter().zip(&strength.data) {
|
|
||||||
if pixel[3] > 0. {
|
|
||||||
assert!(*strength > 0.98, "a pixel of alpha {} keeps only {strength}", pixel[3]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Premultiplied colors varying across the plane up to its edges, every seventh pixel transparent and some translucent.
|
|
||||||
fn colorful(width: usize, height: usize) -> Plane<[f32; 4]> {
|
|
||||||
let data = (0..width * height)
|
|
||||||
.map(|index| {
|
|
||||||
let (x, y) = ((index % width) as f32 / width as f32, (index / width) as f32 / height as f32);
|
|
||||||
let alpha = [0., 0.5, 0.5, 1., 1., 1., 1.][index % 7];
|
|
||||||
[x * alpha, y * alpha, (1. - x * y) * alpha, alpha]
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
Plane { width, height, data }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The box of `half_width` along each axis around a pixel of the plane, summed pixel by pixel with the edge pixels held past the edges.
|
|
||||||
fn summed_box(plane: &Plane<[f32; 4]>, x: usize, y: usize, half_width: DVec2) -> [f32; 4] {
|
|
||||||
let reach = half_width.ceil().as_i64vec2();
|
|
||||||
let (mut sum, mut total) = ([0.; 4], 0.);
|
|
||||||
for offset_y in -reach.y..=reach.y {
|
|
||||||
for offset_x in -reach.x..=reach.x {
|
|
||||||
let weight = box_weight(half_width.x, offset_x.unsigned_abs() as usize) * box_weight(half_width.y, offset_y.unsigned_abs() as usize);
|
|
||||||
let source_x = (x as i64 + offset_x).clamp(0, plane.width as i64 - 1) as usize;
|
|
||||||
let source_y = (y as i64 + offset_y).clamp(0, plane.height as i64 - 1) as usize;
|
|
||||||
let pixel = plane.data[source_y * plane.width + source_x];
|
|
||||||
|
|
||||||
sum = std::array::from_fn(|channel| sum[channel] + weight * pixel[channel] as f64);
|
|
||||||
total += weight;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
sum.map(|channel| (channel / total) as f32)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn variable_box_blurs_box_each_pixel_by_its_own_fraction_of_the_radius() {
|
|
||||||
let image = colorful(37, 29);
|
|
||||||
// Luminances finer than 8-bit codes, with every 41st pixel unblurred
|
|
||||||
let luminances: Vec<f32> = (0..37 * 29).map(|index| if index % 41 == 0 { 0. } else { ((index * 37) % 1000) as f32 / 1000. }).collect();
|
|
||||||
let radius = DVec2::new(9.3, 6.);
|
|
||||||
|
|
||||||
for linear in [false, true] {
|
|
||||||
let blurred = variable_box_blur(&image, &luminances, radius, linear);
|
|
||||||
let decoded = if linear { image.map(transferred(srgb_to_linear)) } else { image.clone() };
|
|
||||||
|
|
||||||
// Counting in 4096 steps rounds by up to half a step, which gamma encoding stretches up to 13 times near black
|
|
||||||
let tolerance = if linear { 2e-3 } else { 2e-4 };
|
|
||||||
|
|
||||||
for (index, &luminance) in luminances.iter().enumerate() {
|
|
||||||
// A luminance of 0 leaves its pixel exactly as it is
|
|
||||||
if luminance <= 0. {
|
|
||||||
assert_eq!(blurred.data[index], image.data[index]);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
let summed = summed_box(&decoded, index % 37, index / 37, radius * luminance as f64);
|
|
||||||
let expected = if linear { transferred(linear_to_srgb)(summed) } else { summed };
|
|
||||||
for channel in 0..4 {
|
|
||||||
let difference = (blurred.data[index][channel] - expected[channel]).abs();
|
|
||||||
assert!(
|
|
||||||
difference < tolerance,
|
|
||||||
"pixel {index} of luminance {luminance} differs by {difference} in channel {channel} (linear: {linear})"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn variable_box_blurs_of_one_fraction_of_the_radius_are_the_box_blur_of_that_half_width() {
|
|
||||||
let image = colorful(48, 40);
|
|
||||||
let luminances = vec![0.6; 48 * 40];
|
|
||||||
let radius = DVec2::new(20., 12.5);
|
|
||||||
let half_width = radius * 0.6_f32 as f64;
|
|
||||||
|
|
||||||
for linear in [false, true] {
|
|
||||||
let variable = variable_box_blur(&image, &luminances, radius, linear);
|
|
||||||
let even = blur(image.clone(), (BlurKernel::Box { radius: half_width.x }, BlurKernel::Box { radius: half_width.y }), linear);
|
|
||||||
for (index, (variable, even)) in variable.data.iter().zip(&even.data).enumerate() {
|
|
||||||
for channel in 0..4 {
|
|
||||||
let difference = (variable[channel] - even[channel]).abs();
|
|
||||||
assert!(difference < 2e-4, "pixel {index} differs by {difference} in channel {channel} (linear: {linear})");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -1,228 +0,0 @@
|
|||||||
//! The CPU steps of the layer styles' finer options: the outline's paints, the bevel's contour and texture, and the glows' grain.
|
|
||||||
|
|
||||||
use crate::effect_kernels::{NEGLIGIBLE_LENGTH, Plane};
|
|
||||||
use crate::filter_kernels::field_values;
|
|
||||||
use core_types::Color;
|
|
||||||
use core_types::transfer_curve::{TransferCurve, TransferCurveEvaluator};
|
|
||||||
use glam::{DAffine2, DVec2, DVec3};
|
|
||||||
use graphic_types::effects::{
|
|
||||||
ANTIALIASED_CONTOUR_OFFSETS, BEVEL_FOOT_FADE, BevelStyle, GRADIENT_TABLE_SIZE, GlowFill, bevel_lighting, bevel_lit, contour_end_slopes, contour_gradient_position, extended_contour,
|
|
||||||
slope_contour_input, slope_contour_reshapes, texture_gray,
|
|
||||||
};
|
|
||||||
use graphic_types::filters::{FieldSampling, MAX_FIELD_SAMPLES_PER_AXIS, RandomField};
|
|
||||||
use raster_types::parallel_rows::fill_rows;
|
|
||||||
|
|
||||||
/// An outline's coverage outside the content's edge and inside it, where it reaches, and each pixel's place across it for a contour gradient.
|
|
||||||
pub(super) struct OutlineBands {
|
|
||||||
pub outside: Option<Plane<f32>>,
|
|
||||||
pub inside: Option<Plane<f32>>,
|
|
||||||
pub positions: Option<Plane<f32>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The bands of an outline reaching `outside` pixels past the edge of the `silhouette` and `inside` pixels within it.
|
|
||||||
/// With a contour gradient's `start` and `span` in pixels (see `contour_gradient_span`), it also places each pixel across the outline.
|
|
||||||
/// Both bands grow by chamfer distances, which also measure each pixel's center from the edge for its place. O(width × height × log(weight)).
|
|
||||||
pub(super) fn outline_bands(silhouette: &Plane<f32>, outside: f64, inside: f64, contour_gradient: Option<(f64, f64)>) -> OutlineBands {
|
|
||||||
let outward = (outside >= NEGLIGIBLE_LENGTH || contour_gradient.is_some()).then(|| silhouette.distances_to_silhouette(outside + 1.));
|
|
||||||
let inward = (inside >= NEGLIGIBLE_LENGTH || contour_gradient.is_some()).then(|| silhouette.map(|alpha| 1. - alpha).distances_to_silhouette(inside + 1.));
|
|
||||||
|
|
||||||
// The silhouette grown by the band's width, as `Plane::grown` grows it
|
|
||||||
let band = |distances: &Option<Plane<f32>>, width: f64| {
|
|
||||||
let reach = width as f32 + 1.;
|
|
||||||
distances
|
|
||||||
.as_ref()
|
|
||||||
.filter(|_| width >= NEGLIGIBLE_LENGTH)
|
|
||||||
.map(|distances| distances.map(|nearest| (reach - nearest).clamp(0., 1.)))
|
|
||||||
};
|
|
||||||
|
|
||||||
// Each pixel's center lies half a pixel short of its distance from the edge, inside or out
|
|
||||||
let positions = match (&outward, &inward, contour_gradient) {
|
|
||||||
(Some(outward), Some(inward), Some((start, span))) => Some(outward.zip(inward, |outward, inward| {
|
|
||||||
let signed_distance = (outward - 0.5).max(0.) - (inward - 0.5).max(0.);
|
|
||||||
contour_gradient_position(signed_distance, start as f32, span as f32)
|
|
||||||
})),
|
|
||||||
_ => None,
|
|
||||||
};
|
|
||||||
|
|
||||||
OutlineBands {
|
|
||||||
outside: band(&outward, outside),
|
|
||||||
inside: band(&inward, inside),
|
|
||||||
positions,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The premultiplied gamma-encoded color of a contour `gradient` at each pixel's place across the outline, from the same table of samples the other renderers read.
|
|
||||||
pub(super) fn contour_gradient_colors(gradient: &GlowFill, positions: &Plane<f32>) -> Plane<[f32; 4]> {
|
|
||||||
let Some((samples, opacity)) = gradient.gradient_samples(GRADIENT_TABLE_SIZE) else {
|
|
||||||
return positions.map(|_| [0.; 4]);
|
|
||||||
};
|
|
||||||
let last = GRADIENT_TABLE_SIZE - 1;
|
|
||||||
|
|
||||||
positions.map(|position| {
|
|
||||||
let [red, green, blue, alpha] = samples[((position * last as f32).round() as usize).min(last)];
|
|
||||||
let alpha = alpha * opacity;
|
|
||||||
[red * alpha, green * alpha, blue * alpha, alpha]
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The gray of a bevel's texture at each pixel of a plane `width` by `height`, from its `colors` premultiplied in 8 bits as the GPU draws it.
|
|
||||||
pub(super) fn texture_grays(colors: Vec<Color>, width: usize, height: usize) -> Plane<f32> {
|
|
||||||
let data = colors
|
|
||||||
.into_iter()
|
|
||||||
.map(|color| {
|
|
||||||
let [red, green, blue, alpha] = color.to_gamma_srgb_channels();
|
|
||||||
texture_gray([red * alpha, green * alpha, blue * alpha, alpha].map(|channel| (channel * 255.).round() / 255.))
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
Plane { width, height, data }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What shapes a bevel's surface besides its height: a contour reshaping its slopes across a percentage of them, and a texture's gray sinking it by a percentage of its span.
|
|
||||||
pub(super) struct BevelSurface<'a> {
|
|
||||||
pub style: BevelStyle,
|
|
||||||
pub slope_contour: &'a TransferCurve,
|
|
||||||
pub slope_range: f64,
|
|
||||||
/// Whether the slope contour is sampled at nine points across each pixel.
|
|
||||||
pub slope_antialiased: bool,
|
|
||||||
pub texture: Option<Plane<f32>>,
|
|
||||||
pub texture_depth: f64,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The offsets toward a pixel's right and lower neighbors at which an antialiased contour samples it, or just the pixel itself.
|
|
||||||
fn sample_offsets(antialiased: bool) -> Vec<[f64; 2]> {
|
|
||||||
match antialiased {
|
|
||||||
true => ANTIALIASED_CONTOUR_OFFSETS.iter().flat_map(|&y| ANTIALIASED_CONTOUR_OFFSETS.map(|x| [x, y])).collect(),
|
|
||||||
false => vec![[0., 0.]],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A plane's value at `offset` from the pixel at `x` and `y` toward its right and lower neighbors, interpolated between them and holding the edge pixels beyond the edges.
|
|
||||||
fn sample_between(plane: &Plane<f32>, x: isize, y: isize, [offset_x, offset_y]: [f64; 2]) -> f64 {
|
|
||||||
let (columns, rows) = (plane.width as isize, plane.height as isize);
|
|
||||||
let at = |x: isize, y: isize| plane.data[(y.clamp(0, rows - 1) * columns + x.clamp(0, columns - 1)) as usize] as f64;
|
|
||||||
|
|
||||||
let top = at(x, y) * (1. - offset_x) + at(x + 1, y) * offset_x;
|
|
||||||
let bottom = at(x, y + 1) * (1. - offset_x) + at(x + 1, y + 1) * offset_x;
|
|
||||||
top * (1. - offset_y) + bottom * offset_y
|
|
||||||
}
|
|
||||||
|
|
||||||
/// How much each pixel of a bevel's surface is lit by the `light` past a flat surface's brightness (its highlight), and how much it falls short (its shadow), each from 0 to 1.
|
|
||||||
/// The surface's `height` runs from -0.5 at the slopes' foot to 0.5 at their top, which rise `rise` pixels as the `surface` options shape them, and it's lit through the `gloss` contour, antialiased if paired with true.
|
|
||||||
/// For PSD interop, a slope is the difference across a pixel's neighbors averaged over the three rows or columns they span, and antialiasing averages nine samples offset toward the right and lower neighbors.
|
|
||||||
/// O(width × height), nine times over when antialiased.
|
|
||||||
pub(super) fn bevel_shading(height: &Plane<f32>, surface: &BevelSurface, rise: f64, light: DVec3, gloss: Option<&(TransferCurveEvaluator, bool)>) -> [Plane<f32>; 2] {
|
|
||||||
let (columns, rows) = (height.width as isize, height.height as isize);
|
|
||||||
let reshaped = slope_contour_reshapes(surface.slope_contour, surface.style, surface.slope_range);
|
|
||||||
let contour = surface.slope_contour.evaluator();
|
|
||||||
let slopes = contour_end_slopes(&contour);
|
|
||||||
let texture_depth = surface.texture_depth / 100.;
|
|
||||||
|
|
||||||
// The surface's height in units of its span at an offset from a pixel, reshaped by the contour and sunk by the texture
|
|
||||||
let surface_at = |x: isize, y: isize, offset: [f64; 2]| {
|
|
||||||
let t = sample_between(height, x, y, offset) + 0.5;
|
|
||||||
let shaped = match reshaped {
|
|
||||||
true => extended_contour(&contour, slopes, slope_contour_input(t, surface.style, surface.slope_range)),
|
|
||||||
false => t,
|
|
||||||
};
|
|
||||||
shaped - surface.texture.as_ref().map_or(0., |texture| texture_depth * sample_between(texture, x, y, offset))
|
|
||||||
};
|
|
||||||
|
|
||||||
// How much brighter than flat ground each pixel is lit, averaged over the antialiased contour's samples, each lighting a whole grid of the surface offset alike
|
|
||||||
let offsets = sample_offsets(surface.slope_antialiased && reshaped);
|
|
||||||
let mut brighter = Plane::<f32>::new(height.width, height.height);
|
|
||||||
for &offset in &offsets {
|
|
||||||
let mut shifted = Plane::<f32>::new(height.width, height.height);
|
|
||||||
fill_rows(&mut shifted.data, height.width, |y, row| {
|
|
||||||
row.iter_mut().enumerate().for_each(|(x, value)| *value = surface_at(x as isize, y as isize, offset) as f32)
|
|
||||||
});
|
|
||||||
|
|
||||||
let at = |x: isize, y: isize| shifted.data[(y.clamp(0, rows - 1) * columns + x.clamp(0, columns - 1)) as usize] as f64;
|
|
||||||
fill_rows(&mut brighter.data, height.width, |y, row| {
|
|
||||||
let y = y as isize;
|
|
||||||
for (x, brighter) in row.iter_mut().enumerate() {
|
|
||||||
let x = x as isize;
|
|
||||||
let across = at(x + 1, y - 1) + at(x + 1, y) + at(x + 1, y + 1) - at(x - 1, y - 1) - at(x - 1, y) - at(x - 1, y + 1);
|
|
||||||
let down = at(x - 1, y + 1) + at(x, y + 1) + at(x + 1, y + 1) - at(x - 1, y - 1) - at(x, y - 1) - at(x + 1, y - 1);
|
|
||||||
*brighter += ((bevel_lit(DVec2::new(across, down) * rise / 6., light) - light.z) / offsets.len() as f64) as f32;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// The gloss contour reshapes how lit each pixel is, averaged likewise over samples toward its neighbors when antialiased
|
|
||||||
let brighter = match gloss {
|
|
||||||
Some((gloss, antialiased)) => {
|
|
||||||
let offsets = sample_offsets(*antialiased);
|
|
||||||
let mut glossy = Plane::<f32>::new(height.width, height.height);
|
|
||||||
fill_rows(&mut glossy.data, height.width, |y, row| {
|
|
||||||
for (x, value) in row.iter_mut().enumerate() {
|
|
||||||
let lit = |offset| gloss.evaluate(sample_between(&brighter, x as isize, y as isize, offset) + light.z).clamp(0., 1.);
|
|
||||||
*value = (offsets.iter().map(|&offset| lit(offset)).sum::<f64>() / offsets.len() as f64 - light.z) as f32;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
glossy
|
|
||||||
}
|
|
||||||
None => brighter,
|
|
||||||
};
|
|
||||||
|
|
||||||
let amounts = brighter.map(|brighter| {
|
|
||||||
let (highlight, shadow) = bevel_lighting(brighter as f64, light.z);
|
|
||||||
[highlight as f32, shadow as f32, 0., 0.]
|
|
||||||
});
|
|
||||||
[amounts.map(|[highlight, ..]| highlight), amounts.map(|[_, shadow, ..]| shadow)]
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A bevel's highlight and shadow `amounts` beneath the content, faded out across the slopes' foot by their `height` (from -0.5 at the foot), as a gloss contour or texture needs.
|
|
||||||
/// For PSD interop, that keeps the flat ground they shade from reaching past the foot.
|
|
||||||
pub(super) fn foot_faded(amounts: [Plane<f32>; 2], height: &Plane<f32>) -> [Plane<f32>; 2] {
|
|
||||||
amounts.map(|amount| amount.zip(height, |amount, height| amount.min((height + 0.5) / BEVEL_FOOT_FADE as f32)))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The most samples of grain a pixel takes.
|
|
||||||
const MAX_GRAIN_SAMPLES: usize = (MAX_FIELD_SAMPLES_PER_AXIS * MAX_FIELD_SAMPLES_PER_AXIS) as usize;
|
|
||||||
|
|
||||||
/// The random grain roughening a glow, as [`GlowFill::grained_color_at`] takes it.
|
|
||||||
pub(super) struct GlowGrain {
|
|
||||||
/// Where each pixel samples the grain, fixed to the cells of the effect space.
|
|
||||||
pub sampling: FieldSampling,
|
|
||||||
/// The field of the grain that the glow's seed gives.
|
|
||||||
field: u32,
|
|
||||||
/// How much each sample offsets the alpha (the noise) and moves a gradient's color (the jitter).
|
|
||||||
pub amounts: [f64; 2],
|
|
||||||
/// Which pixels the grain reaches, if not all of them.
|
|
||||||
reaches: Option<Vec<bool>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl GlowGrain {
|
|
||||||
/// The grain roughening a glow filled with `paint` by the `noise` and `jitter` percentages with its `seed`, on a plane that `plane_to_effect` places in the effect space, or `None` if it changes nothing.
|
|
||||||
pub fn new(paint: &GlowFill, noise: f64, jitter: f64, seed: i64, plane_to_effect: DAffine2) -> Option<Self> {
|
|
||||||
let amounts = paint.grain_amounts(noise, jitter)?;
|
|
||||||
|
|
||||||
Some(Self {
|
|
||||||
sampling: FieldSampling::new(plane_to_effect),
|
|
||||||
field: RandomField::GlowGrain.seed(seed),
|
|
||||||
amounts,
|
|
||||||
reaches: None,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The grain kept to the pixels no farther than `reach` from the content's edge, given each pixel's `distances` to it as [`Plane::distances_to_silhouette`] measures them.
|
|
||||||
pub fn within(self, distances: &Plane<f32>, reach: f32) -> Self {
|
|
||||||
let reaches = Some(distances.data.iter().map(|&distance| distance <= reach).collect());
|
|
||||||
Self { reaches, ..self }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The grain's samples from -1 to 1 at the pixel in column and row `pixel` (`index` in its plane), as many as the sampling takes, or `None` past its reach.
|
|
||||||
pub fn samples(&self, pixel: [usize; 2], index: usize) -> Option<([f64; MAX_GRAIN_SAMPLES], usize)> {
|
|
||||||
if self.reaches.as_ref().is_some_and(|reaches| !reaches[index]) {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut samples = [0.; MAX_GRAIN_SAMPLES];
|
|
||||||
let mut count = 0;
|
|
||||||
for cell in self.sampling.sample_cells(pixel).take(MAX_GRAIN_SAMPLES) {
|
|
||||||
samples[count] = 2. * field_values(cell, self.field)[0] as f64 - 1.;
|
|
||||||
count += 1;
|
|
||||||
}
|
|
||||||
Some((samples, count))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -480,10 +480,8 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn values_a_blend_if_hides_stay_hidden_through_adjustments_raising_alpha_as_rasters_do() {
|
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::EffectKind;
|
||||||
use graphic_types::blend_if::BlendIfRanges;
|
use graphic_types::blend_if::BlendIfRanges;
|
||||||
use raster_types::{Image, Raster};
|
|
||||||
|
|
||||||
// Shown only where the gray is at least half
|
// Shown only where the gray is at least half
|
||||||
let mut hides_darks = BlendIfRanges::default();
|
let mut hides_darks = BlendIfRanges::default();
|
||||||
@@ -497,15 +495,8 @@ mod tests {
|
|||||||
opacity: 100.,
|
opacity: 100.,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Black consumed as a color, which agrees with a raster's pixel of it
|
// Black consumed as a color, which the GPU's render of a raster of it agrees with (`blend_ifs_hide_rasters_through_adjustments_raising_alpha_as_they_hide_values` in wgpu-executor)
|
||||||
let black_through = |name: &str, rows: &[(EffectOperation, f64)]| {
|
let black_through = |rows: &[(EffectOperation, f64)]| *evaluate_color_effects(stamped(Color::BLACK, rows)).element();
|
||||||
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
|
// Hidden black stays hidden when made opaque, in its run or the next, where an overlay finds nothing to paint within either
|
||||||
let hidden = [
|
let hidden = [
|
||||||
@@ -514,11 +505,11 @@ mod tests {
|
|||||||
("made opaque and painted in the next run", vec![(blend_if.clone(), 1.), (make_opaque.clone(), 2.), (red.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 {
|
for (name, rows) in hidden {
|
||||||
assert_eq!(black_through(name, &rows).a(), 0., "black {name}");
|
assert_eq!(black_through(&rows).a(), 0., "black {name}");
|
||||||
}
|
}
|
||||||
|
|
||||||
// In its own run, an overlay still paints within the full-strength black
|
// 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.)]);
|
let painted = black_through(&[(blend_if.clone(), 1.), (make_opaque.clone(), 1.), (red, 1.)]);
|
||||||
assert!(close(gamma(painted), [1., 0., 0., 1.]), "{:?}", gamma(painted));
|
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
|
// A ramp made opaque stays hidden where it's dark, in the Blend If's run or the next
|
||||||
|
|||||||
@@ -1,684 +0,0 @@
|
|||||||
//! The Warp on the CPU, drawing the triangles of its tessellated patch in the order the GPU's mesh pass does.
|
|
||||||
|
|
||||||
use crate::effect_kernels::Plane;
|
|
||||||
use crate::resample_kernels::{pixel_area_within, sample_bilinear_within};
|
|
||||||
use glam::DVec2;
|
|
||||||
use graphic_types::resampling::{EffectFrame, WarpFragment, WarpTessellation};
|
|
||||||
use graphic_types::warp::WarpMesh;
|
|
||||||
use raster_types::parallel_rows::fill_rows;
|
|
||||||
|
|
||||||
/// A triangle of the tessellation, as its corners in the texels and their parameters (s, t), wound clockwise on screen.
|
|
||||||
struct Triangle {
|
|
||||||
corners: [DVec2; 3],
|
|
||||||
parameters: [DVec2; 3],
|
|
||||||
/// Twice its area.
|
|
||||||
area: f64,
|
|
||||||
/// Whether the patch turns its sheet over here, as where it folds over itself.
|
|
||||||
reversed: bool,
|
|
||||||
/// The part of the warp it draws.
|
|
||||||
fragment: WarpFragment,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Triangle {
|
|
||||||
/// The triangle drawing a `fragment` with these corners, wound clockwise on screen, or `None` if it covers no area.
|
|
||||||
/// It's reversed where its winding disagrees with the square's `orientation` (the sign of its placement's determinant), which is 0 for the fringe.
|
|
||||||
fn new(mut corners: [(DVec2, DVec2); 3], orientation: f64, fragment: WarpFragment) -> Option<Self> {
|
|
||||||
let area = |corners: &[(DVec2, DVec2); 3]| (corners[1].1 - corners[0].1).perp_dot(corners[2].1 - corners[0].1);
|
|
||||||
let reversed = area(&corners) * orientation < 0.;
|
|
||||||
if area(&corners) < 0. {
|
|
||||||
corners.swap(1, 2);
|
|
||||||
}
|
|
||||||
let area = area(&corners);
|
|
||||||
(area > 0. && area.is_finite()).then(|| Self {
|
|
||||||
corners: corners.map(|(_, texel)| texel),
|
|
||||||
parameters: corners.map(|(parameters, _)| parameters),
|
|
||||||
area,
|
|
||||||
reversed,
|
|
||||||
fragment,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The parameters (s, t) interpolated at a `point` in the texels, if the triangle covers it.
|
|
||||||
/// A point on an edge belongs to the triangle only along its top or left edges, so the triangles sharing it cover it once.
|
|
||||||
fn interpolated(&self, point: DVec2) -> Option<DVec2> {
|
|
||||||
let mut weights = [0.; 3];
|
|
||||||
for edge in 0..3 {
|
|
||||||
let (start, end) = (self.corners[(edge + 1) % 3], self.corners[(edge + 2) % 3]);
|
|
||||||
|
|
||||||
// Measured from the same end of the edge for both triangles sharing it, so roundoff can't leave a point on it outside both
|
|
||||||
let side = match (start.x, start.y) < (end.x, end.y) {
|
|
||||||
true => (end - start).perp_dot(point - start),
|
|
||||||
false => -(start - end).perp_dot(point - end),
|
|
||||||
};
|
|
||||||
|
|
||||||
// On screen, clockwise winding puts the top edge heading right and the left edges heading up
|
|
||||||
let top_or_left = (start.y == end.y && end.x > start.x) || end.y < start.y;
|
|
||||||
if side < 0. || (side == 0. && !top_or_left) {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
weights[edge] = side / self.area;
|
|
||||||
}
|
|
||||||
Some(self.parameters[0] * weights[0] + self.parameters[1] * weights[1] + self.parameters[2] * weights[2])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A Warp of the `mesh` (as fractions of its square) prepared for planes of one size, matching the GPU's mesh pass, so several planes warp through it with the work shared.
|
|
||||||
/// The fringe past the square's sides and corners is drawn first, then each triangle of the tessellation paints over those before it the content within the square that its texels' polished sources read,
|
|
||||||
/// leaving clear all that the bent square doesn't cover. For PSD interop, where it folds, the sheet turned over shows on top, like a flap of paper folded toward the viewer, so its triangles are drawn after the rest.
|
|
||||||
pub struct WarpRasterizer {
|
|
||||||
square: EffectFrame,
|
|
||||||
tessellation: Option<WarpTessellation>,
|
|
||||||
triangles: Vec<Option<Triangle>>,
|
|
||||||
/// The triangles each row of pixel centers may cross, in the order they're drawn.
|
|
||||||
crossing: Vec<Vec<u32>>,
|
|
||||||
width: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl WarpRasterizer {
|
|
||||||
/// The warp of the `mesh` within the `square` (see [`graphic_types::resampling::warp_frame`]) for planes `width` by `height`. O(triangles and the rows they cross).
|
|
||||||
pub fn new(mesh: &WarpMesh, square: &EffectFrame, width: usize, height: usize) -> Self {
|
|
||||||
let tessellation = WarpTessellation::new(mesh, square, DVec2::new(width as f64, height as f64));
|
|
||||||
let mut triangles = Vec::new();
|
|
||||||
let mut crossing: Vec<Vec<u32>> = vec![Vec::new(); height];
|
|
||||||
|
|
||||||
if let Some(tessellation) = &tessellation {
|
|
||||||
// The fringe's quads along the left, right, top, and bottom sides, then past the corners where both sides meet, each split into two triangles as the GPU draws them
|
|
||||||
let [columns, rows] = tessellation.cells;
|
|
||||||
let quad = |[first, second, third, fourth]: [(DVec2, DVec2); 4], fragment| [Triangle::new([first, second, third], 0., fragment), Triangle::new([first, third, fourth], 0., fragment)];
|
|
||||||
for side in (0..4).filter(|&side| tessellation.sides[side]) {
|
|
||||||
let segments = if side < 2 { rows } else { columns };
|
|
||||||
for along in 0..segments {
|
|
||||||
let corners = [(along, false), (along + 1, false), (along + 1, true), (along, true)].map(|(along, outer)| tessellation.fringe_vertex(side, along, outer));
|
|
||||||
triangles.extend(quad(corners, WarpFragment::PastSide(side)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for corner in (0..4).filter(|&corner| tessellation.sides[corner % 2] && tessellation.sides[2 + corner / 2]) {
|
|
||||||
let corners = [[false, false], [true, false], [true, true], [false, true]].map(|outer| tessellation.corner_vertex(corner, outer));
|
|
||||||
triangles.extend(quad(corners, WarpFragment::PastCorner(corner)));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Each cell's two triangles, cell by cell across each row of cells and row by row down, as the GPU draws them
|
|
||||||
let vertices: Vec<(DVec2, DVec2)> = (0..=rows)
|
|
||||||
.flat_map(|row| (0..=columns).map(move |column| (column, row)))
|
|
||||||
.map(|index| tessellation.vertex(index.into()))
|
|
||||||
.collect();
|
|
||||||
let corner = |column: u32, row: u32| vertices[(row * (columns + 1) + column) as usize];
|
|
||||||
let orientation = tessellation.source.matrix2.determinant().signum();
|
|
||||||
triangles.reserve(2 * (columns * rows) as usize);
|
|
||||||
for row in 0..rows {
|
|
||||||
for column in 0..columns {
|
|
||||||
let [top_left, top_right, bottom_left, bottom_right] = [corner(column, row), corner(column + 1, row), corner(column, row + 1), corner(column + 1, row + 1)];
|
|
||||||
triangles.extend([
|
|
||||||
Triangle::new([top_left, top_right, bottom_right], orientation, WarpFragment::Within),
|
|
||||||
Triangle::new([top_left, bottom_right, bottom_left], orientation, WarpFragment::Within),
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Those turned over are drawn after the rest
|
|
||||||
let drawn = [false, true]
|
|
||||||
.into_iter()
|
|
||||||
.flat_map(|reversed| (triangles.iter().enumerate()).filter_map(move |(index, triangle)| Some((index, triangle.as_ref().filter(|triangle| triangle.reversed == reversed)?))));
|
|
||||||
for (index, triangle) in drawn {
|
|
||||||
let (top, bottom) = triangle
|
|
||||||
.corners
|
|
||||||
.iter()
|
|
||||||
.fold((f64::INFINITY, f64::NEG_INFINITY), |(top, bottom), corner| (top.min(corner.y), bottom.max(corner.y)));
|
|
||||||
let first = (top - 0.5).ceil().max(0.);
|
|
||||||
let last = (bottom - 0.5).floor().min(height as f64 - 1.);
|
|
||||||
if first <= last {
|
|
||||||
(first as usize..=last as usize).for_each(|y| crossing[y].push(index as u32));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Self {
|
|
||||||
square: *square,
|
|
||||||
tessellation,
|
|
||||||
triangles,
|
|
||||||
crossing,
|
|
||||||
width,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The `plane` (of the size the warp was prepared for) carried through the warp. O(width × height).
|
|
||||||
pub fn warped(&self, plane: &Plane<[f32; 4]>) -> Plane<[f32; 4]> {
|
|
||||||
if plane.width != self.width || plane.height != self.crossing.len() {
|
|
||||||
log::error!(
|
|
||||||
"A Warp prepared for {} by {} pixels was given a plane {} by {}",
|
|
||||||
self.width,
|
|
||||||
self.crossing.len(),
|
|
||||||
plane.width,
|
|
||||||
plane.height
|
|
||||||
);
|
|
||||||
return plane.clone();
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut result = Plane::<[f32; 4]>::new(plane.width, plane.height);
|
|
||||||
let Some(tessellation) = &self.tessellation else { return result };
|
|
||||||
let area_within = pixel_area_within(&self.square);
|
|
||||||
|
|
||||||
// The triangles paint over each other from clear
|
|
||||||
fill_rows(&mut result.data, plane.width, |y, row| {
|
|
||||||
let center_y = y as f64 + 0.5;
|
|
||||||
for triangle in self.crossing[y].iter().filter_map(|&index| self.triangles[index as usize].as_ref()) {
|
|
||||||
let (left, right) = triangle
|
|
||||||
.corners
|
|
||||||
.iter()
|
|
||||||
.fold((f64::INFINITY, f64::NEG_INFINITY), |(left, right), corner| (left.min(corner.x), right.max(corner.x)));
|
|
||||||
let first = (left - 0.5).ceil().max(0.);
|
|
||||||
let last = (right - 0.5).floor().min(plane.width as f64 - 1.);
|
|
||||||
if first > last {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (x, pixel) in row.iter_mut().enumerate().take(last as usize + 1).skip(first as usize) {
|
|
||||||
let target = DVec2::new(x as f64 + 0.5, center_y);
|
|
||||||
let Some(seed) = triangle.interpolated(target) else { continue };
|
|
||||||
let parameters = match triangle.fragment {
|
|
||||||
WarpFragment::Within => tessellation.polished(seed, target),
|
|
||||||
_ => seed,
|
|
||||||
};
|
|
||||||
|
|
||||||
// The content within the square there, faded by how much of the pixel the warped square covers, painted over what earlier triangles left
|
|
||||||
let shade = tessellation.shade(triangle.fragment, parameters, target);
|
|
||||||
let coverage = shade.coverage as f32;
|
|
||||||
if coverage <= 0. {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let color = sample_bilinear_within(plane, tessellation.source.transform_point2(shade.read), &area_within);
|
|
||||||
let painted = color.map(|channel| channel * coverage);
|
|
||||||
*pixel = std::array::from_fn(|channel| painted[channel] + pixel[channel] * (1. - painted[3]));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
result
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use glam::{DAffine2, UVec2};
|
|
||||||
use graphic_types::resampling::{warp_frame, warp_half_fade};
|
|
||||||
use graphic_types::warp::{Warp, WarpStyle};
|
|
||||||
|
|
||||||
/// The plane carried through the Warp of the `mesh` (as fractions of the `square`).
|
|
||||||
fn warped_plane(plane: &Plane<[f32; 4]>, mesh: &WarpMesh, square: &EffectFrame) -> Plane<[f32; 4]> {
|
|
||||||
WarpRasterizer::new(mesh, square, plane.width, plane.height).warped(plane)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A plane 60 by 40 of colors ramping across and down, with the warp's square its middle 40 by 20 pixels.
|
|
||||||
fn ramps() -> (Plane<[f32; 4]>, EffectFrame) {
|
|
||||||
let mut plane = Plane::<[f32; 4]>::new(60, 40);
|
|
||||||
plane.data = (0..60 * 40).map(|index| [(index % 60) as f32 / 60., (index / 60) as f32 / 40., 0.5, 1.]).collect();
|
|
||||||
let square = warp_frame(DAffine2::from_translation(DVec2::new(30., 20.)) * DAffine2::from_scale(DVec2::new(40., 20.)), DAffine2::IDENTITY).unwrap();
|
|
||||||
(plane, square)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn warp(style: WarpStyle, bend: f64) -> Warp {
|
|
||||||
Warp {
|
|
||||||
style,
|
|
||||||
bend,
|
|
||||||
horizontal_distortion: 0.,
|
|
||||||
vertical_distortion: 0.,
|
|
||||||
vertical: false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_warp_without_bend_leaves_every_pixel_within_its_square_as_it_is_and_clears_the_rest() {
|
|
||||||
let (plane, square) = ramps();
|
|
||||||
let warped = warped_plane(&plane, &warp(WarpStyle::Twist, 0.).mesh(square.size), &square);
|
|
||||||
|
|
||||||
// The square's sides run along the pixels' edges, so each pixel lies wholly within or past it
|
|
||||||
for (index, (warped, original)) in warped.data.iter().zip(&plane.data).enumerate() {
|
|
||||||
let within = (10..50).contains(&(index % 60)) && (10..30).contains(&(index / 60));
|
|
||||||
let expected = if within { *original } else { [0.; 4] };
|
|
||||||
let difference = warped.iter().zip(expected).map(|(a, b)| (a - b).abs()).fold(0., f32::max);
|
|
||||||
assert!(difference < 1e-4, "pixel {index} became {warped:?} rather than {expected:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn each_pixel_shows_the_content_where_the_patch_carries_it_from() {
|
|
||||||
let (plane, square) = ramps();
|
|
||||||
let mesh = warp(WarpStyle::Flag, 0.3).mesh(square.size);
|
|
||||||
let warped = warped_plane(&plane, &mesh, &square);
|
|
||||||
|
|
||||||
// The ramps read back where each point of the square lands
|
|
||||||
for uv in [DVec2::new(0.2, 0.3), DVec2::new(0.5, 0.5), DVec2::new(0.85, 0.6)] {
|
|
||||||
let landed = square.to_pixels.transform_point2(mesh.point(uv));
|
|
||||||
let pixel = landed.floor();
|
|
||||||
let color = warped.data[pixel.y as usize * 60 + pixel.x as usize];
|
|
||||||
|
|
||||||
// The pixel's center reads from near the point, which the ramps show to within a pixel
|
|
||||||
let source = square.to_pixels.transform_point2(uv);
|
|
||||||
assert!((color[0] * 60. - source.x as f32).abs() < 1.5, "{uv} reads across from {}, not {}", color[0] * 60., source.x);
|
|
||||||
assert!((color[1] * 40. - source.y as f32).abs() < 1.5, "{uv} reads down from {}, not {}", color[1] * 40., source.y);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn what_lies_outside_the_square_and_what_the_bend_leaves_of_it_clear() {
|
|
||||||
// A flag only raises and lowers the square's content, lowering its top edge on the left and raising it on the right
|
|
||||||
let (plane, square) = ramps();
|
|
||||||
let mesh = warp(WarpStyle::Flag, 0.2).mesh(square.size);
|
|
||||||
let warped = warped_plane(&plane, &mesh, &square);
|
|
||||||
|
|
||||||
// Beside the square, and above it where the flag lowers its top edge, all is clear
|
|
||||||
for (x, y) in [(55, 20), (3, 35), (20, 3)] {
|
|
||||||
assert_eq!(warped.data[y * 60 + x], [0.; 4], "({x}, {y}) isn't clear");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Where it lowers the top edge, what it leaves of the square is clear, and where it raises it, the square's top row shows above the square
|
|
||||||
assert!(warped.data[10 * 60 + 20][3] < 1e-3, "the square's top left shows {:?}", warped.data[10 * 60 + 20]);
|
|
||||||
let raised = warped.data[8 * 60 + 40];
|
|
||||||
assert!((raised[1] * 40. - 10.5).abs() < 1.5 && raised[3] > 0.99, "above the square's top right shows {raised:?}");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether the patch of the `mesh` turns over anywhere within its unit square, so parts of it overlap, by the sign of its Jacobian across a dense grid.
|
|
||||||
fn folds(mesh: &WarpMesh) -> bool {
|
|
||||||
(0..65 * 65).any(|index| {
|
|
||||||
let [_, along_u, along_v] = mesh.point_and_tangents(DVec2::new((index % 65) as f64, (index / 65) as f64) / 64.);
|
|
||||||
along_u.perp_dot(along_v) <= 1e-9
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// How many points of the unit square the patch of `mesh` (in pixels) carries onto `point`, found by splitting the square until its parts are small, then polishing each part's middle onto it.
|
|
||||||
/// A part whose polish settles outside it, or nowhere, splits further, as beside a fold's crease, and the points found from several parts count once.
|
|
||||||
fn preimages(mesh: &WarpMesh, point: DVec2) -> usize {
|
|
||||||
let mut found: Vec<DVec2> = Vec::new();
|
|
||||||
let mut parts = vec![(DVec2::ZERO, DVec2::ONE)];
|
|
||||||
while let Some((start, end)) = parts.pop() {
|
|
||||||
let [min, max] = mesh.over(start, end).hull_bounds();
|
|
||||||
if point.cmplt(min).any() || point.cmpgt(max).any() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let middle = (start + end) / 2.;
|
|
||||||
let split = [
|
|
||||||
(start, middle),
|
|
||||||
(DVec2::new(middle.x, start.y), DVec2::new(end.x, middle.y)),
|
|
||||||
(DVec2::new(start.x, middle.y), DVec2::new(middle.x, end.y)),
|
|
||||||
(middle, end),
|
|
||||||
];
|
|
||||||
let size = (end - start).max_element();
|
|
||||||
if size > 1. / 64. {
|
|
||||||
parts.extend(split);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut uv = middle;
|
|
||||||
for _ in 0..16 {
|
|
||||||
let [landed, along_u, along_v] = mesh.point_and_tangents(uv);
|
|
||||||
let (residual, determinant) = (landed - point, along_u.perp_dot(along_v));
|
|
||||||
if determinant.abs() < 1e-12 {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
uv -= DVec2::new(residual.perp_dot(along_v), along_u.perp_dot(residual)) / determinant;
|
|
||||||
}
|
|
||||||
|
|
||||||
let settled = (mesh.point(uv) - point).length() < 1e-6;
|
|
||||||
if settled && uv.cmpge(DVec2::ZERO).all() && uv.cmple(DVec2::ONE).all() && found.iter().all(|other| other.distance(uv) > 1e-7) {
|
|
||||||
found.push(uv);
|
|
||||||
}
|
|
||||||
let within_part = uv.cmpge(start - 1e-9).all() && uv.cmple(end + 1e-9).all();
|
|
||||||
if !(settled && within_part) && size > 1. / 4096. {
|
|
||||||
parts.extend(split);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
found.len()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// How many layers of content show at each of 8 by 8 samples across `pixel` (its corner) after the Warp of the `mesh` (as fractions of the `square`):
|
|
||||||
/// one for each point of the square the patch carries onto it.
|
|
||||||
fn supersampled_layers(mesh: &WarpMesh, square: &EffectFrame, pixel: DVec2) -> [usize; 64] {
|
|
||||||
let in_pixels = mesh.transformed(square.to_pixels);
|
|
||||||
std::array::from_fn(|index| preimages(&in_pixels, pixel + (DVec2::new((index % 8) as f64, (index / 8) as f64) + 0.5) / 8.))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// How much of the pixel with its corner at `pixel` the `square` itself covers, fading across its sides as a side the warp keeps in place does.
|
|
||||||
fn square_coverage(square: &EffectFrame, pixel: DVec2) -> f32 {
|
|
||||||
let (local, half, half_fade) = (square.pixels_to_local().transform_point2(pixel + 0.5), square.size / 2., warp_half_fade(square));
|
|
||||||
(0.5 + (half - local.abs()) / (2. * half_fade)).clamp(DVec2::ZERO, DVec2::ONE).element_product() as f32
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn sides_a_bend_keeps_in_place_match_the_content_at_any_squeeze_and_offset() {
|
|
||||||
use WarpStyle::*;
|
|
||||||
|
|
||||||
// Content of one color reaching past a square 39 by 19 at quarter-pixel offsets and scaled between pixels (its corners on the reference's samples), and past squares slanted and turned off the grid,
|
|
||||||
// which fisheyes, waves, and twists bend across their range while keeping all four sides in place
|
|
||||||
let bends = (-25..=25)
|
|
||||||
.map(|step| step as f64 * 0.04)
|
|
||||||
.chain([0.58, 0.59, 0.6, 0.61, 0.66, 0.67, 0.68, 0.75, 0.76, 0.77, -0.59, -0.6, -0.76]);
|
|
||||||
let placements = [
|
|
||||||
DAffine2::from_cols_array(&[39., 0., 0., 19., 30., 20.]),
|
|
||||||
DAffine2::from_cols_array(&[39., 0., 0., 19., 30.25, 20.5]),
|
|
||||||
DAffine2::from_cols_array(&[39., 0., 0., 19., 30.5, 20.25]),
|
|
||||||
DAffine2::from_cols_array(&[39., 0., 0., 19., 30.75, 20.75]),
|
|
||||||
DAffine2::from_cols_array(&[42.5, 0., 0., 20.75, 30.25, 20.375]),
|
|
||||||
DAffine2::from_cols_array(&[24., 0., 16., 14., 30.3, 20.6]),
|
|
||||||
DAffine2::from_translation(DVec2::new(30.4, 20.15)) * DAffine2::from_angle(0.5) * DAffine2::from_scale(DVec2::new(30., 14.)),
|
|
||||||
];
|
|
||||||
for (style, bend, placement) in [Fisheye, Wave, Twist]
|
|
||||||
.into_iter()
|
|
||||||
.flat_map(|style| bends.clone().flat_map(move |bend| placements.map(|placement| (style, bend, placement))))
|
|
||||||
{
|
|
||||||
let square = warp_frame(placement, DAffine2::IDENTITY).unwrap();
|
|
||||||
let mesh = warp(style, bend).mesh(square.size);
|
|
||||||
let folding = folds(&mesh);
|
|
||||||
let offset = placement.translation;
|
|
||||||
|
|
||||||
// The 3 by 3 pixels around each corner of an upright square, where its coverage is its area, with the layers a supersampled reference counts across them.
|
|
||||||
// A slanted square's edge fades by its coverage along its axes instead, as the square's own edge does, which the check of every pixel below holds it to.
|
|
||||||
let upright = placement.matrix2.x_axis.y == 0. && placement.matrix2.y_axis.x == 0.;
|
|
||||||
let corners = [DVec2::splat(-0.5), DVec2::new(0.5, -0.5), DVec2::new(-0.5, 0.5), DVec2::splat(0.5)].map(|corner| placement.transform_point2(corner));
|
|
||||||
let around_corners: Vec<(DVec2, [usize; 64])> = corners
|
|
||||||
.into_iter()
|
|
||||||
.filter(|_| upright)
|
|
||||||
.flat_map(|corner| (0..9).map(move |index| (corner - 1.5).floor() + DVec2::new((index % 3) as f64, (index / 3) as f64)))
|
|
||||||
.map(|pixel| (pixel, supersampled_layers(&mesh, &square, pixel)))
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
for alpha in [1., 0.5] {
|
|
||||||
let plane = Plane {
|
|
||||||
data: vec![[alpha; 4]; 60 * 40],
|
|
||||||
..Plane::<[f32; 4]>::new(60, 40)
|
|
||||||
};
|
|
||||||
let warped = warped_plane(&plane, &mesh, &square);
|
|
||||||
|
|
||||||
// Where the patch doesn't fold, it shows the content within the square, clear past it, and the content faded by the square's coverage across its sides.
|
|
||||||
// Where it folds, the layers of opaque content cover at least that much.
|
|
||||||
for (index, pixel) in warped.data.iter().enumerate() {
|
|
||||||
let expected = alpha * square_coverage(&square, DVec2::new((index % 60) as f64, (index / 60) as f64));
|
|
||||||
let error = pixel.iter().map(|channel| (channel - expected).abs()).fold(0., f32::max);
|
|
||||||
let (x, y) = (index % 60, index / 60);
|
|
||||||
if !folding {
|
|
||||||
assert!(
|
|
||||||
error < 1e-4,
|
|
||||||
"{style:?} at {bend} placed at {offset}, alpha {alpha}, shows {pixel:?} rather than {expected} at ({x}, {y})"
|
|
||||||
);
|
|
||||||
} else if alpha == 1. {
|
|
||||||
assert!(pixel[3] > expected - 1e-4, "{style:?} at {bend} placed at {offset} shows {pixel:?}, short of {expected} at ({x}, {y})");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Around each corner, it matches the reference
|
|
||||||
for (pixel, layers) in &around_corners {
|
|
||||||
let reference = layers.iter().map(|&layers| 1. - (1. - alpha).powi(layers as i32)).sum::<f32>() / 64.;
|
|
||||||
let shown = warped.data[pixel.y as usize * 60 + pixel.x as usize][3];
|
|
||||||
assert!(
|
|
||||||
(shown - reference).abs() < 1e-3,
|
|
||||||
"{style:?} at {bend} placed at {offset}, alpha {alpha}, shows {shown} at {pixel} rather than {reference}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn strongly_bent_styles_keep_opaque_content_opaque_within_their_patch_at_any_scale() {
|
|
||||||
use WarpStyle::*;
|
|
||||||
|
|
||||||
// Opaque content past squares 120 by 90 at non-integer scales, which fish (whose sides curve back near each other) and other styles bend far, both ways and turned, and fish within smaller squares
|
|
||||||
let styles = [Fish, Arch, Bulge, Flag, Wave, Fisheye, Squeeze, Twist];
|
|
||||||
let cases = |styles: Vec<WarpStyle>, square: DVec2| {
|
|
||||||
styles.into_iter().flat_map(move |style| {
|
|
||||||
[-1., -0.6, 0.6, 1.].into_iter().flat_map(move |bend| {
|
|
||||||
[false, true]
|
|
||||||
.into_iter()
|
|
||||||
.flat_map(move |vertical| [0.91, 1.09, 1.37].map(move |scale| (style, bend, vertical, square * scale)))
|
|
||||||
})
|
|
||||||
})
|
|
||||||
};
|
|
||||||
for (style, bend, vertical, size) in cases(styles.to_vec(), DVec2::new(120., 90.)).chain(cases(vec![Fish], DVec2::new(60., 40.))) {
|
|
||||||
let (width, height) = ((size.x * 3.) as usize, (size.y * 3.) as usize);
|
|
||||||
let plane = Plane {
|
|
||||||
data: vec![[1.; 4]; width * height],
|
|
||||||
..Plane::<[f32; 4]>::new(width, height)
|
|
||||||
};
|
|
||||||
let center = DVec2::new(width as f64, height as f64) / 2. + DVec2::new(0.3, 0.2);
|
|
||||||
let square = warp_frame(DAffine2::from_translation(center) * DAffine2::from_scale(size), DAffine2::IDENTITY).unwrap();
|
|
||||||
let mesh = Warp { vertical, ..warp(style, bend) }.mesh(square.size);
|
|
||||||
let warped = warped_plane(&plane, &mesh, &square);
|
|
||||||
|
|
||||||
// Each pixel the patch carries a point of the square onto, which lies at least a pixel within the patch and two from the curves its sides bend into, is opaque
|
|
||||||
let in_pixels = mesh.transformed(square.to_pixels);
|
|
||||||
let sides: Vec<DVec2> = (0..=400)
|
|
||||||
.flat_map(|index| {
|
|
||||||
let t = index as f64 / 400.;
|
|
||||||
[DVec2::new(0., t), DVec2::new(1., t), DVec2::new(t, 0.), DVec2::new(t, 1.)]
|
|
||||||
})
|
|
||||||
.map(|uv| in_pixels.point(uv))
|
|
||||||
.collect();
|
|
||||||
for index in 0..101 * 101 {
|
|
||||||
let uv = DVec2::new((index % 101) as f64, (index / 101) as f64) / 100.;
|
|
||||||
let pixel = in_pixels.point(uv).floor();
|
|
||||||
let within_plane = pixel.cmpge(DVec2::ZERO).all() && pixel.x < width as f64 && pixel.y < height as f64;
|
|
||||||
if !within_plane || sides.iter().any(|side| side.distance(pixel + 0.5) < 2.) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
let alpha = warped.data[pixel.y as usize * width + pixel.x as usize][3];
|
|
||||||
let within_patch = || {
|
|
||||||
[DVec2::ZERO, DVec2::X, -DVec2::X, DVec2::Y, -DVec2::Y]
|
|
||||||
.iter()
|
|
||||||
.all(|&offset| preimages(&in_pixels, pixel + 0.5 + offset) > 0)
|
|
||||||
};
|
|
||||||
assert!(
|
|
||||||
alpha > 0.99 || !within_patch(),
|
|
||||||
"{style:?} at {bend}, vertical {vertical}, within a square {size}, shows {alpha} at {pixel} from {uv}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn sides_curving_sharply_toward_a_pixel_fade_it() {
|
|
||||||
// Opaque content past a square 10 by 200 that a flag waves far, so its top side's crest curves tightly past the pixel (28, 87), a third of a pixel within it
|
|
||||||
let plane = Plane {
|
|
||||||
data: vec![[1.; 4]; 80 * 500],
|
|
||||||
..Plane::<[f32; 4]>::new(80, 500)
|
|
||||||
};
|
|
||||||
let square = warp_frame(DAffine2::from_cols_array(&[10., 0., 0., 200., 25.625, 300.75]), DAffine2::IDENTITY).unwrap();
|
|
||||||
let warped = warped_plane(&plane, &warp(WarpStyle::Flag, 1.).mesh(square.size), &square);
|
|
||||||
|
|
||||||
// It fades by the third of a pixel, as two thirds past the pixel's middle, though the curve's tangent where the pixel's source lies passes two pixels away
|
|
||||||
let alpha = warped.data[87 * 80 + 28][3];
|
|
||||||
assert!((alpha - 0.83).abs() < 0.02, "the pixel shows alpha {alpha}");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn fisheyes_squeezing_the_content_nearly_flat_against_a_side_keep_it_seamless() {
|
|
||||||
// Opaque content past a square with its top side three quarters of the way down a row of pixels, against which fisheyes squeeze the content nearly flat
|
|
||||||
for bend in [0.59, 0.6] {
|
|
||||||
let plane = Plane {
|
|
||||||
data: vec![[1.; 4]; 60 * 40],
|
|
||||||
..Plane::<[f32; 4]>::new(60, 40)
|
|
||||||
};
|
|
||||||
let square = warp_frame(DAffine2::from_cols_array(&[39., 0., 0., 19., 30.5, 20.25]), DAffine2::IDENTITY).unwrap();
|
|
||||||
let warped = warped_plane(&plane, &warp(WarpStyle::Fisheye, bend).mesh(square.size), &square);
|
|
||||||
for (index, pixel) in warped.data.iter().enumerate() {
|
|
||||||
let expected = square_coverage(&square, DVec2::new((index % 60) as f64, (index / 60) as f64));
|
|
||||||
assert!(
|
|
||||||
(pixel[3] - expected).abs() < 1e-4,
|
|
||||||
"bent {bend}, ({}, {}) shows {pixel:?} rather than {expected}",
|
|
||||||
index % 60,
|
|
||||||
index / 60
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn slanted_squares_keep_the_content_as_it_is_past_corners_they_keep_in_place() {
|
|
||||||
// Opaque content past a square slanted to corners an eighth of a turn sharp, off the pixel grid, within which a fisheye keeps the sides in place
|
|
||||||
let plane = Plane {
|
|
||||||
data: vec![[1.; 4]; 120 * 80],
|
|
||||||
..Plane::<[f32; 4]>::new(120, 80)
|
|
||||||
};
|
|
||||||
let square = warp_frame(DAffine2::from_cols_array(&[40., 0., 40., 40., 61., 40.75]), DAffine2::IDENTITY).unwrap();
|
|
||||||
let warped = warped_plane(&plane, &warp(WarpStyle::Fisheye, 0.4).mesh(square.size), &square);
|
|
||||||
for (index, pixel) in warped.data.iter().enumerate() {
|
|
||||||
let expected = square_coverage(&square, DVec2::new((index % 120) as f64, (index / 120) as f64));
|
|
||||||
assert!((pixel[3] - expected).abs() < 1e-4, "({}, {}) shows {pixel:?} rather than {expected}", index % 120, index / 120);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn folds_returning_over_a_side_change_smoothly_as_the_side_moves() {
|
|
||||||
// Clear rows down through the one a square's top side runs through the middle of, and opaque rows below, which a fisheye folds out over the clear rows and back
|
|
||||||
let alpha_at = |down: f64| {
|
|
||||||
let mut plane = Plane::<[f32; 4]>::new(60, 40);
|
|
||||||
plane.data[11 * 60..].fill([1.; 4]);
|
|
||||||
let square = warp_frame(DAffine2::from_cols_array(&[39., 0., 0., 19., 30.5, down]), DAffine2::IDENTITY).unwrap();
|
|
||||||
warped_plane(&plane, &warp(WarpStyle::Fisheye, 1.).mesh(square.size), &square).data[10 * 60 + 30][3]
|
|
||||||
};
|
|
||||||
|
|
||||||
// Moving the side a fiftieth of a pixel across the pixel's center moves its fade only as far
|
|
||||||
let (above, below) = (alpha_at(19.99), alpha_at(20.01));
|
|
||||||
assert!((above - below).abs() < 0.03, "the pixel's alpha jumps from {above} to {below}");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn folds_out_past_a_side_clear_what_lies_outside_the_square_beneath_them() {
|
|
||||||
// Opaque rows down to just above a square's top side, and clear rows below, which a fisheye folds out over the rows above
|
|
||||||
let mut plane = Plane::<[f32; 4]>::new(60, 40);
|
|
||||||
plane.data[..10 * 60].fill([1.; 4]);
|
|
||||||
let square = warp_frame(DAffine2::from_cols_array(&[39., 0., 0., 19., 30.5, 20.]), DAffine2::IDENTITY).unwrap();
|
|
||||||
let warped = warped_plane(&plane, &warp(WarpStyle::Fisheye, 1.).mesh(square.size), &square);
|
|
||||||
|
|
||||||
// The fold carries only the square's clear content, and the rows above clear
|
|
||||||
for (index, pixel) in warped.data.iter().enumerate() {
|
|
||||||
assert!(pixel[3] < 1e-4, "({}, {}) shows {pixel:?}", index % 60, index / 60);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn content_well_outside_the_bent_square_clears() {
|
|
||||||
// Opaque content 80 by 60 pixels, within which a flag bends a square 30 by 20 at its middle
|
|
||||||
let plane = Plane {
|
|
||||||
data: vec![[1.; 4]; 80 * 60],
|
|
||||||
..Plane::<[f32; 4]>::new(80, 60)
|
|
||||||
};
|
|
||||||
let square = warp_frame(DAffine2::from_cols_array(&[30., 0., 0., 20., 40., 30.]), DAffine2::IDENTITY).unwrap();
|
|
||||||
let mesh = warp(WarpStyle::Flag, 0.4).mesh(square.size);
|
|
||||||
let warped = warped_plane(&plane, &mesh, &square);
|
|
||||||
|
|
||||||
// The pixels within two and a half of where the patch carries the square, past which its edge's fade and its fringe's miters reach nothing
|
|
||||||
let in_pixels = mesh.transformed(square.to_pixels);
|
|
||||||
let mut near = vec![false; 80 * 60];
|
|
||||||
for index in 0..201 * 201 {
|
|
||||||
let point = in_pixels.point(DVec2::new((index % 201) as f64, (index / 201) as f64) / 200.);
|
|
||||||
for (x, y) in (-3..=3).flat_map(|y| (-3..=3).map(move |x| (x, y))) {
|
|
||||||
let pixel = (point - 0.5).round() + DVec2::new(x as f64, y as f64);
|
|
||||||
if (pixel + 0.5).distance(point) <= 2.5 && pixel.cmpge(DVec2::ZERO).all() && pixel.x < 80. && pixel.y < 60. {
|
|
||||||
near[pixel.y as usize * 80 + pixel.x as usize] = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// All else is clear, though the content was opaque there
|
|
||||||
let far: Vec<usize> = (0..80 * 60).filter(|&index| !near[index]).collect();
|
|
||||||
assert!(far.len() > 2000, "only {} pixels lie far from the patch", far.len());
|
|
||||||
for index in far {
|
|
||||||
assert_eq!(warped.data[index], [0.; 4], "({}, {}) shows {:?}", index % 80, index / 80, warped.data[index]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn nothing_wholly_outside_a_slanted_or_turned_square_is_carried_through_it() {
|
|
||||||
// Clear content but for an opaque pixel just above the top side of a slanted square, which an upper arc raises past where the pixel lies,
|
|
||||||
// or just above the top corner of a square turned an eighth, which an arc bends far around
|
|
||||||
let cases = [
|
|
||||||
(UVec2::new(80, 40), UVec2::new(30, 9), WarpStyle::ArcUpper, 0.5, [40., 0., 40., 4., 50., 12.]),
|
|
||||||
(UVec2::new(80, 60), UVec2::new(40, 9), WarpStyle::Arc, 0.8, [20., 20., -20., 20., 40.5, 30.01]),
|
|
||||||
];
|
|
||||||
for (size, opaque, style, bend, transform) in cases {
|
|
||||||
let mut plane = Plane::<[f32; 4]>::new(size.x as usize, size.y as usize);
|
|
||||||
plane.data[(opaque.y * size.x + opaque.x) as usize] = [1.; 4];
|
|
||||||
let square = warp_frame(DAffine2::from_cols_array(&transform), DAffine2::IDENTITY).unwrap();
|
|
||||||
let warped = warped_plane(&plane, &warp(style, bend).mesh(square.size), &square);
|
|
||||||
|
|
||||||
// The patch carries none of the pixel anywhere, and the pixel clears where it lies
|
|
||||||
for (index, pixel) in warped.data.iter().enumerate() {
|
|
||||||
assert!(pixel[3] < 1e-3, "{style:?} shows {pixel:?} at ({}, {})", index % plane.width, index / plane.width);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn squares_far_smaller_than_a_pixel_paint_nothing_past_the_content() {
|
|
||||||
// Opaque content 25 pixels across at a hundredth of a pixel per unit, twisted within a square one unit across at its middle, which its reach keeps within the content
|
|
||||||
let mut plane = Plane::<[f32; 4]>::new(64, 64);
|
|
||||||
for y in 0..25 {
|
|
||||||
plane.data[y * 64..y * 64 + 25].fill([1.; 4]);
|
|
||||||
}
|
|
||||||
let square = warp_frame(DAffine2::from_translation(DVec2::splat(1275.)), DAffine2::from_scale(DVec2::splat(0.01))).unwrap();
|
|
||||||
let warped = warped_plane(&plane, &warp(WarpStyle::Twist, 0.8).mesh(square.size), &square);
|
|
||||||
|
|
||||||
for (index, pixel) in warped.data.iter().enumerate() {
|
|
||||||
let (x, y) = (index % 64, index / 64);
|
|
||||||
assert!((x < 25 && y < 25) || pixel[3] < 1e-3, "({x}, {y}) past the content shows {pixel:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn folds_show_the_sheet_turned_over_on_top() {
|
|
||||||
// Columns that double back across the middle, so it's covered by the left and right of the content and by the sheet between them turned over
|
|
||||||
let (plane, square) = ramps();
|
|
||||||
let mesh = WarpMesh(std::array::from_fn(|row| [0., 1.5, -0.5, 1.].map(|x| DVec2::new(x, row as f64 / 3.))));
|
|
||||||
let warped = warped_plane(&plane, &mesh, &square);
|
|
||||||
|
|
||||||
// For PSD interop, the middle shows the turned sheet, which reads near the content's middle rather than a quarter in from either side
|
|
||||||
let red = warped.data[20 * 60 + 30][0];
|
|
||||||
assert!((red - 0.49).abs() < 0.03, "the middle shows red {red}");
|
|
||||||
assert!(warped.data[20 * 60 + 30][3] > 0.999);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn mirrored_squares_fold_as_the_mirror_of_upright_ones() {
|
|
||||||
// The fold above in the square and content mirrored left to right, where the turned sheet winds the other way on screen
|
|
||||||
let (plane, square) = ramps();
|
|
||||||
let mesh = WarpMesh(std::array::from_fn(|row| [0., 1.5, -0.5, 1.].map(|x| DVec2::new(x, row as f64 / 3.))));
|
|
||||||
let mirror = |index: usize| index - index % 60 + 59 - index % 60;
|
|
||||||
let mirrored_plane = Plane {
|
|
||||||
data: (0..60 * 40).map(|index| plane.data[mirror(index)]).collect(),
|
|
||||||
..plane.clone()
|
|
||||||
};
|
|
||||||
let mirrored_square = square.placed(DAffine2::from_translation(DVec2::new(60., 0.)) * DAffine2::from_scale(DVec2::new(-1., 1.)));
|
|
||||||
|
|
||||||
let upright = warped_plane(&plane, &mesh, &square);
|
|
||||||
let mirrored = warped_plane(&mirrored_plane, &mesh, &mirrored_square);
|
|
||||||
for (index, color) in upright.data.iter().enumerate() {
|
|
||||||
let difference = color.iter().zip(mirrored.data[mirror(index)]).map(|(a, b)| (a - b).abs()).fold(0., f32::max);
|
|
||||||
assert!(difference < 1e-3, "pixel {index} shows {color:?} upright but {:?} mirrored", mirrored.data[mirror(index)]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn every_style_at_its_extremes_paints_colors_within_range() {
|
|
||||||
use WarpStyle::*;
|
|
||||||
let (plane, square) = ramps();
|
|
||||||
|
|
||||||
for style in [Arc, ArcLower, ArcUpper, Arch, Bulge, ShellLower, ShellUpper, Flag, Wave, Fish, Rise, Fisheye, Inflate, Squeeze, Twist] {
|
|
||||||
for (bend, horizontal_distortion, vertical_distortion) in [(1., 0., 0.), (-1., 0., 0.), (1., 1., 1.), (-1., -1., 1.), (1., -1., -1.), (0., 1., -1.)] {
|
|
||||||
for vertical in [false, true] {
|
|
||||||
let warp = Warp {
|
|
||||||
style,
|
|
||||||
bend,
|
|
||||||
horizontal_distortion,
|
|
||||||
vertical_distortion,
|
|
||||||
vertical,
|
|
||||||
};
|
|
||||||
let warped = warped_plane(&plane, &warp.mesh(square.size), &square);
|
|
||||||
|
|
||||||
// Premultiplied, each color lies within its alpha, which lies within 0 to 1
|
|
||||||
let within = |pixel: &[f32; 4]| pixel.iter().all(|channel| channel.is_finite() && (0.0..=pixel[3] + 1e-4).contains(channel)) && pixel[3] <= 1. + 1e-4;
|
|
||||||
assert!(warped.data.iter().all(within), "{warp:?} paints colors out of range");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,14 +1,17 @@
|
|||||||
|
use crate::deferred_image::{self, DeferredContent, DeferredImage};
|
||||||
use crate::renderer::{
|
use crate::renderer::{
|
||||||
ItemRef, RenderParams, SvgGradientLayer, composite_paint_colors, faded_paint_color, format_transform_matrix, gradient_placement, gradient_shape, paint_draws_by_its_colors, painted_gradient,
|
ItemRef, RenderParams, SvgGradientLayer, composite_paint_colors, faded_paint_color, format_transform_matrix, gradient_placement, gradient_shape, paint_draws_by_its_colors, painted_gradient,
|
||||||
spread_adjusted_samples, svg_gradient_standard, transform_is_invertible, with_two_stops_at_least, write_svg_gradient_paint,
|
spread_adjusted_samples, svg_gradient_standard, transform_is_invertible, with_two_stops_at_least, write_svg_gradient_paint,
|
||||||
};
|
};
|
||||||
use crate::{Render, RenderSvgSegmentList, SvgRender};
|
use crate::{Render, RenderSvgSegmentList, SvgRender};
|
||||||
|
use core_types::blending::BlendMode;
|
||||||
use core_types::color::SRGBA8;
|
use core_types::color::SRGBA8;
|
||||||
use core_types::list::List;
|
use core_types::list::List;
|
||||||
use core_types::uuid::generate_uuid;
|
use core_types::uuid::generate_uuid;
|
||||||
use core_types::{ATTR_TRANSFORM, Color};
|
use core_types::{ATTR_TRANSFORM, Color};
|
||||||
use glam::{DAffine2, DVec2};
|
use glam::{DAffine2, DVec2};
|
||||||
use graphic_types::Graphic;
|
use graphic_types::Graphic;
|
||||||
|
use graphic_types::resampling::frame_of_bounds;
|
||||||
use graphic_types::vector_types::vector::style::{Stroke, StrokeAlign, StrokeCap, StrokeJoin};
|
use graphic_types::vector_types::vector::style::{Stroke, StrokeAlign, StrokeCap, StrokeJoin};
|
||||||
use std::fmt::Write;
|
use std::fmt::Write;
|
||||||
use vector_types::Gradient;
|
use vector_types::Gradient;
|
||||||
@@ -39,13 +42,11 @@ impl PaintTarget {
|
|||||||
pub trait RenderExt {
|
pub trait RenderExt {
|
||||||
type Output;
|
type Output;
|
||||||
|
|
||||||
/// `user_to_document` maps the user space the painted element sits in, before its `element_transform`, into the document, and the filters reading the element read it `paint_reach` past the view, in document pixels.
|
/// The `render` draws the painted element in its user space before the `element_transform`, taking the paint's defs and any images the GPU renders for it.
|
||||||
#[allow(clippy::too_many_arguments)]
|
#[allow(clippy::too_many_arguments)]
|
||||||
fn render(
|
fn render(
|
||||||
&self,
|
&self,
|
||||||
svg_defs: &mut String,
|
render: &mut SvgRender,
|
||||||
user_to_document: DAffine2,
|
|
||||||
paint_reach: f64,
|
|
||||||
item_transform: DAffine2,
|
item_transform: DAffine2,
|
||||||
element_transform: DAffine2,
|
element_transform: DAffine2,
|
||||||
stroke_transform: DAffine2,
|
stroke_transform: DAffine2,
|
||||||
@@ -72,9 +73,7 @@ impl RenderExt for List<Color> {
|
|||||||
|
|
||||||
fn render(
|
fn render(
|
||||||
&self,
|
&self,
|
||||||
_svg_defs: &mut String,
|
_render: &mut SvgRender,
|
||||||
_user_to_document: DAffine2,
|
|
||||||
_paint_reach: f64,
|
|
||||||
_item_transform: DAffine2,
|
_item_transform: DAffine2,
|
||||||
_element_transform: DAffine2,
|
_element_transform: DAffine2,
|
||||||
_stroke_transform: DAffine2,
|
_stroke_transform: DAffine2,
|
||||||
@@ -199,12 +198,10 @@ fn render_gradient_paint(
|
|||||||
impl RenderExt for List<Gradient> {
|
impl RenderExt for List<Gradient> {
|
||||||
type Output = Option<u64>;
|
type Output = Option<u64>;
|
||||||
|
|
||||||
/// Adds the gradient def through mutating the first argument, returning the gradient ID, or `None` when the list is empty.
|
/// Adds the gradient def to the render's defs, returning the gradient ID, or `None` when the list is empty.
|
||||||
fn render(
|
fn render(
|
||||||
&self,
|
&self,
|
||||||
svg_defs: &mut String,
|
render: &mut SvgRender,
|
||||||
_user_to_document: DAffine2,
|
|
||||||
_paint_reach: f64,
|
|
||||||
item_transform: DAffine2,
|
item_transform: DAffine2,
|
||||||
element_transform: DAffine2,
|
element_transform: DAffine2,
|
||||||
stroke_transform: DAffine2,
|
stroke_transform: DAffine2,
|
||||||
@@ -214,7 +211,7 @@ impl RenderExt for List<Gradient> {
|
|||||||
) -> Self::Output {
|
) -> Self::Output {
|
||||||
render_gradient_paint(
|
render_gradient_paint(
|
||||||
(!self.is_empty()).then_some(ItemRef::ListItem(self, 0)),
|
(!self.is_empty()).then_some(ItemRef::ListItem(self, 0)),
|
||||||
svg_defs,
|
&mut render.svg_defs,
|
||||||
item_transform,
|
item_transform,
|
||||||
element_transform,
|
element_transform,
|
||||||
stroke_transform,
|
stroke_transform,
|
||||||
@@ -230,9 +227,7 @@ impl RenderExt for Stroke {
|
|||||||
/// Provide the shape-related SVG attributes for the stroke. The paint-related attributes for the stroke are generated from `Graphic::render` with `PaintTarget::Stroke`.
|
/// Provide the shape-related SVG attributes for the stroke. The paint-related attributes for the stroke are generated from `Graphic::render` with `PaintTarget::Stroke`.
|
||||||
fn render(
|
fn render(
|
||||||
&self,
|
&self,
|
||||||
_svg_defs: &mut String,
|
_render: &mut SvgRender,
|
||||||
_user_to_document: DAffine2,
|
|
||||||
_paint_reach: f64,
|
|
||||||
_item_transform: DAffine2,
|
_item_transform: DAffine2,
|
||||||
_element_transform: DAffine2,
|
_element_transform: DAffine2,
|
||||||
_stroke_transform: DAffine2,
|
_stroke_transform: DAffine2,
|
||||||
@@ -291,9 +286,7 @@ impl RenderExt for Graphic {
|
|||||||
|
|
||||||
fn render(
|
fn render(
|
||||||
&self,
|
&self,
|
||||||
svg_defs: &mut String,
|
render: &mut SvgRender,
|
||||||
user_to_document: DAffine2,
|
|
||||||
paint_reach: f64,
|
|
||||||
item_transform: DAffine2,
|
item_transform: DAffine2,
|
||||||
element_transform: DAffine2,
|
element_transform: DAffine2,
|
||||||
stroke_transform: DAffine2,
|
stroke_transform: DAffine2,
|
||||||
@@ -306,33 +299,21 @@ impl RenderExt for Graphic {
|
|||||||
|
|
||||||
match self {
|
match self {
|
||||||
Graphic::Color(item) if by_colors => render_color_paint(faded_paint_color(ItemRef::Item(item), render_params.for_mask), target),
|
Graphic::Color(item) if by_colors => render_color_paint(faded_paint_color(ItemRef::Item(item), render_params.for_mask), target),
|
||||||
Graphic::ColorList(color_list) if by_colors => color_list.render(
|
Graphic::ColorList(color_list) if by_colors => color_list.render(render, item_transform, element_transform, stroke_transform, bounds, render_params, target),
|
||||||
svg_defs,
|
Graphic::Gradient(item) if by_colors => render_gradient_paint(
|
||||||
user_to_document,
|
Some(ItemRef::Item(item)),
|
||||||
paint_reach,
|
&mut render.svg_defs,
|
||||||
item_transform,
|
item_transform,
|
||||||
element_transform,
|
element_transform,
|
||||||
stroke_transform,
|
stroke_transform,
|
||||||
bounds,
|
bounds,
|
||||||
render_params,
|
render_params.for_mask,
|
||||||
target,
|
)
|
||||||
),
|
.map(|gradient_id| format!(r##" {paint_attr}="url(#{gradient_id})""##))
|
||||||
Graphic::Gradient(item) if by_colors => render_gradient_paint(Some(ItemRef::Item(item)), svg_defs, item_transform, element_transform, stroke_transform, bounds, render_params.for_mask)
|
.unwrap_or_else(|| format!(r#" {paint_attr}="none""#)),
|
||||||
.map(|gradient_id| format!(r##" {paint_attr}="url(#{gradient_id})""##))
|
|
||||||
.unwrap_or_else(|| format!(r#" {paint_attr}="none""#)),
|
|
||||||
// One gradient resolves to a paint server; stacking several needs them composited, which only the pattern below can do
|
// One gradient resolves to a paint server; stacking several needs them composited, which only the pattern below can do
|
||||||
Graphic::GradientList(gradient_list) if by_colors => gradient_list
|
Graphic::GradientList(gradient_list) if by_colors => gradient_list
|
||||||
.render(
|
.render(render, item_transform, element_transform, stroke_transform, bounds, render_params, target)
|
||||||
svg_defs,
|
|
||||||
user_to_document,
|
|
||||||
paint_reach,
|
|
||||||
item_transform,
|
|
||||||
element_transform,
|
|
||||||
stroke_transform,
|
|
||||||
bounds,
|
|
||||||
render_params,
|
|
||||||
target,
|
|
||||||
)
|
|
||||||
.map(|gradient_id| format!(r##" {paint_attr}="url(#{gradient_id})""##))
|
.map(|gradient_id| format!(r##" {paint_attr}="url(#{gradient_id})""##))
|
||||||
.unwrap_or_else(|| format!(r#" {paint_attr}="none""#)),
|
.unwrap_or_else(|| format!(r#" {paint_attr}="none""#)),
|
||||||
Graphic::None(_) | Graphic::NoneList(_) => format!(r#" {paint_attr}="none""#),
|
Graphic::None(_) | Graphic::NoneList(_) => format!(r#" {paint_attr}="none""#),
|
||||||
@@ -363,8 +344,7 @@ impl RenderExt for Graphic {
|
|||||||
} else {
|
} else {
|
||||||
bounds
|
bounds
|
||||||
};
|
};
|
||||||
let content_to_document = user_to_document * element_transform * stroke_transform;
|
render_svg_pattern(render, self, element_transform * stroke_transform, stroke_transform, bounds, render_params)
|
||||||
render_svg_pattern(svg_defs, self, content_to_document, paint_reach, stroke_transform, bounds, render_params)
|
|
||||||
.map(|id| format!(r##" {paint_attr}="url(#{id})""##))
|
.map(|id| format!(r##" {paint_attr}="url(#{id})""##))
|
||||||
.unwrap_or_else(|| format!(r#" {paint_attr}="none""#))
|
.unwrap_or_else(|| format!(r#" {paint_attr}="none""#))
|
||||||
}
|
}
|
||||||
@@ -372,18 +352,10 @@ impl RenderExt for Graphic {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Emits an SVG `<pattern>` paint server into `svg_defs` that renders the given graphic as the paint content, and returns the pattern ID.
|
/// Emits an SVG `<pattern>` paint server into the render's defs that renders the given graphic as the paint content, and returns the pattern ID.
|
||||||
/// Currently, this function is only used for clipping-based filling and stroking, not considering tiling yet.
|
/// Currently, this function is only used for clipping-based filling and stroking, not considering tiling yet.
|
||||||
/// `content_to_document` maps the paint's own space, which `stroke_transform` places inside the painted element's `element_transform`, into the document, and the filters reading the element read it `paint_reach` past the view.
|
/// `content_transform` places the paint's own space in the render's user space, where `stroke_transform` places it inside the painted element's transform.
|
||||||
fn render_svg_pattern(
|
fn render_svg_pattern(render: &mut SvgRender, paint: &Graphic, content_transform: DAffine2, stroke_transform: DAffine2, bounds: DAffine2, render_params: &RenderParams) -> Option<String> {
|
||||||
svg_defs: &mut String,
|
|
||||||
paint: &Graphic,
|
|
||||||
content_to_document: DAffine2,
|
|
||||||
paint_reach: f64,
|
|
||||||
stroke_transform: DAffine2,
|
|
||||||
bounds: DAffine2,
|
|
||||||
render_params: &RenderParams,
|
|
||||||
) -> Option<String> {
|
|
||||||
let min = bounds.transform_point2(DVec2::ZERO);
|
let min = bounds.transform_point2(DVec2::ZERO);
|
||||||
let max = bounds.transform_point2(DVec2::ONE);
|
let max = bounds.transform_point2(DVec2::ONE);
|
||||||
let size = max - min;
|
let size = max - min;
|
||||||
@@ -392,12 +364,42 @@ fn render_svg_pattern(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Render the pattern content recursively
|
// Render the pattern content recursively
|
||||||
|
let content_to_document = render.transform * content_transform;
|
||||||
|
let paint_params = render_params.for_pattern();
|
||||||
let mut content = SvgRender::new();
|
let mut content = SvgRender::new();
|
||||||
content.transform = content_to_document;
|
content.transform = content_to_document;
|
||||||
content.ancestors_reach = paint_reach;
|
content.ancestors_reach = render.ancestors_reach;
|
||||||
paint.render_svg(&mut content, &render_params.for_pattern());
|
paint.render_svg(&mut content, &paint_params);
|
||||||
|
let mut markup = content.svg.to_svg_string();
|
||||||
|
|
||||||
|
// A paint leaving out what only the GPU draws becomes the GPU's image of it, where something fills that
|
||||||
|
if content.paint_needs_gpu {
|
||||||
|
if render.drawing_deferred_markup || render_params.inside_pattern {
|
||||||
|
render.leave_out_for_gpu(render_params);
|
||||||
|
} else {
|
||||||
|
let id = generate_uuid();
|
||||||
|
render.deferred_images.push(DeferredImage {
|
||||||
|
id,
|
||||||
|
content: DeferredContent::Item(paint.clone()),
|
||||||
|
// Seen within the shape it fills, as Vello paints it
|
||||||
|
render_params: RenderParams {
|
||||||
|
paint_frame: Some(frame_of_bounds([min, max], content_to_document)),
|
||||||
|
..paint_params
|
||||||
|
},
|
||||||
|
user_to_document: content_to_document,
|
||||||
|
bounds: [min, max],
|
||||||
|
margin: render.ancestors_reach,
|
||||||
|
opacity: 1.,
|
||||||
|
blend_mode: BlendMode::Normal,
|
||||||
|
mask: None,
|
||||||
|
});
|
||||||
|
let (opening, closing) = deferred_image::image_markers(id);
|
||||||
|
markup = format!("{opening}{markup}{closing}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Unwrap the inner def element
|
// Unwrap the inner def element
|
||||||
|
let svg_defs = &mut render.svg_defs;
|
||||||
write!(svg_defs, "{}", content.svg_defs).unwrap();
|
write!(svg_defs, "{}", content.svg_defs).unwrap();
|
||||||
|
|
||||||
let pattern_transform = stroke_transform * DAffine2::from_translation(min);
|
let pattern_transform = stroke_transform * DAffine2::from_translation(min);
|
||||||
@@ -417,7 +419,7 @@ fn render_svg_pattern(
|
|||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
let content_shift = format_transform_matrix(DAffine2::from_translation(-min));
|
let content_shift = format_transform_matrix(DAffine2::from_translation(-min));
|
||||||
write!(svg_defs, r##"<g transform="{content_shift}">{}</g></pattern>"##, content.svg.to_svg_string()).unwrap();
|
write!(svg_defs, r##"<g transform="{content_shift}">{markup}</g></pattern>"##).unwrap();
|
||||||
|
|
||||||
Some(pattern_id)
|
Some(pattern_id)
|
||||||
}
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -7,7 +7,7 @@ use glam::DVec2;
|
|||||||
use graphic_types::effects::EffectCapture;
|
use graphic_types::effects::EffectCapture;
|
||||||
use graphic_types::filters::{AVERAGE_VISIBILITY_RAMP, Convolution, HIGH_PASS_GRAY, Surroundings, UnsharpBlur, fill_shifts, noise_extent, unsharp, unsharp_change};
|
use graphic_types::filters::{AVERAGE_VISIBILITY_RAMP, Convolution, HIGH_PASS_GRAY, Surroundings, UnsharpBlur, fill_shifts, noise_extent, unsharp, unsharp_change};
|
||||||
use graphic_types::{EffectOperation, Effects, MinimumMaximumMode};
|
use graphic_types::{EffectOperation, Effects, MinimumMaximumMode};
|
||||||
use raster_kernels::effect_kernels::{MAX_DIRECT_BOX_RADIUS, box_weight};
|
use raster_kernels::effect_planning::{MAX_DIRECT_BOX_RADIUS, box_weight};
|
||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
/// The most weights an `feConvolveMatrix` kernel holds before browsers carry it out with less precision.
|
/// The most weights an `feConvolveMatrix` kernel holds before browsers carry it out with less precision.
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ use glam::{DAffine2, DVec2};
|
|||||||
use graphic_types::effects::{EffectOperation, Effects, spans_along_axes};
|
use graphic_types::effects::{EffectOperation, Effects, spans_along_axes};
|
||||||
use graphic_types::masks::{MASK_LUMINANCE_WEIGHTS, 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 graphic_types::{Appearance, Graphic};
|
||||||
use raster_kernels::effect_kernels::NEGLIGIBLE_LENGTH;
|
use raster_kernels::effect_planning::NEGLIGIBLE_LENGTH;
|
||||||
use std::fmt::Write;
|
use std::fmt::Write;
|
||||||
use std::ops::Range;
|
use std::ops::Range;
|
||||||
|
|
||||||
@@ -74,21 +74,32 @@ pub(super) fn holds_effects(graphic: &Graphic) -> bool {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether the graphic or anything nested in it is a GPU image, which SVG markup can't draw.
|
/// Whether the graphic, anything nested in it, or any paint its appearance fills or strokes them with, is a GPU image or a generator, which only the GPU draws.
|
||||||
fn holds_gpu_image(graphic: &Graphic) -> bool {
|
fn holds_gpu_content(graphic: &Graphic) -> bool {
|
||||||
|
fn paints_hold(appearance: Option<&Appearance>) -> bool {
|
||||||
|
appearance.is_some_and(|appearance| appearance.covers_with_paints().any(|(_, paint)| paint.is_some_and(holds_gpu_content)))
|
||||||
|
}
|
||||||
|
fn list_paints_hold<T>(list: &List<T>) -> bool {
|
||||||
|
(0..list.len()).any(|index| paints_hold(list.attribute(ATTR_APPEARANCE, index)))
|
||||||
|
}
|
||||||
|
|
||||||
match graphic {
|
match graphic {
|
||||||
Graphic::RasterGPU(_) => true,
|
Graphic::RasterGPU(_) | Graphic::Generator(_) => true,
|
||||||
Graphic::RasterGPUList(list) => !list.is_empty(),
|
Graphic::RasterGPUList(list) => !list.is_empty(),
|
||||||
Graphic::Graphic(item) => holds_gpu_image(item.element()),
|
Graphic::GeneratorList(list) => !list.is_empty(),
|
||||||
Graphic::GraphicList(list) => list.iter_element_values().any(holds_gpu_image),
|
Graphic::Graphic(item) => paints_hold(item.attribute(ATTR_APPEARANCE)) || holds_gpu_content(item.element()),
|
||||||
|
Graphic::GraphicList(list) => list_paints_hold(list) || list.iter_element_values().any(holds_gpu_content),
|
||||||
|
Graphic::Vector(item) => paints_hold(item.attribute(ATTR_APPEARANCE)),
|
||||||
|
Graphic::VectorList(list) => list_paints_hold(list),
|
||||||
|
Graphic::Text(item) => paints_hold(item.attribute(ATTR_APPEARANCE)),
|
||||||
|
Graphic::TextList(list) => list_paints_hold(list),
|
||||||
_ => false,
|
_ => false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether SVG draws a blur's `radius_mask` as markup in its filter, keeping the blur resolution-independent, rather than taking its luminance as the GPU's map.
|
/// Whether markup embedded as an image draws the graphic whole, which no map or image of the GPU's reaches, so it holds neither effects nor what only the GPU draws.
|
||||||
/// Markup embedded as an image reaches no maps of the radius mask's own effects.
|
pub(super) fn draws_as_embedded_markup(graphic: &Graphic) -> bool {
|
||||||
pub(super) fn radius_mask_draws_as_markup(radius_mask: &Graphic) -> bool {
|
!holds_effects(graphic) && !holds_gpu_content(graphic)
|
||||||
!holds_effects(radius_mask) && !holds_gpu_image(radius_mask)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A mask's graphic placed by its content's `placement`, which it follows.
|
/// A mask's graphic placed by its content's `placement`, which it follows.
|
||||||
@@ -187,8 +198,7 @@ pub(super) fn write_endless_content_mask(render: &mut SvgRender, effects: &Effec
|
|||||||
mask_render.transform = render.transform;
|
mask_render.transform = render.transform;
|
||||||
mask_render.ancestors_reach = render.ancestors_reach + feather_reach;
|
mask_render.ancestors_reach = render.ancestors_reach + feather_reach;
|
||||||
mask.render_svg(&mut mask_render, &live_params);
|
mask.render_svg(&mut mask_render, &live_params);
|
||||||
render.effect_maps.append(&mut mask_render.effect_maps);
|
render.take_gpu_images(&mut mask_render, render_params);
|
||||||
render.deferred_images.append(&mut mask_render.deferred_images);
|
|
||||||
let markup = format!("<defs>{}</defs>{}", mask_render.svg_defs, mask_render.svg.to_svg_string());
|
let markup = format!("<defs>{}</defs>{}", mask_render.svg_defs, mask_render.svg.to_svg_string());
|
||||||
|
|
||||||
let sigma = svg_feather_sigma(feather, length_scale);
|
let sigma = svg_feather_sigma(feather, length_scale);
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ use graphic_types::effects::{EffectCapture, GRADIENT_TABLE_SIZE, GlowFill};
|
|||||||
pub(super) enum OutlineBandColors {
|
pub(super) enum OutlineBandColors {
|
||||||
/// The markup of a drawn paint.
|
/// The markup of a drawn paint.
|
||||||
Drawn(String),
|
Drawn(String),
|
||||||
|
/// A drawn paint that embedding its markup as an image can't draw whole, which the GPU's map gives.
|
||||||
|
DrawnOnGpu,
|
||||||
ContourGradient(GlowFill),
|
ContourGradient(GlowFill),
|
||||||
/// The primitive holding the colors, once made.
|
/// The primitive holding the colors, once made.
|
||||||
Made(String),
|
Made(String),
|
||||||
@@ -18,6 +20,10 @@ impl SvgFilterPrimitives {
|
|||||||
let made = match colors {
|
let made = match colors {
|
||||||
OutlineBandColors::Made(made) => return made.clone(),
|
OutlineBandColors::Made(made) => return made.clone(),
|
||||||
OutlineBandColors::Drawn(markup) => self.paint_image(markup, region),
|
OutlineBandColors::Drawn(markup) => self.paint_image(markup, region),
|
||||||
|
OutlineBandColors::DrawnOnGpu => self.map(EffectCapture {
|
||||||
|
index,
|
||||||
|
plane: EffectCapture::DRAWN_PAINT_PLANE,
|
||||||
|
}),
|
||||||
OutlineBandColors::ContourGradient(gradient) => {
|
OutlineBandColors::ContourGradient(gradient) => {
|
||||||
let positions = self.map(EffectCapture { index, plane: 2 });
|
let positions = self.map(EffectCapture { index, plane: 2 });
|
||||||
self.contour_gradient_colors(&positions, gradient)
|
self.contour_gradient_colors(&positions, gradient)
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ use graphic_types::effects::spans_along_axes;
|
|||||||
use graphic_types::{EffectOperation, Effects};
|
use graphic_types::{EffectOperation, Effects};
|
||||||
use kurbo::{BezPath, PathEl, Shape};
|
use kurbo::{BezPath, PathEl, Shape};
|
||||||
use linesweeper::topology::Topology;
|
use linesweeper::topology::Topology;
|
||||||
use raster_kernels::effect_kernels::NEGLIGIBLE_LENGTH;
|
use raster_kernels::effect_planning::NEGLIGIBLE_LENGTH;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::fmt::Write;
|
use std::fmt::Write;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
@@ -219,7 +219,7 @@ impl SvgRender {
|
|||||||
/// Whether the markup drawn since the backdrop `root` draws through canvases, as images and the GPU's images of content do in the viewport the `render_params` draw in,
|
/// Whether the markup drawn since the backdrop `root` draws through canvases, as images and the GPU's images of content do in the viewport the `render_params` draw in,
|
||||||
/// even where the content reading it embeds its own images. O(segments drawn since the root).
|
/// even where the content reading it embeds its own images. O(segments drawn since the root).
|
||||||
fn draws_canvases_since(&self, root: usize, render_params: &RenderParams) -> bool {
|
fn draws_canvases_since(&self, root: usize, render_params: &RenderParams) -> bool {
|
||||||
let in_viewport = !(render_params.for_export || render_params.thumbnail || render_params.for_mask || render_params.inside_pattern);
|
let in_viewport = !(render_params.for_export || render_params.for_mask || render_params.inside_pattern);
|
||||||
let start = self.open_groups.groups[root].content_start;
|
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());
|
let draws_canvas = |segment: &SvgSegment| segment.as_str().contains("data-canvas-placeholder") || deferred_image::holds_image_markers(segment.as_str());
|
||||||
in_viewport && self.svg[start..].iter().any(draws_canvas)
|
in_viewport && self.svg[start..].iter().any(draws_canvas)
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ mod geometry;
|
|||||||
mod geometry_cache;
|
mod geometry_cache;
|
||||||
pub mod misc;
|
pub mod misc;
|
||||||
mod path;
|
mod path;
|
||||||
|
mod path_chart;
|
||||||
pub mod reference_point;
|
pub mod reference_point;
|
||||||
pub mod style;
|
pub mod style;
|
||||||
mod vector_attributes;
|
mod vector_attributes;
|
||||||
@@ -21,6 +22,7 @@ pub use flatten::{WorkingVector, vector_from_legacy_parts};
|
|||||||
pub use geometry::VectorGeometry;
|
pub use geometry::VectorGeometry;
|
||||||
pub use geometry_cache::{GeometryCache, PlacedContours, SetVectorPaths, set_paths_at};
|
pub use geometry_cache::{GeometryCache, PlacedContours, SetVectorPaths, set_paths_at};
|
||||||
pub use path::*;
|
pub use path::*;
|
||||||
|
pub use path_chart::PathChart;
|
||||||
pub use reference_point::*;
|
pub use reference_point::*;
|
||||||
pub use vector_attributes::*;
|
pub use vector_attributes::*;
|
||||||
pub use vector_modification::*;
|
pub use vector_modification::*;
|
||||||
|
|||||||
@@ -0,0 +1,677 @@
|
|||||||
|
//! The chart a paint mapped along a stroke's paths reads its position from: arc length along each contour, and offset across the stroke's width.
|
||||||
|
|
||||||
|
use super::misc::{dvec2_to_point, point_to_dvec2};
|
||||||
|
use super::style::{Stroke, StrokeAlign, StrokeCap, StrokeJoin};
|
||||||
|
use glam::DVec2;
|
||||||
|
use kurbo::{BezPath, CubicBez, Line, ParamCurve, ParamCurveArclen, PathEl, PathSeg, QuadBez, Shape};
|
||||||
|
use std::ops::Range;
|
||||||
|
|
||||||
|
/// Accuracy of each path segment's arc length, the same kurbo measures dashes with, so the chart's dashes line up with the drawn ones.
|
||||||
|
const ARC_LENGTH_ACCURACY: f64 = 1e-6;
|
||||||
|
|
||||||
|
/// Maps points around a stroke to `(u, v)` coordinates. `u` runs from 0 to 1 along the arc length of each contour from its start point,
|
||||||
|
/// extending past open ends through their caps. `v` runs from 0 on the stroke's left edge to 1 on its right edge, relative to the contour's direction.
|
||||||
|
///
|
||||||
|
/// The path is flattened into straight pieces, and each piece is charted on its own, as a GPU pass reading the same pieces would chart it.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct PathChart {
|
||||||
|
pieces: Vec<ChartPiece>,
|
||||||
|
contours: Vec<ChartContour>,
|
||||||
|
/// The stroke's weight, across which `v` spans 0 to 1.
|
||||||
|
width: f64,
|
||||||
|
/// How far a cap reaches along the path past the end of an open contour or a dash.
|
||||||
|
cap_reach: f64,
|
||||||
|
/// -1 where the stroke space mirrors the path's own space, so the right side stays the path's own right side.
|
||||||
|
side_sign: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One straight piece of a flattened contour.
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
struct ChartPiece {
|
||||||
|
start: DVec2,
|
||||||
|
end: DVec2,
|
||||||
|
/// Arc length along the contour where the piece starts.
|
||||||
|
arc_start: f64,
|
||||||
|
/// Arc length the piece spans, scaled so a curve's pieces add up to the curve's exact arc length.
|
||||||
|
arc_span: f64,
|
||||||
|
contour: usize,
|
||||||
|
/// Whether the piece begins an open contour, so the chart extends backward past its start through the cap.
|
||||||
|
extends_backward: bool,
|
||||||
|
/// Whether the piece ends an open contour, so the chart extends forward past its end through the cap.
|
||||||
|
extends_forward: bool,
|
||||||
|
/// The corner where the piece meets the next piece of its contour.
|
||||||
|
join: Option<ChartJoin>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
struct ChartJoin {
|
||||||
|
/// Unit direction of the next piece.
|
||||||
|
next_direction: DVec2,
|
||||||
|
/// Whether the corner's outer wedge is measured by distance from the corner, rather than from the two pieces' lines like a miter.
|
||||||
|
round: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
struct ChartContour {
|
||||||
|
start: DVec2,
|
||||||
|
length: f64,
|
||||||
|
closed: bool,
|
||||||
|
/// Offset toward the right side where `v` is 0.
|
||||||
|
band_start: f64,
|
||||||
|
pieces: Range<usize>,
|
||||||
|
/// The sorted arc length intervals the stroke draws, or `None` when it draws all of a closed contour.
|
||||||
|
drawn: Option<Vec<(f64, f64)>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A contour flattened into straight pieces, before the chart's rules are attached to them.
|
||||||
|
struct FlatContour {
|
||||||
|
start: DVec2,
|
||||||
|
closed: bool,
|
||||||
|
pieces: Vec<FlatPiece>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct FlatPiece {
|
||||||
|
start: DVec2,
|
||||||
|
end: DVec2,
|
||||||
|
arc_span: f64,
|
||||||
|
/// Whether the piece ends one of the path's segments, rather than ending inside a flattened curve.
|
||||||
|
ends_segment: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PathChart {
|
||||||
|
/// Charts `path`, which lies in the stroke's space as placed by `stroke.transform`, flattening its curves to within `tolerance`.
|
||||||
|
pub fn new(path: &BezPath, stroke: &Stroke, tolerance: f64) -> Self {
|
||||||
|
let side_sign = if stroke.transform.matrix2.determinant() < 0. { -1. } else { 1. };
|
||||||
|
let flat_contours = flatten_contours(path, tolerance.max(1e-9));
|
||||||
|
|
||||||
|
// Like the renderer, alignment only applies when every contour is closed, and then draws the stroke at twice its weight with one side masked away
|
||||||
|
let aligned = stroke.align != StrokeAlign::Center && flat_contours.iter().all(|contour| contour.closed);
|
||||||
|
let width = stroke.weight;
|
||||||
|
let drawn_half_width = if aligned { width } else { width / 2. };
|
||||||
|
let cap_reach = if stroke.cap == StrokeCap::Butt { 0. } else { drawn_half_width };
|
||||||
|
let dash_lengths: Vec<f64> = stroke.dash_lengths.iter().map(|length| length.max(0.)).collect();
|
||||||
|
|
||||||
|
let mut chart = Self {
|
||||||
|
pieces: Vec::new(),
|
||||||
|
contours: Vec::with_capacity(flat_contours.len()),
|
||||||
|
width,
|
||||||
|
cap_reach,
|
||||||
|
side_sign,
|
||||||
|
};
|
||||||
|
|
||||||
|
for (contour_index, flat_contour) in flat_contours.iter().enumerate() {
|
||||||
|
let first_piece = chart.pieces.len();
|
||||||
|
let piece_count = flat_contour.pieces.len();
|
||||||
|
|
||||||
|
// Lay the pieces end to end along the contour's arc length
|
||||||
|
let mut arc_start = 0.;
|
||||||
|
for (index, piece) in flat_contour.pieces.iter().enumerate() {
|
||||||
|
let is_last = index + 1 == piece_count;
|
||||||
|
let next = if is_last && flat_contour.closed {
|
||||||
|
flat_contour.pieces.first()
|
||||||
|
} else {
|
||||||
|
flat_contour.pieces.get(index + 1)
|
||||||
|
};
|
||||||
|
let join = next.map(|next| ChartJoin {
|
||||||
|
next_direction: (next.end - next.start).normalize(),
|
||||||
|
round: !piece.ends_segment || stroke.join == StrokeJoin::Round,
|
||||||
|
});
|
||||||
|
|
||||||
|
chart.pieces.push(ChartPiece {
|
||||||
|
start: piece.start,
|
||||||
|
end: piece.end,
|
||||||
|
arc_start,
|
||||||
|
arc_span: piece.arc_span,
|
||||||
|
contour: contour_index,
|
||||||
|
extends_backward: index == 0 && !flat_contour.closed,
|
||||||
|
extends_forward: is_last && !flat_contour.closed,
|
||||||
|
join,
|
||||||
|
});
|
||||||
|
arc_start += piece.arc_span;
|
||||||
|
}
|
||||||
|
let length = arc_start;
|
||||||
|
|
||||||
|
// The band covers the stroke's width about the contour, or for an aligned stroke, the side the fill keeps
|
||||||
|
let band_start = match stroke.align {
|
||||||
|
_ if !aligned => -width / 2.,
|
||||||
|
StrokeAlign::Inside if right_side_is_filled(path, flat_contour, side_sign) => 0.,
|
||||||
|
StrokeAlign::Outside if !right_side_is_filled(path, flat_contour, side_sign) => 0.,
|
||||||
|
_ => -width,
|
||||||
|
};
|
||||||
|
|
||||||
|
let drawn = match dash_intervals(&dash_lengths, stroke.dash_offset, length) {
|
||||||
|
Some(intervals) => Some(intervals),
|
||||||
|
None if flat_contour.closed => None,
|
||||||
|
None => Some(vec![(0., length)]),
|
||||||
|
};
|
||||||
|
|
||||||
|
chart.contours.push(ChartContour {
|
||||||
|
start: flat_contour.start,
|
||||||
|
length,
|
||||||
|
closed: flat_contour.closed,
|
||||||
|
band_start,
|
||||||
|
pieces: first_piece..chart.pieces.len(),
|
||||||
|
drawn,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
chart
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The `(u, v)` coordinates of `point`, given in stroke space, from the latest piece in path order that draws over it, or else from the nearest piece,
|
||||||
|
/// for points such as antialiased fringes that no piece draws over. `None` when there is no stroke to chart. O(pieces).
|
||||||
|
pub fn chart_at(&self, point: DVec2) -> Option<(f64, f64)> {
|
||||||
|
if self.width <= 0. || !self.width.is_finite() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut charted = None;
|
||||||
|
for piece in &self.pieces {
|
||||||
|
let contour = &self.contours[piece.contour];
|
||||||
|
if let Some(coordinates) = self.body_coordinates(piece, contour, point) {
|
||||||
|
charted = Some(coordinates);
|
||||||
|
}
|
||||||
|
if let Some(coordinates) = self.join_coordinates(piece, contour, point) {
|
||||||
|
charted = Some(coordinates);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
charted.or_else(|| self.nearest_coordinates(point))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The point in stroke space at `u` (clamped to 0 to 1) along the contour at the given index.
|
||||||
|
pub fn point_at(&self, contour: usize, u: f64) -> Option<DVec2> {
|
||||||
|
let contour = self.contours.get(contour)?;
|
||||||
|
let pieces = &self.pieces[contour.pieces.clone()];
|
||||||
|
if pieces.is_empty() {
|
||||||
|
return Some(contour.start);
|
||||||
|
}
|
||||||
|
|
||||||
|
let arc = u.clamp(0., 1.) * contour.length;
|
||||||
|
let index = pieces.partition_point(|piece| piece.arc_start + piece.arc_span < arc).min(pieces.len() - 1);
|
||||||
|
let piece = &pieces[index];
|
||||||
|
let along = ((arc - piece.arc_start) / piece.arc_span).clamp(0., 1.);
|
||||||
|
Some(piece.start.lerp(piece.end, along))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The body of the stroke around the piece, extended past an open contour's ends through its caps.
|
||||||
|
fn body_coordinates(&self, piece: &ChartPiece, contour: &ChartContour, point: DVec2) -> Option<(f64, f64)> {
|
||||||
|
let chord = piece.end - piece.start;
|
||||||
|
let offset = point - piece.start;
|
||||||
|
let along = offset.dot(chord) / chord.length_squared();
|
||||||
|
if (along < 0. && !piece.extends_backward) || (along > 1. && !piece.extends_forward) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
let across = offset.dot(self.right_normal(chord.normalize()));
|
||||||
|
let arc = piece.arc_start + along * piece.arc_span;
|
||||||
|
if !self.in_band(contour, across) || !contour.draws(arc, self.cap_reach) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
Some(self.coordinates(contour, arc, across))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The wedge on the outer side of the corner at the piece's end, between where its body ends and the next piece's body begins.
|
||||||
|
/// The whole wedge takes the corner's arc length, so colors fan around it.
|
||||||
|
fn join_coordinates(&self, piece: &ChartPiece, contour: &ChartContour, point: DVec2) -> Option<(f64, f64)> {
|
||||||
|
let join = piece.join?;
|
||||||
|
let incoming = (piece.end - piece.start).normalize();
|
||||||
|
let outgoing = join.next_direction;
|
||||||
|
|
||||||
|
let offset = point - piece.end;
|
||||||
|
if offset.dot(incoming) <= 0. || offset.dot(outgoing) >= 0. {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The outer side is opposite the turn, except at a full reversal, where both sides are outer
|
||||||
|
let across_incoming = offset.dot(self.right_normal(incoming));
|
||||||
|
let across_outgoing = offset.dot(self.right_normal(outgoing));
|
||||||
|
let turn = outgoing.dot(self.right_normal(incoming));
|
||||||
|
let outer_side = if turn != 0. {
|
||||||
|
-turn.signum()
|
||||||
|
} else if across_incoming < 0. {
|
||||||
|
-1.
|
||||||
|
} else {
|
||||||
|
1.
|
||||||
|
};
|
||||||
|
|
||||||
|
// A miter measures the larger distance from the two pieces' lines, which stays within the band all the way to its tip
|
||||||
|
let distance = if join.round {
|
||||||
|
offset.length()
|
||||||
|
} else {
|
||||||
|
(outer_side * across_incoming).max(outer_side * across_outgoing)
|
||||||
|
};
|
||||||
|
let across = outer_side * distance;
|
||||||
|
|
||||||
|
let arc = piece.arc_start + piece.arc_span;
|
||||||
|
if !self.in_band(contour, across) || !contour.draws(arc, self.cap_reach) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
Some(self.coordinates(contour, arc, across))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The coordinates from the nearest point on any piece, measured across that piece's line. O(pieces).
|
||||||
|
fn nearest_coordinates(&self, point: DVec2) -> Option<(f64, f64)> {
|
||||||
|
let mut nearest: Option<(f64, &ChartPiece, f64)> = None;
|
||||||
|
for piece in &self.pieces {
|
||||||
|
let chord = piece.end - piece.start;
|
||||||
|
let along = ((point - piece.start).dot(chord) / chord.length_squared()).clamp(0., 1.);
|
||||||
|
let distance_squared = point.distance_squared(piece.start + chord * along);
|
||||||
|
|
||||||
|
// Ties go to the later piece, as overlaps do
|
||||||
|
if nearest.is_none_or(|(nearest_distance_squared, ..)| distance_squared <= nearest_distance_squared) {
|
||||||
|
nearest = Some((distance_squared, piece, along));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let (_, piece, along) = nearest?;
|
||||||
|
let contour = &self.contours[piece.contour];
|
||||||
|
let across = (point - piece.start).dot(self.right_normal((piece.end - piece.start).normalize()));
|
||||||
|
Some(self.coordinates(contour, piece.arc_start + along * piece.arc_span, across))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn coordinates(&self, contour: &ChartContour, arc: f64, across: f64) -> (f64, f64) {
|
||||||
|
(arc / contour.length, (across - contour.band_start) / self.width)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn in_band(&self, contour: &ChartContour, across: f64) -> bool {
|
||||||
|
(contour.band_start..=contour.band_start + self.width).contains(&across)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The unit normal toward the right side of a piece running in `direction`.
|
||||||
|
fn right_normal(&self, direction: DVec2) -> DVec2 {
|
||||||
|
self.side_sign * direction.perp()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ChartContour {
|
||||||
|
/// Whether the stroke draws at `arc` along the contour, counting caps that reach `cap_reach` past the ends of what it draws.
|
||||||
|
fn draws(&self, arc: f64, cap_reach: f64) -> bool {
|
||||||
|
let Some(intervals) = &self.drawn else { return true };
|
||||||
|
|
||||||
|
// The last interval starting within reach reaches the furthest, since the intervals are sorted and disjoint
|
||||||
|
let draws_at = |arc: f64| {
|
||||||
|
let count = intervals.partition_point(|&(start, _)| start <= arc + cap_reach);
|
||||||
|
count > 0 && intervals[count - 1].1 + cap_reach >= arc
|
||||||
|
};
|
||||||
|
|
||||||
|
// A closed contour's dashes continue across its start point
|
||||||
|
draws_at(arc) || (self.closed && (draws_at(arc - self.length) || draws_at(arc + self.length)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Splits the path into its contours, each flattened into straight pieces whose arc lengths add up to each segment's exact arc length.
|
||||||
|
fn flatten_contours(path: &BezPath, tolerance: f64) -> Vec<FlatContour> {
|
||||||
|
let mut contours: Vec<FlatContour> = Vec::new();
|
||||||
|
let mut last_point = DVec2::ZERO;
|
||||||
|
|
||||||
|
for element in path.elements() {
|
||||||
|
let end = match *element {
|
||||||
|
PathEl::MoveTo(point) => {
|
||||||
|
last_point = point_to_dvec2(point);
|
||||||
|
contours.push(FlatContour {
|
||||||
|
start: last_point,
|
||||||
|
closed: false,
|
||||||
|
pieces: Vec::new(),
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
PathEl::ClosePath => {
|
||||||
|
let Some(contour) = contours.last_mut() else { continue };
|
||||||
|
if !contour.closed {
|
||||||
|
push_segment(contour, PathSeg::Line(Line::new(dvec2_to_point(last_point), dvec2_to_point(contour.start))), tolerance);
|
||||||
|
contour.closed = true;
|
||||||
|
last_point = contour.start;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
PathEl::LineTo(p1) => p1,
|
||||||
|
PathEl::QuadTo(_, p2) => p2,
|
||||||
|
PathEl::CurveTo(_, _, p3) => p3,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Drawing after a contour closes, without moving first, begins another contour where the closed one started
|
||||||
|
if contours.last().is_none_or(|contour| contour.closed) {
|
||||||
|
contours.push(FlatContour {
|
||||||
|
start: last_point,
|
||||||
|
closed: false,
|
||||||
|
pieces: Vec::new(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let Some(contour) = contours.last_mut() else { continue };
|
||||||
|
|
||||||
|
let p0 = dvec2_to_point(last_point);
|
||||||
|
let segment = match *element {
|
||||||
|
PathEl::QuadTo(p1, p2) => PathSeg::Quad(QuadBez::new(p0, p1, p2)),
|
||||||
|
PathEl::CurveTo(p1, p2, p3) => PathSeg::Cubic(CubicBez::new(p0, p1, p2, p3)),
|
||||||
|
_ => PathSeg::Line(Line::new(p0, end)),
|
||||||
|
};
|
||||||
|
push_segment(contour, segment, tolerance);
|
||||||
|
last_point = point_to_dvec2(end);
|
||||||
|
}
|
||||||
|
|
||||||
|
contours
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Appends a path segment's flattened pieces, scaling their chord lengths to add up to its arc length so `u` reaches exactly 1 at the contour's end.
|
||||||
|
/// Segments of no length are skipped, as the stroker skips them.
|
||||||
|
fn push_segment(contour: &mut FlatContour, segment: PathSeg, tolerance: f64) {
|
||||||
|
let arc_length = segment.arclen(ARC_LENGTH_ACCURACY);
|
||||||
|
if arc_length <= 0. || !arc_length.is_finite() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut points = Vec::new();
|
||||||
|
kurbo::flatten([PathEl::MoveTo(segment.start()), segment.as_path_el()], tolerance, |element| {
|
||||||
|
if let PathEl::MoveTo(point) | PathEl::LineTo(point) = element {
|
||||||
|
points.push(point_to_dvec2(point));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let chord_length: f64 = points.windows(2).map(|pair| pair[0].distance(pair[1])).sum();
|
||||||
|
if chord_length <= 0. || !chord_length.is_finite() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let scale = arc_length / chord_length;
|
||||||
|
|
||||||
|
let first_new_piece = contour.pieces.len();
|
||||||
|
for pair in points.windows(2) {
|
||||||
|
let length = pair[0].distance(pair[1]);
|
||||||
|
if length > 0. {
|
||||||
|
contour.pieces.push(FlatPiece {
|
||||||
|
start: pair[0],
|
||||||
|
end: pair[1],
|
||||||
|
arc_span: length * scale,
|
||||||
|
ends_segment: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if contour.pieces.len() > first_new_piece
|
||||||
|
&& let Some(last) = contour.pieces.last_mut()
|
||||||
|
{
|
||||||
|
last.ends_segment = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the fill (nonzero) lies on the contour's right side, probed just beside the middle of its longest piece.
|
||||||
|
fn right_side_is_filled(path: &BezPath, contour: &FlatContour, side_sign: f64) -> bool {
|
||||||
|
let Some(piece) = contour.pieces.iter().max_by(|a, b| a.start.distance_squared(a.end).total_cmp(&b.start.distance_squared(b.end))) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
let chord = piece.end - piece.start;
|
||||||
|
let right = side_sign * chord.normalize().perp();
|
||||||
|
let probe = piece.start.lerp(piece.end, 0.5) + right * chord.length() * 1e-4;
|
||||||
|
path.winding(dvec2_to_point(probe)) != 0
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The arc length intervals kurbo draws as dashes along a contour of the given `length`, with the pattern restarting at its start,
|
||||||
|
/// or `None` when the pattern draws a solid line.
|
||||||
|
fn dash_intervals(lengths: &[f64], offset: f64, length: f64) -> Option<Vec<(f64, f64)>> {
|
||||||
|
// An odd-length pattern repeats with the dash and gap roles swapped, so its phase comes back around after two repetitions
|
||||||
|
let pattern_length: f64 = lengths.iter().sum();
|
||||||
|
let period = if lengths.len() % 2 == 1 { 2. * pattern_length } else { pattern_length };
|
||||||
|
let phase = offset.rem_euclid(period);
|
||||||
|
if lengths.is_empty() || period <= 0. || !phase.is_finite() || !length.is_finite() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find where the offset lands in the pattern
|
||||||
|
let mut index = 0;
|
||||||
|
let mut remaining = lengths[0] - phase;
|
||||||
|
let mut drawing = true;
|
||||||
|
while remaining < 0. {
|
||||||
|
index = (index + 1) % lengths.len();
|
||||||
|
remaining += lengths[index];
|
||||||
|
drawing = !drawing;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Walk the pattern along the contour, alternating between dashes and gaps
|
||||||
|
let mut intervals = Vec::new();
|
||||||
|
let mut position = 0.;
|
||||||
|
loop {
|
||||||
|
let end = position + remaining;
|
||||||
|
if drawing {
|
||||||
|
intervals.push((position, end.min(length)));
|
||||||
|
}
|
||||||
|
if end >= length {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
position = end;
|
||||||
|
index = (index + 1) % lengths.len();
|
||||||
|
remaining = lengths[index];
|
||||||
|
drawing = !drawing;
|
||||||
|
}
|
||||||
|
|
||||||
|
Some(intervals)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use glam::DAffine2;
|
||||||
|
|
||||||
|
const TOLERANCE: f64 = 0.01;
|
||||||
|
|
||||||
|
fn polyline(points: &[(f64, f64)], closed: bool) -> BezPath {
|
||||||
|
let mut path = BezPath::new();
|
||||||
|
for (index, &(x, y)) in points.iter().enumerate() {
|
||||||
|
if index == 0 {
|
||||||
|
path.move_to((x, y));
|
||||||
|
} else {
|
||||||
|
path.line_to((x, y));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if closed {
|
||||||
|
path.close_path();
|
||||||
|
}
|
||||||
|
path
|
||||||
|
}
|
||||||
|
|
||||||
|
#[track_caller]
|
||||||
|
fn assert_chart(chart: &PathChart, point: (f64, f64), expected: (f64, f64)) {
|
||||||
|
let Some((u, v)) = chart.chart_at(DVec2::new(point.0, point.1)) else {
|
||||||
|
panic!("{point:?} should be charted");
|
||||||
|
};
|
||||||
|
assert!(
|
||||||
|
(u - expected.0).abs() < 1e-9 && (v - expected.1).abs() < 1e-9,
|
||||||
|
"{point:?} charted at {:?}, expected {expected:?}",
|
||||||
|
(u, v)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_straight_line_runs_u_along_it_and_v_from_its_left_edge_to_its_right() {
|
||||||
|
let chart = PathChart::new(&polyline(&[(0., 0.), (100., 0.)], false), &Stroke::new(10.), TOLERANCE);
|
||||||
|
|
||||||
|
// Heading along +X with +Y down, the right side is +Y
|
||||||
|
assert_chart(&chart, (25., -5.), (0.25, 0.));
|
||||||
|
assert_chart(&chart, (50., 0.), (0.5, 0.5));
|
||||||
|
assert_chart(&chart, (75., 5.), (0.75, 1.));
|
||||||
|
assert_chart(&chart, (100., 2.5), (1., 0.75));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn closed_contours_each_span_zero_to_one_from_their_start_points() {
|
||||||
|
let mut path = polyline(&[(0., 0.), (10., 0.), (10., 10.), (0., 10.)], true);
|
||||||
|
path.extend(polyline(&[(120., 0.), (120., 10.), (110., 10.), (110., 0.)], true));
|
||||||
|
let chart = PathChart::new(&path, &Stroke::new(2.), TOLERANCE);
|
||||||
|
|
||||||
|
assert_chart(&chart, (5., 0.), (5. / 40., 0.5));
|
||||||
|
assert_chart(&chart, (0., 5.), (35. / 40., 0.5));
|
||||||
|
assert_chart(&chart, (120., 5.), (5. / 40., 0.5));
|
||||||
|
assert_chart(&chart, (115., 0.), (35. / 40., 0.5));
|
||||||
|
|
||||||
|
assert_eq!(chart.point_at(0, 0.5), Some(DVec2::new(10., 10.)));
|
||||||
|
assert_eq!(chart.point_at(1, 0.), Some(DVec2::new(120., 0.)));
|
||||||
|
assert_eq!(chart.point_at(1, 0.25), Some(DVec2::new(120., 10.)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_round_joins_wedge_keeps_the_arc_length_of_its_corner() {
|
||||||
|
let stroke = Stroke {
|
||||||
|
join: StrokeJoin::Round,
|
||||||
|
..Stroke::new(20.)
|
||||||
|
};
|
||||||
|
let chart = PathChart::new(&polyline(&[(0., 0.), (100., 0.), (100., 100.)], false), &stroke, TOLERANCE);
|
||||||
|
|
||||||
|
// Turning right at the corner, its wedge lies on the left, where `v` falls from 0.5 at the corner to 0 at the round edge
|
||||||
|
for (x, y) in [(105., -5.), (107., -2.), (101., -9.), (100.5, -0.5)] {
|
||||||
|
let distance = DVec2::new(x - 100., y).length();
|
||||||
|
assert_chart(&chart, (x, y), (0.5, 0.5 - distance / 20.));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_miters_tip_keeps_v_within_zero_to_one() {
|
||||||
|
let stroke = Stroke {
|
||||||
|
join_miter_limit: 100.,
|
||||||
|
..Stroke::new(10.)
|
||||||
|
};
|
||||||
|
let points = [(0., 0.), (100., 0.), (0., 50.)];
|
||||||
|
let chart = PathChart::new(&polyline(&points, false), &stroke, TOLERANCE);
|
||||||
|
|
||||||
|
let corner = DVec2::new(100., 0.);
|
||||||
|
let incoming = DVec2::X;
|
||||||
|
let outgoing = (DVec2::new(0., 50.) - corner).normalize();
|
||||||
|
let corner_u = 100. / (100. + DVec2::new(100., 50.).length());
|
||||||
|
|
||||||
|
// The sharp right turn's miter points along the bisector of the two left normals, reaching the stroke's left edge at its tip
|
||||||
|
let left_normals = [-incoming.perp(), -outgoing.perp()];
|
||||||
|
let bisector = (left_normals[0] + left_normals[1]).normalize();
|
||||||
|
let tip_distance = 5. / bisector.dot(left_normals[0]);
|
||||||
|
for fraction in [0.1, 0.5, 0.9, 0.999] {
|
||||||
|
let point = corner + bisector * tip_distance * fraction;
|
||||||
|
assert_chart(&chart, (point.x, point.y), (corner_u, 0.5 * (1. - fraction)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn caps_extend_u_below_zero_and_above_one_linearly() {
|
||||||
|
let path = polyline(&[(0., 0.), (100., 0.)], false);
|
||||||
|
for cap in [StrokeCap::Square, StrokeCap::Round] {
|
||||||
|
let chart = PathChart::new(&path, &Stroke { cap, ..Stroke::new(10.) }, TOLERANCE);
|
||||||
|
assert_chart(&chart, (-3., 1.), (-0.03, 0.6));
|
||||||
|
assert_chart(&chart, (104., -2.), (1.04, 0.3));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Past a butt cap, nothing draws, so the fringe takes the nearest point on the path
|
||||||
|
let chart = PathChart::new(
|
||||||
|
&path,
|
||||||
|
&Stroke {
|
||||||
|
cap: StrokeCap::Butt,
|
||||||
|
..Stroke::new(10.)
|
||||||
|
},
|
||||||
|
TOLERANCE,
|
||||||
|
);
|
||||||
|
assert_chart(&chart, (-3., 1.), (0., 0.6));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn dashes_chart_like_the_solid_stroke_and_a_gap_never_wins_over_a_dash() {
|
||||||
|
let line = polyline(&[(0., 0.), (100., 0.)], false);
|
||||||
|
let dashed = Stroke {
|
||||||
|
dash_lengths: vec![10., 10.],
|
||||||
|
..Stroke::new(4.)
|
||||||
|
};
|
||||||
|
let solid_chart = PathChart::new(&line, &Stroke::new(4.), TOLERANCE);
|
||||||
|
let dashed_chart = PathChart::new(&line, &dashed, TOLERANCE);
|
||||||
|
for x in [5., 15., 25., 92.] {
|
||||||
|
let point = DVec2::new(x, 1.);
|
||||||
|
assert_eq!(dashed_chart.chart_at(point), solid_chart.chart_at(point), "the dashed stroke should chart like the solid one at {x}");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Each vertical line crosses the horizontal one 45 or 55 units along itself, where its own dash pattern draws or skips
|
||||||
|
let crossing_u = |crossing_x: f64, vertical_start_y: f64| {
|
||||||
|
let mut path = line.clone();
|
||||||
|
path.extend(polyline(&[(crossing_x, vertical_start_y), (crossing_x, vertical_start_y + 100.)], false));
|
||||||
|
let chart = PathChart::new(&path, &dashed, TOLERANCE);
|
||||||
|
chart.chart_at(DVec2::new(crossing_x, 0.)).map(|(u, _)| u)
|
||||||
|
};
|
||||||
|
|
||||||
|
// The later line's gap leaves the earlier line's dash showing
|
||||||
|
assert_eq!(crossing_u(5., -55.), Some(0.05));
|
||||||
|
// The later line's dash covers the earlier line's gap
|
||||||
|
assert_eq!(crossing_u(15., -45.), Some(0.45));
|
||||||
|
// Where both draw, the later line is on top
|
||||||
|
assert_eq!(crossing_u(25., -45.), Some(0.45));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_figure_eights_later_pass_wins_with_the_fold_on_its_bands_edge() {
|
||||||
|
let chart = PathChart::new(&polyline(&[(0., 0.), (100., 100.), (100., 0.), (0., 100.)], true), &Stroke::new(10.), TOLERANCE);
|
||||||
|
let diagonal = 100. * 2_f64.sqrt();
|
||||||
|
let length = 2. * diagonal + 200.;
|
||||||
|
|
||||||
|
// The crossing belongs to the second diagonal, which comes later
|
||||||
|
let Some((u, _)) = chart.chart_at(DVec2::new(50., 50.)) else {
|
||||||
|
panic!("the crossing should be charted")
|
||||||
|
};
|
||||||
|
assert!((u - (diagonal + 100. + diagonal / 2.) / length).abs() < 1e-9);
|
||||||
|
|
||||||
|
// Along the first diagonal, the fold lies at the edge of the second one's band, where x and y pass 50 + 5 / √2 ≈ 53.54
|
||||||
|
let Some((inside_u, _)) = chart.chart_at(DVec2::splat(53.4)) else {
|
||||||
|
panic!("the fold should be charted")
|
||||||
|
};
|
||||||
|
let Some((outside_u, _)) = chart.chart_at(DVec2::splat(53.7)) else {
|
||||||
|
panic!("past the fold should be charted")
|
||||||
|
};
|
||||||
|
assert!(inside_u > 0.5, "within the later band, the later pass should win");
|
||||||
|
assert!((outside_u - 53.7 * 2_f64.sqrt() / length).abs() < 1e-9, "past the later band, the earlier pass should show");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_curves_end_reaches_u_of_one() {
|
||||||
|
let mut path = BezPath::new();
|
||||||
|
path.move_to((0., 0.));
|
||||||
|
path.curve_to((30., 80.), (70., -80.), (100., 0.));
|
||||||
|
let chart = PathChart::new(&path, &Stroke::new(2.), TOLERANCE);
|
||||||
|
|
||||||
|
let Some((u, v)) = chart.chart_at(DVec2::new(100., 0.)) else {
|
||||||
|
panic!("the end should be charted")
|
||||||
|
};
|
||||||
|
assert!((u - 1.).abs() < 1e-9, "the end should chart at u = 1, not {u}");
|
||||||
|
assert!((v - 0.5).abs() < 1e-9);
|
||||||
|
|
||||||
|
let Some(end) = chart.point_at(0, 1.) else { panic!("the contour should exist") };
|
||||||
|
assert!(end.abs_diff_eq(DVec2::new(100., 0.), 1e-9));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn inside_and_outside_bands_lie_on_their_side_of_the_fill() {
|
||||||
|
let clockwise = polyline(&[(0., 0.), (100., 0.), (100., 100.), (0., 100.)], true);
|
||||||
|
let counterclockwise = polyline(&[(0., 0.), (0., 100.), (100., 100.), (100., 0.)], true);
|
||||||
|
let aligned = |align| Stroke { align, ..Stroke::new(10.) };
|
||||||
|
|
||||||
|
// Clockwise on screen, the right side is inside, so the inside band runs from the path (left edge) inward
|
||||||
|
let chart = PathChart::new(&clockwise, &aligned(StrokeAlign::Inside), TOLERANCE);
|
||||||
|
assert_chart(&chart, (50., 2.), (0.125, 0.2));
|
||||||
|
let chart = PathChart::new(&clockwise, &aligned(StrokeAlign::Outside), TOLERANCE);
|
||||||
|
assert_chart(&chart, (50., -2.), (0.125, 0.8));
|
||||||
|
|
||||||
|
// Counterclockwise, the right side is outside, so the inside band runs inward to the path (right edge)
|
||||||
|
let chart = PathChart::new(&counterclockwise, &aligned(StrokeAlign::Inside), TOLERANCE);
|
||||||
|
assert_chart(&chart, (2., 50.), (0.125, 0.8));
|
||||||
|
let chart = PathChart::new(&counterclockwise, &aligned(StrokeAlign::Outside), TOLERANCE);
|
||||||
|
assert_chart(&chart, (-2., 50.), (0.125, 0.2));
|
||||||
|
|
||||||
|
// An open path isn't aligned, so its band stays centered
|
||||||
|
let chart = PathChart::new(&polyline(&[(0., 0.), (100., 0.)], false), &aligned(StrokeAlign::Inside), TOLERANCE);
|
||||||
|
assert_chart(&chart, (50., 0.), (0.5, 0.5));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_mirrored_stroke_transform_flips_v() {
|
||||||
|
let mirrored = Stroke {
|
||||||
|
transform: DAffine2::from_scale(DVec2::new(1., -1.)),
|
||||||
|
..Stroke::new(10.)
|
||||||
|
};
|
||||||
|
let chart = PathChart::new(&polyline(&[(0., 0.), (100., 0.)], false), &mirrored, TOLERANCE);
|
||||||
|
|
||||||
|
assert_chart(&chart, (25., -5.), (0.25, 1.));
|
||||||
|
assert_chart(&chart, (75., 5.), (0.75, 0.));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -138,6 +138,20 @@ impl StrokeAlign {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Where a stroke's paint is placed: in the plane, or along the stroke's paths.
|
||||||
|
#[repr(C)]
|
||||||
|
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||||
|
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, graphene_hash::CacheHash, DynAny, node_macro::ChoiceType)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||||
|
#[widget(Radio)]
|
||||||
|
pub enum PaintMapping {
|
||||||
|
/// The paint is placed in the canvas as usual.
|
||||||
|
#[default]
|
||||||
|
Plane,
|
||||||
|
/// The paint follows the stroke, its Along direction running the length of each path and Across running from the left edge to the right.
|
||||||
|
Path,
|
||||||
|
}
|
||||||
|
|
||||||
// Backs the control bar's stroke popover radio and legacy document parsing: the relative order
|
// Backs the control bar's stroke popover radio and legacy document parsing: the relative order
|
||||||
// of the Fill and Stroke nodes in the chain is what actually determines the paint order
|
// of the Fill and Stroke nodes in the chain is what actually determines the paint order
|
||||||
#[repr(C)]
|
#[repr(C)]
|
||||||
@@ -220,6 +234,8 @@ pub struct Stroke {
|
|||||||
pub join_miter_limit: f64,
|
pub join_miter_limit: f64,
|
||||||
#[cfg_attr(feature = "serde", serde(default))]
|
#[cfg_attr(feature = "serde", serde(default))]
|
||||||
pub align: StrokeAlign,
|
pub align: StrokeAlign,
|
||||||
|
#[cfg_attr(feature = "serde", serde(default))]
|
||||||
|
pub paint_mapping: PaintMapping,
|
||||||
#[cfg_attr(feature = "serde", serde(default = "daffine2_identity"))]
|
#[cfg_attr(feature = "serde", serde(default = "daffine2_identity"))]
|
||||||
pub transform: DAffine2,
|
pub transform: DAffine2,
|
||||||
}
|
}
|
||||||
@@ -234,6 +250,7 @@ impl Stroke {
|
|||||||
join: StrokeJoin::Miter,
|
join: StrokeJoin::Miter,
|
||||||
join_miter_limit: 4.,
|
join_miter_limit: 4.,
|
||||||
align: StrokeAlign::Center,
|
align: StrokeAlign::Center,
|
||||||
|
paint_mapping: PaintMapping::Plane,
|
||||||
transform: DAffine2::IDENTITY,
|
transform: DAffine2::IDENTITY,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -247,6 +264,7 @@ impl Stroke {
|
|||||||
join: if time < 0.5 { self.join } else { other.join },
|
join: if time < 0.5 { self.join } else { other.join },
|
||||||
join_miter_limit: self.join_miter_limit + (other.join_miter_limit - self.join_miter_limit) * time,
|
join_miter_limit: self.join_miter_limit + (other.join_miter_limit - self.join_miter_limit) * time,
|
||||||
align: if time < 0.5 { self.align } else { other.align },
|
align: if time < 0.5 { self.align } else { other.align },
|
||||||
|
paint_mapping: if time < 0.5 { self.paint_mapping } else { other.paint_mapping },
|
||||||
transform: {
|
transform: {
|
||||||
// Decompose into scale/rotation/skew and interpolate each component separately.
|
// Decompose into scale/rotation/skew and interpolate each component separately.
|
||||||
// We do this instead of linear matrix interpolation because that passes through a zero matrix
|
// We do this instead of linear matrix interpolation because that passes through a zero matrix
|
||||||
@@ -351,6 +369,7 @@ impl Default for Stroke {
|
|||||||
join: StrokeJoin::Miter,
|
join: StrokeJoin::Miter,
|
||||||
join_miter_limit: 4.,
|
join_miter_limit: 4.,
|
||||||
align: StrokeAlign::Center,
|
align: StrokeAlign::Center,
|
||||||
|
paint_mapping: PaintMapping::Plane,
|
||||||
transform: DAffine2::IDENTITY,
|
transform: DAffine2::IDENTITY,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ fastnoise-lite = { workspace = true, features = ["wgsl"] }
|
|||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
# Local dependencies
|
# Local dependencies
|
||||||
graphene-resource = { workspace = true }
|
graphene-resource = { workspace = true }
|
||||||
|
svg-convert = { workspace = true }
|
||||||
|
|
||||||
# Required dependencies
|
# Required dependencies
|
||||||
# Turns on the shader translators of every backend for the tests, whichever of them the platform's own backends build with
|
# Turns on the shader translators of every backend for the tests, whichever of them the platform's own backends build with
|
||||||
|
|||||||
@@ -21,8 +21,7 @@ impl Context {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The context the GPU tests run on, which wgpu's environment variables can aim at each backend and shader compiler in turn.
|
/// The context the GPU tests run on, which wgpu's environment variables can aim at each backend and shader compiler in turn.
|
||||||
#[cfg(test)]
|
pub async fn for_tests() -> Option<Self> {
|
||||||
pub(crate) async fn for_tests() -> Option<Self> {
|
|
||||||
let context = ContextBuilder::new().with_environment_overrides().build().await;
|
let context = ContextBuilder::new().with_environment_overrides().build().await;
|
||||||
|
|
||||||
// A backend asked for by name fails the tests if it can't run them, rather than passing them all as skipped
|
// A backend asked for by name fails the tests if it can't run them, rather than passing them all as skipped
|
||||||
|
|||||||
@@ -1,64 +1,133 @@
|
|||||||
use crate::WgpuExecutor;
|
use crate::WgpuExecutor;
|
||||||
use core_types::ops::ConvertAsync;
|
|
||||||
use core_types::transform::Footprint;
|
use core_types::transform::Footprint;
|
||||||
use raster_types::{CPU, Raster, Texture};
|
use raster_types::{Raster, Texture};
|
||||||
use rendering::CanvasImage;
|
use rendering::CanvasImage;
|
||||||
use rendering::deferred_image::{DeferredImage, DeferredImagePlacement, EffectMap, EffectMapPlacement, MAX_DEFERRED_IMAGE_PIXELS, substitute_deferred_image, substitute_effect_map};
|
use rendering::deferred_image::{DeferredImage, DeferredImagePlacement, EffectMap, EffectMapPlacement, MAX_DEFERRED_IMAGE_PIXELS, substitute_deferred_image, substitute_effect_map};
|
||||||
|
|
||||||
impl WgpuExecutor {
|
/// The maps and images the GPU rendered for the placeholders of an SVG, with the first failure to render one in view, whose placeholder stays.
|
||||||
/// Renders the maps of effects' coverages that an SVG of the view `footprint` takes, with where its filters place each.
|
pub struct SvgPlaceholderRenders {
|
||||||
/// Maps out of view, or that fail to render, keep their placeholders.
|
effect_maps: Vec<(EffectMapPlacement, Texture)>,
|
||||||
pub fn render_effect_maps(&self, effect_maps: &[EffectMap], footprint: Footprint) -> Vec<(EffectMapPlacement, Texture)> {
|
deferred_images: Vec<(DeferredImagePlacement, Texture)>,
|
||||||
let max_pixels = MAX_DEFERRED_IMAGE_PIXELS.min(self.context().device.limits().max_texture_dimension_2d);
|
failure: Option<anyhow::Error>,
|
||||||
|
}
|
||||||
|
|
||||||
effect_maps
|
impl SvgPlaceholderRenders {
|
||||||
|
/// Whether nothing was rendered and nothing failed to, as when every placeholder is out of view.
|
||||||
|
pub fn is_empty(&self) -> bool {
|
||||||
|
self.effect_maps.is_empty() && self.deferred_images.is_empty() && self.failure.is_none()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether any of the maps and images an SVG of the view `footprint` takes from the GPU lie in view, needing a GPU to fill their placeholders.
|
||||||
|
pub fn svg_placeholders_in_view(effect_maps: &[EffectMap], deferred_images: &[DeferredImage], footprint: Footprint) -> bool {
|
||||||
|
let (document_to_view, view_size) = (footprint.transform, footprint.resolution.as_dvec2());
|
||||||
|
effect_maps.iter().any(|map| map.layout(document_to_view, view_size, MAX_DEFERRED_IMAGE_PIXELS).is_some())
|
||||||
|
|| deferred_images.iter().any(|deferred| deferred.layout(document_to_view, view_size, MAX_DEFERRED_IMAGE_PIXELS).is_some())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Logs the `error`, keeping it as the `failure` if it's the first.
|
||||||
|
fn record_failure(failure: &mut Option<anyhow::Error>, error: anyhow::Error) {
|
||||||
|
log::error!("{error:#}");
|
||||||
|
failure.get_or_insert(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WgpuExecutor {
|
||||||
|
/// Renders the maps and images an SVG of the view `footprint` takes from the GPU. Those out of view keep their placeholders.
|
||||||
|
pub fn render_svg_placeholders(&self, effect_maps: &[EffectMap], deferred_images: &[DeferredImage], footprint: Footprint) -> SvgPlaceholderRenders {
|
||||||
|
let max_pixels = MAX_DEFERRED_IMAGE_PIXELS.min(self.context().device.limits().max_texture_dimension_2d);
|
||||||
|
let mut failure = None;
|
||||||
|
|
||||||
|
let effect_maps = effect_maps
|
||||||
.iter()
|
.iter()
|
||||||
.filter_map(|map| {
|
.filter_map(|map| {
|
||||||
let layout = map.layout(footprint.transform, footprint.resolution.as_dvec2(), max_pixels)?;
|
let layout = map.layout(footprint.transform, footprint.resolution.as_dvec2(), max_pixels)?;
|
||||||
match self.render_vello(layout.size, layout.document_to_pixels, &mut |scene| map.draw(scene, &layout)) {
|
match self.render_vello(layout.size, layout.document_to_pixels, &mut |scene| map.draw(scene, &layout)) {
|
||||||
Ok(texture) => Some((layout.placement, texture)),
|
Ok(texture) => Some((layout.placement, texture)),
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
log::error!("Failed to render a map of an effect's coverage for an SVG filter: {error}");
|
record_failure(&mut failure, error.context("Failed to render a map of an effect's coverage for an SVG filter"));
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.collect()
|
.collect();
|
||||||
}
|
|
||||||
|
|
||||||
/// Reads back the maps of effects' coverages, putting each in `svg` in place of its placeholder.
|
let deferred_images = deferred_images
|
||||||
pub async fn resolve_effect_maps(&self, svg: &mut String, maps: Vec<(EffectMapPlacement, Texture)>) {
|
|
||||||
for (placement, texture) in maps {
|
|
||||||
let map: Raster<CPU> = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, self.clone()).await;
|
|
||||||
substitute_effect_map(svg, &placement, &map);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Renders images of the content an SVG of the view `footprint` describes defers to the GPU, with where the SVG draws each.
|
|
||||||
/// Content out of view, or that fails to render, keeps the markup standing in for it.
|
|
||||||
pub fn render_deferred_svg_images(&self, deferred_images: &[DeferredImage], footprint: Footprint) -> Vec<(DeferredImagePlacement, Texture)> {
|
|
||||||
let max_pixels = MAX_DEFERRED_IMAGE_PIXELS.min(self.context().device.limits().max_texture_dimension_2d);
|
|
||||||
|
|
||||||
deferred_images
|
|
||||||
.iter()
|
.iter()
|
||||||
.filter_map(|deferred| {
|
.filter_map(|deferred| {
|
||||||
let layout = deferred.layout(footprint.transform, footprint.resolution.as_dvec2(), max_pixels)?;
|
let layout = deferred.layout(footprint.transform, footprint.resolution.as_dvec2(), max_pixels)?;
|
||||||
match self.render_vello(layout.size, layout.document_to_pixels, &mut |scene| deferred.draw(scene, &layout)) {
|
match self.render_vello(layout.size, layout.document_to_pixels, &mut |scene| deferred.draw(scene, &layout)) {
|
||||||
Ok(texture) => Some((layout.placement, texture)),
|
Ok(texture) => Some((layout.placement, texture)),
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
log::error!("Failed to render an image of content with effects SVG can't express: {error}");
|
record_failure(&mut failure, error.context("Failed to render an image of content SVG can't draw"));
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.collect()
|
.collect();
|
||||||
}
|
|
||||||
|
|
||||||
/// Reads back the images of deferred content, putting each in `svg` in place of the markup standing in for its content.
|
SvgPlaceholderRenders {
|
||||||
pub async fn resolve_deferred_svg_images(&self, svg: &mut String, image_data: &mut Vec<(u64, CanvasImage)>, images: Vec<(DeferredImagePlacement, Texture)>) {
|
effect_maps,
|
||||||
for (placement, texture) in images {
|
deferred_images,
|
||||||
let image: Raster<CPU> = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, self.clone()).await;
|
failure,
|
||||||
substitute_deferred_image(svg, image_data, &placement, &image);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Reads back the `renders`, putting each in `svg` in place of its placeholder. Images drawn to canvases are added to `image_data`.
|
||||||
|
/// Fails with the first map or image that failed to render or read back, after putting in place all that didn't.
|
||||||
|
pub async fn substitute_svg_placeholders(&self, svg: &mut String, image_data: &mut Vec<(u64, CanvasImage)>, renders: SvgPlaceholderRenders) -> anyhow::Result<()> {
|
||||||
|
let SvgPlaceholderRenders {
|
||||||
|
effect_maps,
|
||||||
|
deferred_images,
|
||||||
|
failure,
|
||||||
|
} = renders;
|
||||||
|
let maps_failure = self.resolve_effect_maps(svg, effect_maps).await.err();
|
||||||
|
let images_failure = self.resolve_deferred_svg_images(svg, image_data, deferred_images).await.err();
|
||||||
|
|
||||||
|
match failure.or(maps_failure).or(images_failure) {
|
||||||
|
Some(failure) => Err(failure),
|
||||||
|
None => Ok(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Renders the maps of effects' coverages that an SVG of the view `footprint` takes, with where its filters place each.
|
||||||
|
/// Maps out of view, or that fail to render, keep their placeholders.
|
||||||
|
pub fn render_effect_maps(&self, effect_maps: &[EffectMap], footprint: Footprint) -> Vec<(EffectMapPlacement, Texture)> {
|
||||||
|
self.render_svg_placeholders(effect_maps, &[], footprint).effect_maps
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads back the maps of effects' coverages, putting each in `svg` in place of its placeholder.
|
||||||
|
/// Fails with the first that fails to read back, after putting in place all that didn't.
|
||||||
|
async fn resolve_effect_maps(&self, svg: &mut String, maps: Vec<(EffectMapPlacement, Texture)>) -> anyhow::Result<()> {
|
||||||
|
let mut failure = None;
|
||||||
|
for (placement, texture) in maps {
|
||||||
|
match self.try_download(Raster::new_gpu(texture)).await {
|
||||||
|
Ok(map) => substitute_effect_map(svg, &placement, &map),
|
||||||
|
Err(error) => {
|
||||||
|
record_failure(&mut failure, error.context("Failed to read back a map of an effect's coverage for an SVG filter"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
failure.map_or(Ok(()), Err)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Renders images of the content an SVG of the view `footprint` describes defers to the GPU, with where the SVG draws each.
|
||||||
|
/// Content out of view, or that fails to render, keeps the markup standing in for it.
|
||||||
|
pub fn render_deferred_svg_images(&self, deferred_images: &[DeferredImage], footprint: Footprint) -> Vec<(DeferredImagePlacement, Texture)> {
|
||||||
|
self.render_svg_placeholders(&[], deferred_images, footprint).deferred_images
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads back the images of deferred content, putting each in `svg` in place of the markup standing in for its content. Images drawn to canvases are added to `image_data`.
|
||||||
|
/// Fails with the first that fails to read back, after putting in place all that didn't.
|
||||||
|
pub async fn resolve_deferred_svg_images(&self, svg: &mut String, image_data: &mut Vec<(u64, CanvasImage)>, images: Vec<(DeferredImagePlacement, Texture)>) -> anyhow::Result<()> {
|
||||||
|
let mut failure = None;
|
||||||
|
for (placement, texture) in images {
|
||||||
|
match self.try_download(Raster::new_gpu(texture)).await {
|
||||||
|
Ok(image) => substitute_deferred_image(svg, image_data, &placement, &image),
|
||||||
|
Err(error) => {
|
||||||
|
record_failure(&mut failure, error.context("Failed to read back an image of content SVG can't draw"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
failure.map_or(Ok(()), Err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -23,6 +23,7 @@ use wgpu::util::DeviceExt;
|
|||||||
pub use buffer::Buffer;
|
pub use buffer::Buffer;
|
||||||
pub use context::Context as WgpuContext;
|
pub use context::Context as WgpuContext;
|
||||||
pub use context::ContextBuilder as WgpuContextBuilder;
|
pub use context::ContextBuilder as WgpuContextBuilder;
|
||||||
|
pub use deferred_svg_images::{SvgPlaceholderRenders, svg_placeholders_in_view};
|
||||||
pub use pipeline::Pipeline as WgpuPipeline;
|
pub use pipeline::Pipeline as WgpuPipeline;
|
||||||
pub use pipeline::PipelineCache as WgpuPipelineCache;
|
pub use pipeline::PipelineCache as WgpuPipelineCache;
|
||||||
pub use pipeline::PipelineError as WgpuPipelineError;
|
pub use pipeline::PipelineError as WgpuPipelineError;
|
||||||
@@ -198,6 +199,12 @@ impl WgpuExecutor {
|
|||||||
Self::with_context(WgpuContext::new().await?)
|
Self::with_context(WgpuContext::new().await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The executor GPU tests run on, on the context [`WgpuContext::for_tests`] makes, or `None` without a GPU.
|
||||||
|
#[cfg(not(target_family = "wasm"))]
|
||||||
|
pub async fn for_tests() -> Option<Self> {
|
||||||
|
Self::with_context(WgpuContext::for_tests().await?)
|
||||||
|
}
|
||||||
|
|
||||||
pub fn with_context(context: WgpuContext) -> Option<Self> {
|
pub fn with_context(context: WgpuContext) -> Option<Self> {
|
||||||
let vello_renderer = VelloRenderer::new(&context.device, &context.adapter);
|
let vello_renderer = VelloRenderer::new(&context.device, &context.adapter);
|
||||||
|
|
||||||
|
|||||||
@@ -7,8 +7,6 @@ use core_types::{ATTR_BLEND_MODE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFOR
|
|||||||
use glam::{DAffine2, DVec2, UVec2};
|
use glam::{DAffine2, DVec2, UVec2};
|
||||||
use graphic_types::Graphic;
|
use graphic_types::Graphic;
|
||||||
use graphic_types::effects::{EffectOperation, Effects};
|
use graphic_types::effects::{EffectOperation, Effects};
|
||||||
use raster_kernels::adjustments::preserves_alpha;
|
|
||||||
use raster_kernels::raster_effects::adjusted_raster;
|
|
||||||
use raster_types::{CPU, Image, Pixels, Raster};
|
use raster_types::{CPU, Image, Pixels, Raster};
|
||||||
use rendering::{Render, RenderOutputType, RenderParams, leading_raster_adjustments};
|
use rendering::{Render, RenderOutputType, RenderParams, leading_raster_adjustments};
|
||||||
|
|
||||||
@@ -67,10 +65,6 @@ impl WgpuExecutor {
|
|||||||
return Ok(carried_out(item, raster));
|
return Ok(carried_out(item, raster));
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(adjusted) = adjusted_without_render(&item, &effects, fill) {
|
|
||||||
return Ok(carried_out(item, adjusted));
|
|
||||||
}
|
|
||||||
|
|
||||||
let reach = effects_reach(&effects, size.as_dvec2());
|
let reach = effects_reach(&effects, size.as_dvec2());
|
||||||
if !reach.is_finite() {
|
if !reach.is_finite() {
|
||||||
anyhow::bail!("The effects on a {} by {} image reach too far to render", size.x, size.y);
|
anyhow::bail!("The effects on a {} by {} image reach too far to render", size.x, size.y);
|
||||||
@@ -126,16 +120,8 @@ impl WgpuExecutor {
|
|||||||
anyhow::bail!("The GPU's textures and buffers can't hold a tile of a {} by {} image's render with its effects", size.x, size.y);
|
anyhow::bail!("The GPU's textures and buffers can't hold a tile of a {} by {} image's render with its effects", size.x, size.y);
|
||||||
};
|
};
|
||||||
|
|
||||||
// The raster's render carries out leading adjustments changing alpha on its image's own pixels, which a crop's group can't, so they're carried out first
|
// The raster's render carries out its leading adjustments on its image's own pixels, which a crop's group can't, so each crop takes them as its own
|
||||||
if crops {
|
let leading_adjustments = if crops { leading_raster_adjustments(&content).len() } else { 0 };
|
||||||
let leading_adjustments = leading_raster_adjustments(&content);
|
|
||||||
if leading_adjustments.iter().any(|adjustment| !preserves_alpha(adjustment)) {
|
|
||||||
let adjusted = adjusted_raster(content.element(), &leading_adjustments);
|
|
||||||
let (_, attributes) = content.into_parts();
|
|
||||||
content = Item::from_parts(adjusted, attributes);
|
|
||||||
content.set_attribute(ATTR_EFFECTS, effects.after(leading_adjustments.len()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let whole = List::new_from_item(content.clone());
|
let whole = List::new_from_item(content.clone());
|
||||||
if !crops && grown_size.cmple(tile_size).all() {
|
if !crops && grown_size.cmple(tile_size).all() {
|
||||||
@@ -154,7 +140,7 @@ impl WgpuExecutor {
|
|||||||
true => {
|
true => {
|
||||||
let start = origin.saturating_sub(margin + reach);
|
let start = origin.saturating_sub(margin + reach);
|
||||||
let end = (origin + size_in_tile + reach).saturating_sub(margin).min(size);
|
let end = (origin + size_in_tile + reach).saturating_sub(margin).min(size);
|
||||||
self.render_tile(&cropped(&content, start, end), tile_to_pixels, size_in_tile).await?
|
self.render_tile(&cropped(&content, leading_adjustments, start, end), tile_to_pixels, size_in_tile).await?
|
||||||
}
|
}
|
||||||
false => self.render_tile(&whole, tile_to_pixels, size_in_tile).await?,
|
false => self.render_tile(&whole, tile_to_pixels, size_in_tile).await?,
|
||||||
};
|
};
|
||||||
@@ -197,25 +183,10 @@ fn carried_out(item: Item<Raster<CPU>>, raster: Raster<CPU>) -> Item<Pixels> {
|
|||||||
item
|
item
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The image with its `effects` and `fill` carried out on the CPU if the effects are all adjustments its render carries out on its own pixels, or `None` if any needs a render.
|
|
||||||
/// The CPU keeps the adjustments' full precision, including values past 0 to 1 and colors beneath zero alpha, which an 8-bit download would lose.
|
|
||||||
fn adjusted_without_render(item: &Item<Raster<CPU>>, effects: &Effects, fill: f64) -> Option<Raster<CPU>> {
|
|
||||||
let adjustments = leading_raster_adjustments(item);
|
|
||||||
if adjustments.len() < effects.operations().count() {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Under a partial fill, the leading adjustments all keep alpha, so fading after them matches fading before
|
|
||||||
let mut adjusted = adjusted_raster(item.element(), &adjustments);
|
|
||||||
if fill < 1. {
|
|
||||||
adjusted.data_mut().data.iter_mut().for_each(|color| *color = color.with_alpha(color.a() * fill as f32));
|
|
||||||
}
|
|
||||||
Some(adjusted)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The raster `content` drawn from only its image's pixels from `start` up to `end`, at their own resolution where they lie in the whole image.
|
/// The raster `content` drawn from only its image's pixels from `start` up to `end`, at their own resolution where they lie in the whole image.
|
||||||
/// The crop sits within a group taking the content's placement and effects, so the effects measure and place what they draw as for the whole image.
|
/// The crop sits within a group taking the content's placement and effects, so the effects measure and place what they draw as for the whole image,
|
||||||
fn cropped(content: &Item<Raster<CPU>>, start: UVec2, end: UVec2) -> List<Graphic> {
|
/// but for the first `leading_adjustments` of them, which the crop takes as its own for its render to carry out on its pixels.
|
||||||
|
fn cropped(content: &Item<Raster<CPU>>, leading_adjustments: usize, start: UVec2, end: UVec2) -> List<Graphic> {
|
||||||
let image = content.element();
|
let image = content.element();
|
||||||
let (size, crop_size) = (UVec2::new(image.width, image.height), end.saturating_sub(start));
|
let (size, crop_size) = (UVec2::new(image.width, image.height), end.saturating_sub(start));
|
||||||
if crop_size.cmpeq(UVec2::ZERO).any() {
|
if crop_size.cmpeq(UVec2::ZERO).any() {
|
||||||
@@ -234,10 +205,18 @@ fn cropped(content: &Item<Raster<CPU>>, start: UVec2, end: UVec2) -> List<Graphi
|
|||||||
data,
|
data,
|
||||||
};
|
};
|
||||||
let placement = DAffine2::from_translation(start.as_dvec2() / size.as_dvec2()) * DAffine2::from_scale(crop_size.as_dvec2() / size.as_dvec2());
|
let placement = DAffine2::from_translation(start.as_dvec2() / size.as_dvec2()) * DAffine2::from_scale(crop_size.as_dvec2() / size.as_dvec2());
|
||||||
let crop = Item::new_from_element(Raster::new_cpu(crop)).with_attribute(ATTR_TRANSFORM, placement);
|
let mut crop = Item::new_from_element(Raster::new_cpu(crop)).with_attribute(ATTR_TRANSFORM, placement);
|
||||||
|
|
||||||
|
let effects: Effects = content.attribute_cloned_or_default(ATTR_EFFECTS);
|
||||||
let (_, attributes) = content.clone().into_parts();
|
let (_, attributes) = content.clone().into_parts();
|
||||||
List::new_from_item(Item::from_parts(Graphic::RasterCPU(Box::new(crop)), attributes))
|
if leading_adjustments == 0 {
|
||||||
|
return List::new_from_item(Item::from_parts(Graphic::RasterCPU(Box::new(crop)), attributes));
|
||||||
|
}
|
||||||
|
|
||||||
|
crop.set_attribute(ATTR_EFFECTS, effects.run(0..leading_adjustments).into_owned());
|
||||||
|
let mut group = Item::from_parts(Graphic::RasterCPU(Box::new(crop)), attributes);
|
||||||
|
group.set_attribute(ATTR_EFFECTS, effects.after(leading_adjustments));
|
||||||
|
List::new_from_item(group)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// How far, in whole pixels along each axis of an image of `size` pixels, its `effects` paint and read past each pixel and its edges.
|
/// How far, in whole pixels along each axis of an image of `size` pixels, its `effects` paint and read past each pixel and its edges.
|
||||||
@@ -345,6 +324,19 @@ mod tests {
|
|||||||
color.a() < 0.02
|
color.a() < 0.02
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_margin_too_large_is_cut_short_to_fit_the_pixel_limit() {
|
||||||
|
// A tall strip whose margins alone would grow it eightfold past the limit
|
||||||
|
let size = DVec2::new(1., 16_384.);
|
||||||
|
let margin = DVec2::splat(3000.);
|
||||||
|
|
||||||
|
let fitted = (margin * margin_fraction_that_fits(size, margin)).floor();
|
||||||
|
let grown_area = (size + 2. * fitted).element_product();
|
||||||
|
|
||||||
|
assert!(grown_area <= MAX_PIXELS_WITH_MARGIN, "the grown image has {grown_area} pixels");
|
||||||
|
assert!(grown_area > 0.99 * MAX_PIXELS_WITH_MARGIN, "the grown image has only {grown_area} pixels");
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn an_image_without_effects_comes_back_as_it_is() {
|
fn an_image_without_effects_comes_back_as_it_is() {
|
||||||
let Some(executor) = executor() else { return };
|
let Some(executor) = executor() else { return };
|
||||||
@@ -375,8 +367,8 @@ mod tests {
|
|||||||
for image in [without_effects, with_no_effects] {
|
for image in [without_effects, with_no_effects] {
|
||||||
let read_back = block_on(executor.read_back(image.clone())).unwrap();
|
let read_back = block_on(executor.read_back(image.clone())).unwrap();
|
||||||
|
|
||||||
let faded: Vec<_> = image.element().data.iter().map(|color| color.with_alpha(0.5)).collect();
|
let faded = image.element().data.iter().map(|color| color.with_alpha(0.5)).collect();
|
||||||
assert_eq!(read_back.element().data, faded);
|
assert_alike(read_back.element(), &Image { width: 20, height: 20, data: faded }, 2);
|
||||||
assert!(read_back.attribute::<Effects>(ATTR_EFFECTS).is_none());
|
assert!(read_back.attribute::<Effects>(ATTR_EFFECTS).is_none());
|
||||||
assert!(read_back.attribute::<f64>(ATTR_OPACITY_FILL).is_none());
|
assert!(read_back.attribute::<f64>(ATTR_OPACITY_FILL).is_none());
|
||||||
|
|
||||||
@@ -411,54 +403,37 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn adjustments_carried_out_on_the_cpu_match_their_render() {
|
fn adjustments_alone_are_read_back_as_their_definitions_draw_them() {
|
||||||
let Some((executor, limits)) = executor_and_limits() else { return };
|
|
||||||
|
|
||||||
// Opaque, so the render's straight alpha keeps every color
|
|
||||||
let operations = [uneven_levels(1.), graphic_types::Adjustment::Invert].map(EffectOperation::Adjustment);
|
|
||||||
let image = image_of_pixels(DVec2::ONE, |x, y| Color::from_rgbaf32_unchecked(x as f32 / 20., y as f32 / 20., 0.5, 1.), &operations);
|
|
||||||
let (effects, transform) = (image.attribute::<Effects>(ATTR_EFFECTS).unwrap().clone(), image.attribute_cloned_or_default(ATTR_TRANSFORM));
|
|
||||||
|
|
||||||
let on_the_cpu = adjusted_without_render(&image, &effects, 1.).expect("adjustments alone need no render");
|
|
||||||
let rendered = block_on(executor.render_at_pixel_grid(&image, &effects, transform, DVec2::ZERO, DVec2::ZERO, limits)).unwrap();
|
|
||||||
|
|
||||||
// The render carries out leading adjustments on the image's own pixels too, then draws them into an 8-bit texture
|
|
||||||
assert_alike(&on_the_cpu, &rendered, ADJUSTMENT_TOLERANCE);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn adjustments_alone_are_carried_out_on_the_cpu() {
|
|
||||||
use graphic_types::Adjustment;
|
use graphic_types::Adjustment;
|
||||||
|
use raster_kernels::adjustments::adjust_color;
|
||||||
|
|
||||||
let Some(executor) = executor() else { return };
|
let Some(executor) = executor() else { return };
|
||||||
|
|
||||||
|
// Each pixel's color through the adjustments one after another, faded by `fill`
|
||||||
|
let adjusted = |image: &Item<Raster<CPU>>, adjustments: &[Adjustment], fill: f32| -> Image<Color> {
|
||||||
|
let data = (image.element().data.iter())
|
||||||
|
.map(|&color| adjustments.iter().fold(color, |color, adjustment| adjust_color(adjustment, color)))
|
||||||
|
.map(|color| color.with_alpha(color.a() * fill))
|
||||||
|
.collect();
|
||||||
|
Image { width: 20, height: 20, data }
|
||||||
|
};
|
||||||
|
|
||||||
|
// A Levels stack bending alpha
|
||||||
let adjustments = [uneven_levels(2.2), Adjustment::Invert];
|
let adjustments = [uneven_levels(2.2), Adjustment::Invert];
|
||||||
let operations: Vec<_> = adjustments.iter().cloned().map(EffectOperation::Adjustment).collect();
|
let operations: Vec<_> = adjustments.iter().cloned().map(EffectOperation::Adjustment).collect();
|
||||||
|
let color = |x: u32, y: u32| Color::from_rgbaf32_unchecked(x as f32 / 20., y as f32 / 20., 0.5, (x + y) as f32 / 40.);
|
||||||
// A Levels stack bending alpha, with fine steps 8 bits can't hold
|
|
||||||
let color = |x: u32, y: u32| Color::from_rgbaf32_unchecked(x as f32 / 1000., y as f32 / 20., 0.5, (x + y) as f32 / 40.);
|
|
||||||
let image = image_of_pixels(DVec2::ONE, color, &operations);
|
let image = image_of_pixels(DVec2::ONE, color, &operations);
|
||||||
let expected = adjusted_raster(image.element(), &adjustments);
|
let read_back = block_on(executor.read_back(image.clone())).unwrap();
|
||||||
let read_back = block_on(executor.read_back(image)).unwrap();
|
assert_premultiplied_alike(read_back.element(), &adjusted(&image, &adjustments, 1.));
|
||||||
assert_eq!(**read_back.element(), *expected.data());
|
|
||||||
assert!(read_back.attribute::<Effects>(ATTR_EFFECTS).is_none());
|
assert!(read_back.attribute::<Effects>(ATTR_EFFECTS).is_none());
|
||||||
|
|
||||||
// Inverting keeps alpha, so a partial fill fades the inverted colors, which stay beneath zero alpha
|
// Inverting keeps alpha, so a partial fill fades the inverted colors, and fully transparent pixels stay so
|
||||||
let color = |x: u32, y: u32| Color::from_rgbaf32_unchecked(x as f32 / 20., 0.25, 1., if y < 10 { 0. } else { 0.8 });
|
let color = |x: u32, y: u32| Color::from_rgbaf32_unchecked(x as f32 / 20., 0.25, 1., if y < 10 { 0. } else { 0.8 });
|
||||||
let mut image = image_of_pixels(DVec2::ONE, color, &[EffectOperation::Adjustment(Adjustment::Invert)]);
|
let mut image = image_of_pixels(DVec2::ONE, color, &[EffectOperation::Adjustment(Adjustment::Invert)]);
|
||||||
image.set_attribute(ATTR_OPACITY_FILL, 0.5);
|
image.set_attribute(ATTR_OPACITY_FILL, 0.5);
|
||||||
let inverted = adjusted_raster(image.element(), &[Adjustment::Invert]);
|
let read_back = block_on(executor.read_back(image.clone())).unwrap();
|
||||||
let read_back = block_on(executor.read_back(image)).unwrap();
|
|
||||||
assert!(read_back.attribute::<f64>(ATTR_OPACITY_FILL).is_none());
|
assert!(read_back.attribute::<f64>(ATTR_OPACITY_FILL).is_none());
|
||||||
for (index, (color, inverted)) in read_back.element().data.iter().zip(&inverted.data().data).enumerate() {
|
assert_premultiplied_alike(read_back.element(), &adjusted(&image, &[Adjustment::Invert], 0.5));
|
||||||
assert_eq!(*color, inverted.with_alpha(inverted.a() * 0.5), "pixel {index}");
|
|
||||||
assert!(color.r() + color.g() + color.b() > 0., "pixel {index} lost its color");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Effects past adjustments need a render
|
|
||||||
let outlined = image_of_pixels(DVec2::ONE, |_, _| Color::WHITE, &[outline(2.)]);
|
|
||||||
let effects = outlined.attribute::<Effects>(ATTR_EFFECTS).unwrap();
|
|
||||||
assert!(adjusted_without_render(&outlined, effects, 1.).is_none());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -528,9 +503,6 @@ mod tests {
|
|||||||
Some((executor, ReadbackLimits::of(executor)))
|
Some((executor, ReadbackLimits::of(executor)))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// How many 8-bit levels the CPU's adjustments and the render of them may part by, which is the render's rounding to its 8-bit texture.
|
|
||||||
const ADJUSTMENT_TOLERANCE: u8 = 1;
|
|
||||||
|
|
||||||
/// Asserts that two images have the same size and 8-bit pixels within `tolerance` levels of each other.
|
/// Asserts that two images have the same size and 8-bit pixels within `tolerance` levels of each other.
|
||||||
fn assert_alike(actual: &Image<Color>, expected: &Image<Color>, tolerance: u8) {
|
fn assert_alike(actual: &Image<Color>, expected: &Image<Color>, tolerance: u8) {
|
||||||
assert_eq!((actual.width, actual.height), (expected.width, expected.height));
|
assert_eq!((actual.width, actual.height), (expected.width, expected.height));
|
||||||
@@ -544,6 +516,20 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Asserts that two images have the same size and premultiplied gamma-encoded channels within the 8-bit rounding of a render's premultiplied texture and its straight download.
|
||||||
|
fn assert_premultiplied_alike(actual: &Image<Color>, expected: &Image<Color>) {
|
||||||
|
assert_eq!((actual.width, actual.height), (expected.width, expected.height));
|
||||||
|
let premultiplied = |color: Color| {
|
||||||
|
let [red, green, blue, alpha] = color.to_gamma_srgb_channels();
|
||||||
|
[red * alpha, green * alpha, blue * alpha, alpha].map(|channel| channel * 255.)
|
||||||
|
};
|
||||||
|
for (index, (actual, expected)) in actual.data.iter().zip(&expected.data).enumerate() {
|
||||||
|
let (shown, wanted) = (premultiplied(*actual), premultiplied(*expected));
|
||||||
|
let difference = (0..4).map(|channel| (shown[channel] - wanted[channel]).abs()).fold(0., f32::max);
|
||||||
|
assert!(difference <= 1.5, "pixel {index} is {actual:?} rather than {expected:?}, {difference} levels apart");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn tiles_small_enough_for_the_download_buffer_match_one_render() {
|
fn tiles_small_enough_for_the_download_buffer_match_one_render() {
|
||||||
let Some((executor, limits)) = executor_and_limits() else { return };
|
let Some((executor, limits)) = executor_and_limits() else { return };
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ fn vertex(@builtin(vertex_index) index: u32) -> @builtin(position) vec4<f32> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// The straight color of the source pixel under `position`, in linear light if the source holds that, or else gamma-encoded,
|
// The straight color of the source pixel under `position`, in linear light if the source holds that, or else gamma-encoded,
|
||||||
// with a fully transparent pixel's color left at 0, matching `straight_linear_color`
|
// with a fully transparent pixel's color left at 0, matching `adjust_premultiplied`
|
||||||
fn source_color(position: vec4<f32>) -> vec4<f32> {
|
fn source_color(position: vec4<f32>) -> vec4<f32> {
|
||||||
let pixel = textureLoad(source, vec2<i32>(position.xy), 0);
|
let pixel = textureLoad(source, vec2<i32>(position.xy), 0);
|
||||||
if pixel.a <= 0. {
|
if pixel.a <= 0. {
|
||||||
|
|||||||
@@ -12,8 +12,7 @@ use graphic_types::effects::{EffectCapture, GRADIENT_GLOW_FADE, GRADIENT_TABLE_S
|
|||||||
use graphic_types::masks::{mask_feather_sigma, masked_radius_blur_levels};
|
use graphic_types::masks::{mask_feather_sigma, masked_radius_blur_levels};
|
||||||
use graphic_types::resampling::{DisplacementField, EffectFrame, FrameWarp, HalftoneScreen, RadialBlur, WarpTessellation, warp_frame, warp_of};
|
use graphic_types::resampling::{DisplacementField, EffectFrame, FrameWarp, HalftoneScreen, RadialBlur, WarpTessellation, warp_frame, warp_of};
|
||||||
use graphic_types::{Adjustment, BevelDirection, BevelStyle, BevelTechnique, EffectOperation, Effects, GlowSource, GlowTechnique};
|
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::effect_planning::{BlurKernel, MAX_DIRECT_BOX_RADIUS, MotionBlurShear, NEGLIGIBLE_LENGTH, chamfer_passes};
|
||||||
use raster_kernels::resample_kernels::MotionBlurShear;
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::sync::{Mutex, PoisonError};
|
use std::sync::{Mutex, PoisonError};
|
||||||
use vello_gpu::kurbo::Affine;
|
use vello_gpu::kurbo::Affine;
|
||||||
@@ -45,10 +44,10 @@ const CONTOUR_SAMPLES: u32 = 256;
|
|||||||
/// How many samples of a glow's or outline's gradient the shaders read.
|
/// How many samples of a glow's or outline's gradient the shaders read.
|
||||||
const GRADIENT_SAMPLES: u32 = GRADIENT_TABLE_SIZE as u32;
|
const GRADIENT_SAMPLES: u32 = GRADIENT_TABLE_SIZE as u32;
|
||||||
|
|
||||||
/// How many taps the shader's parameters hold, enough for a blur kernel of [`raster_kernels::effect_kernels::MAX_KERNEL_REACH`] texels to each side in pairs, and few enough that a pass reading them all stays quick.
|
/// How many taps the shader's parameters hold, enough for a blur kernel of [`raster_kernels::effect_planning::MAX_KERNEL_REACH`] texels to each side in pairs, and few enough that a pass reading them all stays quick.
|
||||||
/// A filter kernel with more takes a pass for each part of them.
|
/// A filter kernel with more takes a pass for each part of them.
|
||||||
const PARAMETER_TAPS: usize = 81;
|
const PARAMETER_TAPS: usize = 81;
|
||||||
const _: () = assert!(PARAMETER_TAPS > 2 * raster_kernels::effect_kernels::MAX_KERNEL_REACH.div_ceil(2));
|
const _: () = assert!(PARAMETER_TAPS > 2 * raster_kernels::effect_planning::MAX_KERNEL_REACH.div_ceil(2));
|
||||||
|
|
||||||
/// How many renders a pooled texture survives unused before it is freed.
|
/// How many renders a pooled texture survives unused before it is freed.
|
||||||
const UNUSED_TEXTURE_RENDER_LIMIT: u64 = 3;
|
const UNUSED_TEXTURE_RENDER_LIMIT: u64 = 3;
|
||||||
@@ -622,6 +621,9 @@ impl EffectPasses {
|
|||||||
},
|
},
|
||||||
_ => None,
|
_ => None,
|
||||||
};
|
};
|
||||||
|
if let Some(paint) = drawn_paint {
|
||||||
|
capture_plane(&mut recorder, EffectCapture::DRAWN_PAINT_PLANE, paint, true);
|
||||||
|
}
|
||||||
|
|
||||||
let (outside, inside) = outline_extents(weight * length_scale, align);
|
let (outside, inside) = outline_extents(weight * length_scale, align);
|
||||||
let contour_span = matches!(outline_fill, OutlineFill::ContourGradient(_))
|
let contour_span = matches!(outline_fill, OutlineFill::ContourGradient(_))
|
||||||
@@ -792,6 +794,7 @@ impl EffectPasses {
|
|||||||
}
|
}
|
||||||
EffectOperation::PaintOverlay { blend_mode, opacity, .. } => {
|
EffectOperation::PaintOverlay { blend_mode, opacity, .. } => {
|
||||||
let Some(paint) = paints.next() else { continue };
|
let Some(paint) = paints.next() else { continue };
|
||||||
|
capture_plane(&mut recorder, EffectCapture::DRAWN_PAINT_PLANE, paint, true);
|
||||||
let painted = recorder.scale(paint, (opacity / 100.) as f32);
|
let painted = recorder.scale(paint, (opacity / 100.) as f32);
|
||||||
recorder.place_within(layered.then_some((&mut pieces, piece(0))), content, &mut full, &mut filled, painted, None, blend_mode);
|
recorder.place_within(layered.then_some((&mut pieces, piece(0))), content, &mut full, &mut filled, painted, None, blend_mode);
|
||||||
}
|
}
|
||||||
@@ -1443,11 +1446,11 @@ fn changes_nothing(operation: &EffectOperation, length_scale: f64) -> bool {
|
|||||||
/// Which pixels seed a distance pass, and how far from each one its edge lies.
|
/// Which pixels seed a distance pass, and how far from each one its edge lies.
|
||||||
#[derive(Clone, Copy)]
|
#[derive(Clone, Copy)]
|
||||||
enum Seeds {
|
enum Seeds {
|
||||||
/// The covered pixels, with their antialiased edges placed by coverage, matching `distances_to_silhouette`.
|
/// The covered pixels, with their antialiased edges placed by coverage.
|
||||||
Covered,
|
Covered,
|
||||||
/// The pixels of a distance texture lying up to 3 past a grow of so many pixels, matching `distances_through_seeds` of how far short of the grown edge they lie.
|
/// The pixels of a distance texture lying up to 3 past a grow of so many pixels, with how far short of the grown edge they lie as head starts.
|
||||||
PastGrow { grow: f64 },
|
PastGrow { grow: f64 },
|
||||||
/// Every pixel, with its value as a head start, matching `distances_through_seeds` of values that are all finite.
|
/// Every pixel, with its value as a head start.
|
||||||
Weighted,
|
Weighted,
|
||||||
/// Like `Covered`, but measured in straight lines rather than by `chamfer_length`.
|
/// Like `Covered`, but measured in straight lines rather than by `chamfer_length`.
|
||||||
CoveredStraight,
|
CoveredStraight,
|
||||||
@@ -1539,7 +1542,7 @@ impl PassRecorder<'_> {
|
|||||||
self.run(entry_point, COVERAGE_FORMAT, self.size, content, None, None, parameters)
|
self.run(entry_point, COVERAGE_FORMAT, self.size, content, None, None, parameters)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The strength from 0 to 1 of a shadow or glow cast from a `silhouette`'s coverage, shaped for PSD interop, matching the CPU's `cast`:
|
/// The strength from 0 to 1 of a shadow or glow cast from a `silhouette`'s coverage, shaped for PSD interop:
|
||||||
/// grown by the `spread` percentage of its `size` (in document pixels, `length_scale` pixels each), softened over the rest by the `technique`, then strengthened by its `range` percentage and reshaped by its `contour`.
|
/// grown by the `spread` percentage of its `size` (in document pixels, `length_scale` pixels each), softened over the rest by the `technique`, then strengthened by its `range` percentage and reshaped by its `contour`.
|
||||||
#[expect(clippy::too_many_arguments)]
|
#[expect(clippy::too_many_arguments)]
|
||||||
fn cast(&mut self, silhouette: wgpu::Texture, size: f64, spread: f64, technique: GlowTechnique, range: f64, contour: &TransferCurve, length_scale: f64) -> wgpu::Texture {
|
fn cast(&mut self, silhouette: wgpu::Texture, size: f64, spread: f64, technique: GlowTechnique, range: f64, contour: &TransferCurve, length_scale: f64) -> wgpu::Texture {
|
||||||
@@ -1586,7 +1589,7 @@ impl PassRecorder<'_> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The `silhouette` grown outward by `distance` pixels, matching the CPU's `grown`.
|
/// The `silhouette` grown outward by `distance` pixels.
|
||||||
fn grown(&mut self, silhouette: wgpu::Texture, distance: f64) -> wgpu::Texture {
|
fn grown(&mut self, silhouette: wgpu::Texture, distance: f64) -> wgpu::Texture {
|
||||||
let to_silhouette = self.distances(&silhouette, distance + 1., Seeds::Covered);
|
let to_silhouette = self.distances(&silhouette, distance + 1., Seeds::Covered);
|
||||||
self.textures.release(silhouette);
|
self.textures.release(silhouette);
|
||||||
@@ -1611,7 +1614,7 @@ impl PassRecorder<'_> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The `strength` strengthened by the `range` percentage and reshaped by the `contour`, matching the CPU's `shaped`, or `None` where they leave it as it is.
|
/// The `strength` strengthened by the `range` percentage and reshaped by the `contour`, or `None` where they leave it as it is.
|
||||||
fn shaped(&mut self, strength: &wgpu::Texture, range: f64, contour: &TransferCurve) -> Option<wgpu::Texture> {
|
fn shaped(&mut self, strength: &wgpu::Texture, range: f64, contour: &TransferCurve) -> Option<wgpu::Texture> {
|
||||||
if range >= 100. && contour.is_identity() {
|
if range >= 100. && contour.is_identity() {
|
||||||
return None;
|
return None;
|
||||||
@@ -1626,7 +1629,6 @@ impl PassRecorder<'_> {
|
|||||||
|
|
||||||
/// The premultiplied color a glow filled with the gradient in `paint` paints at each pixel, from its `strength` after range and contour and its `raw` strength before them.
|
/// The premultiplied color a glow filled with the gradient in `paint` paints at each pixel, from its `strength` after range and contour and its `raw` strength before them.
|
||||||
/// An outer glow `fades` out with its raw strength (the `content`), and a `grain` roughens it, kept within the reach that an inner glow's distances (then the `content`) give.
|
/// An outer glow `fades` out with its raw strength (the `content`), and a `grain` roughens it, kept within the reach that an inner glow's distances (then the `content`) give.
|
||||||
/// Matches the CPU's `glow_tint`.
|
|
||||||
fn gradient_glow_tint(&mut self, paint: &GlowFill, strength: &wgpu::Texture, content: &wgpu::Texture, fades: bool, grain: Option<&styles::GlowGrain>) -> Option<wgpu::Texture> {
|
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, 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: Vec<half::f16> = samples.into_iter().flatten().map(half::f16::from_f32).collect();
|
||||||
@@ -1641,7 +1643,7 @@ impl PassRecorder<'_> {
|
|||||||
Some(self.run("gradient_glow_tint", WORKING_FORMAT, self.size, strength, Some(&samples), Some(content), parameters))
|
Some(self.run("gradient_glow_tint", WORKING_FORMAT, self.size, strength, Some(&samples), Some(content), parameters))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Each pixel's distance from the `seeds` in `seed_values`, matching the CPU's distance passes, or far past `reach` pixels.
|
/// Each pixel's distance from the `seeds` in `seed_values`, or far past `reach` pixels.
|
||||||
/// Jump flooding finds them in a pass for each halving of a step that starts past `reach`, then two more halvings and those of [`chamfer_passes`] along the chamfer steps. O(width × height × log(reach)).
|
/// Jump flooding finds them in a pass for each halving of a step that starts past `reach`, then two more halvings and those of [`chamfer_passes`] along the chamfer steps. O(width × height × log(reach)).
|
||||||
fn distances(&mut self, seed_values: &wgpu::Texture, reach: f64, seeds: Seeds) -> wgpu::Texture {
|
fn distances(&mut self, seed_values: &wgpu::Texture, reach: f64, seeds: Seeds) -> wgpu::Texture {
|
||||||
let (mode, grow, straight) = match seeds {
|
let (mode, grow, straight) = match seeds {
|
||||||
@@ -1864,7 +1866,7 @@ impl PassRecorder<'_> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// A bevel's height over the `style`'s slopes `size` pixels wide, shaped by the `technique`, from -0.5 at their foot to 0.5 at their top, with how many pixels they rise.
|
/// A bevel's height over the `style`'s slopes `size` pixels wide, shaped by the `technique`, from -0.5 at their foot to 0.5 at their top, with how many pixels they rise.
|
||||||
/// It's cast from the `content`'s silhouette and centered on the edge, where half floats are finest. Matches the CPU's `bevel_height`.
|
/// It's cast from the `content`'s silhouette and centered on the edge, where half floats are finest.
|
||||||
fn bevel_height(&mut self, content: &wgpu::Texture, style: BevelStyle, technique: BevelTechnique, size: f64) -> (wgpu::Texture, f64) {
|
fn bevel_height(&mut self, content: &wgpu::Texture, style: BevelStyle, technique: BevelTechnique, size: f64) -> (wgpu::Texture, f64) {
|
||||||
let span = match style {
|
let span = match style {
|
||||||
BevelStyle::InnerBevel | BevelStyle::OuterBevel => size,
|
BevelStyle::InnerBevel | BevelStyle::OuterBevel => size,
|
||||||
@@ -2107,7 +2109,7 @@ mod tests {
|
|||||||
let taps = kernel_taps(kernel, kernel.levels());
|
let taps = kernel_taps(kernel, kernel.levels());
|
||||||
|
|
||||||
assert!(
|
assert!(
|
||||||
taps.len() <= 1 + 2 * raster_kernels::effect_kernels::MAX_KERNEL_REACH.div_ceil(2),
|
taps.len() <= 1 + 2 * raster_kernels::effect_planning::MAX_KERNEL_REACH.div_ceil(2),
|
||||||
"{kernel:?} needs {} taps",
|
"{kernel:?} needs {} taps",
|
||||||
taps.len()
|
taps.len()
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -69,7 +69,7 @@ fn cast_inverse_silhouette(@builtin(position) position: vec4<f32>) -> @location(
|
|||||||
return vec4<f32>(1. - sample_source(position.xy * parameters.target_to_uv - parameters.offset).a);
|
return vec4<f32>(1. - sample_source(position.xy * parameters.target_to_uv - parameters.offset).a);
|
||||||
}
|
}
|
||||||
|
|
||||||
// The length of an offset along the shortest path of steps one texel straight, one diagonally, or a knight's move away, matching `chamfer_length`
|
// The length of an offset along the shortest path of steps one texel straight, one diagonally, or a knight's move away
|
||||||
fn chamfer_length(offset: vec2<f32>) -> f32 {
|
fn chamfer_length(offset: vec2<f32>) -> f32 {
|
||||||
let long = max(abs(offset.x), abs(offset.y));
|
let long = max(abs(offset.x), abs(offset.y));
|
||||||
let short = min(abs(offset.x), abs(offset.y));
|
let short = min(abs(offset.x), abs(offset.y));
|
||||||
@@ -81,8 +81,8 @@ fn chamfer_length(offset: vec2<f32>) -> f32 {
|
|||||||
|
|
||||||
// Jump flooding keeps each texel's offset from the nearest seed found so far (xy) and whether one is found (z). The `content` input holds the seeds' values.
|
// Jump flooding keeps each texel's offset from the nearest seed found so far (xy) and whether one is found (z). The `content` input holds the seeds' values.
|
||||||
// With `values.y` 0, the seeds are the covered texels and a distance runs to the edge within the seed, placed by its coverage.
|
// With `values.y` 0, the seeds are the covered texels and a distance runs to the edge within the seed, placed by its coverage.
|
||||||
// With `values.y` 1, the seeds are the texels past a grow of `values.z` texels and a distance runs to that grown edge, matching `distances_through_seeds`.
|
// With `values.y` 1, the seeds are the texels past a grow of `values.z` texels and a distance runs to that grown edge.
|
||||||
// With `values.y` 2, every texel seeds with its value as a head start, matching `distances_through_seeds` of values that are all finite.
|
// With `values.y` 2, every texel seeds with its value as a head start.
|
||||||
// With `amount` 1, offsets are measured in straight lines rather than by `chamfer_length`.
|
// With `amount` 1, offsets are measured in straight lines rather than by `chamfer_length`.
|
||||||
fn is_seed(value: f32) -> bool {
|
fn is_seed(value: f32) -> bool {
|
||||||
if parameters.values.y > 1.5 {
|
if parameters.values.y > 1.5 {
|
||||||
@@ -135,7 +135,7 @@ fn jump_flood_step(@builtin(position) position: vec4<f32>) -> @location(0) vec4<
|
|||||||
best_distance = seed_distance(pixel, best.xy);
|
best_distance = seed_distance(pixel, best.xy);
|
||||||
}
|
}
|
||||||
|
|
||||||
// By rows from the top, the order the CPU visits them in too
|
// By rows from the top
|
||||||
for (var neighbor_y = -radius; neighbor_y <= radius; neighbor_y++) {
|
for (var neighbor_y = -radius; neighbor_y <= radius; neighbor_y++) {
|
||||||
for (var neighbor_x = -radius; neighbor_x <= radius; neighbor_x++) {
|
for (var neighbor_x = -radius; neighbor_x <= radius; neighbor_x++) {
|
||||||
let long = max(abs(neighbor_x), abs(neighbor_y));
|
let long = max(abs(neighbor_x), abs(neighbor_y));
|
||||||
@@ -337,7 +337,7 @@ fn accumulate(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32>
|
|||||||
return tinted + beneath * (1. - tinted.a);
|
return tinted + beneath * (1. - tinted.a);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Places a tinted part of an interior piece within the full-strength `content`'s share of each pixel of the image (`source`), matching the CPU's `composite_in_share`.
|
// Places a tinted part of an interior piece within the full-strength `content`'s share of each pixel of the image (`source`).
|
||||||
// It mixes with the image's own colors by the blend mode numbered `values.x` in gamma, and with `values.y` 1, `secondary` is already tinted.
|
// It mixes with the image's own colors by the blend mode numbered `values.x` in gamma, and with `values.y` 1, `secondary` is already tinted.
|
||||||
// `values.z` picks the part: 0 the whole piece, 1 the part blending with the content, or 2 that part for a piece whose part over the content takes what its fill lets show through, at opacity `amount`.
|
// `values.z` picks the part: 0 the whole piece, 1 the part blending with the content, or 2 that part for a piece whose part over the content takes what its fill lets show through, at opacity `amount`.
|
||||||
@fragment
|
@fragment
|
||||||
@@ -405,7 +405,7 @@ fn knock_out_by_layer(@builtin(position) position: vec4<f32>) -> @location(0) ve
|
|||||||
}
|
}
|
||||||
|
|
||||||
// A chiseled bevel's height from -0.5 at its foot `values.w` texels outside the edge to 0.5 at its top as far inside, from the distances in from the edge (`source`) and out from it (`secondary`).
|
// A chiseled bevel's height from -0.5 at its foot `values.w` texels outside the edge to 0.5 at its top as far inside, from the distances in from the edge (`source`) and out from it (`secondary`).
|
||||||
// It's kept from `values.x` to `values.y` texels across the edge, and with `values.z` 1 (a soft chisel, given distances through its slope-limited matte) measured by their difference alone. Matches the CPU's `bevel_height`.
|
// It's kept from `values.x` to `values.y` texels across the edge, and with `values.z` 1 (a soft chisel, given distances through its slope-limited matte) measured by their difference alone.
|
||||||
@fragment
|
@fragment
|
||||||
fn chisel_height(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
fn chisel_height(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||||
let pixel = vec2<i32>(position.xy);
|
let pixel = vec2<i32>(position.xy);
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
//! The GPU passes of the filter effects, matching the CPU's `filter_kernels`.
|
//! The GPU passes of the filter effects.
|
||||||
|
|
||||||
use super::{PARAMETER_TAPS, Parameters, PassRecorder, SUMS_FORMAT, WORKING_FORMAT};
|
use super::{PARAMETER_TAPS, Parameters, PassRecorder, SUMS_FORMAT, WORKING_FORMAT};
|
||||||
use glam::{DAffine2, DMat2, DVec2, UVec2};
|
use glam::{DAffine2, DMat2, DVec2, UVec2};
|
||||||
@@ -8,8 +8,7 @@ use graphic_types::filters::{
|
|||||||
};
|
};
|
||||||
use graphic_types::resampling::EffectFrame;
|
use graphic_types::resampling::EffectFrame;
|
||||||
use graphic_types::{EffectOperation, MinimumMaximumMode};
|
use graphic_types::{EffectOperation, MinimumMaximumMode};
|
||||||
use raster_kernels::effect_kernels::BlurKernel;
|
use raster_kernels::effect_planning::{BlurKernel, pixel_fill_shifts};
|
||||||
use raster_kernels::filter_kernels::pixel_fill_shifts;
|
|
||||||
|
|
||||||
/// The most texels a neighborhood's first pass reads each way, beyond which each further pass at most doubles its reach by reading two texels.
|
/// The most texels a neighborhood's first pass reads each way, beyond which each further pass at most doubles its reach by reading two texels.
|
||||||
const MAX_FIRST_NEIGHBORHOOD_PASS_RADIUS: u32 = 8;
|
const MAX_FIRST_NEIGHBORHOOD_PASS_RADIUS: u32 = 8;
|
||||||
@@ -123,7 +122,7 @@ impl PassRecorder<'_> {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// A filter sharpening the coverage fades the fill's result by the share of the full-strength coverage each texel's fill left, matching the CPU's `faded_by_shares`
|
// A filter sharpening the coverage fades the fill's result by the share of the full-strength coverage each texel's fill left
|
||||||
let unfiltered = full.as_ref().unwrap_or(content);
|
let unfiltered = full.as_ref().unwrap_or(content);
|
||||||
let shares = filled
|
let shares = filled
|
||||||
.as_ref()
|
.as_ref()
|
||||||
@@ -237,7 +236,7 @@ impl PassRecorder<'_> {
|
|||||||
result.unwrap_or_else(|| self.scale(source, 1.))
|
result.unwrap_or_else(|| self.scale(source, 1.))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The opaque weighted sum `convolution` describes of the image's colors, those visible judged by the `full`-strength content, matching the CPU's `convolve` before the image's coverage returns.
|
/// The opaque weighted sum `convolution` describes of the image's colors, those visible judged by the `full`-strength content, before the image's coverage returns.
|
||||||
fn convolve(&mut self, image: &wgpu::Texture, full: &wgpu::Texture, convolution: &Convolution, lengths_to_pixels: DMat2) -> wgpu::Texture {
|
fn convolve(&mut self, image: &wgpu::Texture, full: &wgpu::Texture, convolution: &Convolution, lengths_to_pixels: DMat2) -> wgpu::Texture {
|
||||||
let colors = self.surrounded_colors(image, full, convolution.surroundings, convolution.reach(), lengths_to_pixels);
|
let colors = self.surrounded_colors(image, full, convolution.surroundings, convolution.reach(), lengths_to_pixels);
|
||||||
let taps = convolution_taps(convolution, lengths_to_pixels);
|
let taps = convolution_taps(convolution, lengths_to_pixels);
|
||||||
@@ -254,7 +253,7 @@ impl PassRecorder<'_> {
|
|||||||
convolved
|
convolved
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The opaque colors a filter reading the image within `reach` document pixels sees, as its `surroundings` describe, those visible judged by the `full`-strength content, matching the CPU's `SurroundedColors`.
|
/// The opaque colors a filter reading the image within `reach` document pixels sees, as its `surroundings` describe, those visible judged by the `full`-strength content.
|
||||||
fn surrounded_colors(&mut self, image: &wgpu::Texture, full: &wgpu::Texture, surroundings: Surroundings, reach: f64, lengths_to_pixels: DMat2) -> wgpu::Texture {
|
fn surrounded_colors(&mut self, image: &wgpu::Texture, full: &wgpu::Texture, surroundings: Surroundings, reach: f64, lengths_to_pixels: DMat2) -> wgpu::Texture {
|
||||||
match surroundings {
|
match surroundings {
|
||||||
Surroundings::Continued => self.visible_colors(image, full, reach, lengths_to_pixels),
|
Surroundings::Continued => self.visible_colors(image, full, reach, lengths_to_pixels),
|
||||||
@@ -268,7 +267,7 @@ impl PassRecorder<'_> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Filtered opaque `colors` given the image's coverage, as their `surroundings` describe, matching the CPU's `uncovered`, in place of the colors.
|
/// Filtered opaque `colors` given the image's coverage, as their `surroundings` describe, in place of the colors.
|
||||||
fn uncover(&mut self, colors: wgpu::Texture, image: &wgpu::Texture, surroundings: Surroundings) -> wgpu::Texture {
|
fn uncover(&mut self, colors: wgpu::Texture, image: &wgpu::Texture, surroundings: Surroundings) -> wgpu::Texture {
|
||||||
let gray = match surroundings {
|
let gray = match surroundings {
|
||||||
Surroundings::Continued => -1.,
|
Surroundings::Continued => -1.,
|
||||||
@@ -303,13 +302,13 @@ impl PassRecorder<'_> {
|
|||||||
uncovered
|
uncovered
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The image's straight colors as the filters read them, matching the CPU's `visible_colors`, with texels faint in the `full`-strength content taking the nearest visible color within `reach` document pixels.
|
/// The image's straight colors as the filters read them, with texels faint in the `full`-strength content taking the nearest visible color within `reach` document pixels.
|
||||||
fn visible_colors(&mut self, image: &wgpu::Texture, full: &wgpu::Texture, reach: f64, lengths_to_pixels: DMat2) -> wgpu::Texture {
|
fn visible_colors(&mut self, image: &wgpu::Texture, full: &wgpu::Texture, reach: f64, lengths_to_pixels: DMat2) -> wgpu::Texture {
|
||||||
let shifts: Vec<[f32; 4]> = pixel_fill_shifts(reach, lengths_to_pixels).into_iter().map(|[x, y]| [x as f32, y as f32, 0., 0.]).collect();
|
let shifts: Vec<[f32; 4]> = pixel_fill_shifts(reach, lengths_to_pixels).into_iter().map(|[x, y]| [x as f32, y as f32, 0., 0.]).collect();
|
||||||
self.run_in_chunks("visible_colors", WORKING_FORMAT, image, Some(full), &shifts, [VISIBLE_ALPHA, 0.])
|
self.run_in_chunks("visible_colors", WORKING_FORMAT, image, Some(full), &shifts, [VISIBLE_ALPHA, 0.])
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The opaque result of Find Edges on the image matted over white, before its coverage returns, matching the CPU's `find_edges`.
|
/// The opaque result of Find Edges on the image matted over white, before its coverage returns.
|
||||||
fn find_edges(&mut self, image: &wgpu::Texture, lengths_to_pixels: DMat2) -> wgpu::Texture {
|
fn find_edges(&mut self, image: &wgpu::Texture, lengths_to_pixels: DMat2) -> wgpu::Texture {
|
||||||
let colors = self.surrounded_colors(image, image, Surroundings::Matted(1.), 1., lengths_to_pixels);
|
let colors = self.surrounded_colors(image, image, Surroundings::Matted(1.), 1., lengths_to_pixels);
|
||||||
let edges = self.run_in_chunks("find_edges", WORKING_FORMAT, &colors, None, &sobel_taps(lengths_to_pixels), [0., 1.]);
|
let edges = self.run_in_chunks("find_edges", WORKING_FORMAT, &colors, None, &sobel_taps(lengths_to_pixels), [0., 1.]);
|
||||||
@@ -317,7 +316,7 @@ impl PassRecorder<'_> {
|
|||||||
edges
|
edges
|
||||||
}
|
}
|
||||||
|
|
||||||
/// For PSD interop, the share of its change Edges Only makes in each channel of each texel, the edge gain of the channel's Sobel gradient there, matching the CPU's `edge_gains`.
|
/// For PSD interop, the share of its change Edges Only makes in each channel of each texel, the edge gain of the channel's Sobel gradient there.
|
||||||
/// The colors are read continued past those visible in the `full`-strength content, and the coverage with none beyond it.
|
/// The colors are read continued past those visible in the `full`-strength content, and the coverage with none beyond it.
|
||||||
fn edge_gains(&mut self, image: &wgpu::Texture, full: &wgpu::Texture, lengths_to_pixels: DMat2) -> wgpu::Texture {
|
fn edge_gains(&mut self, image: &wgpu::Texture, full: &wgpu::Texture, lengths_to_pixels: DMat2) -> wgpu::Texture {
|
||||||
// A faint texel the gradient reads finds its nearest visible color within the square of a pixel around it
|
// A faint texel the gradient reads finds its nearest visible color within the square of a pixel around it
|
||||||
@@ -339,7 +338,7 @@ impl PassRecorder<'_> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The image with each straight color and its coverage sharpened against the `blur` around it, by the amount and threshold fractions in `sharpening`,
|
/// The image with each straight color and its coverage sharpened against the `blur` around it, by the amount and threshold fractions in `sharpening`,
|
||||||
/// or with none, a high pass of its colors, those visible judged by the `full`-strength content, matching the CPU's `unsharp_mask`.
|
/// or with none, a high pass of its colors, those visible judged by the `full`-strength content.
|
||||||
fn unsharp_mask(&mut self, image: &wgpu::Texture, full: &wgpu::Texture, blur: UnsharpBlur, sharpening: Option<[f32; 2]>, lengths_to_pixels: DMat2) -> wgpu::Texture {
|
fn unsharp_mask(&mut self, image: &wgpu::Texture, full: &wgpu::Texture, blur: UnsharpBlur, sharpening: Option<[f32; 2]>, lengths_to_pixels: DMat2) -> wgpu::Texture {
|
||||||
let visibility = Parameters {
|
let visibility = Parameters {
|
||||||
values: [0., 0., VISIBLE_ALPHA, 0.],
|
values: [0., 0., VISIBLE_ALPHA, 0.],
|
||||||
@@ -384,7 +383,7 @@ impl PassRecorder<'_> {
|
|||||||
sharpened
|
sharpened
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The average in every channel of each texel's four nearest neighbors ([`SHARPEN_NEIGHBORS`]), with none beyond the edges, matching the CPU's `neighbors_average`.
|
/// The average in every channel of each texel's four nearest neighbors ([`SHARPEN_NEIGHBORS`]), with none beyond the edges.
|
||||||
fn neighbors_average(&mut self, texture: &wgpu::Texture, lengths_to_pixels: DMat2) -> wgpu::Texture {
|
fn neighbors_average(&mut self, texture: &wgpu::Texture, lengths_to_pixels: DMat2) -> wgpu::Texture {
|
||||||
let taps = SHARPEN_NEIGHBORS.map(|shift| {
|
let taps = SHARPEN_NEIGHBORS.map(|shift| {
|
||||||
let shift = lengths_to_pixels * shift;
|
let shift = lengths_to_pixels * shift;
|
||||||
@@ -394,7 +393,7 @@ impl PassRecorder<'_> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The image with each texel's color the lightest (or with `maximum` false, the darkest) in the square of `radius` document pixels around it,
|
/// The image with each texel's color the lightest (or with `maximum` false, the darkest) in the square of `radius` document pixels around it,
|
||||||
/// and its coverage the opposite extreme, matching the CPU's `neighborhood_extreme`. O(width × height × log radius), with the radius along each axis at most the texture's size along it.
|
/// and its coverage the opposite extreme. O(width × height × log radius), with the radius along each axis at most the texture's size along it.
|
||||||
fn neighborhood_extreme(&mut self, image: &wgpu::Texture, radius: f64, maximum: bool, lengths_to_pixels: DMat2) -> wgpu::Texture {
|
fn neighborhood_extreme(&mut self, image: &wgpu::Texture, radius: f64, maximum: bool, lengths_to_pixels: DMat2) -> wgpu::Texture {
|
||||||
let spans = spans_along_axes(lengths_to_pixels);
|
let spans = spans_along_axes(lengths_to_pixels);
|
||||||
let ([near_x, far_x], fraction) = neighborhood_radii(radius, spans.x);
|
let ([near_x, far_x], fraction) = neighborhood_radii(radius, spans.x);
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ fn visible_color_at(pixel: vec2<i32>) -> vec4<f32> {
|
|||||||
return select(vec4<f32>(0.), vec4<f32>(color.rgb / color.a, 1.), visible);
|
return select(vec4<f32>(0.), vec4<f32>(color.rgb / color.a, 1.), visible);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Each texel's straight color as the filters read it, matching the CPU's `visible_colors`: its own if it's visible, otherwise that of the first visible texel `taps[i].xy` texels away,
|
// Each texel's straight color as the filters read it: its own if it's visible, otherwise that of the first visible texel `taps[i].xy` texels away,
|
||||||
// or failing that its own if it has any coverage. A pass after others (`values.z` 1) keeps the color they found (`content`), and only the last (`values.w` 1) falls back to the texel's own.
|
// or failing that its own if it has any coverage. A pass after others (`values.z` 1) keeps the color they found (`content`), and only the last (`values.w` 1) falls back to the texel's own.
|
||||||
@fragment
|
@fragment
|
||||||
fn visible_colors(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
fn visible_colors(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||||
@@ -58,7 +58,7 @@ fn color_at(pixel: vec2<i32>) -> vec4<f32> {
|
|||||||
return textureLoad(source, pixel, 0);
|
return textureLoad(source, pixel, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
// The colors at a position in texels from the first texel's center, interpolated between those of the four texels around it with a color, matching the CPU's `BilinearTap`
|
// The colors at a position in texels from the first texel's center, interpolated between those of the four texels around it with a color
|
||||||
fn color_between(position: vec2<f32>) -> vec3<f32> {
|
fn color_between(position: vec2<f32>) -> vec3<f32> {
|
||||||
let whole = floor(position);
|
let whole = floor(position);
|
||||||
let fraction = position - whole;
|
let fraction = position - whole;
|
||||||
@@ -71,7 +71,7 @@ fn color_between(position: vec2<f32>) -> vec3<f32> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// The weighted sum of the colors (`source`) read `taps[i].xy` texels away, each weighted by `taps[i].z`, raised by the offset `values.x` and clamped,
|
// The weighted sum of the colors (`source`) read `taps[i].xy` texels away, each weighted by `taps[i].z`, raised by the offset `values.x` and clamped,
|
||||||
// matching the CPU's `convolve` before the content's coverage returns. A pass after others (`values.z` 1) adds to their sum (`content`), and only the last (`values.w` 1) clamps it.
|
// before the content's coverage returns. A pass after others (`values.z` 1) adds to their sum (`content`), and only the last (`values.w` 1) clamps it.
|
||||||
@fragment
|
@fragment
|
||||||
fn convolve_taps(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
fn convolve_taps(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||||
let pixel = vec2<i32>(position.xy);
|
let pixel = vec2<i32>(position.xy);
|
||||||
@@ -92,7 +92,7 @@ fn convolve_taps(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f3
|
|||||||
return vec4<f32>(sum, 1.);
|
return vec4<f32>(sum, 1.);
|
||||||
}
|
}
|
||||||
|
|
||||||
// For PSD interop, each channel of the colors matted over white (`source`) darkened by the length of its Sobel gradient, matching the CPU's `find_edges`.
|
// For PSD interop, each channel of the colors matted over white (`source`) darkened by the length of its Sobel gradient.
|
||||||
// Each tap `taps[i].xy` texels away weighs `taps[i].z` across and `taps[i].w` down.
|
// Each tap `taps[i].xy` texels away weighs `taps[i].z` across and `taps[i].w` down.
|
||||||
@fragment
|
@fragment
|
||||||
fn find_edges(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
fn find_edges(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||||
@@ -109,7 +109,7 @@ fn find_edges(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32>
|
|||||||
return vec4<f32>(clamp(1. - sqrt(across * across + down * down), vec3<f32>(0.), vec3<f32>(1.)), 1.);
|
return vec4<f32>(clamp(1. - sqrt(across * across + down * down), vec3<f32>(0.), vec3<f32>(1.)), 1.);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Filtered opaque colors (`source`) given the `content` texel's coverage, matching the CPU's `uncovered`: as straight colors, or with `values.z` at or above 0, lifted off the gray of that level they were filtered over
|
// Filtered opaque colors (`source`) given the `content` texel's coverage: as straight colors, or with `values.z` at or above 0, lifted off the gray of that level they were filtered over
|
||||||
@fragment
|
@fragment
|
||||||
fn uncover(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
fn uncover(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||||
let pixel = vec2<i32>(position.xy);
|
let pixel = vec2<i32>(position.xy);
|
||||||
@@ -123,7 +123,7 @@ fn uncover(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
|||||||
return vec4<f32>(clamp(colors - gray * (1. - alpha), vec3<f32>(0.), vec3<f32>(alpha)), alpha);
|
return vec4<f32>(clamp(colors - gray * (1. - alpha), vec3<f32>(0.), vec3<f32>(alpha)), alpha);
|
||||||
}
|
}
|
||||||
|
|
||||||
// The colors and coverage a neighborhood maximum (with `values.z` 1) or minimum works on, matching the CPU's `neighborhood_extreme`:
|
// The colors and coverage a neighborhood maximum (with `values.z` 1) or minimum works on:
|
||||||
// the straight colors of covered texels for the maximum, black elsewhere, or for the minimum the colors matted over white
|
// the straight colors of covered texels for the maximum, black elsewhere, or for the minimum the colors matted over white
|
||||||
@fragment
|
@fragment
|
||||||
fn neighborhood_prepare(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
fn neighborhood_prepare(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||||
@@ -151,7 +151,7 @@ fn neighborhood_texel(pixel: vec2<i32>) -> vec4<f32> {
|
|||||||
return textureLoad(source, pixel, 0);
|
return textureLoad(source, pixel, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
// The extremes over `values.x` texels each way along `step`, read one by one, matching the CPU's `window_extremes`
|
// The extremes over `values.x` texels each way along `step`, read one by one
|
||||||
@fragment
|
@fragment
|
||||||
fn neighborhood_extreme(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
fn neighborhood_extreme(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||||
let pixel = vec2<i32>(position.xy);
|
let pixel = vec2<i32>(position.xy);
|
||||||
@@ -187,7 +187,7 @@ fn premultiplied_extremes(extremes: vec4<f32>) -> vec4<f32> {
|
|||||||
return vec4<f32>(clamp(extremes.rgb - (1. - extremes.a), vec3<f32>(0.), vec3<f32>(extremes.a)), extremes.a);
|
return vec4<f32>(clamp(extremes.rgb - (1. - extremes.a), vec3<f32>(0.), vec3<f32>(extremes.a)), extremes.a);
|
||||||
}
|
}
|
||||||
|
|
||||||
// The extremes (`source`) back as premultiplied colors, mixed toward those of the next whole radius (`secondary`) by the fraction `values.x`, matching the CPU's `neighborhood_extreme`
|
// The extremes (`source`) back as premultiplied colors, mixed toward those of the next whole radius (`secondary`) by the fraction `values.x`
|
||||||
@fragment
|
@fragment
|
||||||
fn neighborhood_finish(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
fn neighborhood_finish(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||||
let pixel = vec2<i32>(position.xy);
|
let pixel = vec2<i32>(position.xy);
|
||||||
@@ -196,7 +196,7 @@ fn neighborhood_finish(@builtin(position) position: vec4<f32>) -> @location(0) v
|
|||||||
return mix(near, far, parameters.values.x);
|
return mix(near, far, parameters.values.x);
|
||||||
}
|
}
|
||||||
|
|
||||||
// The texels (`source`) read `taps[i].xy` texels away between those around them, each weighted by `taps[i].z`, with none beyond the edges (`values.y` below 0), matching the CPU's `neighbors_average`.
|
// The texels (`source`) read `taps[i].xy` texels away between those around them, each weighted by `taps[i].z`, with none beyond the edges (`values.y` below 0).
|
||||||
// A pass after others (`values.z` 1) adds to their sum (`content`), and the last (`values.w` 1) clamps it.
|
// A pass after others (`values.z` 1) adds to their sum (`content`), and the last (`values.w` 1) clamps it.
|
||||||
@fragment
|
@fragment
|
||||||
fn sum_taps(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
fn sum_taps(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||||
@@ -232,7 +232,7 @@ fn visible_only(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32
|
|||||||
return select(vec4<f32>(0.), vec4<f32>(color.rgb / color.a, 1.), visible);
|
return select(vec4<f32>(0.), vec4<f32>(color.rgb / color.a, 1.), visible);
|
||||||
}
|
}
|
||||||
|
|
||||||
// The blurred visibilities between which unsharp masking eases from comparing a texel against its own color to the visible colors' average, matching the CPU's
|
// The blurred visibilities between which unsharp masking eases from comparing a texel against its own color to the visible colors' average, matching graphic-types' `AVERAGE_VISIBILITY_RAMP`
|
||||||
const AVERAGE_VISIBILITY_RAMP: vec2<f32> = vec2<f32>(8. / 255., 24. / 255.);
|
const AVERAGE_VISIBILITY_RAMP: vec2<f32> = vec2<f32>(8. / 255., 24. / 255.);
|
||||||
|
|
||||||
// The average of the visible colors a texel's own straight color is compared against, from the blur of them made opaque among the rest left out (`blurred`),
|
// The average of the visible colors a texel's own straight color is compared against, from the blur of them made opaque among the rest left out (`blurred`),
|
||||||
@@ -242,10 +242,10 @@ fn visible_average(own: vec3<f32>, blurred: vec4<f32>) -> vec3<f32> {
|
|||||||
return select(own, own + (blurred.rgb / blurred.a - own) * weight, weight > 0.);
|
return select(own, own + (blurred.rgb / blurred.a - own) * weight, weight > 0.);
|
||||||
}
|
}
|
||||||
|
|
||||||
// For PSD interop, the middle gray a high pass centers its differences on, matching the CPU's
|
// For PSD interop, the middle gray a high pass centers its differences on, matching graphic-types' `HIGH_PASS_GRAY`
|
||||||
const HIGH_PASS_GRAY: f32 = 128. / 255.;
|
const HIGH_PASS_GRAY: f32 = 128. / 255.;
|
||||||
|
|
||||||
// For PSD interop, the Sobel gradient lengths between which Edges Only ramps from no change to the whole of it, matching the CPU's
|
// For PSD interop, the Sobel gradient lengths between which Edges Only ramps from no change to the whole of it
|
||||||
const EDGE_GAIN_RAMP: vec2<f32> = vec2<f32>(0.25, 1.);
|
const EDGE_GAIN_RAMP: vec2<f32> = vec2<f32>(0.25, 1.);
|
||||||
|
|
||||||
// The image's coverage (`secondary`) at a position in texels from the first texel's center, interpolated between the four texels around it, with none beyond the edges
|
// The image's coverage (`secondary`) at a position in texels from the first texel's center, interpolated between the four texels around it, with none beyond the edges
|
||||||
@@ -264,7 +264,7 @@ fn coverage_between(position: vec2<f32>) -> f32 {
|
|||||||
return mix(mix(corners[0], corners[1], fraction.x), mix(corners[2], corners[3], fraction.x), fraction.y);
|
return mix(mix(corners[0], corners[1], fraction.x), mix(corners[2], corners[3], fraction.x), fraction.y);
|
||||||
}
|
}
|
||||||
|
|
||||||
// For PSD interop, the share of its change Edges Only makes in each channel, by the length of the channel's Sobel gradient, matching the CPU's `edge_gains`.
|
// For PSD interop, the share of its change Edges Only makes in each channel, by the length of the channel's Sobel gradient.
|
||||||
// Each tap `taps[i].xy` texels away weighs `taps[i].z` across and `taps[i].w` down, read on the continued colors (`source`) and the image's coverage (`secondary`).
|
// Each tap `taps[i].xy` texels away weighs `taps[i].z` across and `taps[i].w` down, read on the continued colors (`source`) and the image's coverage (`secondary`).
|
||||||
@fragment
|
@fragment
|
||||||
fn edge_gains(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
fn edge_gains(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||||
@@ -284,7 +284,7 @@ fn edge_gains(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32>
|
|||||||
}
|
}
|
||||||
|
|
||||||
// What the unsharp mask compares the image (`source`) against for Edges Only: its straight colors moved toward their neighbors' visible average (`secondary`) by the share their edge gains (`content`) give,
|
// What the unsharp mask compares the image (`source`) against for Edges Only: its straight colors moved toward their neighbors' visible average (`secondary`) by the share their edge gains (`content`) give,
|
||||||
// made opaque so the unsharp mask reads them as the whole average. With `values.z` 1, it's the coverage moved toward its neighbors' average instead, matching the CPU's `unsharp_mask`.
|
// made opaque so the unsharp mask reads them as the whole average. With `values.z` 1, it's the coverage moved toward its neighbors' average instead.
|
||||||
@fragment
|
@fragment
|
||||||
fn edges_only_average(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
fn edges_only_average(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||||
let pixel = vec2<i32>(position.xy);
|
let pixel = vec2<i32>(position.xy);
|
||||||
@@ -307,7 +307,7 @@ fn unsharp_change(difference: vec4<f32>) -> vec4<f32> {
|
|||||||
return sign(difference) * max(parameters.values.x * abs(difference) - parameters.values.y, vec4<f32>(0.));
|
return sign(difference) * max(parameters.values.x * abs(difference) - parameters.values.y, vec4<f32>(0.));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sharpens the straight colors and coverage of the image (`source`) against the blur of its visible colors (`secondary`) and of its coverage (`content`), matching the CPU's `unsharp_mask`.
|
// Sharpens the straight colors and coverage of the image (`source`) against the blur of its visible colors (`secondary`) and of its coverage (`content`).
|
||||||
// With `values.w` 1, it's a high pass instead: the colors' difference from their blur around middle gray, with the coverage kept.
|
// With `values.w` 1, it's a high pass instead: the colors' difference from their blur around middle gray, with the coverage kept.
|
||||||
@fragment
|
@fragment
|
||||||
fn unsharp_mask(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
fn unsharp_mask(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||||
@@ -328,7 +328,7 @@ fn unsharp_mask(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32
|
|||||||
return vec4<f32>(sharpened.rgb * sharpened.a, sharpened.a);
|
return vec4<f32>(sharpened.rgb * sharpened.a, sharpened.a);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Each texel's share of the full-strength content's coverage (`content`) that the faded fill (`source`) left, matching the CPU's `fill_shares`
|
// Each texel's share of the full-strength content's coverage (`content`) that the faded fill (`source`) left
|
||||||
@fragment
|
@fragment
|
||||||
fn fill_shares(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
fn fill_shares(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||||
let pixel = vec2<i32>(position.xy);
|
let pixel = vec2<i32>(position.xy);
|
||||||
@@ -337,8 +337,7 @@ fn fill_shares(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32>
|
|||||||
return vec4<f32>(0., 0., 0., select(0., min(filled / full, 1.), full > 0.));
|
return vec4<f32>(0., 0., 0., select(0., min(filled / full, 1.), full > 0.));
|
||||||
}
|
}
|
||||||
|
|
||||||
// The fill's filtered straight colors (`source`) at the coverage of the full-strength content's filtered result (`secondary`) scaled by each texel's share of it (`content`),
|
// The fill's filtered straight colors (`source`) at the coverage of the full-strength content's filtered result (`secondary`) scaled by each texel's share of it (`content`)
|
||||||
// matching the CPU's `faded_by_shares`
|
|
||||||
@fragment
|
@fragment
|
||||||
fn faded_by_shares(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
fn faded_by_shares(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||||
let pixel = vec2<i32>(position.xy);
|
let pixel = vec2<i32>(position.xy);
|
||||||
@@ -355,7 +354,7 @@ fn faded_by_shares(@builtin(position) position: vec4<f32>) -> @location(0) vec4<
|
|||||||
return vec4<f32>(colors * alpha, alpha);
|
return vec4<f32>(colors * alpha, alpha);
|
||||||
}
|
}
|
||||||
|
|
||||||
// The fill's straight colors (`source`) at the full-strength content's coverage (`secondary`), or where the fill left none, that content's own, matching the CPU's `at_full_coverage`
|
// The fill's straight colors (`source`) at the full-strength content's coverage (`secondary`), or where the fill left none, that content's own
|
||||||
@fragment
|
@fragment
|
||||||
fn at_full_coverage(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
fn at_full_coverage(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||||
let pixel = vec2<i32>(position.xy);
|
let pixel = vec2<i32>(position.xy);
|
||||||
@@ -375,10 +374,10 @@ fn at_full_coverage(@builtin(position) position: vec4<f32>) -> @location(0) vec4
|
|||||||
// Random fields
|
// Random fields
|
||||||
// =============
|
// =============
|
||||||
|
|
||||||
// For PSD interop, how many standard deviations Gaussian noise reaches, matching the CPU's
|
// For PSD interop, how many standard deviations Gaussian noise reaches, matching graphic-types' `GAUSSIAN_NOISE_LIMIT`
|
||||||
const GAUSSIAN_NOISE_LIMIT: f32 = 3.5;
|
const GAUSSIAN_NOISE_LIMIT: f32 = 3.5;
|
||||||
|
|
||||||
// Values strictly between 0 and 1 from the top 23 bits of each hash, which an f32 holds exactly with the half added, matching the CPU's `unit_interval`
|
// Values strictly between 0 and 1 from the top 23 bits of each hash, which an f32 holds exactly with the half added
|
||||||
fn unit_interval(hash: vec3<u32>) -> vec3<f32> {
|
fn unit_interval(hash: vec3<u32>) -> vec3<f32> {
|
||||||
return (vec3<f32>(hash >> vec3<u32>(9u)) + 0.5) / 8388608.;
|
return (vec3<f32>(hash >> vec3<u32>(9u)) + 0.5) / 8388608.;
|
||||||
}
|
}
|
||||||
@@ -412,7 +411,7 @@ fn sample_offset(column: u32, row: u32) -> vec2<f32> {
|
|||||||
return ((vec2<f32>(f32(column), f32(row)) + 0.5) / parameters.taps[2].xy - 0.5) * parameters.taps[2].zw;
|
return ((vec2<f32>(f32(column), f32(row)) + 0.5) / parameters.taps[2].xy - 0.5) * parameters.taps[2].zw;
|
||||||
}
|
}
|
||||||
|
|
||||||
// The offsets Speckle gives a texel's colors, matching the CPU's `speckle`: its noise averaged over its samples (Gaussian with `values.z` 1), the same for every color with `values.w` 1,
|
// The offsets Speckle gives a texel's colors: its noise averaged over its samples (Gaussian with `values.z` 1), the same for every color with `values.w` 1,
|
||||||
// scaled by `values.x` and kept within `values.y` either way
|
// scaled by `values.x` and kept within `values.y` either way
|
||||||
fn noise_offsets(position: vec2<f32>) -> vec3<f32> {
|
fn noise_offsets(position: vec2<f32>) -> vec3<f32> {
|
||||||
let counts = sample_counts();
|
let counts = sample_counts();
|
||||||
@@ -456,7 +455,7 @@ fn speckle(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
|||||||
return vec4<f32>(noisy * color.a, color.a);
|
return vec4<f32>(noisy * color.a, color.a);
|
||||||
}
|
}
|
||||||
|
|
||||||
// How much of a texel Dissolve shows, matching the CPU's `dissolve_field`: the share of its samples passing the opacity `values.x`, deviating from it less by `values.y`,
|
// How much of a texel Dissolve shows: the share of its samples passing the opacity `values.x`, deviating from it less by `values.y`,
|
||||||
// and the threshold level from 0 to 254 its coverage must pass
|
// and the threshold level from 0 to 254 its coverage must pass
|
||||||
fn dissolve_field(position: vec2<f32>) -> vec2<f32> {
|
fn dissolve_field(position: vec2<f32>) -> vec2<f32> {
|
||||||
let counts = sample_counts();
|
let counts = sample_counts();
|
||||||
|
|||||||
@@ -3,10 +3,10 @@
|
|||||||
use super::{COVERAGE_FORMAT, Parameters, PassRecorder, SUMS_FORMAT, Seeds, WORKING_FORMAT};
|
use super::{COVERAGE_FORMAT, Parameters, PassRecorder, SUMS_FORMAT, Seeds, WORKING_FORMAT};
|
||||||
use glam::DVec2;
|
use glam::DVec2;
|
||||||
use graphic_types::masks::{MaskMode, feather_parts, mask_density_line, masked_radius_blur_interpolation};
|
use graphic_types::masks::{MaskMode, feather_parts, mask_density_line, masked_radius_blur_interpolation};
|
||||||
use raster_kernels::effect_kernels::{BlurKernel, NEGLIGIBLE_LENGTH, variable_box_scale};
|
use raster_kernels::effect_planning::{BlurKernel, NEGLIGIBLE_LENGTH, variable_box_scale};
|
||||||
|
|
||||||
impl PassRecorder<'_> {
|
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`.
|
/// How much the `mask` graphic's texture shows the content at each pixel, from 0 to 1.
|
||||||
/// Its coverage is softened by a Gaussian of standard deviation `sigma` in pixels, then mapped through its `density` percentage, flipped if `invert`.
|
/// 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 {
|
pub(super) fn mask_strength(&mut self, mask: &wgpu::Texture, mode: MaskMode, density: f64, sigma: f64, invert: bool) -> wgpu::Texture {
|
||||||
let weights = Parameters {
|
let weights = Parameters {
|
||||||
@@ -44,7 +44,7 @@ impl PassRecorder<'_> {
|
|||||||
self.run("content_with_layer_fade", WORKING_FORMAT, self.size, content, Some(fade), None, Parameters::default())
|
self.run("content_with_layer_fade", WORKING_FORMAT, self.size, content, Some(fade), None, Parameters::default())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// How much a feather of `distance` pixels keeps of the `full`-strength content at each pixel, from 0 to 1, as `feather_parts` defines it, matching the CPU's `feather_strength`.
|
/// How much a feather of `distance` pixels keeps of the `full`-strength content at each pixel, from 0 to 1, as `feather_parts` defines it.
|
||||||
pub(super) fn feather_strength(&mut self, full: &wgpu::Texture, distance: f64) -> wgpu::Texture {
|
pub(super) fn feather_strength(&mut self, full: &wgpu::Texture, distance: f64) -> wgpu::Texture {
|
||||||
let outside = self.run("feather_outside", COVERAGE_FORMAT, self.size, full, None, None, Parameters::default());
|
let outside = self.run("feather_outside", COVERAGE_FORMAT, self.size, full, None, None, Parameters::default());
|
||||||
let (erosion, sigma) = feather_parts(distance);
|
let (erosion, sigma) = feather_parts(distance);
|
||||||
@@ -65,7 +65,7 @@ impl PassRecorder<'_> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Blurs both the full-strength content (`content` itself until a pass replaces it) and the faded fill by the interpolation between Gaussian `levels` (from `masked_radius_blur_levels`, here in pixels)
|
/// Blurs both the full-strength content (`content` itself until a pass replaces it) and the faded fill by the interpolation between Gaussian `levels` (from `masked_radius_blur_levels`, here in pixels)
|
||||||
/// the map's `luminance` picks, matching the CPU's `masked_radius_blur`. The `luminance` holds 8-bit codes as fractions of 255.
|
/// the map's `luminance` picks. The `luminance` holds 8-bit codes as fractions of 255.
|
||||||
/// The levels blur in linear light if `linear`, and the full-strength content is left as it is unless `full_is_read`.
|
/// The levels blur in linear light if `linear`, and the full-strength content is left as it is unless `full_is_read`.
|
||||||
#[allow(clippy::too_many_arguments)]
|
#[allow(clippy::too_many_arguments)]
|
||||||
pub(super) fn masked_radius_blur(
|
pub(super) fn masked_radius_blur(
|
||||||
@@ -122,7 +122,7 @@ impl PassRecorder<'_> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Box blurs both the full-strength content (`content` itself until a pass replaces it) and the faded fill at each texel by its own half width,
|
/// Box blurs both the full-strength content (`content` itself until a pass replaces it) and the faded fill at each texel by its own half width,
|
||||||
/// the fraction of the `radius` in pixels along each axis that the map's unrounded `luminance` gives, matching the CPU's `variable_box_blur`.
|
/// the fraction of the `radius` in pixels along each axis that the map's unrounded `luminance` gives.
|
||||||
/// It blurs in linear light if `linear`, and leaves the full-strength content as it is unless `full_is_read`.
|
/// It blurs in linear light if `linear`, and leaves the full-strength content as it is unless `full_is_read`.
|
||||||
#[allow(clippy::too_many_arguments)]
|
#[allow(clippy::too_many_arguments)]
|
||||||
pub(super) fn masked_box_blur(
|
pub(super) fn masked_box_blur(
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ use graphic_types::resampling::{
|
|||||||
DISPLACEMENT_NEUTRAL_LEVEL, DisplacementField, EffectFrame, FrameWarp, HALFTONE_BOX_NUDGE, HalftoneScreen, MAX_AVERAGED_PIXELS, MAX_WAVE_GENERATORS, RadialBlur, RadialBlurMethod, tie_nudge,
|
DISPLACEMENT_NEUTRAL_LEVEL, DisplacementField, EffectFrame, FrameWarp, HALFTONE_BOX_NUDGE, HalftoneScreen, MAX_AVERAGED_PIXELS, MAX_WAVE_GENERATORS, RadialBlur, RadialBlurMethod, tie_nudge,
|
||||||
};
|
};
|
||||||
use graphic_types::vector_types::GradientSpread;
|
use graphic_types::vector_types::GradientSpread;
|
||||||
use raster_kernels::resample_kernels::{MotionBlurShear, PixelateCells, halftone_cells, halftone_table_count, pixelation_table_fits};
|
use raster_kernels::effect_planning::{MotionBlurShear, PixelateCells, halftone_cells, halftone_table_count, pixelation_table_fits};
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
thread_local! {
|
thread_local! {
|
||||||
@@ -48,7 +48,7 @@ pub(super) enum Displacement<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl PassRecorder<'_> {
|
impl PassRecorder<'_> {
|
||||||
/// `texture` smeared along the motion blur's line by its two shears around a box, in linear light if `linear`, matching the CPU's `motion_blurred`.
|
/// `texture` smeared along the motion blur's line by its two shears around a box, in linear light if `linear`.
|
||||||
pub(super) fn motion_blur(&mut self, texture: wgpu::Texture, shear: &MotionBlurShear, linear: bool) -> wgpu::Texture {
|
pub(super) fn motion_blur(&mut self, texture: wgpu::Texture, shear: &MotionBlurShear, linear: bool) -> wgpu::Texture {
|
||||||
let [start, end] = shear.box_span();
|
let [start, end] = shear.box_span();
|
||||||
let mut taps = [[0.; 4]; PARAMETER_TAPS];
|
let mut taps = [[0.; 4]; PARAMETER_TAPS];
|
||||||
@@ -68,7 +68,7 @@ impl PassRecorder<'_> {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `texture` blurred along the radial blur's arcs or lines, in the effect space that `effect_to_pixels` places on the texture's pixels, in linear light if `linear`, matching the CPU's `radial_blurred`.
|
/// `texture` blurred along the radial blur's arcs or lines, in the effect space that `effect_to_pixels` places on the texture's pixels, in linear light if `linear`.
|
||||||
pub(super) fn radial_blur(&mut self, texture: wgpu::Texture, blur: &RadialBlur, effect_to_pixels: DAffine2, linear: bool) -> wgpu::Texture {
|
pub(super) fn radial_blur(&mut self, texture: wgpu::Texture, blur: &RadialBlur, effect_to_pixels: DAffine2, linear: bool) -> wgpu::Texture {
|
||||||
// The shader measures offsets from the center in the circle's space, placed here in double precision, since positions can lie far from the effect space's origin
|
// The shader measures offsets from the center in the circle's space, placed here in double precision, since positions can lie far from the effect space's origin
|
||||||
let circle_to_pixels = effect_to_pixels * blur.transform;
|
let circle_to_pixels = effect_to_pixels * blur.transform;
|
||||||
@@ -95,7 +95,7 @@ impl PassRecorder<'_> {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `texture` warped relative to the `frame`, matching the CPU's `frame_warped`.
|
/// `texture` warped relative to the `frame`.
|
||||||
pub(super) fn frame_warp(&mut self, texture: wgpu::Texture, warp: &FrameWarp, frame: &EffectFrame) -> wgpu::Texture {
|
pub(super) fn frame_warp(&mut self, texture: wgpu::Texture, warp: &FrameWarp, frame: &EffectFrame) -> wgpu::Texture {
|
||||||
let [kind, setting, extra] = warp.shader_parameters();
|
let [kind, setting, extra] = warp.shader_parameters();
|
||||||
let mut taps = frame_taps(frame);
|
let mut taps = frame_taps(frame);
|
||||||
@@ -112,7 +112,7 @@ impl PassRecorder<'_> {
|
|||||||
warped
|
warped
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `texture` with each texel moved by the `displacement` relative to the `frame`, matching the CPU's `displaced`.
|
/// `texture` with each texel moved by the `displacement` relative to the `frame`.
|
||||||
pub(super) fn displace(&mut self, texture: wgpu::Texture, displacement: Displacement, frame: &EffectFrame, edge_mode: GradientSpread) -> wgpu::Texture {
|
pub(super) fn displace(&mut self, texture: wgpu::Texture, displacement: Displacement, frame: &EffectFrame, edge_mode: GradientSpread) -> wgpu::Texture {
|
||||||
let mut taps = frame_taps(frame);
|
let mut taps = frame_taps(frame);
|
||||||
let (half_pixel, pixel_extent) = (frame.half_pixel().as_vec2(), frame.pixel_extent().as_vec2());
|
let (half_pixel, pixel_extent) = (frame.half_pixel().as_vec2(), frame.pixel_extent().as_vec2());
|
||||||
@@ -177,7 +177,7 @@ impl PassRecorder<'_> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The size of the texture holding a pixelation's `tables` of cells `count` across and down, a row after another, as wide as a table's rows where that fits within the device's limit, or else as wide as it allows.
|
/// The size of the texture holding a pixelation's `tables` of cells `count` across and down, a row after another, as wide as a table's rows where that fits within the device's limit, or else as wide as it allows.
|
||||||
/// `None` where that's still too tall, or where the tables don't fit [`pixelation_table_fits`], which the CPU refuses alike.
|
/// `None` where that's still too tall, or where the tables don't fit [`pixelation_table_fits`].
|
||||||
fn table_size(&self, count: [usize; 2], tables: usize) -> Option<UVec2> {
|
fn table_size(&self, count: [usize; 2], tables: usize) -> Option<UVec2> {
|
||||||
let limit = self.device.limits().max_texture_dimension_2d as usize;
|
let limit = self.device.limits().max_texture_dimension_2d as usize;
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
@@ -215,7 +215,7 @@ impl PassRecorder<'_> {
|
|||||||
sums
|
sums
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `texture` broken into Pixelate's cells with a corner at `offset` from the content's origin, each filled with its average, matching the CPU's `pixelated`.
|
/// `texture` broken into Pixelate's cells with a corner at `offset` from the content's origin, each filled with its average.
|
||||||
/// It's left as it is where its cells don't fit [`pixelation_table_fits`], or are more than a texture can hold however its rows wrap.
|
/// It's left as it is where its cells don't fit [`pixelation_table_fits`], or are more than a texture can hold however its rows wrap.
|
||||||
pub(super) fn pixelate(&mut self, texture: wgpu::Texture, cell_size: f64, offset: DVec2, frame: &EffectFrame) -> wgpu::Texture {
|
pub(super) fn pixelate(&mut self, texture: wgpu::Texture, cell_size: f64, offset: DVec2, frame: &EffectFrame) -> wgpu::Texture {
|
||||||
let cells = PixelateCells::new(cell_size, offset, frame, self.size.x as usize, self.size.y as usize);
|
let cells = PixelateCells::new(cell_size, offset, frame, self.size.x as usize, self.size.y as usize);
|
||||||
@@ -246,7 +246,7 @@ impl PassRecorder<'_> {
|
|||||||
pixelated
|
pixelated
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `texture` printed as a color halftone on the channels' `screens`, matching the CPU's `halftoned`.
|
/// `texture` printed as a color halftone on the channels' `screens`.
|
||||||
pub(super) fn halftone(&mut self, texture: wgpu::Texture, screens: &[HalftoneScreen; 3], frame: &EffectFrame) -> wgpu::Texture {
|
pub(super) fn halftone(&mut self, texture: wgpu::Texture, screens: &[HalftoneScreen; 3], frame: &EffectFrame) -> wgpu::Texture {
|
||||||
// Each channel's dots lie one channel's rows after another, as many across and down as the most any channel needs
|
// Each channel's dots lie one channel's rows after another, as many across and down as the most any channel needs
|
||||||
let cells = screens.map(|screen| halftone_cells(self.size.x as usize, self.size.y as usize, &screen, frame));
|
let cells = screens.map(|screen| halftone_cells(self.size.x as usize, self.size.y as usize, &screen, frame));
|
||||||
@@ -294,7 +294,7 @@ impl PassRecorder<'_> {
|
|||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
|
|
||||||
// Half floats would place a large dot's edge too coarsely to match the CPU's
|
// Half floats would place a large dot's edge too coarsely
|
||||||
let dots = self.run("halftone_dots", SUMS_FORMAT, table, &texture, None, row_sums.as_ref(), parameters);
|
let dots = self.run("halftone_dots", SUMS_FORMAT, table, &texture, None, row_sums.as_ref(), parameters);
|
||||||
let halftone = self.run("halftone", texture.format(), self.size, &texture, None, Some(&dots), parameters);
|
let halftone = self.run("halftone", texture.format(), self.size, &texture, None, Some(&dots), parameters);
|
||||||
row_sums.into_iter().chain([dots, texture]).for_each(|used| self.textures.release(used));
|
row_sums.into_iter().chain([dots, texture]).for_each(|used| self.textures.release(used));
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ use glam::{DAffine2, DVec2, DVec3};
|
|||||||
use graphic_types::BevelStyle;
|
use graphic_types::BevelStyle;
|
||||||
use graphic_types::effects::{BEVEL_FOOT_FADE, GRADIENT_GLOW_FADE, GlowFill, JITTER_EXPECTATION_SAMPLES, contour_end_slopes, slope_contour_reshapes};
|
use graphic_types::effects::{BEVEL_FOOT_FADE, GRADIENT_GLOW_FADE, GlowFill, JITTER_EXPECTATION_SAMPLES, contour_end_slopes, slope_contour_reshapes};
|
||||||
use graphic_types::filters::{FieldSampling, RandomField};
|
use graphic_types::filters::{FieldSampling, RandomField};
|
||||||
use raster_kernels::effect_kernels::NEGLIGIBLE_LENGTH;
|
use raster_kernels::effect_planning::NEGLIGIBLE_LENGTH;
|
||||||
|
|
||||||
/// An outline's coverage outside the content's edge and inside it, where it reaches, and each pixel's place across it for a contour gradient.
|
/// An outline's coverage outside the content's edge and inside it, where it reaches, and each pixel's place across it for a contour gradient.
|
||||||
pub(super) struct OutlineBands {
|
pub(super) struct OutlineBands {
|
||||||
@@ -17,7 +17,7 @@ pub(super) struct OutlineBands {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl PassRecorder<'_> {
|
impl PassRecorder<'_> {
|
||||||
/// The bands of an outline reaching `outside` texels past the edge of the content's silhouette and `inside` texels within it, matching the CPU's `outline_bands`.
|
/// The bands of an outline reaching `outside` texels past the edge of the content's silhouette and `inside` texels within it.
|
||||||
/// With a contour gradient's `start` and `span` in texels, it also places each texel across the outline.
|
/// With a contour gradient's `start` and `span` in texels, it also places each texel across the outline.
|
||||||
pub(super) fn outline_bands(&mut self, content: &wgpu::Texture, outside: f64, inside: f64, contour_gradient: Option<(f64, f64)>) -> OutlineBands {
|
pub(super) fn outline_bands(&mut self, content: &wgpu::Texture, outside: f64, inside: f64, contour_gradient: Option<(f64, f64)>) -> OutlineBands {
|
||||||
let distances = |recorder: &mut Self, inverse: bool, reach: f64| {
|
let distances = |recorder: &mut Self, inverse: bool, reach: f64| {
|
||||||
@@ -68,7 +68,7 @@ impl PassRecorder<'_> {
|
|||||||
painted
|
painted
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The `band`'s coverage of a contour `gradient` at each texel's place across the outline, in place of the band, matching the CPU's `contour_gradient_colors`.
|
/// The `band`'s coverage of a contour `gradient` at each texel's place across the outline, in place of the band.
|
||||||
pub(super) fn contour_gradient_band(&mut self, band: wgpu::Texture, positions: &wgpu::Texture, gradient: &GlowFill) -> wgpu::Texture {
|
pub(super) fn contour_gradient_band(&mut self, band: wgpu::Texture, positions: &wgpu::Texture, gradient: &GlowFill) -> wgpu::Texture {
|
||||||
let Some((samples, opacity)) = gradient.gradient_samples(GRADIENT_SAMPLES as usize) else {
|
let Some((samples, opacity)) = gradient.gradient_samples(GRADIENT_SAMPLES as usize) else {
|
||||||
return band;
|
return band;
|
||||||
@@ -100,7 +100,7 @@ pub(super) struct BevelSurface<'a> {
|
|||||||
/// The first tap [`field_parameters`] leaves free, which holds a grain's own parameters.
|
/// The first tap [`field_parameters`] leaves free, which holds a grain's own parameters.
|
||||||
const GRAIN_TAP: usize = 5;
|
const GRAIN_TAP: usize = 5;
|
||||||
|
|
||||||
/// The random grain roughening a glow, matching the CPU's `GlowGrain`.
|
/// The random grain roughening a glow.
|
||||||
pub(super) struct GlowGrain {
|
pub(super) struct GlowGrain {
|
||||||
/// Where each texel samples the grain, fixed to the cells of the effect space.
|
/// Where each texel samples the grain, fixed to the cells of the effect space.
|
||||||
sampling: FieldSampling,
|
sampling: FieldSampling,
|
||||||
@@ -155,7 +155,7 @@ impl PassRecorder<'_> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// How much brighter than flat ground the `light` lights each texel of a bevel's surface, negative where darker, with its `height` running from -0.5 at its slopes' foot to 0.5 at their top.
|
/// How much brighter than flat ground the `light` lights each texel of a bevel's surface, negative where darker, with its `height` running from -0.5 at its slopes' foot to 0.5 at their top.
|
||||||
/// The slopes rise `rise` texels as the `surface` options shape them. Matches the CPU's `bevel_shading` before its gloss contour.
|
/// The slopes rise `rise` texels as the `surface` options shape them.
|
||||||
/// With `direct` as `Some(shadow)`, it's instead the highlight, or if `shadow` the shadow, that makes without a gloss contour or a fade at the foot.
|
/// With `direct` as `Some(shadow)`, it's instead the highlight, or if `shadow` the shadow, that makes without a gloss contour or a fade at the foot.
|
||||||
pub(super) fn bevel_lit(&mut self, height: &wgpu::Texture, surface: &BevelSurface, rise: f64, light: DVec3, direct: Option<bool>) -> wgpu::Texture {
|
pub(super) fn bevel_lit(&mut self, height: &wgpu::Texture, surface: &BevelSurface, rise: f64, light: DVec3, direct: Option<bool>) -> wgpu::Texture {
|
||||||
let reshaped = slope_contour_reshapes(surface.slope_contour, surface.style, surface.slope_range);
|
let reshaped = slope_contour_reshapes(surface.slope_contour, surface.style, surface.slope_range);
|
||||||
@@ -190,7 +190,6 @@ impl PassRecorder<'_> {
|
|||||||
|
|
||||||
/// The highlight, or if `shadow` the shadow, of each texel of a bevel's surface lit `brighter` than flat ground, of brightness `light_z`.
|
/// The highlight, or if `shadow` the shadow, of each texel of a bevel's surface lit `brighter` than flat ground, of brightness `light_z`.
|
||||||
/// The `gloss` contour's samples, if any, reshape how lit it is first, antialiased if paired with true. If `fades_at_foot`, it fades out across the slopes' foot by its `height`.
|
/// The `gloss` contour's samples, if any, reshape how lit it is first, antialiased if paired with true. If `fades_at_foot`, it fades out across the slopes' foot by its `height`.
|
||||||
/// Matches the CPU's `bevel_shading` and `foot_faded`.
|
|
||||||
pub(super) fn bevel_amount(&mut self, brighter: &wgpu::Texture, height: &wgpu::Texture, gloss: Option<&(wgpu::Texture, bool)>, light_z: f64, shadow: bool, fades_at_foot: bool) -> wgpu::Texture {
|
pub(super) fn bevel_amount(&mut self, brighter: &wgpu::Texture, height: &wgpu::Texture, gloss: Option<&(wgpu::Texture, bool)>, light_z: f64, shadow: bool, fades_at_foot: bool) -> wgpu::Texture {
|
||||||
let flag = |on: bool| if on { 1. } else { 0. };
|
let flag = |on: bool| if on { 1. } else { 0. };
|
||||||
let mut taps = [[0.; 4]; PARAMETER_TAPS];
|
let mut taps = [[0.; 4]; PARAMETER_TAPS];
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ fn warp_taps(square: &EffectFrame, tessellation: &WarpTessellation) -> [[f32; 4]
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl PassRecorder<'_> {
|
impl PassRecorder<'_> {
|
||||||
/// `texture` with the content within its `square` carried through the warp's `tessellation` (made for this recorder's size), and all else cleared, matching the CPU's `WarpRasterizer`.
|
/// `texture` with the content within its `square` carried through the warp's `tessellation` (made for this recorder's size), and all else cleared.
|
||||||
pub(super) fn warp_effect(&mut self, texture: wgpu::Texture, square: &EffectFrame, tessellation: &WarpTessellation) -> wgpu::Texture {
|
pub(super) fn warp_effect(&mut self, texture: wgpu::Texture, square: &EffectFrame, tessellation: &WarpTessellation) -> wgpu::Texture {
|
||||||
let parameters = Parameters {
|
let parameters = Parameters {
|
||||||
values: [tessellation.source.matrix2.determinant().signum() as f32, 0., 0., 0.],
|
values: [tessellation.source.matrix2.determinant().signum() as f32, 0., 0., 0.],
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
//! The GPU pass that renders tiles of generators' patterns, matching the CPU's renders of them.
|
//! The GPU pass that renders tiles of generators' patterns, matching the CPU's samples of them.
|
||||||
|
|
||||||
use crate::vello_render::TEXTURE_FORMAT;
|
use crate::vello_render::TEXTURE_FORMAT;
|
||||||
use bytemuck::{Pod, Zeroable};
|
use bytemuck::{Pod, Zeroable};
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
// Renders a tile of a generator's pattern, sampled at the centers of the tile's pixels, as opaque gamma-encoded color like the CPU's tiles.
|
// Renders a tile of a generator's pattern, sampled at the centers of the tile's pixels, as opaque gamma-encoded color like the CPU's samples.
|
||||||
// Each pattern's shader is this followed by its own, whose `Parameters` start with the tile's top left corner in the pattern's space and its pixel size there.
|
// Each pattern's shader is this followed by its own, whose `Parameters` start with the tile's top left corner in the pattern's space and its pixel size there.
|
||||||
|
|
||||||
// One triangle that covers the whole target
|
// One triangle that covers the whole target
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ fn content_with_layer_fade(@builtin(position) position: vec4<f32>) -> @location(
|
|||||||
return vec4<f32>(textureLoad(secondary, pixel, 0).r, 0., 0., textureLoad(source, pixel, 0).a);
|
return vec4<f32>(textureLoad(secondary, pixel, 0).r, 0., 0., textureLoad(source, pixel, 0).a);
|
||||||
}
|
}
|
||||||
|
|
||||||
// The alpha at or below which a feather counts content as absent, matching `FEATHER_FOOTPRINT_ALPHA`
|
// The alpha at or below which a feather counts content as absent, half an 8-bit level, so the faint tail of a blur doesn't count as content
|
||||||
const FEATHER_FOOTPRINT_ALPHA: f32 = 0.5 / 255.;
|
const FEATHER_FOOTPRINT_ALPHA: f32 = 0.5 / 255.;
|
||||||
|
|
||||||
// The coverage of the area outside the footprint of the content in `source`, with its edge falling within the texels bordering it by their alpha relative to the largest beside them
|
// The coverage of the area outside the footprint of the content in `source`, with its edge falling within the texels bordering it by their alpha relative to the largest beside them
|
||||||
@@ -61,7 +61,7 @@ fn feather_outside(@builtin(position) position: vec4<f32>) -> @location(0) vec4<
|
|||||||
}
|
}
|
||||||
|
|
||||||
// How much the footprint eroded by `values.x` texels covers each texel, given its distance to the area outside the footprint plus half a texel in `source`,
|
// How much the footprint eroded by `values.x` texels covers each texel, given its distance to the area outside the footprint plus half a texel in `source`,
|
||||||
// relative to its own coverage of the footprint (one less the outside coverage in `secondary`), matching the CPU's `erode`
|
// relative to its own coverage of the footprint (one less the outside coverage in `secondary`)
|
||||||
@fragment
|
@fragment
|
||||||
fn feather_erode(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
fn feather_erode(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||||
let pixel = vec2<i32>(position.xy);
|
let pixel = vec2<i32>(position.xy);
|
||||||
@@ -70,7 +70,7 @@ fn feather_erode(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f3
|
|||||||
return vec4<f32>(select(eroded, min(eroded / coverage, 1.), coverage > 0.));
|
return vec4<f32>(select(eroded, min(eroded / coverage, 1.), coverage > 0.));
|
||||||
}
|
}
|
||||||
|
|
||||||
// The luminance of a masked radius blur's map in `source`, premultiplied, rounded to its 8-bit code to match `masked_radius_blur_code`, or with `values.x` 1 unrounded for a box blur
|
// The luminance of a masked radius blur's map in `source`, premultiplied, rounded to its 8-bit code, or with `values.x` 1 unrounded for a box blur
|
||||||
@fragment
|
@fragment
|
||||||
fn masked_radius_blur_luminance(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
fn masked_radius_blur_luminance(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||||
let map = textureLoad(source, vec2<i32>(position.xy), 0);
|
let map = textureLoad(source, vec2<i32>(position.xy), 0);
|
||||||
@@ -170,7 +170,7 @@ fn continued_span(part: i32, start: i32, end: i32, size: i32) -> vec3<i32> {
|
|||||||
return vec3<i32>(inner_start, inner_end, 1);
|
return vec3<i32>(inner_start, inner_end, 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
// The two channels' counts over the texels from `start` up to `end`, with those past the edges repeating the nearest edge texel, matching the CPU's `counts_continued`
|
// The two channels' counts over the texels from `start` up to `end`, with those past the edges repeating the nearest edge texel
|
||||||
fn counts_continued(start: vec2<i32>, end: vec2<i32>) -> vec2<f32> {
|
fn counts_continued(start: vec2<i32>, end: vec2<i32>) -> vec2<f32> {
|
||||||
let size = vec2<i32>(textureDimensions(content));
|
let size = vec2<i32>(textureDimensions(content));
|
||||||
|
|
||||||
@@ -188,7 +188,7 @@ fn counts_continued(start: vec2<i32>, end: vec2<i32>) -> vec2<f32> {
|
|||||||
return counts;
|
return counts;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Box blurs two channels of each texel by its own half width, the fraction of the radius `values.xy` in texels its luminance in `secondary` gives, matching the CPU's `variable_box_blur`.
|
// Box blurs two channels of each texel by its own half width, the fraction of the radius `values.xy` in texels its luminance in `secondary` gives.
|
||||||
// The first pass (`values.w` 0) blurs red and green, and the second blue and alpha, taking red and green from the first in `source`, encoding to gamma with `amount` 1.
|
// The first pass (`values.w` 0) blurs red and green, and the second blue and alpha, taking red and green from the first in `source`, encoding to gamma with `amount` 1.
|
||||||
// The running sums in `content` count in `values.z` steps, and texels of no luminance keep their color from `source`.
|
// The running sums in `content` count in `values.z` steps, and texels of no luminance keep their color from `source`.
|
||||||
@fragment
|
@fragment
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -10,7 +10,7 @@ fn texel_or_transparent(texel: vec2<i32>) -> vec4<f32> {
|
|||||||
return textureLoad(source, texel, 0);
|
return textureLoad(source, texel, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
// The source at a point in texels, interpolated between the four texel centers around it, with transparency past the edges, matching the CPU's `sample_bilinear`
|
// The source at a point in texels, interpolated between the four texel centers around it, with transparency past the edges
|
||||||
fn sample_bilinear(point: vec2<f32>) -> vec4<f32> {
|
fn sample_bilinear(point: vec2<f32>) -> vec4<f32> {
|
||||||
let position = point - 0.5;
|
let position = point - 0.5;
|
||||||
let base = floor(position);
|
let base = floor(position);
|
||||||
@@ -22,7 +22,7 @@ fn sample_bilinear(point: vec2<f32>) -> vec4<f32> {
|
|||||||
return mix(top, bottom, fraction.y);
|
return mix(top, bottom, fraction.y);
|
||||||
}
|
}
|
||||||
|
|
||||||
// The Keys cubic convolution kernel with a = -0.75, matching the CPU's `keys_cubic`
|
// The Keys cubic convolution kernel with a = -0.75
|
||||||
fn keys_cubic(value: f32) -> f32 {
|
fn keys_cubic(value: f32) -> f32 {
|
||||||
let a = -0.75;
|
let a = -0.75;
|
||||||
let x = abs(value);
|
let x = abs(value);
|
||||||
@@ -143,7 +143,7 @@ fn within_frame(frame: Frame, local: vec2<f32>) -> bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// A radial blur around or through its center, spanning `values.x` (a spin's angle, or a zoom's share of the distance to the center),
|
// A radial blur around or through its center, spanning `values.x` (a spin's angle, or a zoom's share of the distance to the center),
|
||||||
// spinning with `values.y` 0 or zooming with 1, at up to `values.z` texels per unit of its circle's space along an arc, matching the CPU's `radial_blurred`.
|
// spinning with `values.y` 0 or zooming with 1, at up to `values.z` texels per unit of its circle's space along an arc.
|
||||||
// `taps[0..3]` hold the maps from texels into its circle's space, measured from the center, and back.
|
// `taps[0..3]` hold the maps from texels into its circle's space, measured from the center, and back.
|
||||||
@fragment
|
@fragment
|
||||||
fn radial_blur(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
fn radial_blur(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||||
@@ -239,19 +239,19 @@ fn frame_warp_source(local: vec2<f32>, half: vec2<f32>) -> vec2<f32> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Matching `NEGLIGIBLE_COVERAGE` and `UNTOUCHED_COVERAGE`
|
// Frame coverage below the first is roundoff at a side a texel only touches, and below the second counts as none for the reads leaving out what the frame touches
|
||||||
const NEGLIGIBLE_COVERAGE: f32 = 1. / 65536.;
|
const NEGLIGIBLE_COVERAGE: f32 = 1. / 65536.;
|
||||||
const UNTOUCHED_COVERAGE: f32 = 1. / 256.;
|
const UNTOUCHED_COVERAGE: f32 = 1. / 256.;
|
||||||
|
|
||||||
// How much of a texel centered at `local` the frame covers along each axis, ramping from 1 at `half_texel` within a side to 0 at `half_texel` past it, matching the CPU's `frame_coverage`
|
// How much of a texel centered at `local` the frame covers along each axis, ramping from 1 at `half_texel` within a side to 0 at `half_texel` past it
|
||||||
fn frame_coverage(local: vec2<f32>, half: vec2<f32>, half_texel: vec2<f32>) -> vec2<f32> {
|
fn frame_coverage(local: vec2<f32>, half: vec2<f32>, half_texel: vec2<f32>) -> vec2<f32> {
|
||||||
return clamp(0.5 + (half - abs(local)) / (2. * half_texel), vec2<f32>(0.), vec2<f32>(1.));
|
return clamp(0.5 + (half - abs(local)) / (2. * half_texel), vec2<f32>(0.), vec2<f32>(1.));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Matching `CLIPPED_CORNERS`
|
// The most corners a texel clipped by the four sides of a frame can have
|
||||||
const CLIPPED_CORNERS: i32 = 8;
|
const CLIPPED_CORNERS: i32 = 8;
|
||||||
|
|
||||||
// How much of the texel at `texel` (its corner) the frame covers, which reaches `texel_extent` along its sides: the share of its area left after clipping it by each of the frame's sides, matching the CPU's `pixel_area_within`
|
// How much of the texel at `texel` (its corner) the frame covers, which reaches `texel_extent` along its sides: the share of its area left after clipping it by each of the frame's sides
|
||||||
fn texel_area_within(frame: Frame, texel: vec2<f32>, texel_extent: vec2<f32>) -> f32 {
|
fn texel_area_within(frame: Frame, texel: vec2<f32>, texel_extent: vec2<f32>) -> f32 {
|
||||||
let center = transform_point(frame.texels_to_local, texel + 0.5);
|
let center = transform_point(frame.texels_to_local, texel + 0.5);
|
||||||
let half = frame.half_size;
|
let half = frame.half_size;
|
||||||
@@ -309,7 +309,7 @@ fn texel_area_within(frame: Frame, texel: vec2<f32>, texel_extent: vec2<f32>) ->
|
|||||||
return min(abs(twice_area) / 2., 1.);
|
return min(abs(twice_area) / 2., 1.);
|
||||||
}
|
}
|
||||||
|
|
||||||
// The source at a point in texels interpolated as `sample_bilinear` does, with each of the four texels weighted by the share of it the frame covers (see `texel_area_within`), so none the frame misses is read, matching the CPU's `sample_bilinear_within`.
|
// The source at a point in texels interpolated as `sample_bilinear` does, with each of the four texels weighted by the share of it the frame covers (see `texel_area_within`), so none the frame misses is read.
|
||||||
// Where the frame covers none of them, the nearest it covers among the 16 around stands in, the first of those equally near.
|
// Where the frame covers none of them, the nearest it covers among the 16 around stands in, the first of those equally near.
|
||||||
fn sample_bilinear_within(frame: Frame, point: vec2<f32>, texel_extent: vec2<f32>) -> vec4<f32> {
|
fn sample_bilinear_within(frame: Frame, point: vec2<f32>, texel_extent: vec2<f32>) -> vec4<f32> {
|
||||||
let position = point - 0.5;
|
let position = point - 0.5;
|
||||||
@@ -354,7 +354,7 @@ fn sample_bilinear_within(frame: Frame, point: vec2<f32>, texel_extent: vec2<f32
|
|||||||
return nearest;
|
return nearest;
|
||||||
}
|
}
|
||||||
|
|
||||||
// A warp relative to the frame, matching the CPU's `frame_warped`. Twirl, Pinch, and Spherize carry every texel, leaving what lies past their ellipse or band as it is.
|
// A warp relative to the frame. Twirl, Pinch, and Spherize carry every texel, leaving what lies past their ellipse or band as it is.
|
||||||
// Polar Coordinates reads only the texels the frame covers wholly (see `sample_bilinear_on_side`, a texel reaching `taps[4].zw` along its sides and half of one `taps[4].xy`) and clears what lies outside it, fading those its edge cuts through by how much it covers.
|
// Polar Coordinates reads only the texels the frame covers wholly (see `sample_bilinear_on_side`, a texel reaching `taps[4].zw` along its sides and half of one `taps[4].xy`) and clears what lies outside it, fading those its edge cuts through by how much it covers.
|
||||||
@fragment
|
@fragment
|
||||||
fn frame_warp(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
fn frame_warp(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||||
@@ -387,7 +387,7 @@ fn frame_warp(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32>
|
|||||||
var far = near;
|
var far = near;
|
||||||
var toward_far = 0.;
|
var toward_far = 0.;
|
||||||
|
|
||||||
// Wrapping meets the frame's left and right sides at the seam straight up from the center, so it reads across them, matching the CPU's `wrapped_across_sides`
|
// Wrapping meets the frame's left and right sides at the seam straight up from the center, so it reads across them
|
||||||
let wrap = parameters.values.y < 0.5;
|
let wrap = parameters.values.y < 0.5;
|
||||||
if wrap && point.x > high.x {
|
if wrap && point.x > high.x {
|
||||||
far.x = low.x;
|
far.x = low.x;
|
||||||
@@ -406,12 +406,12 @@ fn frame_warp(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32>
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Only wrapping's rim fades, where its source passes the bottom side, matching the CPU
|
// Only wrapping's rim fades, where its source passes the bottom side
|
||||||
let fade = select(1., clamp(0.5 + (half.y - point.y) / (2. * half_texel.y), 0., 1.), wrap);
|
let fade = select(1., clamp(0.5 + (half.y - point.y) / (2. * half_texel.y), 0., 1.), wrap);
|
||||||
return held_at_opaque(read) * fade * coverage;
|
return held_at_opaque(read) * fade * coverage;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Where a texel outside a frame (`half` its size) reads from a `point` in its local space, kept out of the frame: a point within a texel's `extent` of it moves out past its nearest side, that far beyond, matching the CPU's `pushed_out_of_frame`
|
// Where a texel outside a frame (`half` its size) reads from a `point` in its local space, kept out of the frame: a point within a texel's `extent` of it moves out past its nearest side, that far beyond
|
||||||
fn pushed_out_of_frame(point: vec2<f32>, half: vec2<f32>, extent: vec2<f32>) -> vec2<f32> {
|
fn pushed_out_of_frame(point: vec2<f32>, half: vec2<f32>, extent: vec2<f32>) -> vec2<f32> {
|
||||||
let gap = half + extent - abs(point);
|
let gap = half + extent - abs(point);
|
||||||
if any(gap <= vec2<f32>(0.)) {
|
if any(gap <= vec2<f32>(0.)) {
|
||||||
@@ -446,7 +446,7 @@ struct SideRead {
|
|||||||
beside_share: f32,
|
beside_share: f32,
|
||||||
}
|
}
|
||||||
|
|
||||||
// The source at a point in texels interpolated as `sample_bilinear` does, but only between the texels on one side of the frame's edge (see `texel_on_side`), matching the CPU's `sample_bilinear_on_side`.
|
// The source at a point in texels interpolated as `sample_bilinear` does, but only between the texels on one side of the frame's edge (see `texel_on_side`).
|
||||||
// The texels the edge cuts through hold the content's own edge, so they're left out. Where all four are, as at a corner, the nearest texel on that side stands in.
|
// The texels the edge cuts through hold the content's own edge, so they're left out. Where all four are, as at a corner, the nearest texel on that side stands in.
|
||||||
// Content too thin to cover any texel wholly is instead unmixed from what lies past the frame beside it in the texels the frame touches, which the caller takes out by the share this gives.
|
// Content too thin to cover any texel wholly is instead unmixed from what lies past the frame beside it in the texels the frame touches, which the caller takes out by the share this gives.
|
||||||
fn sample_bilinear_on_side(frame: Frame, point: vec2<f32>, texel_extent: vec2<f32>, half_texel: vec2<f32>, within: bool) -> SideRead {
|
fn sample_bilinear_on_side(frame: Frame, point: vec2<f32>, texel_extent: vec2<f32>, half_texel: vec2<f32>, within: bool) -> SideRead {
|
||||||
@@ -506,7 +506,7 @@ fn sample_bilinear_on_side(frame: Frame, point: vec2<f32>, texel_extent: vec2<f3
|
|||||||
return SideRead(bilinear_sum / covered, (touched - covered) / covered);
|
return SideRead(bilinear_sum / covered, (touched - covered) / covered);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Premultiplied channels kept from going negative, scaled down to opaque past it, and with the color held within the alpha, matching the CPU's `held_at_opaque`
|
// Premultiplied channels kept from going negative, scaled down to opaque past it, and with the color held within the alpha
|
||||||
fn held_at_opaque(color: vec4<f32>) -> vec4<f32> {
|
fn held_at_opaque(color: vec4<f32>) -> vec4<f32> {
|
||||||
let kept = max(color, vec4<f32>(0.));
|
let kept = max(color, vec4<f32>(0.));
|
||||||
let scaled = kept / max(kept.a, 1.);
|
let scaled = kept / max(kept.a, 1.);
|
||||||
@@ -578,7 +578,7 @@ fn displacement_at(texel: vec2<i32>, local: vec2<f32>) -> vec2<f32> {
|
|||||||
return field_displacement(local);
|
return field_displacement(local);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Moves each texel by a displacement, reading past the frame by the edge mode `values.z` (0 pad, 1 reflect, 2 repeat, 3 clear, a texel reaching `taps[4].zw` along the frame's sides and half of one `taps[4].xy`), matching the CPU's `displaced`.
|
// Moves each texel by a displacement, reading past the frame by the edge mode `values.z` (0 pad, 1 reflect, 2 repeat, 3 clear, a texel reaching `taps[4].zw` along the frame's sides and half of one `taps[4].xy`).
|
||||||
// The modes that keep the content within the frame keep what lies outside it there too, moved by the same displacement, and mix the texels the frame's edge cuts through by how much of them it covers.
|
// The modes that keep the content within the frame keep what lies outside it there too, moved by the same displacement, and mix the texels the frame's edge cuts through by how much of them it covers.
|
||||||
@fragment
|
@fragment
|
||||||
fn displace(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
fn displace(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||||
@@ -613,7 +613,7 @@ fn displace(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
|||||||
far = near;
|
far = near;
|
||||||
}
|
}
|
||||||
if mode == 2u {
|
if mode == 2u {
|
||||||
// Within a texel's extent of a side, a wrapped source mixes the texels just inside it with those just inside the opposite side, matching the CPU's `wrapped_across_sides`
|
// Within a texel's extent of a side, a wrapped source mixes the texels just inside it with those just inside the opposite side
|
||||||
let wrapped = point + half - floor((point + half) / (2. * half)) * (2. * half) - half;
|
let wrapped = point + half - floor((point + half) / (2. * half)) * (2. * half) - half;
|
||||||
let above = wrapped > high;
|
let above = wrapped > high;
|
||||||
let below = wrapped < low;
|
let below = wrapped < low;
|
||||||
@@ -652,16 +652,16 @@ fn displace(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
|||||||
// The most texels a pixelation tests one by one for one of its cells or dots, matching `MAX_AVERAGED_PIXELS`
|
// The most texels a pixelation tests one by one for one of its cells or dots, matching `MAX_AVERAGED_PIXELS`
|
||||||
const MAX_AVERAGED_TEXELS: f32 = 65536.;
|
const MAX_AVERAGED_TEXELS: f32 = 65536.;
|
||||||
|
|
||||||
// How many texels from the texture's origin a pixelation's averaging scans at most along each axis, matching `MAX_AVERAGED_PIXEL_COORDINATE`
|
// How many texels from the texture's origin a pixelation's averaging scans at most along each axis, past which single-precision texel centers aren't exact
|
||||||
const MAX_AVERAGED_TEXEL_COORDINATE: f32 = 16777216.;
|
const MAX_AVERAGED_TEXEL_COORDINATE: f32 = 16777216.;
|
||||||
|
|
||||||
// How many rows past the texture's top and bottom an average counts one by one, matching `MAX_COUNTED_ROWS`
|
// How many rows past the texture's top and bottom an average counts one by one, past which each it counts stands for those beside it
|
||||||
const MAX_COUNTED_ROWS: i32 = 4096;
|
const MAX_COUNTED_ROWS: i32 = 4096;
|
||||||
|
|
||||||
// How many columns past the ends of a run, found from bounds in the frame's local space, its test may still accept, matching the CPU's `RUN_SLACK`
|
// How many columns past the ends of a run, found from bounds in the frame's local space, its test may still accept
|
||||||
const RUN_SLACK: i32 = 2;
|
const RUN_SLACK: i32 = 2;
|
||||||
|
|
||||||
// How far the bounds a run is found from grow, in texels along the frame's sides, matching the CPU's `RUN_BOUNDS_SLACK`
|
// How far the bounds a run is found from grow, in texels along the frame's sides
|
||||||
const RUN_BOUNDS_SLACK: f32 = 1. / 8.;
|
const RUN_BOUNDS_SLACK: f32 = 1. / 8.;
|
||||||
|
|
||||||
// Matching `HALFTONE_SNAP_NUDGE` and `HALFTONE_RADIUS_ITERATIONS`
|
// Matching `HALFTONE_SNAP_NUDGE` and `HALFTONE_RADIUS_ITERATIONS`
|
||||||
@@ -784,13 +784,13 @@ fn columns_within_axis(columns: vec2<f32>, start: f32, step: f32, low: f32, high
|
|||||||
return vec2<f32>(max(columns.x, min(a, b)), min(columns.y, max(a, b)));
|
return vec2<f32>(max(columns.x, min(a, b)), min(columns.y, max(a, b)));
|
||||||
}
|
}
|
||||||
|
|
||||||
// The columns, as reals, at which a row of texels with centers at `start` plus each column times `step` in the frame's local space lies in the rectangle from `low` to `high` there, matching the CPU's `columns_within`
|
// The columns, as reals, at which a row of texels with centers at `start` plus each column times `step` in the frame's local space lies in the rectangle from `low` to `high` there
|
||||||
fn columns_within(start: vec2<f32>, step: vec2<f32>, low: vec2<f32>, high: vec2<f32>) -> vec2<f32> {
|
fn columns_within(start: vec2<f32>, step: vec2<f32>, low: vec2<f32>, high: vec2<f32>) -> vec2<f32> {
|
||||||
let columns = columns_within_axis(-EMPTY_COLUMNS, start.x, step.x, low.x, high.x);
|
let columns = columns_within_axis(-EMPTY_COLUMNS, start.x, step.x, low.x, high.x);
|
||||||
return columns_within_axis(columns, start.y, step.y, low.y, high.y);
|
return columns_within_axis(columns, start.y, step.y, low.y, high.y);
|
||||||
}
|
}
|
||||||
|
|
||||||
// The columns at which a row of texels lies within bounds grown by the slack, and whether it's `marginal`, lying within them only by that slack, matching the CPU's `average_by_rows`
|
// The columns at which a row of texels lies within bounds grown by the slack, and whether it's `marginal`, lying within them only by that slack
|
||||||
struct RowEstimate {
|
struct RowEstimate {
|
||||||
columns: vec2<f32>,
|
columns: vec2<f32>,
|
||||||
marginal: bool,
|
marginal: bool,
|
||||||
@@ -802,8 +802,8 @@ fn row_estimate(start: vec2<f32>, step: vec2<f32>, low: vec2<f32>, high: vec2<f3
|
|||||||
return RowEstimate(columns_within(start, step, low - slack, high + slack), shrunk.x > shrunk.y);
|
return RowEstimate(columns_within(start, step, low - slack, high + slack), shrunk.x > shrunk.y);
|
||||||
}
|
}
|
||||||
|
|
||||||
// The first and last columns from `bounds.x` to `bounds.y` of row `y` in the `kind` of run, which lie within `RUN_SLACK` of the `estimate`'s ends, or a first past the last where none do,
|
// The first and last columns from `bounds.x` to `bounds.y` of row `y` in the `kind` of run, which lie within `RUN_SLACK` of the `estimate`'s ends, or a first past the last where none do.
|
||||||
// matching the CPU's `settled_run`. A marginal row holds a run reaching an end of the estimate if any, so only the columns near its ends are searched.
|
// A marginal row holds a run reaching an end of the estimate if any, so only the columns near its ends are searched.
|
||||||
fn settled_run(frame: Frame, test: RegionTest, y: i32, estimate: RowEstimate, bounds: vec2<i32>, kind: u32) -> vec2<i32> {
|
fn settled_run(frame: Frame, test: RegionTest, y: i32, estimate: RowEstimate, bounds: vec2<i32>, kind: u32) -> vec2<i32> {
|
||||||
let reach = vec2<f32>(f32(bounds.x - RUN_SLACK), f32(bounds.y + RUN_SLACK));
|
let reach = vec2<f32>(f32(bounds.x - RUN_SLACK), f32(bounds.y + RUN_SLACK));
|
||||||
let search_start = max(i32(clamp(ceil(estimate.columns.x), reach.x, reach.y)) - RUN_SLACK, bounds.x);
|
let search_start = max(i32(clamp(ceil(estimate.columns.x), reach.x, reach.y)) - RUN_SLACK, bounds.x);
|
||||||
@@ -872,7 +872,7 @@ fn run_sum(y: i32, run: vec2<i32>) -> vec4<f32> {
|
|||||||
return sum;
|
return sum;
|
||||||
}
|
}
|
||||||
|
|
||||||
// The `index`th row an average counts of those from `rows.x` to `rows.y`, and how many rows it stands for, matching the CPU's `averaged_rows`:
|
// The `index`th row an average counts of those from `rows.x` to `rows.y`, and how many rows it stands for:
|
||||||
// rows above a texture `height` tall in groups of `group`, then its own rows, then rows below in groups, each group standing in by its middle row
|
// rows above a texture `height` tall in groups of `group`, then its own rows, then rows below in groups, each group standing in by its middle row
|
||||||
fn averaged_row(index: i32, rows: vec2<i32>, height: i32, group: i32) -> vec2<i32> {
|
fn averaged_row(index: i32, rows: vec2<i32>, height: i32, group: i32) -> vec2<i32> {
|
||||||
let before = vec2<i32>(rows.x, min(rows.y, -1));
|
let before = vec2<i32>(rows.x, min(rows.y, -1));
|
||||||
@@ -894,7 +894,7 @@ fn averaged_row(index: i32, rows: vec2<i32>, height: i32, group: i32) -> vec2<i3
|
|||||||
return vec2<i32>(top + (count - 1) / 2, count);
|
return vec2<i32>(top + (count - 1) / 2, count);
|
||||||
}
|
}
|
||||||
|
|
||||||
// The average `region_average` takes over a region spanning too many texels to test one by one, from `start` to `end`, from the running sums along each row in `content`, matching the CPU's `average_by_rows`.
|
// The average `region_average` takes over a region spanning too many texels to test one by one, from `start` to `end`, from the running sums along each row in `content`.
|
||||||
// Each row's run of the texels it counts is found from the bounds of the region (from `low` to `high` in the frame's local space) and of the frame along it, settled by the test at its ends.
|
// Each row's run of the texels it counts is found from the bounds of the region (from `low` to `high` in the frame's local space) and of the frame along it, settled by the test at its ends.
|
||||||
fn region_average_by_rows(frame: Frame, low: vec2<f32>, high: vec2<f32>, test: RegionTest, start: vec2<i32>, end: vec2<i32>) -> vec4<f32> {
|
fn region_average_by_rows(frame: Frame, low: vec2<f32>, high: vec2<f32>, test: RegionTest, start: vec2<i32>, end: vec2<i32>) -> vec4<f32> {
|
||||||
let height = i32(textureDimensions(source).y);
|
let height = i32(textureDimensions(source).y);
|
||||||
@@ -980,8 +980,8 @@ fn averaged_row_count(rows: vec2<i32>, height: i32, group: i32) -> i32 {
|
|||||||
return (before + group - 1) / group + within + (after + group - 1) / group;
|
return (before + group - 1) / group + within + (after + group - 1) / group;
|
||||||
}
|
}
|
||||||
|
|
||||||
// The average of the source's texels in the rectangle `size` across at `corner` in the frame's local space that `test` counts, with those past the texture's edges transparent, or -1 without any,
|
// The average of the source's texels in the rectangle `size` across at `corner` in the frame's local space that `test` counts, with those past the texture's edges transparent, or -1 without any.
|
||||||
// matching the CPU's `average_on_side`. Those the frame's edge cuts through count for the share of each it covers.
|
// Those the frame's edge cuts through count for the share of each it covers.
|
||||||
// A region spanning too many texels to test one by one sums each row's run of them, where `taps[15].x` says `content` holds the running sums along each row.
|
// A region spanning too many texels to test one by one sums each row's run of them, where `taps[15].x` says `content` holds the running sums along each row.
|
||||||
fn region_average(frame: Frame, corner: vec2<f32>, size: vec2<f32>, test: RegionTest) -> vec4<f32> {
|
fn region_average(frame: Frame, corner: vec2<f32>, size: vec2<f32>, test: RegionTest) -> vec4<f32> {
|
||||||
let region = rectangle_to_texels(frame, corner, size);
|
let region = rectangle_to_texels(frame, corner, size);
|
||||||
@@ -1026,7 +1026,7 @@ fn region_average(frame: Frame, corner: vec2<f32>, size: vec2<f32>, test: Region
|
|||||||
cut_sum += row_cut_sum;
|
cut_sum += row_cut_sum;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Over the summed shares, or the summed alpha where that's more, matching the CPU's `region_average`
|
// Over the summed shares, or the summed alpha where that's more
|
||||||
if count > 0. {
|
if count > 0. {
|
||||||
return sum / max(count, sum.a);
|
return sum / max(count, sum.a);
|
||||||
}
|
}
|
||||||
@@ -1046,9 +1046,9 @@ fn table_texel(entry: u32, width: u32) -> vec2<i32> {
|
|||||||
return vec2<i32>(vec2<u32>(entry % width, entry / width));
|
return vec2<i32>(vec2<u32>(entry % width, entry / width));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Each texel the average of a cell of Pixelate's grid (or -1 without any of its texels sampled), matching the CPU's `pixelated`.
|
// Each texel the average of a cell of Pixelate's grid (or -1 without any of its texels sampled).
|
||||||
// The table holds `taps[6].x` cells across and `taps[6].y` down from the cell `values.yz`, a row after another along rows `taps[6].z` texels across.
|
// The table holds `taps[6].x` cells across and `taps[6].y` down from the cell `values.yz`, a row after another along rows `taps[6].z` texels across.
|
||||||
// The cells the frame's sides cut end or start at those sides, matching the CPU's `PixelateCells::to_pixels`.
|
// The cells the frame's sides cut end or start at those sides.
|
||||||
@fragment
|
@fragment
|
||||||
fn pixelate_cells(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
fn pixelate_cells(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||||
let frame = frame_parameters();
|
let frame = frame_parameters();
|
||||||
@@ -1087,7 +1087,7 @@ fn pixelate_average(frame: Frame, local: vec2<f32>, original: vec4<f32>) -> vec4
|
|||||||
// Matching `f64::next_up` closely enough for a point mirrored out past the frame's side to land past it
|
// Matching `f64::next_up` closely enough for a point mirrored out past the frame's side to land past it
|
||||||
const PAST_SIDE: f32 = 1.0000005;
|
const PAST_SIDE: f32 = 1.0000005;
|
||||||
|
|
||||||
// A point in the local space of a frame (`half` its size) mirrored across the sides it lies within `half_texel` inside of, matching the CPU's `mirrored_outside`
|
// A point in the local space of a frame (`half` its size) mirrored across the sides it lies within `half_texel` inside of
|
||||||
fn mirrored_outside(local: vec2<f32>, half: vec2<f32>, half_texel: vec2<f32>) -> vec2<f32> {
|
fn mirrored_outside(local: vec2<f32>, half: vec2<f32>, half_texel: vec2<f32>) -> vec2<f32> {
|
||||||
if any(abs(local) > half) {
|
if any(abs(local) > half) {
|
||||||
return local;
|
return local;
|
||||||
@@ -1109,7 +1109,7 @@ fn pixelate(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
|||||||
|
|
||||||
var outside = vec4<f32>(0.);
|
var outside = vec4<f32>(0.);
|
||||||
if coverage < 1. {
|
if coverage < 1. {
|
||||||
// Without a texel of its cell sampled, what's left of the texel's color beyond its share within the frame, matching the CPU's `pixelated`
|
// Without a texel of its cell sampled, what's left of the texel's color beyond its share within the frame
|
||||||
var own_past = original;
|
var own_past = original;
|
||||||
if coverage >= NEGLIGIBLE_COVERAGE {
|
if coverage >= NEGLIGIBLE_COVERAGE {
|
||||||
own_past = original * (1. - coverage / max(coverage, original.a)) / (1. - coverage);
|
own_past = original * (1. - coverage / max(coverage, original.a)) / (1. - coverage);
|
||||||
@@ -1278,7 +1278,7 @@ fn halftone_entry(channel: i32, cell: vec2<i32>) -> u32 {
|
|||||||
return (u32(channel) * u32(parameters.taps[14].z) + u32(cell.y)) * u32(parameters.values.z) + u32(cell.x);
|
return (u32(channel) * u32(parameters.taps[14].z) + u32(cell.y)) * u32(parameters.values.z) + u32(cell.x);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Each texel one cell of a channel's table of dots, along rows `taps[14].w` texels across in the order `halftone_entry` gives, matching the CPU's `halftoned`.
|
// Each texel one cell of a channel's table of dots, along rows `taps[14].w` texels across in the order `halftone_entry` gives.
|
||||||
// It holds the dot's center offset from its lattice point, or for a whole unit the dots snap to together, how many do (xy), then its radii within the frame (z) and past it (w) as shares of the lattice's side.
|
// It holds the dot's center offset from its lattice point, or for a whole unit the dots snap to together, how many do (xy), then its radii within the frame (z) and past it (w) as shares of the lattice's side.
|
||||||
@fragment
|
@fragment
|
||||||
fn halftone_dots(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
fn halftone_dots(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||||
@@ -1326,14 +1326,14 @@ fn halftone_dots(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f3
|
|||||||
return vec4<f32>(held, halftone_dot_radius(1. - within, side) / side, halftone_dot_radius(1. - past, side) / side);
|
return vec4<f32>(held, halftone_dot_radius(1. - within, side) / side, halftone_dot_radius(1. - past, side) / side);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Each texel printed as the tone a halftone's dots average to, each channel over white and kept at its alpha, matching the CPU's `halftone_tone`
|
// Each texel printed as the tone a halftone's dots average to, each channel over white and kept at its alpha
|
||||||
@fragment
|
@fragment
|
||||||
fn halftone_tone(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
fn halftone_tone(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||||
let pixel = textureLoad(source, vec2<i32>(position.xy), 0);
|
let pixel = textureLoad(source, vec2<i32>(position.xy), 0);
|
||||||
return vec4<f32>((pixel.rgb + 1. - pixel.a) * pixel.a, pixel.a);
|
return vec4<f32>((pixel.rgb + 1. - pixel.a) * pixel.a, pixel.a);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Each texel printed as a white ground with each channel's dots of ink from `content`, keeping its alpha, matching the CPU's `halftoned`.
|
// Each texel printed as a white ground with each channel's dots of ink from `content`, keeping its alpha.
|
||||||
// Texels within the frame take the dots' radii within it, and others those past it, with those the frame's edge cuts through (`taps[7].xy` half a texel along its sides) mixed by how much of them it covers.
|
// Texels within the frame take the dots' radii within it, and others those past it, with those the frame's edge cuts through (`taps[7].xy` half a texel along its sides) mixed by how much of them it covers.
|
||||||
@fragment
|
@fragment
|
||||||
fn halftone(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
fn halftone(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||||
@@ -1393,7 +1393,7 @@ fn halftone_white(frame: Frame, local: vec2<f32>, side: i32) -> vec3<f32> {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// A dot smaller than a subsample covers no more of it than its own area, matching the CPU
|
// A dot smaller than a subsample covers no more of it than its own area
|
||||||
let most = PI * radius * radius / (subsample_width * subsample_width);
|
let most = PI * radius * radius / (subsample_width * subsample_width);
|
||||||
var inked = 0.;
|
var inked = 0.;
|
||||||
for (var down = 0; down < HALFTONE_SUBSAMPLES; down++) {
|
for (var down = 0; down < HALFTONE_SUBSAMPLES; down++) {
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ fn paint_band(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32>
|
|||||||
}
|
}
|
||||||
|
|
||||||
// The band's coverage (`content`) of the gradient `secondary` holds in a row of straight colors from its start to its end, at each texel's place across the outline (`source`),
|
// The band's coverage (`content`) of the gradient `secondary` holds in a row of straight colors from its start to its end, at each texel's place across the outline (`source`),
|
||||||
// faded by the opacity `amount`, matching the CPU's `contour_gradient_colors`
|
// faded by the opacity `amount`
|
||||||
@fragment
|
@fragment
|
||||||
fn contour_gradient_band(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
fn contour_gradient_band(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||||
let pixel = vec2<i32>(position.xy);
|
let pixel = vec2<i32>(position.xy);
|
||||||
@@ -49,7 +49,7 @@ fn contour_gradient_band(@builtin(position) position: vec4<f32>) -> @location(0)
|
|||||||
return vec4<f32>(color.rgb * alpha, alpha);
|
return vec4<f32>(color.rgb * alpha, alpha);
|
||||||
}
|
}
|
||||||
|
|
||||||
// A texture's value at `offset` from `pixel` toward its right and lower neighbors, interpolated between them and holding the edge texels beyond the edges, matching the CPU's `sample_between`
|
// A texture's value at `offset` from `pixel` toward its right and lower neighbors, interpolated between them and holding the edge texels beyond the edges
|
||||||
fn texel_between(texture: texture_2d<f32>, pixel: vec2<i32>, offset: vec2<f32>) -> vec4<f32> {
|
fn texel_between(texture: texture_2d<f32>, pixel: vec2<i32>, offset: vec2<f32>) -> vec4<f32> {
|
||||||
let last = vec2<i32>(textureDimensions(texture)) - 1;
|
let last = vec2<i32>(textureDimensions(texture)) - 1;
|
||||||
if all(offset == vec2<f32>(0.)) {
|
if all(offset == vec2<f32>(0.)) {
|
||||||
@@ -62,7 +62,6 @@ fn texel_between(texture: texture_2d<f32>, pixel: vec2<i32>, offset: vec2<f32>)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// A bevel's surface in units of its span at `offset` from `pixel`, from its height (`source`, centered on the edge) reshaped by the contour, if `taps[1].x` is 1, then sunk by the texture's gray.
|
// A bevel's surface in units of its span at `offset` from `pixel`, from its height (`source`, centered on the edge) reshaped by the contour, if `taps[1].x` is 1, then sunk by the texture's gray.
|
||||||
// Matches the CPU's `bevel_shading`.
|
|
||||||
// The contour, a row in `secondary`, spans the range `taps[0].y` down from an inner bevel's top (`taps[0].x` 0), up from an outer bevel's foot (1), or an emboss's whole slope (2), continued past its ends along the slopes `taps[0].zw`.
|
// The contour, a row in `secondary`, spans the range `taps[0].y` down from an inner bevel's top (`taps[0].x` 0), up from an outer bevel's foot (1), or an emboss's whole slope (2), continued past its ends along the slopes `taps[0].zw`.
|
||||||
// The texture is the premultiplied `content`, sinking the surface by its gray times `taps[1].z`.
|
// The texture is the premultiplied `content`, sinking the surface by its gray times `taps[1].z`.
|
||||||
fn bevel_surface_at(pixel: vec2<i32>, offset: vec2<f32>) -> f32 {
|
fn bevel_surface_at(pixel: vec2<i32>, offset: vec2<f32>) -> f32 {
|
||||||
@@ -95,7 +94,7 @@ fn bevel_surface_at(pixel: vec2<i32>, offset: vec2<f32>) -> f32 {
|
|||||||
return surface - parameters.taps[1].z * dot(texture, vec3<f32>(0.299, 0.587, 0.114));
|
return surface - parameters.taps[1].z * dot(texture, vec3<f32>(0.299, 0.587, 0.114));
|
||||||
}
|
}
|
||||||
|
|
||||||
// How much brighter than flat ground the light toward `values.xyz` lights a bevel's surface rising `values.w` texels for each unit, negative where darker, matching the CPU's `bevel_shading`.
|
// How much brighter than flat ground the light toward `values.xyz` lights a bevel's surface rising `values.w` texels for each unit, negative where darker.
|
||||||
// Its slope is the difference across a texel's neighbors averaged over three rows or columns, and with `taps[1].y` 1 the contour's nine samples toward the right and lower neighbors are averaged.
|
// Its slope is the difference across a texel's neighbors averaged over three rows or columns, and with `taps[1].y` 1 the contour's nine samples toward the right and lower neighbors are averaged.
|
||||||
// With `taps[1].w` 1 or 2, it's instead the highlight or shadow that makes, for a bevel with no gloss contour or fade at the foot.
|
// With `taps[1].w` 1 or 2, it's instead the highlight or shadow that makes, for a bevel with no gloss contour or fade at the foot.
|
||||||
@fragment
|
@fragment
|
||||||
@@ -141,7 +140,7 @@ fn bevel_amount_of(brighter: f32, light_z: f32, shadow: bool) -> f32 {
|
|||||||
return select(0., clamp(brighter / (1. - light_z), 0., 1.), light_z < 1.);
|
return select(0., clamp(brighter / (1. - light_z), 0., 1.), light_z < 1.);
|
||||||
}
|
}
|
||||||
|
|
||||||
// A bevel's highlight, or with `values.w` 1 its shadow, from how much brighter than a flat surface's brightness `values.x` it's lit (`source`), matching the CPU's `bevel_shading`.
|
// A bevel's highlight, or with `values.w` 1 its shadow, from how much brighter than a flat surface's brightness `values.x` it's lit (`source`).
|
||||||
// With `values.y` 1, the gloss contour `secondary` holds in a row reshapes how lit it is first, averaged over nine samples toward the right and lower neighbors with `values.z` 1.
|
// With `values.y` 1, the gloss contour `secondary` holds in a row reshapes how lit it is first, averaged over nine samples toward the right and lower neighbors with `values.z` 1.
|
||||||
// With `taps[0].x` 1, it reaches no more than the height (`content`, centered on the edge) above the foot divided by `amount`, fading out across the slopes' foot.
|
// With `taps[0].x` 1, it reaches no more than the height (`content`, centered on the edge) above the foot divided by `amount`, fading out across the slopes' foot.
|
||||||
@fragment
|
@fragment
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
// The Warp's pass, drawing the fringe past its square's sides and corners, then each cell of its tessellated patch as two triangles over those before,
|
// The Warp's pass, drawing the fringe past its square's sides and corners, then each cell of its tessellated patch as two triangles over those before, from clear.
|
||||||
// from clear, matching the CPU's `WarpRasterizer`.
|
|
||||||
// Its square lies in `taps[0..5]`, then from `WARP_TAPS` its patch's control points in texels, how far its edge fades across its sides and which sides it reaches, and where its parameters read the content (see `warp_taps`).
|
// Its square lies in `taps[0..5]`, then from `WARP_TAPS` its patch's control points in texels, how far its edge fades across its sides and which sides it reaches, and where its parameters read the content (see `warp_taps`).
|
||||||
|
|
||||||
// Matching `WARP_POLISH_STEPS`
|
// Matching `WARP_POLISH_STEPS`
|
||||||
@@ -325,8 +324,8 @@ fn warp_cell_corner(cell: vec2<u32>, corner: u32) -> vec2<u32> {
|
|||||||
return cell + vec2<u32>(select(0u, 1u, corner == 1u || corner == 2u || corner == 4u), select(0u, 1u, corner == 2u || corner == 4u || corner == 5u));
|
return cell + vec2<u32>(select(0u, 1u, corner == 1u || corner == 2u || corner == 4u), select(0u, 1u, corner == 2u || corner == 4u || corner == 5u));
|
||||||
}
|
}
|
||||||
|
|
||||||
// The fringe's quads along the left, right, top, and bottom sides, then past the corners where both sides meet, then each cell's two triangles, cell by cell across each row and row by row down,
|
// The fringe's quads along the left, right, top, and bottom sides, then past the corners where both sides meet, then each cell's two triangles, cell by cell across each row and row by row down.
|
||||||
// matching the CPU's `WarpRasterizer`. The first instance draws the fringe and the triangles wound as the square is (`values.x` its orientation's sign), and the second draws those turned over, on top.
|
// The first instance draws the fringe and the triangles wound as the square is (`values.x` its orientation's sign), and the second draws those turned over, on top.
|
||||||
@vertex
|
@vertex
|
||||||
fn warp_vertex(@builtin(vertex_index) index: u32, @builtin(instance_index) instance: u32) -> WarpVertex {
|
fn warp_vertex(@builtin(vertex_index) index: u32, @builtin(instance_index) instance: u32) -> WarpVertex {
|
||||||
let cells = vec2<u32>(parameters.taps[WARP_TAPS + 10u].zw);
|
let cells = vec2<u32>(parameters.taps[WARP_TAPS + 10u].zw);
|
||||||
|
|||||||
@@ -31,3 +31,10 @@ glam = { workspace = true }
|
|||||||
|
|
||||||
# Optional workspace dependencies
|
# Optional workspace dependencies
|
||||||
serde = { workspace = true, optional = true }
|
serde = { workspace = true, optional = true }
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
# Local dependencies
|
||||||
|
wgpu-executor = { workspace = true }
|
||||||
|
|
||||||
|
# Workspace dependencies
|
||||||
|
futures = { workspace = true }
|
||||||
@@ -683,7 +683,7 @@ mod test {
|
|||||||
use core_types::list::{ATTR_EFFECTS, Item};
|
use core_types::list::{ATTR_EFFECTS, Item};
|
||||||
use core_types::{ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_START_CURVATURE, ATTR_TRANSFORM, Color};
|
use core_types::{ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_START_CURVATURE, ATTR_TRANSFORM, Color};
|
||||||
use glam::{DAffine2, DVec2};
|
use glam::{DAffine2, DVec2};
|
||||||
use graphic_types::raster_types::{Image, Raster};
|
use graphic_types::raster_types::{CPU, Image, Raster};
|
||||||
use graphic_types::{Effects, Graphic};
|
use graphic_types::{Effects, Graphic};
|
||||||
use vector_types::{Gradient, GradientForm};
|
use vector_types::{Gradient, GradientForm};
|
||||||
|
|
||||||
@@ -731,6 +731,13 @@ mod test {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The single pixel of the raster `item` with its effects carried out on the GPU and read back, or `None` without a GPU.
|
||||||
|
fn rendered_pixel(item: Item<Raster<CPU>>) -> Option<Color> {
|
||||||
|
let executor = futures::executor::block_on(wgpu_executor::WgpuExecutor::for_tests())?;
|
||||||
|
let rendered = futures::executor::block_on(executor.read_back(item)).expect("the effects render");
|
||||||
|
Some(rendered.element().data[0])
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn paint_overlay_multiplies_a_color_into_the_content() {
|
fn paint_overlay_multiplies_a_color_into_the_content() {
|
||||||
let image_color = Color::from_rgbaf32_unchecked(0.7, 0.6, 0.5, 0.4);
|
let image_color = Color::from_rgbaf32_unchecked(0.7, 0.6, 0.5, 0.4);
|
||||||
@@ -745,11 +752,11 @@ mod test {
|
|||||||
false.into(),
|
false.into(),
|
||||||
DAffine2::IDENTITY.into(),
|
DAffine2::IDENTITY.into(),
|
||||||
);
|
);
|
||||||
let result = raster_kernels::evaluate_raster_effects(result).into_element();
|
let Some(color) = rendered_pixel(result) else { return };
|
||||||
|
|
||||||
// Multiplying by green keeps only the green channel. It blends within the content's share, so the translucent content keeps its own alpha.
|
// Multiplying by green keeps only the green channel. It blends within the content's share, so the translucent content keeps its own alpha.
|
||||||
let expected = Color::from_rgbaf32_unchecked(0., image_color.g(), 0., image_color.a());
|
let expected = Color::from_rgbaf32_unchecked(0., image_color.g(), 0., image_color.a());
|
||||||
assert!((result.data[0].to_vec4() - expected.to_vec4()).abs().max_element() < 1e-4, "{:?} against {expected:?}", result.data[0]);
|
assert!((color.to_vec4() - expected.to_vec4()).abs().max_element() < 0.01, "{color:?} against {expected:?}");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -766,7 +773,7 @@ mod test {
|
|||||||
false.into(),
|
false.into(),
|
||||||
DAffine2::IDENTITY.into(),
|
DAffine2::IDENTITY.into(),
|
||||||
);
|
);
|
||||||
let color = raster_kernels::evaluate_raster_effects(result).into_element().data[0];
|
let Some(color) = rendered_pixel(result) else { return };
|
||||||
|
|
||||||
assert!(color.r() > 0.05 && color.r() < 0.95, "half the black paint leaves {color:?}");
|
assert!(color.r() > 0.05 && color.r() < 0.95, "half the black paint leaves {color:?}");
|
||||||
}
|
}
|
||||||
@@ -1019,7 +1026,7 @@ mod test {
|
|||||||
false.into(),
|
false.into(),
|
||||||
DAffine2::IDENTITY.into(),
|
DAffine2::IDENTITY.into(),
|
||||||
);
|
);
|
||||||
let color = raster_kernels::evaluate_raster_effects(result).into_element().data[0];
|
let Some(color) = rendered_pixel(result) else { return };
|
||||||
|
|
||||||
assert!(color.r() > 0.99, "the hidden black paint leaves {color:?}");
|
assert!(color.r() > 0.99, "the hidden black paint leaves {color:?}");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -97,9 +97,15 @@ fn feather<T>(
|
|||||||
mod test {
|
mod test {
|
||||||
use core_types::Color;
|
use core_types::Color;
|
||||||
use core_types::list::{Item, List};
|
use core_types::list::{Item, List};
|
||||||
use graphic_types::raster_types::{Image, Raster};
|
use graphic_types::raster_types::{CPU, Image, Pixels, Raster};
|
||||||
use graphic_types::{Graphic, MaskMode};
|
use graphic_types::{Graphic, MaskMode};
|
||||||
|
|
||||||
|
/// The GPU's render of the raster `item` with its effects carried out, read back, or `None` without a GPU.
|
||||||
|
fn rendered(item: Item<Raster<CPU>>) -> Option<Item<Pixels>> {
|
||||||
|
let executor = futures::executor::block_on(wgpu_executor::WgpuExecutor::for_tests())?;
|
||||||
|
Some(futures::executor::block_on(executor.read_back(item)).expect("the effects render"))
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_gray_luminance_mask_shows_the_content_at_its_gray_level() {
|
fn a_gray_luminance_mask_shows_the_content_at_its_gray_level() {
|
||||||
let content = Item::new_from_element(Raster::new_cpu(Image::new(1, 1, Color::WHITE)));
|
let content = Item::new_from_element(Raster::new_cpu(Image::new(1, 1, Color::WHITE)));
|
||||||
@@ -115,15 +121,24 @@ mod test {
|
|||||||
0_f64.into(),
|
0_f64.into(),
|
||||||
invert.into(),
|
invert.into(),
|
||||||
);
|
);
|
||||||
raster_kernels::evaluate_raster_effects(result).into_element().data[0].a()
|
rendered(result).map(|rendered| rendered.element().data[0].a())
|
||||||
};
|
};
|
||||||
|
|
||||||
// Luminance is taken on gamma-encoded channels, so a middle gray shows half the content, as a PSD mask's gray level does
|
// Luminance is taken on gamma-encoded channels, so a middle gray shows half the content, as a PSD mask's gray level does
|
||||||
assert!((masked(MaskMode::Luminance, 100., false) - 0.5).abs() < 1e-3);
|
let cases = [
|
||||||
assert!((masked(MaskMode::Luminance, 100., true) - 0.5).abs() < 1e-3);
|
(MaskMode::Luminance, 100., false, 0.5),
|
||||||
assert!((masked(MaskMode::Luminance, 50., false) - 0.75).abs() < 1e-3, "half the density hides half as much");
|
(MaskMode::Luminance, 100., true, 0.5),
|
||||||
assert!((masked(MaskMode::Alpha, 100., false) - 1.).abs() < 1e-6, "an opaque mask shows everything by its alpha");
|
(MaskMode::Luminance, 50., false, 0.75),
|
||||||
assert!(masked(MaskMode::Alpha, 100., true) < 1e-6);
|
(MaskMode::Alpha, 100., false, 1.),
|
||||||
|
(MaskMode::Alpha, 100., true, 0.),
|
||||||
|
];
|
||||||
|
for (mode, density, invert, expected) in cases {
|
||||||
|
let Some(alpha) = masked(mode, density, invert) else { return };
|
||||||
|
assert!(
|
||||||
|
(alpha - expected).abs() < 0.005,
|
||||||
|
"{mode:?} at a density of {density} (inverted: {invert}) shows {alpha} rather than {expected}"
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -156,7 +171,8 @@ mod test {
|
|||||||
let mirror = DAffine2::from_translation(DVec2::new(4., 0.)) * DAffine2::from_scale(DVec2::new(-1., 1.));
|
let mirror = DAffine2::from_translation(DVec2::new(4., 0.)) * DAffine2::from_scale(DVec2::new(-1., 1.));
|
||||||
masked.set_attribute(ATTR_TRANSFORM, mirror * placement);
|
masked.set_attribute(ATTR_TRANSFORM, mirror * placement);
|
||||||
|
|
||||||
let alphas: Vec<f32> = raster_kernels::evaluate_raster_effects(masked).into_element().data.iter().map(|color| color.a().round()).collect();
|
let Some(rendered) = rendered(masked) else { return };
|
||||||
|
let alphas: Vec<f32> = rendered.element().data.iter().map(|color| color.a().round()).collect();
|
||||||
assert_eq!(alphas, [0., 0., 1., 1.], "the mask hides the half of the image it covered before the transform");
|
assert_eq!(alphas, [0., 0., 1., 1.], "the mask hides the half of the image it covered before the transform");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
use core_types::list::{Item, List};
|
use core_types::list::{Item, List};
|
||||||
use core_types::transform::Footprint;
|
|
||||||
use core_types::{CacheHash, CloneVarArgs, Color, Context, Ctx, ExtractAll, ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime, Interrupt, OwnedContextImpl};
|
use core_types::{CacheHash, CloneVarArgs, Color, Context, Ctx, ExtractAll, ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime, Interrupt, OwnedContextImpl};
|
||||||
use glam::{DAffine2, DVec2};
|
use glam::{DAffine2, DVec2};
|
||||||
use graphene_animation::AnimationCurve;
|
use graphene_animation::AnimationCurve;
|
||||||
@@ -82,7 +81,6 @@ fn step_real_time<T>(
|
|||||||
Context -> Item<f64>,
|
Context -> Item<f64>,
|
||||||
Context -> Item<String>,
|
Context -> Item<String>,
|
||||||
Context -> Item<DAffine2>,
|
Context -> Item<DAffine2>,
|
||||||
Context -> Item<Footprint>,
|
|
||||||
Context -> Item<DVec2>,
|
Context -> Item<DVec2>,
|
||||||
Context -> Item<Vector>,
|
Context -> Item<Vector>,
|
||||||
Context -> Item<Graphic>,
|
Context -> Item<Graphic>,
|
||||||
@@ -130,7 +128,6 @@ fn step_animation_time<T>(
|
|||||||
Context -> Item<f64>,
|
Context -> Item<f64>,
|
||||||
Context -> Item<String>,
|
Context -> Item<String>,
|
||||||
Context -> Item<DAffine2>,
|
Context -> Item<DAffine2>,
|
||||||
Context -> Item<Footprint>,
|
|
||||||
Context -> Item<DVec2>,
|
Context -> Item<DVec2>,
|
||||||
Context -> Item<Vector>,
|
Context -> Item<Vector>,
|
||||||
Context -> Item<Graphic>,
|
Context -> Item<Graphic>,
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
use core::f64;
|
use core::f64;
|
||||||
use core_types::context::{CloneVarArgs, Context, ContextModification, Ctx, ExtractAll};
|
use core_types::context::{CloneVarArgs, Context, ContextModification, Ctx, ExtractAll};
|
||||||
use core_types::list::{AttributeValueDyn, Item, List, ListDyn, NodeIdPath};
|
use core_types::list::{AttributeValueDyn, Item, List, ListDyn, NodeIdPath};
|
||||||
use core_types::transform::Footprint;
|
|
||||||
use core_types::{Color, Interrupt, OwnedContextImpl};
|
use core_types::{Color, Interrupt, OwnedContextImpl};
|
||||||
use glam::{DAffine2, DVec2};
|
use glam::{DAffine2, DVec2};
|
||||||
use graphene_animation::AnimationCurve;
|
use graphene_animation::AnimationCurve;
|
||||||
@@ -22,7 +21,6 @@ fn context_modification<T>(
|
|||||||
Context -> Item<f64>,
|
Context -> Item<f64>,
|
||||||
Context -> Item<String>,
|
Context -> Item<String>,
|
||||||
Context -> Item<DAffine2>,
|
Context -> Item<DAffine2>,
|
||||||
Context -> Item<Footprint>,
|
|
||||||
Context -> Item<DVec2>,
|
Context -> Item<DVec2>,
|
||||||
Context -> Item<Vector>,
|
Context -> Item<Vector>,
|
||||||
Context -> Item<Graphic>,
|
Context -> Item<Graphic>,
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ use core_types::math::bbox::Bbox;
|
|||||||
use core_types::ops::ConvertAsync;
|
use core_types::ops::ConvertAsync;
|
||||||
use core_types::transform::Footprint;
|
use core_types::transform::Footprint;
|
||||||
use core_types::{ATTR_EDITOR_MERGED_LAYERS, ATTR_TRANSFORM, NodeError};
|
use core_types::{ATTR_EDITOR_MERGED_LAYERS, ATTR_TRANSFORM, NodeError};
|
||||||
use glam::{DAffine2, UVec2};
|
use glam::{DAffine2, DVec2, UVec2};
|
||||||
pub use graph_craft::application_io::resource::{Resource, ResourceHash, ResourceId};
|
pub use graph_craft::application_io::resource::{Resource, ResourceHash, ResourceId};
|
||||||
pub use graph_craft::application_io::*;
|
pub use graph_craft::application_io::*;
|
||||||
pub use graph_craft::document::value::RenderOutputType;
|
pub use graph_craft::document::value::RenderOutputType;
|
||||||
@@ -229,31 +229,46 @@ fn svg_to_graphic(_: impl Ctx, #[name("SVG")] svg: Item<String>) -> Result<List<
|
|||||||
svg_convert::convert(&svg, &svg_convert::Options::default())
|
svg_convert::convert(&svg, &svg_convert::Options::default())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Renders a view of the input graphics within an area defined by the *Footprint*, producing a raster image.
|
/// Renders the input graphics within a rectangle into a raster image of a chosen resolution.
|
||||||
#[node_macro::node(category("Raster"), icon("NodeRasterize"), placeholder = pending_raster)]
|
///
|
||||||
|
/// Raster effects work on any graphic without this, so it's only needed to bake graphics into pixels.
|
||||||
|
#[node_macro::node(category("Raster"), icon("NodeRasterize"), version(2), placeholder = pending_raster)]
|
||||||
async fn rasterize(
|
async fn rasterize(
|
||||||
_: impl Ctx,
|
_: impl Ctx,
|
||||||
/// The graphics to render as an image.
|
/// The graphics to render as an image.
|
||||||
data: List<Graphic>,
|
data: List<Graphic>,
|
||||||
/// The area of the document to render, and the resolution to render it at.
|
/// Places the rectangle the image covers, measured from the origin of the content's local coordinate space. By default, it's a square 1000 px across centered at (500, 500).
|
||||||
#[default(0., 0., 1000., 1000.)]
|
#[unit(" px")]
|
||||||
footprint: Item<Footprint>,
|
#[default(500., 500., 1000., 1000.)]
|
||||||
|
transform: Item<DAffine2>,
|
||||||
|
/// The number of pixels across and down the image, spread over the rectangle whatever its size. By default, it's 1000 by 1000, one pixel per px of the default rectangle.
|
||||||
|
#[unit(" px")]
|
||||||
|
#[hard(1..)]
|
||||||
|
#[default(1000., 1000.)]
|
||||||
|
resolution: Item<DVec2>,
|
||||||
#[scope(wgpu_executor::IDENTIFIER)] executor: Item<::wgpu_executor::WgpuExecutor>,
|
#[scope(wgpu_executor::IDENTIFIER)] executor: Item<::wgpu_executor::WgpuExecutor>,
|
||||||
) -> Result<List<Raster<CPU>>, NodeError> {
|
) -> Result<List<Raster<CPU>>, NodeError> {
|
||||||
rasterize_with_vello(data, footprint.into_element(), executor.into_element()).await
|
rasterize_with_vello(data, *transform.element(), resolution.element().as_uvec2(), executor.into_element()).await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn rasterize_with_vello(data: List<Graphic>, footprint: Footprint, executor: ::wgpu_executor::WgpuExecutor) -> Result<List<Raster<CPU>>, NodeError> {
|
/// Renders `data` within the rectangle `transform` places, a unit square centered on its origin, as an image of `resolution` pixels.
|
||||||
let resolution = footprint.resolution;
|
async fn rasterize_with_vello(data: List<Graphic>, transform: DAffine2, resolution: UVec2, executor: ::wgpu_executor::WgpuExecutor) -> Result<List<Raster<CPU>>, NodeError> {
|
||||||
if footprint.transform.matrix2.determinant() == 0. || resolution.cmpeq(UVec2::ZERO).any() {
|
if transform.matrix2.determinant() == 0. || resolution.cmpeq(UVec2::ZERO).any() {
|
||||||
log::trace!("Invalid footprint received for rasterization");
|
log::trace!("Invalid area or resolution received for rasterization");
|
||||||
return Ok(List::new());
|
return Ok(List::new());
|
||||||
}
|
}
|
||||||
|
|
||||||
let aabb = Bbox::from_transform(footprint.transform).to_axis_aligned_bbox();
|
// An image fills the unit square from its corner rather than its center
|
||||||
|
let image_transform = transform * DAffine2::from_translation(DVec2::splat(-0.5));
|
||||||
|
|
||||||
|
let aabb = Bbox::from_transform(image_transform).to_axis_aligned_bbox();
|
||||||
let view = DAffine2::from_scale(resolution.as_dvec2() / aabb.size()) * DAffine2::from_translation(-aabb.start);
|
let view = DAffine2::from_scale(resolution.as_dvec2() / aabb.size()) * DAffine2::from_translation(-aabb.start);
|
||||||
let render_params = RenderParams {
|
let render_params = RenderParams {
|
||||||
footprint,
|
footprint: Footprint {
|
||||||
|
transform: image_transform,
|
||||||
|
resolution,
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
for_export: true,
|
for_export: true,
|
||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
@@ -265,12 +280,12 @@ async fn rasterize_with_vello(data: List<Graphic>, footprint: Footprint, executo
|
|||||||
// The input's layers stay reachable so the renderer can expose their click targets to the editor's tools
|
// The input's layers stay reachable so the renderer can expose their click targets to the editor's tools
|
||||||
Ok(List::new_from_item(
|
Ok(List::new_from_item(
|
||||||
Item::new_from_element(raster)
|
Item::new_from_element(raster)
|
||||||
.with_attribute(ATTR_TRANSFORM, footprint.transform)
|
.with_attribute(ATTR_TRANSFORM, image_transform)
|
||||||
.with_attribute(ATTR_EDITOR_MERGED_LAYERS, data),
|
.with_attribute(ATTR_EDITOR_MERGED_LAYERS, data),
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn pending_raster(_data: &List<Graphic>, _footprint: &Item<Footprint>, _executor: &Item<::wgpu_executor::WgpuExecutor>) -> List<Raster<CPU>> {
|
fn pending_raster(_data: &List<Graphic>, _transform: &Item<DAffine2>, _resolution: &Item<DVec2>, _executor: &Item<::wgpu_executor::WgpuExecutor>) -> List<Raster<CPU>> {
|
||||||
List::new()
|
List::new()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -328,28 +343,53 @@ fn wgpu_executor(_: impl Ctx, #[scope(application_io::IDENTIFIER)] application_i
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use core_types::Color;
|
use core_types::Color;
|
||||||
use glam::DVec2;
|
|
||||||
|
/// A red rectangle covering x from 0 to 500 px and y from 0 to 1000 px.
|
||||||
|
fn left_half_red() -> List<Graphic> {
|
||||||
|
let red = Item::new_from_element(Raster::new_cpu(Image::new(1, 1, Color::RED))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::new(500., 1000.)));
|
||||||
|
List::new_from_item(Item::new_from_element(Graphic::RasterCPU(Box::new(red))))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Asserts each pixel of the image's first row is red for the first `red_columns` columns and transparent after.
|
||||||
|
fn assert_first_row_red_up_to(image: &Image<Color>, red_columns: u32) {
|
||||||
|
for x in 0..image.width {
|
||||||
|
let expected_red = x < red_columns;
|
||||||
|
assert_eq!(
|
||||||
|
image.data[x as usize].a() > 0.5,
|
||||||
|
expected_red,
|
||||||
|
"pixel {x} should be {}",
|
||||||
|
if expected_red { "red" } else { "transparent" }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn rasterize_renders_the_footprint_area_at_its_resolution() {
|
async fn rasterize_renders_its_area_at_its_resolution() {
|
||||||
let Some(executor) = ::wgpu_executor::WgpuExecutor::new().await else { return };
|
let Some(executor) = ::wgpu_executor::WgpuExecutor::for_tests().await else { return };
|
||||||
|
|
||||||
let red = Item::new_from_element(Raster::new_cpu(Image::new(1, 1, Color::RED))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::new(500., 1000.)));
|
let area = DAffine2::from_scale_angle_translation(DVec2::splat(1000.), 0., DVec2::splat(500.));
|
||||||
let data = List::new_from_item(Item::new_from_element(Graphic::RasterCPU(Box::new(red))));
|
let output = rasterize_with_vello(left_half_red(), area, UVec2::splat(4), executor).await.expect("Rasterize should render");
|
||||||
let footprint = Footprint {
|
|
||||||
transform: DAffine2::from_scale(DVec2::splat(1000.)),
|
|
||||||
resolution: UVec2::splat(4),
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
|
|
||||||
let output = rasterize_with_vello(data, footprint, executor).await.expect("Rasterize should render");
|
|
||||||
|
|
||||||
let image = output.iter_element_values().next().expect("Rasterize should output one image").data();
|
let image = output.iter_element_values().next().expect("Rasterize should output one image").data();
|
||||||
assert_eq!((image.width, image.height), (4, 4));
|
assert_eq!((image.width, image.height), (4, 4));
|
||||||
for x in 0..4 {
|
assert_first_row_red_up_to(image, 2);
|
||||||
let pixel = image.data[(4 + x) as usize];
|
}
|
||||||
let expected_red = x < 2;
|
|
||||||
assert_eq!(pixel.a() > 0.5, expected_red, "pixel {x} should be {}", if expected_red { "red" } else { "transparent" });
|
// What 'Rasterize' version 1 output for a footprint, its migrated area transform and resolution reproduce
|
||||||
}
|
#[tokio::test]
|
||||||
|
async fn rasterize_renders_a_migrated_footprint_where_it_did() {
|
||||||
|
let Some(executor) = ::wgpu_executor::WgpuExecutor::for_tests().await else { return };
|
||||||
|
|
||||||
|
// Version 1 rendered the 4 by 2 pixel footprint over x from 250 to 750 px, its transform placing the image's corner-anchored unit square
|
||||||
|
let footprint_transform = DAffine2::from_scale_angle_translation(DVec2::new(500., 1000.), 0., DVec2::new(250., 0.));
|
||||||
|
let migrated_area = footprint_transform * DAffine2::from_translation(DVec2::splat(0.5));
|
||||||
|
|
||||||
|
let output = rasterize_with_vello(left_half_red(), migrated_area, UVec2::new(4, 2), executor).await.expect("Rasterize should render");
|
||||||
|
|
||||||
|
assert_eq!(output.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM, 0), footprint_transform);
|
||||||
|
|
||||||
|
let image = output.element(0).expect("Rasterize should output one image").data();
|
||||||
|
assert_eq!((image.width, image.height), (4, 2));
|
||||||
|
assert_first_row_red_up_to(image, 2);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -47,7 +47,6 @@ pub struct CacheKey {
|
|||||||
pub rotation: u64,
|
pub rotation: u64,
|
||||||
pub for_export: bool,
|
pub for_export: bool,
|
||||||
pub for_mask: bool,
|
pub for_mask: bool,
|
||||||
pub thumbnail: bool,
|
|
||||||
pub aligned_strokes: bool,
|
pub aligned_strokes: bool,
|
||||||
pub stroke_below: bool,
|
pub stroke_below: bool,
|
||||||
pub animation_time_ms: i64,
|
pub animation_time_ms: i64,
|
||||||
@@ -64,7 +63,6 @@ impl CacheKey {
|
|||||||
rotation: f64,
|
rotation: f64,
|
||||||
for_export: bool,
|
for_export: bool,
|
||||||
for_mask: bool,
|
for_mask: bool,
|
||||||
thumbnail: bool,
|
|
||||||
aligned_strokes: bool,
|
aligned_strokes: bool,
|
||||||
stroke_below: bool,
|
stroke_below: bool,
|
||||||
animation_time: f64,
|
animation_time: f64,
|
||||||
@@ -89,7 +87,6 @@ impl CacheKey {
|
|||||||
rotation: quantized_rotation.to_bits(),
|
rotation: quantized_rotation.to_bits(),
|
||||||
for_export,
|
for_export,
|
||||||
for_mask,
|
for_mask,
|
||||||
thumbnail,
|
|
||||||
aligned_strokes,
|
aligned_strokes,
|
||||||
stroke_below,
|
stroke_below,
|
||||||
animation_time_ms: (animation_time * 1000.).round() as i64,
|
animation_time_ms: (animation_time * 1000.).round() as i64,
|
||||||
@@ -418,7 +415,6 @@ fn render_output_cache(
|
|||||||
rotation,
|
rotation,
|
||||||
render_params.for_export,
|
render_params.for_export,
|
||||||
render_params.for_mask,
|
render_params.for_mask,
|
||||||
render_params.thumbnail,
|
|
||||||
render_params.aligned_strokes,
|
render_params.aligned_strokes,
|
||||||
render_params.stroke_below,
|
render_params.stroke_below,
|
||||||
ctx.try_animation_time().unwrap_or(0.),
|
ctx.try_animation_time().unwrap_or(0.),
|
||||||
@@ -797,7 +793,9 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn regions_out_of_view_are_held_weakly_and_those_in_view_strongly() {
|
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 Some(context) = futures::executor::block_on(wgpu_executor::WgpuContext::for_tests()) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
let cache = TileCache::default();
|
let cache = TileCache::default();
|
||||||
|
|
||||||
let mut pool = Vec::new();
|
let mut pool = Vec::new();
|
||||||
@@ -812,7 +810,9 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_parked_region_back_in_view_is_reused() {
|
fn a_parked_region_back_in_view_is_reused() {
|
||||||
let Some(context) = futures::executor::block_on(wgpu_executor::WgpuContext::new()) else { return };
|
let Some(context) = futures::executor::block_on(wgpu_executor::WgpuContext::for_tests()) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
let cache = TileCache::default();
|
let cache = TileCache::default();
|
||||||
|
|
||||||
let (_, parked) = show(&cache, &context.device, &view(0), &zoom(1));
|
let (_, parked) = show(&cache, &context.device, &view(0), &zoom(1));
|
||||||
@@ -823,7 +823,9 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_parked_region_the_pool_evicted_is_rendered_again() {
|
fn a_parked_region_the_pool_evicted_is_rendered_again() {
|
||||||
let Some(context) = futures::executor::block_on(wgpu_executor::WgpuContext::new()) else { return };
|
let Some(context) = futures::executor::block_on(wgpu_executor::WgpuContext::for_tests()) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
let cache = TileCache::default();
|
let cache = TileCache::default();
|
||||||
|
|
||||||
let (_, evicted) = show(&cache, &context.device, &view(0), &zoom(1));
|
let (_, evicted) = show(&cache, &context.device, &view(0), &zoom(1));
|
||||||
@@ -837,7 +839,9 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn the_regions_of_an_earlier_cache_key_are_reused_on_returning_to_it() {
|
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 Some(context) = futures::executor::block_on(wgpu_executor::WgpuContext::for_tests()) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
let cache = TileCache::default();
|
let cache = TileCache::default();
|
||||||
|
|
||||||
let (_, parked) = show(&cache, &context.device, &view(0), &zoom(1));
|
let (_, parked) = show(&cache, &context.device, &view(0), &zoom(1));
|
||||||
@@ -848,7 +852,9 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn the_regions_of_cache_keys_older_than_the_most_recent_ones_are_released() {
|
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 Some(context) = futures::executor::block_on(wgpu_executor::WgpuContext::for_tests()) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
let cache = TileCache::default();
|
let cache = TileCache::default();
|
||||||
|
|
||||||
let (_, oldest) = show(&cache, &context.device, &view(0), &zoom(0));
|
let (_, oldest) = show(&cache, &context.device, &view(0), &zoom(0));
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ use graphic_types::{Artboard, Graphic, Vector};
|
|||||||
use rendering::vello_scene_builder::VelloSceneBuilder;
|
use rendering::vello_scene_builder::VelloSceneBuilder;
|
||||||
use rendering::{Render, RenderMetadata, RenderOutputType as RenderOutputTypeRequest, RenderParams, SvgRender, SvgRenderOutput};
|
use rendering::{Render, RenderMetadata, RenderOutputType as RenderOutputTypeRequest, RenderParams, SvgRender, SvgRenderOutput};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use svg_readback::SvgReadbackSlot;
|
use svg_readback::{SvgInViewSlot, SvgReadbackSlot};
|
||||||
use vector_types::Gradient;
|
use vector_types::Gradient;
|
||||||
use wgpu_executor::WgpuExecutor;
|
use wgpu_executor::WgpuExecutor;
|
||||||
|
|
||||||
@@ -91,6 +91,7 @@ fn render(
|
|||||||
#[scope("runtime")] runtime: Item<RuntimeHandle>,
|
#[scope("runtime")] runtime: Item<RuntimeHandle>,
|
||||||
#[source_id] source: Item<SourceId>,
|
#[source_id] source: Item<SourceId>,
|
||||||
#[data] svg_readback: SvgReadbackSlot,
|
#[data] svg_readback: SvgReadbackSlot,
|
||||||
|
#[data] svg_in_view: SvgInViewSlot,
|
||||||
) -> Poll<Item<RenderOutput>> {
|
) -> Poll<Item<RenderOutput>> {
|
||||||
let footprint = ctx.footprint();
|
let footprint = ctx.footprint();
|
||||||
let render_params = ctx
|
let render_params = ctx
|
||||||
@@ -105,15 +106,16 @@ fn render(
|
|||||||
// Content drawing only the part of it in view draws its markup for this view
|
// Content drawing only the part of it in view draws its markup for this view
|
||||||
let ty = match ty {
|
let ty = match ty {
|
||||||
RenderIntermediateType::SvgInView(content) => {
|
RenderIntermediateType::SvgInView(content) => {
|
||||||
let mut render = SvgRender::new();
|
|
||||||
let in_view = RenderParams {
|
let in_view = RenderParams {
|
||||||
view: Some(*footprint),
|
view: Some(*footprint),
|
||||||
..render_params.clone()
|
..render_params.clone()
|
||||||
};
|
};
|
||||||
content.render_svg(&mut render, &in_view);
|
RenderIntermediateType::Svg(svg_in_view.render(&content, &in_view))
|
||||||
RenderIntermediateType::Svg(Arc::new(render.into()))
|
}
|
||||||
|
ty => {
|
||||||
|
svg_in_view.clear();
|
||||||
|
ty
|
||||||
}
|
}
|
||||||
ty => ty,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut render_params = render_params.clone();
|
let mut render_params = render_params.clone();
|
||||||
@@ -131,7 +133,7 @@ fn render(
|
|||||||
assert!(output.svg_defs.is_empty());
|
assert!(output.svg_defs.is_empty());
|
||||||
|
|
||||||
let executor = executor.eval(&Context::default()).value().map(Item::into_element);
|
let executor = executor.eval(&Context::default()).value().map(Item::into_element);
|
||||||
svg_readback.poll(output, *footprint, executor, runtime.element(), *source.element())
|
svg_readback.poll(output, *footprint, executor, render_params.for_export, runtime.element(), *source.element())
|
||||||
}
|
}
|
||||||
(RenderOutputTypeRequest::Vello, RenderIntermediateType::Vello(data)) => {
|
(RenderOutputTypeRequest::Vello, RenderIntermediateType::Vello(data)) => {
|
||||||
// The latest SVG render isn't needed anymore, and a finished one holds a whole SVG export
|
// The latest SVG render isn't needed anymore, and a finished one holds a whole SVG export
|
||||||
|
|||||||
@@ -3,10 +3,61 @@ use core_types::transform::Footprint;
|
|||||||
use core_types::{CacheHash, Poll, RuntimeHandle, SourceId};
|
use core_types::{CacheHash, Poll, RuntimeHandle, SourceId};
|
||||||
use futures::future::{AbortHandle, Abortable};
|
use futures::future::{AbortHandle, Abortable};
|
||||||
use graph_craft::document::value::RenderOutputType;
|
use graph_craft::document::value::RenderOutputType;
|
||||||
use rendering::SvgRenderOutput;
|
use rendering::{Render, RenderParams, SvgRender, SvgRenderOutput};
|
||||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||||
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
|
use std::sync::{Arc, Mutex, MutexGuard, PoisonError, Weak};
|
||||||
use wgpu_executor::WgpuExecutor;
|
use wgpu_executor::{NoGpuError, WgpuExecutor, svg_placeholders_in_view};
|
||||||
|
|
||||||
|
/// The latest SVG of content drawing only the part of it in view, which evaluations for the same content and view (like those its readbacks wake) reuse,
|
||||||
|
/// keeping the IDs of its placeholders as content drawing all of itself keeps those of its cached intermediate SVG.
|
||||||
|
#[derive(Clone, Debug, Default)]
|
||||||
|
pub struct SvgInViewSlot(Arc<Mutex<Option<SvgInView>>>);
|
||||||
|
|
||||||
|
struct SvgInView {
|
||||||
|
content: Weak<dyn Render + Send + Sync>,
|
||||||
|
/// Hashes the render parameters, which hold the view.
|
||||||
|
key: u64,
|
||||||
|
output: Arc<SvgRenderOutput>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Debug for SvgInView {
|
||||||
|
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
formatter.debug_struct("SvgInView").field("key", &self.key).finish_non_exhaustive()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SvgInViewSlot {
|
||||||
|
fn lock(&self) -> MutexGuard<'_, Option<SvgInView>> {
|
||||||
|
self.0.lock().unwrap_or_else(PoisonError::into_inner)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drops the latest SVG.
|
||||||
|
pub fn clear(&self) {
|
||||||
|
*self.lock() = None;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The SVG of the `content` drawn with the `render_params` that give it its view, drawn again only for other content or parameters.
|
||||||
|
pub fn render(&self, content: &Arc<dyn Render + Send + Sync>, render_params: &RenderParams) -> Arc<SvgRenderOutput> {
|
||||||
|
let mut hasher = DefaultHasher::new();
|
||||||
|
render_params.cache_hash(&mut hasher);
|
||||||
|
let key = hasher.finish();
|
||||||
|
|
||||||
|
let mut latest = self.lock();
|
||||||
|
if let Some(latest) = latest.as_ref().filter(|latest| latest.key == key && Weak::ptr_eq(&latest.content, &Arc::downgrade(content))) {
|
||||||
|
return latest.output.clone();
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut render = SvgRender::new();
|
||||||
|
content.render_svg(&mut render, render_params);
|
||||||
|
let output = Arc::new(SvgRenderOutput::from(render));
|
||||||
|
*latest = Some(SvgInView {
|
||||||
|
content: Arc::downgrade(content),
|
||||||
|
key,
|
||||||
|
output: output.clone(),
|
||||||
|
});
|
||||||
|
output
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// The latest SVG render that needs maps and images from the GPU, kept across the render node's evaluations while a task reads them back.
|
/// The latest SVG render that needs maps and images from the GPU, kept across the render node's evaluations while a task reads them back.
|
||||||
/// A render of other content or for another view replaces it, cancelling the readback still underway for the one it replaced.
|
/// A render of other content or for another view replaces it, cancelling the readback still underway for the one it replaced.
|
||||||
@@ -16,13 +67,16 @@ pub struct SvgReadbackSlot(Arc<Mutex<Option<SvgReadback>>>);
|
|||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
struct SvgReadback {
|
struct SvgReadback {
|
||||||
key: u64,
|
key: u64,
|
||||||
finished: Option<RenderOutputType>,
|
finished: Option<Poll<RenderOutputType>>,
|
||||||
task: AbortHandle,
|
/// The task reading the maps and images back, which there's none of without a GPU.
|
||||||
|
task: Option<AbortHandle>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Drop for SvgReadback {
|
impl Drop for SvgReadback {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
self.task.abort();
|
if let Some(task) = &self.task {
|
||||||
|
task.abort();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -37,8 +91,8 @@ impl SvgReadbackSlot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The SVG `output` with the maps and images the GPU renders for it in place of their placeholders, partial with the placeholders while a task reads them back.
|
/// The SVG `output` with the maps and images the GPU renders for it in place of their placeholders, partial with the placeholders while a task reads them back.
|
||||||
/// The task landing evaluates the render node again through its `source`.
|
/// The task landing evaluates the render node again through its `source`. Placeholders in view left unfilled fail the render if it's `for_export`.
|
||||||
pub fn poll(&self, output: SvgRenderOutput, footprint: Footprint, executor: Option<WgpuExecutor>, runtime: &RuntimeHandle, source: SourceId) -> Poll<RenderOutputType> {
|
pub fn poll(&self, output: SvgRenderOutput, footprint: Footprint, executor: Option<WgpuExecutor>, for_export: bool, runtime: &RuntimeHandle, source: SourceId) -> Poll<RenderOutputType> {
|
||||||
let svg = output.svg;
|
let svg = output.svg;
|
||||||
let image_data: Vec<_> = output.image_data.into_iter().collect();
|
let image_data: Vec<_> = output.image_data.into_iter().collect();
|
||||||
|
|
||||||
@@ -51,27 +105,46 @@ impl SvgReadbackSlot {
|
|||||||
let mut hasher = DefaultHasher::new();
|
let mut hasher = DefaultHasher::new();
|
||||||
svg.hash(&mut hasher);
|
svg.hash(&mut hasher);
|
||||||
footprint.cache_hash(&mut hasher);
|
footprint.cache_hash(&mut hasher);
|
||||||
|
for_export.hash(&mut hasher);
|
||||||
let key = hasher.finish();
|
let key = hasher.finish();
|
||||||
|
|
||||||
if self.lock().as_ref().is_none_or(|readback| readback.key != key) {
|
if self.lock().as_ref().is_none_or(|readback| readback.key != key) {
|
||||||
let Some(executor) = executor else {
|
let Some(executor) = executor else {
|
||||||
return Poll::Final(RenderOutputType::Svg { svg, image_data });
|
if !svg_placeholders_in_view(&output.effect_maps, &output.deferred_images, footprint) {
|
||||||
|
self.clear();
|
||||||
|
return Poll::Final(RenderOutputType::Svg { svg, image_data });
|
||||||
|
}
|
||||||
|
|
||||||
|
log::warn!("{NoGpuError}, so the SVG render can't fill the placeholders for its maps and images in view");
|
||||||
|
let finished = with_unfilled_placeholders(RenderOutputType::Svg { svg, image_data }, NoGpuError, for_export);
|
||||||
|
*self.lock() = Some(SvgReadback {
|
||||||
|
key,
|
||||||
|
finished: Some(finished.clone()),
|
||||||
|
task: None,
|
||||||
|
});
|
||||||
|
return finished;
|
||||||
};
|
};
|
||||||
let effect_maps = executor.render_effect_maps(&output.effect_maps, footprint);
|
let renders = executor.render_svg_placeholders(&output.effect_maps, &output.deferred_images, footprint);
|
||||||
let deferred_images = executor.render_deferred_svg_images(&output.deferred_images, footprint);
|
if renders.is_empty() {
|
||||||
if effect_maps.is_empty() && deferred_images.is_empty() {
|
|
||||||
self.clear();
|
self.clear();
|
||||||
return Poll::Final(RenderOutputType::Svg { svg, image_data });
|
return Poll::Final(RenderOutputType::Svg { svg, image_data });
|
||||||
}
|
}
|
||||||
|
|
||||||
let (task, registration) = AbortHandle::new_pair();
|
let (task, registration) = AbortHandle::new_pair();
|
||||||
*self.lock() = Some(SvgReadback { key, finished: None, task });
|
*self.lock() = Some(SvgReadback {
|
||||||
|
key,
|
||||||
|
finished: None,
|
||||||
|
task: Some(task),
|
||||||
|
});
|
||||||
|
|
||||||
let (mut svg, mut image_data) = (svg.clone(), image_data.clone());
|
let (mut svg, mut image_data) = (svg.clone(), image_data.clone());
|
||||||
let readback = async move {
|
let readback = async move {
|
||||||
executor.resolve_effect_maps(&mut svg, effect_maps).await;
|
let filled = executor.substitute_svg_placeholders(&mut svg, &mut image_data, renders).await;
|
||||||
executor.resolve_deferred_svg_images(&mut svg, &mut image_data, deferred_images).await;
|
let output = RenderOutputType::Svg { svg, image_data };
|
||||||
RenderOutputType::Svg { svg, image_data }
|
match filled {
|
||||||
|
Ok(()) => Poll::Final(output),
|
||||||
|
Err(error) => with_unfilled_placeholders(output, error, for_export),
|
||||||
|
}
|
||||||
};
|
};
|
||||||
// Held weakly, the slot is dropped along with the render node, which cancels the readback
|
// Held weakly, the slot is dropped along with the render node, which cancels the readback
|
||||||
let slot = Arc::downgrade(&self.0);
|
let slot = Arc::downgrade(&self.0);
|
||||||
@@ -89,10 +162,15 @@ impl SvgReadbackSlot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let finished = self.lock().as_ref().filter(|readback| readback.key == key).and_then(|readback| readback.finished.clone());
|
let finished = self.lock().as_ref().filter(|readback| readback.key == key).and_then(|readback| readback.finished.clone());
|
||||||
match finished {
|
finished.unwrap_or(Poll::Partial(RenderOutputType::Svg { svg, image_data }))
|
||||||
Some(finished) => Poll::Final(finished),
|
}
|
||||||
None => Poll::Partial(RenderOutputType::Svg { svg, image_data }),
|
}
|
||||||
}
|
|
||||||
|
/// The SVG `output` with placeholders in view the GPU couldn't fill, which fail an export rather than leaving its content out, and which a view shows as they are.
|
||||||
|
fn with_unfilled_placeholders(output: RenderOutputType, error: impl std::fmt::Display, for_export: bool) -> Poll<RenderOutputType> {
|
||||||
|
match for_export {
|
||||||
|
true => Poll::error(format!("{error:#}")),
|
||||||
|
false => Poll::Final(output),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -172,12 +250,12 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn an_svg_render_is_partial_until_its_readback_lands() {
|
fn an_svg_render_is_partial_until_its_readback_lands() {
|
||||||
let Some(executor) = futures::executor::block_on(WgpuExecutor::new()) else { return };
|
let Some(executor) = futures::executor::block_on(WgpuExecutor::for_tests()) else { return };
|
||||||
let tasks = Arc::new(HeldTasks::default());
|
let tasks = Arc::new(HeldTasks::default());
|
||||||
let runtime = AsyncRuntime::new(tasks.clone());
|
let runtime = AsyncRuntime::new(tasks.clone());
|
||||||
let slot = SvgReadbackSlot::default();
|
let slot = SvgReadbackSlot::default();
|
||||||
let output = deferred_svg();
|
let output = deferred_svg();
|
||||||
let poll = || slot.poll(again(&output), view(32), Some(executor.clone()), &runtime.handle(), SourceId(1));
|
let poll = || slot.poll(again(&output), view(32), Some(executor.clone()), false, &runtime.handle(), SourceId(1));
|
||||||
|
|
||||||
// Until the readback lands, the SVG keeps its placeholders, and evaluating the same render again doesn't read it back again
|
// Until the readback lands, the SVG keeps its placeholders, and evaluating the same render again doesn't read it back again
|
||||||
for _ in 0..2 {
|
for _ in 0..2 {
|
||||||
@@ -197,13 +275,67 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_render_for_another_view_cancels_the_readback_of_the_one_it_replaces() {
|
fn placeholders_left_unfilled_fail_an_export_but_show_in_a_view() {
|
||||||
let Some(executor) = futures::executor::block_on(WgpuExecutor::new()) else { return };
|
|
||||||
let tasks = Arc::new(HeldTasks::default());
|
let tasks = Arc::new(HeldTasks::default());
|
||||||
let runtime = AsyncRuntime::new(tasks.clone());
|
let runtime = AsyncRuntime::new(tasks.clone());
|
||||||
let slot = SvgReadbackSlot::default();
|
let slot = SvgReadbackSlot::default();
|
||||||
let output = deferred_svg();
|
let output = deferred_svg();
|
||||||
let poll = |size| slot.poll(again(&output), view(size), Some(executor.clone()), &runtime.handle(), SourceId(1));
|
|
||||||
|
// Without a GPU, an export fails rather than leaving out what the placeholder stands for
|
||||||
|
let export = slot.poll(again(&output), view(32), None, true, &runtime.handle(), SourceId(1));
|
||||||
|
assert!(matches!(export, Poll::Error(_)), "the export should fail");
|
||||||
|
|
||||||
|
let Poll::Final(RenderOutputType::Svg { svg, .. }) = slot.poll(again(&output), view(32), None, false, &runtime.handle(), SourceId(1)) else {
|
||||||
|
panic!("expected the view's SVG")
|
||||||
|
};
|
||||||
|
assert!(svg.contains("deferred-image"), "the view should show the placeholder: {svg}");
|
||||||
|
|
||||||
|
// An export with its placeholder out of view has nothing left out
|
||||||
|
let elsewhere = Footprint {
|
||||||
|
transform: DAffine2::from_translation(DVec2::splat(-1000.)),
|
||||||
|
..view(32)
|
||||||
|
};
|
||||||
|
assert!(matches!(slot.poll(again(&output), elsewhere, None, true, &runtime.handle(), SourceId(1)), Poll::Final(_)));
|
||||||
|
assert!(tasks.take().is_empty(), "nothing can be read back");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn evaluations_of_content_in_view_draw_the_same_placeholders_so_its_readback_finishes_them() {
|
||||||
|
let Some(executor) = futures::executor::block_on(WgpuExecutor::for_tests()) else { return };
|
||||||
|
let tasks = Arc::new(HeldTasks::default());
|
||||||
|
let runtime = AsyncRuntime::new(tasks.clone());
|
||||||
|
let (slot, in_view) = (SvgReadbackSlot::default(), SvgInViewSlot::default());
|
||||||
|
let content: Arc<dyn Render + Send + Sync> = Arc::new(List::new_from_element(graphic_types::Generator::Noise));
|
||||||
|
let render_params = RenderParams {
|
||||||
|
for_export: true,
|
||||||
|
view: Some(view(32)),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let evaluate = || {
|
||||||
|
let output = in_view.render(&content, &render_params);
|
||||||
|
slot.poll(again(&output), view(32), Some(executor.clone()), false, &runtime.handle(), SourceId(1))
|
||||||
|
};
|
||||||
|
|
||||||
|
// The first evaluation draws the generator's placeholder and reads its image back
|
||||||
|
assert!(matches!(evaluate(), Poll::Partial(_)));
|
||||||
|
tasks.take().into_iter().for_each(futures::executor::block_on);
|
||||||
|
|
||||||
|
// The evaluation the readback wakes draws the same placeholder, which the image fills
|
||||||
|
let Poll::Final(RenderOutputType::Svg { svg, .. }) = evaluate() else {
|
||||||
|
panic!("expected a finished SVG")
|
||||||
|
};
|
||||||
|
assert!(svg.contains("data:image/png;base64,") && !svg.contains("deferred-image"), "{svg}");
|
||||||
|
assert!(tasks.take().is_empty(), "nothing should be read back again");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_render_for_another_view_cancels_the_readback_of_the_one_it_replaces() {
|
||||||
|
let Some(executor) = futures::executor::block_on(WgpuExecutor::for_tests()) else { return };
|
||||||
|
let tasks = Arc::new(HeldTasks::default());
|
||||||
|
let runtime = AsyncRuntime::new(tasks.clone());
|
||||||
|
let slot = SvgReadbackSlot::default();
|
||||||
|
let output = deferred_svg();
|
||||||
|
let poll = |size| slot.poll(again(&output), view(size), Some(executor.clone()), false, &runtime.handle(), SourceId(1));
|
||||||
|
|
||||||
assert!(matches!(poll(32), Poll::Partial(_)));
|
assert!(matches!(poll(32), Poll::Partial(_)));
|
||||||
assert!(matches!(poll(64), Poll::Partial(_)));
|
assert!(matches!(poll(64), Poll::Partial(_)));
|
||||||
@@ -223,14 +355,14 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_readback_underway_is_cancelled_once_its_slot_is_dropped() {
|
fn a_readback_underway_is_cancelled_once_its_slot_is_dropped() {
|
||||||
let Some(executor) = futures::executor::block_on(WgpuExecutor::new()) else { return };
|
let Some(executor) = futures::executor::block_on(WgpuExecutor::for_tests()) else { return };
|
||||||
let tasks = Arc::new(HeldTasks::default());
|
let tasks = Arc::new(HeldTasks::default());
|
||||||
let runtime = AsyncRuntime::new(tasks.clone());
|
let runtime = AsyncRuntime::new(tasks.clone());
|
||||||
let slot = SvgReadbackSlot::default();
|
let slot = SvgReadbackSlot::default();
|
||||||
|
|
||||||
let render = slot.poll(deferred_svg(), view(32), Some(executor), &runtime.handle(), SourceId(1));
|
let render = slot.poll(deferred_svg(), view(32), Some(executor), false, &runtime.handle(), SourceId(1));
|
||||||
assert!(matches!(render, Poll::Partial(_)));
|
assert!(matches!(render, Poll::Partial(_)));
|
||||||
let readback = slot.lock().as_ref().unwrap().task.clone();
|
let readback = slot.lock().as_ref().unwrap().task.clone().unwrap();
|
||||||
|
|
||||||
// A render node that's removed drops its slot while the task reading back for it is still to run
|
// A render node that's removed drops its slot while the task reading back for it is still to run
|
||||||
drop(slot);
|
drop(slot);
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
use core_types::context::{CloneVarArgs, ExtractAll};
|
use core_types::context::{CloneVarArgs, ExtractAll};
|
||||||
use core_types::list::{Bundle, Item, List};
|
use core_types::list::{Bundle, Item, List};
|
||||||
use core_types::transform::Footprint;
|
|
||||||
use core_types::{Color, Ctx, OwnedContextImpl, num_traits};
|
use core_types::{Color, Ctx, OwnedContextImpl, num_traits};
|
||||||
use core_types::{Context, Interrupt};
|
use core_types::{Context, Interrupt};
|
||||||
use glam::{DAffine2, DMat2, DVec2};
|
use glam::{DAffine2, DMat2, DVec2};
|
||||||
@@ -2082,24 +2081,6 @@ fn evaluate_gradient(
|
|||||||
Item::new_from_element(color)
|
Item::new_from_element(color)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Constructs a footprint value which may be set to any transformation of a unit square describing a render area, and a render resolution at least 1x1 integer pixels.
|
|
||||||
#[node_macro::node(category("Value"), icon("NodeFootprintValue"))]
|
|
||||||
fn footprint_value(
|
|
||||||
_: impl Ctx,
|
|
||||||
_primary: (),
|
|
||||||
transform: Item<DAffine2>,
|
|
||||||
#[unit(" px")]
|
|
||||||
#[hard(1..)]
|
|
||||||
#[default(100., 100.)]
|
|
||||||
resolution: Item<DVec2>,
|
|
||||||
) -> Item<Footprint> {
|
|
||||||
Item::new_from_element(Footprint {
|
|
||||||
transform: *transform.element(),
|
|
||||||
resolution: resolution.element().as_uvec2(),
|
|
||||||
..Default::default()
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Composes a vec2 from its X and Y components.
|
/// Composes a vec2 from its X and Y components.
|
||||||
///
|
///
|
||||||
/// The inverse of this node is **Vec2 to Numbers**, which decomposes a vec2 back into its X and Y components.
|
/// The inverse of this node is **Vec2 to Numbers**, which decomposes a vec2 back into its X and Y components.
|
||||||
|
|||||||
@@ -1460,7 +1460,10 @@ mod tests {
|
|||||||
let mut square = Item::new_from_element(Raster::new_cpu(Image::new(4, 4, Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(4.)));
|
let mut square = Item::new_from_element(Raster::new_cpu(Image::new(4, 4, Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(4.)));
|
||||||
stamp_effect(&mut square, Effect::new(&shadow));
|
stamp_effect(&mut square, Effect::new(&shadow));
|
||||||
|
|
||||||
let desaturated = raster_kernels::evaluate_raster_effects(desaturate((), square, DesaturateMethod::default().into()));
|
let Some(executor) = futures::executor::block_on(wgpu_executor::WgpuExecutor::for_tests()) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let desaturated = futures::executor::block_on(executor.read_back(desaturate((), square, DesaturateMethod::default().into()))).expect("the effects render");
|
||||||
|
|
||||||
let shaded = desaturated.element().data.iter().filter(|pixel| pixel.a() > 0.5 && pixel.r() < 0.99).collect::<Vec<_>>();
|
let shaded = desaturated.element().data.iter().filter(|pixel| pixel.a() > 0.5 && pixel.r() < 0.99).collect::<Vec<_>>();
|
||||||
assert!(!shaded.is_empty(), "the shadow was carried out");
|
assert!(!shaded.is_empty(), "the shadow was carried out");
|
||||||
@@ -2141,7 +2144,10 @@ mod tests {
|
|||||||
use core_types::ATTR_TRANSFORM;
|
use core_types::ATTR_TRANSFORM;
|
||||||
use glam::DAffine2;
|
use glam::DAffine2;
|
||||||
use graphic_types::{Effect, EffectOperation, stamp_effect};
|
use graphic_types::{Effect, EffectOperation, stamp_effect};
|
||||||
use raster_kernels::evaluate_raster_effects;
|
|
||||||
|
let Some(executor) = futures::executor::block_on(wgpu_executor::WgpuExecutor::for_tests()) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
// A white square in the middle of a transparent image, placed one pixel per document unit, then blurred
|
// A white square in the middle of a transparent image, placed one pixel per document unit, then blurred
|
||||||
let mut image = Image::new(20, 20, Color::TRANSPARENT);
|
let mut image = Image::new(20, 20, Color::TRANSPARENT);
|
||||||
@@ -2160,7 +2166,7 @@ mod tests {
|
|||||||
gamma: false,
|
gamma: false,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
let result = evaluate_raster_effects(super::make_opaque((), item, Item::new_from_element(100.)));
|
let result = futures::executor::block_on(executor.read_back(super::make_opaque((), item, Item::new_from_element(100.)))).expect("the effects render");
|
||||||
|
|
||||||
// Just outside the square, the blur's faint white becomes opaque white, where making it opaque first would have blurred in black
|
// Just outside the square, the blur's faint white becomes opaque white, where making it opaque first would have blurred in black
|
||||||
let transform: DAffine2 = result.attribute_cloned_or_default(ATTR_TRANSFORM);
|
let transform: DAffine2 = result.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||||
|
|||||||
@@ -223,7 +223,7 @@ mod tests {
|
|||||||
fn rendered(graphic: &Item<Graphic>, size: UVec2) -> Option<Vec<[u8; 4]>> {
|
fn rendered(graphic: &Item<Graphic>, size: UVec2) -> Option<Vec<[u8; 4]>> {
|
||||||
use rendering::{Render, RenderParams};
|
use rendering::{Render, RenderParams};
|
||||||
|
|
||||||
let executor = futures::executor::block_on(wgpu_executor::WgpuExecutor::new())?;
|
let executor = futures::executor::block_on(wgpu_executor::WgpuExecutor::for_tests())?;
|
||||||
let list = core_types::list::List::new_from_item(graphic.clone());
|
let list = core_types::list::List::new_from_item(graphic.clone());
|
||||||
let draw = &mut |scene: &mut rendering::vello_scene_builder::VelloSceneBuilder| list.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default());
|
let draw = &mut |scene: &mut rendering::vello_scene_builder::VelloSceneBuilder| list.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default());
|
||||||
let texture = executor.render_vello(size, DAffine2::IDENTITY, draw).expect("the graphic should render");
|
let texture = executor.render_vello(size, DAffine2::IDENTITY, draw).expect("the graphic should render");
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ use vector_types::vector::misc::{
|
|||||||
BezierHandles, CentroidType, ExtrudeJoiningAlgorithm, InterpolationDistribution, ManipulatorGroup, PointSpacingType, RowsOrColumns, Tangent, UnweldMethod, WeldMethod, dvec2_to_point,
|
BezierHandles, CentroidType, ExtrudeJoiningAlgorithm, InterpolationDistribution, ManipulatorGroup, PointSpacingType, RowsOrColumns, Tangent, UnweldMethod, WeldMethod, dvec2_to_point,
|
||||||
handles_to_segment, is_linear, point_to_dvec2, segment_to_handles,
|
handles_to_segment, is_linear, point_to_dvec2, segment_to_handles,
|
||||||
};
|
};
|
||||||
use vector_types::vector::style::{DashPattern, Gradient, GradientSettings, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
|
use vector_types::vector::style::{DashPattern, Gradient, GradientSettings, PaintMapping, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
|
||||||
use vector_types::vector::{
|
use vector_types::vector::{
|
||||||
CurveType, IdCollisionSet, Path, PointId, SegmentId, WorkingVector, curve_type_at, edit_item_geometry, edit_item_points, handle_point, no_paths, paths_from_item_attributes,
|
CurveType, IdCollisionSet, Path, PointId, SegmentId, WorkingVector, curve_type_at, edit_item_geometry, edit_item_points, handle_point, no_paths, paths_from_item_attributes,
|
||||||
paths_from_list_row_attributes, push_path, push_paths, reverse_path_flows, shared_paths_from_item_attributes, span_endpoints, spans,
|
paths_from_list_row_attributes, push_path, push_paths, reverse_path_flows, shared_paths_from_item_attributes, span_endpoints, spans,
|
||||||
@@ -507,7 +507,7 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Applies a stroke style to the vector content, giving an appearance to the area within the outline of the geometry.
|
/// Applies a stroke style to the vector content, giving an appearance to the area within the outline of the geometry.
|
||||||
#[node_macro::node(category("Vector: Style"), icon("NodeStroke"), path(graphene_core::vector), inspector("stroke_inspector"))]
|
#[node_macro::node(category("Vector: Style"), icon("NodeStroke"), path(graphene_core::vector), inspector("stroke_inspector"), version(2))]
|
||||||
fn stroke<V>(
|
fn stroke<V>(
|
||||||
_: impl Ctx,
|
_: impl Ctx,
|
||||||
/// The content with vector paths to apply the stroke style to.
|
/// The content with vector paths to apply the stroke style to.
|
||||||
@@ -536,18 +536,21 @@ fn stroke<V>(
|
|||||||
/// The phase offset distance from the starting point of the dash pattern.
|
/// The phase offset distance from the starting point of the dash pattern.
|
||||||
#[unit(" px")]
|
#[unit(" px")]
|
||||||
dash_offset: Item<f64>,
|
dash_offset: Item<f64>,
|
||||||
|
/// Where the paint is placed: in the canvas like a fill's, or along the stroke's paths.
|
||||||
|
paint_mapping: Item<PaintMapping>,
|
||||||
) -> Item<V>
|
) -> Item<V>
|
||||||
where
|
where
|
||||||
Item<V>: VectorItemMut + Send,
|
Item<V>: VectorItemMut + Send,
|
||||||
{
|
{
|
||||||
let mut content = content;
|
let mut content = content;
|
||||||
let (weight, align, cap, join, miter_limit, dash_offset) = (
|
let (weight, align, cap, join, miter_limit, dash_offset, paint_mapping) = (
|
||||||
weight.into_element(),
|
weight.into_element(),
|
||||||
align.into_element(),
|
align.into_element(),
|
||||||
cap.into_element(),
|
cap.into_element(),
|
||||||
join.into_element(),
|
join.into_element(),
|
||||||
miter_limit.into_element(),
|
miter_limit.into_element(),
|
||||||
dash_offset.into_element(),
|
dash_offset.into_element(),
|
||||||
|
paint_mapping.into_element(),
|
||||||
);
|
);
|
||||||
let dash_lengths = dash_pattern.into_element().clamped_lengths();
|
let dash_lengths = dash_pattern.into_element().clamped_lengths();
|
||||||
|
|
||||||
@@ -559,6 +562,7 @@ where
|
|||||||
join,
|
join,
|
||||||
join_miter_limit: miter_limit,
|
join_miter_limit: miter_limit,
|
||||||
align,
|
align,
|
||||||
|
paint_mapping,
|
||||||
transform: DAffine2::IDENTITY,
|
transform: DAffine2::IDENTITY,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,130 @@
|
|||||||
|
//! Networks whose export `export_layers` replaced with what their layers add, preprocessed, compiled, and evaluated as the editor's are.
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
use core_types::list::List;
|
||||||
|
use core_types::runtime::{AsyncRuntime, Spawn, Task};
|
||||||
|
use core_types::{Color, OwnedContextImpl, Poll};
|
||||||
|
use graph_craft::application_io::PlatformEditorApi;
|
||||||
|
use graph_craft::graphene_compiler::Compiler;
|
||||||
|
use graphene_std::graphic::{as_graphic, extend, into_group};
|
||||||
|
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||||
|
use interpreted_executor::layer_paths::export_layers;
|
||||||
|
use interpreted_executor::util::wrap_network_in_scope;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
struct BlockingSpawner;
|
||||||
|
|
||||||
|
impl Spawn for BlockingSpawner {
|
||||||
|
fn spawn(&self, task: Task) {
|
||||||
|
futures::executor::block_on(task);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the network outputs once it's preprocessed, compiled, and evaluated.
|
||||||
|
fn evaluated(network: NodeNetwork) -> List<Graphic> {
|
||||||
|
let runtime = AsyncRuntime::new(Arc::new(BlockingSpawner));
|
||||||
|
let mut network = wrap_network_in_scope(network, Arc::new(PlatformEditorApi { application_io: None }), runtime.handle());
|
||||||
|
Preprocessor::new().preprocess(&mut network, &|_| None).expect("preprocessing should succeed");
|
||||||
|
let proto_network = Compiler {}.compile_single(network).expect("the network should compile").network;
|
||||||
|
|
||||||
|
let mut executor = DynamicExecutor::default();
|
||||||
|
let (output, _) = executor.update(proto_network).expect("the network should type check and build");
|
||||||
|
let context = OwnedContextImpl::empty().into_context();
|
||||||
|
let Poll::Final(stack) = executor.tree().evaluate(output.node(), &context).expect("the output should evaluate") else {
|
||||||
|
panic!("the stack should be final")
|
||||||
|
};
|
||||||
|
*stack.downcast::<List<Graphic>>().expect("the stack should be graphics")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The color a stacked layer's group holds.
|
||||||
|
fn color_of(graphic: &Graphic) -> Option<Color> {
|
||||||
|
match graphic {
|
||||||
|
Graphic::Color(item) => Some(*item.element()),
|
||||||
|
Graphic::ColorList(list) => list.element(0).copied(),
|
||||||
|
Graphic::Graphic(item) => color_of(item.element()),
|
||||||
|
Graphic::GraphicList(list) => color_of(list.element(0)?),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn proto_node(identifier: ProtoNodeIdentifier, inputs: Vec<NodeInput>) -> DocumentNode {
|
||||||
|
DocumentNode {
|
||||||
|
inputs,
|
||||||
|
implementation: DocumentNodeImplementation::ProtoNode(identifier),
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A network shaped like 'Merge', adding the content it's given as a group onto the stack it's given.
|
||||||
|
fn merge_like() -> NodeNetwork {
|
||||||
|
NodeNetwork {
|
||||||
|
exports: vec![NodeInput::node(NodeId(2), 0)],
|
||||||
|
nodes: [
|
||||||
|
(NodeId(0), proto_node(as_graphic::IDENTIFIER, vec![NodeInput::import(generic!(T), 0)])),
|
||||||
|
(NodeId(1), proto_node(into_group::IDENTIFIER, vec![NodeInput::import(generic!(T), 1)])),
|
||||||
|
(NodeId(2), proto_node(extend::IDENTIFIER, vec![NodeInput::node(NodeId(0), 0), NodeInput::node(NodeId(1), 0)])),
|
||||||
|
]
|
||||||
|
.into_iter()
|
||||||
|
.collect(),
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A layer made from the network with this ID, adding a color onto the stack it's given.
|
||||||
|
fn layer(definition: NetworkId, base: NodeInput, color: Color) -> DocumentNode {
|
||||||
|
DocumentNode {
|
||||||
|
inputs: vec![base, NodeInput::value(TaggedValue::Color(color), false)],
|
||||||
|
implementation: DocumentNodeImplementation::Definition(definition),
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn layers_made_from_one_network_stack_in_the_order_given() {
|
||||||
|
let merge = NetworkId(1);
|
||||||
|
let empty = NodeInput::type_default(list!(Graphic), false);
|
||||||
|
let mut network = NodeNetwork {
|
||||||
|
exports: vec![NodeInput::node(NodeId(20), 0)],
|
||||||
|
nodes: [(NodeId(10), layer(merge, empty, Color::RED)), (NodeId(20), layer(merge, NodeInput::node(NodeId(10), 0), Color::BLUE))]
|
||||||
|
.into_iter()
|
||||||
|
.collect(),
|
||||||
|
definitions: [(merge, merge_like())].into_iter().collect(),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
assert!(export_layers(&mut network, &[NodeId(20), NodeId(10)]).is_some());
|
||||||
|
|
||||||
|
let colors: Vec<_> = evaluated(network).iter_element_values().map(color_of).collect();
|
||||||
|
assert_eq!(colors, [Some(Color::BLUE), Some(Color::RED)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The layer is made from a network holding a 'Merge' node, so what it adds is passed out through both networks
|
||||||
|
#[test]
|
||||||
|
fn a_layer_adding_content_from_a_nested_network_stacks_it() {
|
||||||
|
let (merge, outer) = (NetworkId(1), NetworkId(2));
|
||||||
|
let outer_network = NodeNetwork {
|
||||||
|
exports: vec![NodeInput::node(NodeId(30), 0)],
|
||||||
|
nodes: [(
|
||||||
|
NodeId(30),
|
||||||
|
DocumentNode {
|
||||||
|
inputs: vec![NodeInput::import(generic!(T), 0), NodeInput::import(generic!(T), 1)],
|
||||||
|
implementation: DocumentNodeImplementation::Definition(merge),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
)]
|
||||||
|
.into_iter()
|
||||||
|
.collect(),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let mut network = NodeNetwork {
|
||||||
|
exports: vec![NodeInput::node(NodeId(10), 0)],
|
||||||
|
nodes: [(NodeId(10), layer(outer, NodeInput::type_default(list!(Graphic), false), Color::RED))].into_iter().collect(),
|
||||||
|
definitions: [(merge, merge_like()), (outer, outer_network)].into_iter().collect(),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
assert!(export_layers(&mut network, &[NodeId(10)]).is_some());
|
||||||
|
|
||||||
|
let colors: Vec<_> = evaluated(network).iter_element_values().map(color_of).collect();
|
||||||
|
assert_eq!(colors, [Some(Color::RED)]);
|
||||||
|
}
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate log;
|
extern crate log;
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod export_layers_tests;
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod readback_tests;
|
mod readback_tests;
|
||||||
mod value_types;
|
mod value_types;
|
||||||
|
|||||||
@@ -140,7 +140,7 @@ struct Compiled {
|
|||||||
impl Compiled {
|
impl Compiled {
|
||||||
/// The `network` preprocessed and compiled with a GPU in scope, or `None` without a GPU.
|
/// The `network` preprocessed and compiled with a GPU in scope, or `None` without a GPU.
|
||||||
fn new(network: NodeNetwork) -> Option<Self> {
|
fn new(network: NodeNetwork) -> Option<Self> {
|
||||||
let gpu = futures::executor::block_on(wgpu_executor::WgpuExecutor::new())?;
|
let gpu = futures::executor::block_on(wgpu_executor::WgpuExecutor::for_tests())?;
|
||||||
let application_io = PlatformApplicationIo::new_with_executor(gpu);
|
let application_io = PlatformApplicationIo::new_with_executor(gpu);
|
||||||
Some(Self::with_application_io(network, application_io))
|
Some(Self::with_application_io(network, application_io))
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user