Files
Graphite/node-graph/preprocessor/src/readback_tests.rs
T

589 lines
26 KiB
Rust

//! Node inputs taking `Pixels`, which the compiler reads back from the images wired into them.
use super::*;
use core_types::blending::BlendMode;
use core_types::list::{Item, List};
use core_types::runtime::{AsyncRuntime, Spawn, Task};
use core_types::{ATTR_TRANSFORM, Color, Ctx, ExtractIndex, OwnedContextImpl, Poll};
use glam::{DAffine2, DVec2};
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
use graph_craft::graphene_compiler::Compiler;
use graphene_std::platform_application_io::Resource;
use graphene_std::raster::{CPU, Image, Pixels, Raster};
use graphene_std::vector::style::StrokeAlign;
use graphic_types::{Adjustment, Effect, EffectOperation, Graphic, stamp_effect};
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
use interpreted_executor::util::wrap_network_in_scope;
use std::sync::{Arc, Mutex};
/// A 2 by 2 black image, inverted by an effect if `inverted`, which reads back as white.
fn black_image(inverted: bool) -> Item<Raster<CPU>> {
let mut image = Item::new_from_element(Raster::new_cpu(Image::new(2, 2, Color::BLACK))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(2.)));
if inverted {
stamp_effect(&mut image, Effect::new(&EffectOperation::Adjustment(Adjustment::Invert)));
}
image
}
/// A black image and one inverted to white by its effect, as a list, like the output of Rasterize.
#[node_macro::node(category(""))]
fn black_and_inverted_images(_: impl Ctx, _primary: ()) -> List<Raster<CPU>> {
[black_image(false), black_image(true)].into_iter().collect()
}
/// A black image inverted to white by its effect.
#[node_macro::node(category(""))]
fn inverted_image(_: impl Ctx, _primary: ()) -> Item<Raster<CPU>> {
black_image(true)
}
/// A 4 by 4 image lighter for a higher index in its context, outlined so it reads back through a render. It lands a task after it's asked for, as a load in the browser does.
#[node_macro::node(category(""))]
async fn indexed_image(ctx: impl Ctx + ExtractIndex, _primary: ()) -> Item<Raster<CPU>> {
YieldOnce(false).await;
let index = ctx.try_index().and_then(|mut indices| indices.next()).unwrap_or_default();
let gray = index as f32 / 4.;
let color = Color::from_rgbaf32_unchecked(gray, gray, gray, 1.);
let mut image = Item::new_from_element(Raster::new_cpu(Image::new(4, 4, color))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(4.)));
stamp_effect(&mut image, Effect::new(&outline()));
image
}
/// A black outline a unit wide outside the content, which only a render carries out.
fn outline() -> EffectOperation {
EffectOperation::Outline {
paint: Graphic::from(Color::BLACK),
blend_mode: BlendMode::Normal,
weight: 1.,
align: StrokeAlign::Outside,
contour_gradient: false,
}
}
/// The pixels read back from the image wired into it, as a reader for these tests.
#[node_macro::node(category(""))]
fn read_pixels(_: impl Ctx, pixels: Item<Pixels>) -> Item<Raster<CPU>> {
let (pixels, attributes) = pixels.into_parts();
Item::from_parts(pixels.into_raster(), attributes)
}
/// The size of each image `recorded_pixels` was given, which only one test reads.
static RECORDED_SIZES: Mutex<Vec<(u32, u32)>> = Mutex::new(Vec::new());
/// The pixels read back from the image wired into it, as a reader recording the size of each image it's given.
#[node_macro::node(category(""))]
fn recorded_pixels(_: impl Ctx, pixels: Item<Pixels>) -> Item<Raster<CPU>> {
RECORDED_SIZES.lock().unwrap().push((pixels.element().width, pixels.element().height));
let (pixels, attributes) = pixels.into_parts();
Item::from_parts(pixels.into_raster(), attributes)
}
/// The image it's given, passed on as another node of a second output.
#[node_macro::node(category(""))]
fn same_image(_: impl Ctx, image: Item<Raster<CPU>>) -> Item<Raster<CPU>> {
image
}
/// Pending when first polled, as a download in the browser is until a later task of its event loop.
struct YieldOnce(bool);
impl std::future::Future for YieldOnce {
type Output = ();
fn poll(mut self: std::pin::Pin<&mut Self>, context: &mut std::task::Context<'_>) -> std::task::Poll<()> {
if self.0 {
return std::task::Poll::Ready(());
}
self.0 = true;
context.waker().wake_by_ref();
std::task::Poll::Pending
}
}
/// Holds each spawned task until the test runs it, as the browser runs it after the evaluation that spawned it.
#[derive(Default)]
struct QueuedSpawner(Mutex<Vec<Task>>);
impl Spawn for QueuedSpawner {
fn spawn(&self, task: Task) {
self.0.lock().unwrap().push(task);
}
}
impl QueuedSpawner {
/// Runs each queued task to its end, giving how many there were.
fn run_queued(&self) -> usize {
let tasks = std::mem::take(&mut *self.0.lock().unwrap());
let count = tasks.len();
tasks.into_iter().for_each(futures::executor::block_on);
count
}
fn queued(&self) -> usize {
self.0.lock().unwrap().len()
}
}
/// A network compiled with the editor API in scope, and the runtime its async nodes spawn their tasks on.
struct Compiled {
dynamic_executor: DynamicExecutor,
output: OutputHandle,
runtime: AsyncRuntime,
spawner: Arc<QueuedSpawner>,
editor_api: Arc<PlatformEditorApi>,
}
impl Compiled {
/// The `network` preprocessed and compiled with a GPU in scope, or `None` without a GPU.
fn new(network: NodeNetwork) -> Option<Self> {
let gpu = futures::executor::block_on(wgpu_executor::WgpuExecutor::for_tests())?;
let application_io = PlatformApplicationIo::new_with_executor(gpu);
Some(Self::with_application_io(network, application_io))
}
/// The `network` preprocessed and compiled with the `application_io` in scope.
fn with_application_io(network: NodeNetwork, application_io: PlatformApplicationIo) -> Self {
let spawner = Arc::new(QueuedSpawner::default());
let mut compiled = Self {
dynamic_executor: DynamicExecutor::default(),
output: OutputHandle::default(),
runtime: AsyncRuntime::new(spawner.clone()),
spawner,
editor_api: Arc::new(PlatformEditorApi {
application_io: Some(Arc::new(application_io)),
}),
};
compiled.output = compiled.compile(network);
compiled
}
/// The output of the `network`, compiled beside those before it and sharing the nodes they have in common.
fn compile(&mut self, network: NodeNetwork) -> OutputHandle {
let mut network = wrap_network_in_scope(network, self.editor_api.clone(), self.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 (output, _) = self.dynamic_executor.update(proto_network).expect("the network should type check and build");
self.runtime.update_sources(self.dynamic_executor.sources());
output
}
/// One evaluation of the `output` with the `index` in its context if given, reading the generations the landed tasks bumped, as the editor's evaluations do.
fn evaluate_once(&self, output: &OutputHandle, index: Option<usize>) -> Poll<core_types::registry::Any> {
let mut context = OwnedContextImpl::empty().with_generations(self.runtime.snapshot());
if let Some(index) = index {
context = context.with_index(index);
}
self.dynamic_executor.tree().evaluate(output.node(), &context.into_context()).expect("the output should evaluate")
}
/// The output evaluated until it's final, with the `index` in its context if given, running the tasks each evaluation spawns before the next.
/// Gives how many evaluations that took.
fn evaluate(&self, index: Option<usize>) -> (core_types::registry::Any, usize) {
for evaluations in 1..=1000 {
match self.evaluate_once(&self.output, index) {
Poll::Final(value) => return (value, evaluations),
Poll::Pending | Poll::Partial(_) => {
self.spawner.run_queued();
}
Poll::Error(error) => panic!("the output failed: {error}"),
Poll::Fallback(boxed) => panic!("the output failed: {}", boxed.1),
}
}
panic!("the output never became final")
}
}
fn proto_node(identifier: ProtoNodeIdentifier, inputs: Vec<NodeInput>) -> DocumentNode {
DocumentNode {
inputs,
implementation: DocumentNodeImplementation::ProtoNode(identifier),
..Default::default()
}
}
/// A network of the `node` fed by the `source` node, exporting the node's output `output_index`.
fn network(source: ProtoNodeIdentifier, node: DocumentNode, output_index: usize) -> NodeNetwork {
NodeNetwork {
exports: vec![NodeInput::node(NodeId(1), output_index)],
nodes: [(NodeId(0), proto_node(source, vec![NodeInput::value(TaggedValue::None, false)])), (NodeId(1), node)]
.into_iter()
.collect(),
..Default::default()
}
}
/// The node's inputs as a new one of it gets them.
fn default_inputs(identifier: &ProtoNodeIdentifier) -> Vec<NodeInput> {
let node_registry = core_types::registry::NODE_REGISTRY.lock().unwrap();
let metadata_registry = core_types::registry::NODE_METADATA.lock().unwrap();
let first_node_io = node_registry.get(identifier).and_then(|implementations| implementations.first()).map(|(_, node_io)| node_io);
let metadata = metadata_registry.get(identifier).expect("the node should have registered metadata");
node_inputs(&metadata.fields, first_node_io.unwrap_or(const { &NodeIOTypes::empty() }))
}
fn wire() -> NodeInput {
NodeInput::node(NodeId(0), 0)
}
/// The first pixel of each image, as the gamma-encoded red channel and alpha.
fn first_pixels(images: &List<Raster<CPU>>) -> Vec<(f32, f32)> {
images.iter_element_values().map(|image| (image.data[0].r(), image.data[0].a())).collect()
}
#[test]
fn the_read_back_adapter_takes_the_inputs_of_an_async_node() {
let reader = proto_node(read_pixels::IDENTIFIER, vec![NodeInput::value(TaggedValue::None, false)]);
let mut network = NodeNetwork {
exports: vec![NodeInput::node(NodeId(0), 0)],
nodes: [(NodeId(0), reader)].into_iter().collect(),
..Default::default()
};
let runtime = AsyncRuntime::new(Arc::new(QueuedSpawner::default()));
network = wrap_network_in_scope(network, Arc::default(), runtime.handle());
Preprocessor::new().preprocess(&mut network, &|_| None).expect("preprocessing should succeed");
let adapters: Vec<_> = (network.definitions.values().flat_map(|definition| definition.nodes.values()))
.filter(|node| node.implementation == DocumentNodeImplementation::ProtoNode(graphene_std::read_back::INPUT_ADAPTER))
.collect();
let [adapter] = adapters.as_slice() else {
panic!("the reader's input should have one read-back adapter, but has {}", adapters.len())
};
let environment = [
NodeInput::scope(graphene_std::platform_application_io::wgpu_executor::IDENTIFIER),
NodeInput::scope("runtime"),
NodeInput::Reflection(DocumentNodeMetadata::SourceId),
];
assert_eq!(adapter.inputs[1..], environment, "the adapter takes the executor, runtime, and source ID after the wire");
}
#[test]
fn an_item_wire_reads_back_the_image_with_its_effects() {
let Some(compiled) = Compiled::new(network(inverted_image::IDENTIFIER, proto_node(read_pixels::IDENTIFIER, vec![wire()]), 0)) else {
return;
};
let (output, _) = compiled.evaluate(None);
let image = output.downcast::<Item<Raster<CPU>>>().expect("the reader should output an image");
assert!(image.element().data.iter().all(|color| *color == Color::WHITE), "the black image reads back inverted to white");
}
#[test]
fn a_list_wire_reads_back_each_image() {
let Some(compiled) = Compiled::new(network(black_and_inverted_images::IDENTIFIER, proto_node(read_pixels::IDENTIFIER, vec![wire()]), 0)) else {
return;
};
let (output, _) = compiled.evaluate(None);
let images = output.downcast::<List<Raster<CPU>>>().expect("the reader should output a list of images");
assert_eq!(first_pixels(&images), [(0., 1.), (1., 1.)]);
}
#[test]
fn an_unwired_input_reads_back_no_pixels() {
let inputs = default_inputs(&read_pixels::IDENTIFIER);
assert_eq!(
inputs[0].as_value(),
Some(&TaggedValue::TypeDefault(core_types::item!(Raster<CPU>))),
"an unwired input holds the empty image"
);
let reader = NodeNetwork {
exports: vec![NodeInput::node(NodeId(0), 0)],
nodes: [(NodeId(0), proto_node(read_pixels::IDENTIFIER, inputs))].into_iter().collect(),
..Default::default()
};
let Some(compiled) = Compiled::new(reader) else { return };
let (output, _) = compiled.evaluate(None);
let image = output.downcast::<Item<Raster<CPU>>>().expect("the reader should output an image");
assert!(image.element().data.is_empty());
}
/// Evaluated under a series of contexts as a Repeat node does, the read-back adapter keeps a result for each, so evaluating them again neither waits nor reads back again.
#[test]
fn the_read_back_finishes_under_each_context_in_turn_and_keeps_its_result() {
let Some(compiled) = Compiled::new(network(indexed_image::IDENTIFIER, proto_node(read_pixels::IDENTIFIER, vec![wire()]), 0)) else {
return;
};
let read_back = |index: usize| {
let (output, evaluations) = compiled.evaluate(Some(index));
let image = output.downcast::<Item<Raster<CPU>>>().expect("the reader should output an image");
let raster = image.element();
let middle = raster.data[(raster.height / 2 * raster.width + raster.width / 2) as usize];
(raster.buffer_id(), middle.r(), evaluations)
};
// The source's task lands one evaluation later, and the readback with it
let first: Vec<_> = (0..3).map(read_back).collect();
for (index, &(_, _, evaluations)) in first.iter().enumerate() {
assert_eq!(evaluations, 2, "index {index} should become final once its source lands");
}
assert!(first[0].1 < first[1].1 && first[1].1 < first[2].1, "each index reads back its own image: {first:?}");
// Each landing bumps the source's generation, which the readback's context holds, so this pass may read back again, but each is final at once
let settled: Vec<_> = (0..3).map(read_back).collect();
assert!(
settled.iter().all(|&(_, _, evaluations)| evaluations == 1),
"a landed source keeps each index final at once: {settled:?}"
);
assert_eq!(compiled.spawner.run_queued(), 0, "nothing waits on a task");
// Once nothing lands, each context's read-back pixels are the ones kept for it, in any order
for index in [2, 0, 1] {
let (buffer_id, middle, evaluations) = read_back(index);
assert_eq!(evaluations, 1);
assert_eq!((buffer_id, middle), (settled[index].0, settled[index].1), "index {index} read back again");
}
assert_eq!(compiled.spawner.run_queued(), 0, "nothing waits on a task");
}
/// Readbacks waiting under three contexts at once, asked for by two outputs held together, all finish once what they wait on lands, sharing their pixels between the outputs.
/// A native download lands when it's asked for, so what's held pending is the image each readback waits on, as a download in the browser would be.
#[test]
fn readbacks_pending_under_several_contexts_for_two_outputs_finish_together() {
let Some(mut compiled) = Compiled::new(network(indexed_image::IDENTIFIER, proto_node(recorded_pixels::IDENTIFIER, vec![wire()]), 0)) else {
return;
};
let first_output = compiled.output.clone();
// The second output passes the reader's pixels through one more node, sharing the reader and its readback with the first
let mut second_network = network(indexed_image::IDENTIFIER, proto_node(recorded_pixels::IDENTIFIER, vec![wire()]), 0);
second_network.nodes.insert(NodeId(2), proto_node(same_image::IDENTIFIER, vec![NodeInput::node(NodeId(1), 0)]));
second_network.exports = vec![NodeInput::node(NodeId(2), 0)];
let second_output = compiled.compile(second_network);
// Each context waits on its image's task, which stays queued, and asking again starts nothing new
let asked_for = [(&first_output, 0), (&second_output, 1), (&first_output, 2)];
for _ in 0..2 {
for (output, index) in asked_for {
assert!(matches!(compiled.evaluate_once(output, Some(index)), Poll::Pending), "index {index} should wait on its image");
}
}
assert_eq!(compiled.spawner.queued(), 3, "one task for each context");
assert!(RECORDED_SIZES.lock().unwrap().is_empty(), "the reader ran while its pixels were unfinished");
// Once the images land, both outputs get each context's read-back pixels at once, the same ones
assert_eq!(compiled.spawner.run_queued(), 3);
let buffer_ids = |output: &OutputHandle| -> Vec<u64> {
(0..3)
.map(|index| match compiled.evaluate_once(output, Some(index)) {
Poll::Final(value) => value.downcast::<Item<Raster<CPU>>>().expect("the reader should output an image").element().buffer_id(),
_ => panic!("index {index} should be final once its image landed"),
})
.collect()
};
let first = buffer_ids(&first_output);
assert_eq!(buffer_ids(&second_output), first, "both outputs share each context's pixels");
assert_eq!(buffer_ids(&first_output), first, "evaluating again reuses each context's pixels");
assert_eq!(compiled.spawner.queued(), 0, "nothing was read back again");
// The reader only ever ran on read-back pixels, grown past the 4 by 4 image by its outline
assert!(RECORDED_SIZES.lock().unwrap().iter().all(|&size| size == (8, 8)), "{:?}", RECORDED_SIZES.lock().unwrap());
}
/// Without a GPU, a reader's input is an error.
#[test]
fn a_reader_without_a_gpu_fails() {
let compiled = Compiled::with_application_io(
network(inverted_image::IDENTIFIER, proto_node(read_pixels::IDENTIFIER, vec![wire()]), 0),
PlatformApplicationIo::default(),
);
let Poll::Error(error) = compiled.evaluate_once(&compiled.output, None) else {
panic!("the reader should fail without a GPU")
};
assert!(error.error().is::<wgpu_executor::NoGpuError>(), "the reader failed with {error}");
}
/// An image of 32 by 32 pixels with a dark disc and a red band on a light ground, enough for every reader to find shapes and colors in, inverted by an effect if `inverted`.
fn varied_image(inverted: bool) -> Item<Raster<CPU>> {
let data = (0..32 * 32)
.map(|index| {
let (x, y) = ((index % 32) as f64, (index / 32) as f64);
if DVec2::new(x - 12., y - 12.).length() < 8. {
Color::from_rgbaf32_unchecked(0.05, 0.1, 0.3, 1.)
} else if y >= 24. {
Color::from_rgbaf32_unchecked(0.8, 0.1, 0.1, 1.)
} else {
Color::from_rgbaf32_unchecked(0.9, 0.85, 0.7, 1.)
}
})
.collect();
let mut image = Item::new_from_element(Raster::new_cpu(Image { width: 32, height: 32, data })).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(32.)));
if inverted {
stamp_effect(&mut image, Effect::new(&EffectOperation::Adjustment(Adjustment::Invert)));
}
image
}
/// The varied image as it is.
#[node_macro::node(category(""))]
fn plain_varied_image(_: impl Ctx, _primary: ()) -> Item<Raster<CPU>> {
varied_image(false)
}
/// The varied image inverted by its effect.
#[node_macro::node(category(""))]
fn inverted_varied_image(_: impl Ctx, _primary: ()) -> Item<Raster<CPU>> {
varied_image(true)
}
/// Whether two outputs of a reader are equal, as tagged values where they convert or else as one of the types the readers output.
/// `None` for outputs of a type this can't compare.
fn outputs_equal(a: &core_types::registry::Any, b: &core_types::registry::Any) -> Option<bool> {
if let (Ok(a), Ok(b)) = (TaggedValue::try_from_std_any_ref(&**a), TaggedValue::try_from_std_any_ref(&**b)) {
return Some(a == b);
}
macro_rules! compare_as {
($($ty:ty),*) => {$(
if let (Some(a), Some(b)) = (a.downcast_ref::<$ty>(), b.downcast_ref::<$ty>()) {
return Some(a == b);
}
)*};
}
compare_as!(Item<Raster<CPU>>, List<Raster<CPU>>, List<Color>, List<Graphic>);
// Resources compare by their bytes
if let (Some(a), Some(b)) = (a.downcast_ref::<Item<Resource>>(), b.downcast_ref::<Item<Resource>>()) {
return Some(a.element().as_ref() == b.element().as_ref());
}
None
}
/// Every node input taking `Pixels`, by its node's identifier and its index, besides this module's own readers.
fn pixel_reading_inputs() -> Vec<(ProtoNodeIdentifier, usize)> {
let node_registry = core_types::registry::NODE_REGISTRY.lock().unwrap();
let metadata_registry = core_types::registry::NODE_METADATA.lock().unwrap();
let takes_pixels = |ty: &Type| matches!(ty.clone().normalize_rank().nested_type(), Type::Item(element) | Type::List(element) if **element == concrete!(Pixels));
let mut inputs: Vec<_> = (node_registry.iter())
.filter(|(identifier, _)| metadata_registry.contains_key(*identifier) && ![read_pixels::IDENTIFIER, recorded_pixels::IDENTIFIER].contains(*identifier))
.flat_map(|(identifier, implementations)| {
let indices: HashSet<usize> = (implementations.iter())
.flat_map(|(_, node_io)| node_io.inputs.iter().enumerate().filter(|(_, ty)| takes_pixels(ty)).map(|(index, _)| index))
.collect();
indices.into_iter().map(|index| (identifier.clone(), index))
})
.collect();
inputs.sort_by(|a, b| (a.0.as_str(), a.1).cmp(&(b.0.as_str(), b.1)));
inputs
}
/// Every node input taking `Pixels` reads the pixels as drawn, so an image under an effect gives a different output than the image alone.
/// A node gaining such an input has to be added to the list below on purpose.
#[test]
fn every_pixel_reading_input_reads_the_image_with_its_effects() {
let inputs = pixel_reading_inputs();
let identifiers: Vec<&str> = inputs.iter().map(|(identifier, _)| identifier.as_str()).collect();
let mut readers = [
graphene_std::platform_application_io::image_to_bytes::IDENTIFIER,
graphene_std::raster_nodes::dehaze::dehaze::IDENTIFIER,
graphene_std::raster_nodes::image_color_palette::image_color_palette::IDENTIFIER,
graphene_std::vectorize_nodes::vectorize::IDENTIFIER,
];
readers.sort_by(|a, b| a.as_str().cmp(b.as_str()));
assert_eq!(identifiers, readers.iter().map(ProtoNodeIdentifier::as_str).collect::<Vec<_>>(), "the nodes reading pixels");
for (identifier, index) in inputs {
let mut node_inputs = default_inputs(&identifier);
node_inputs[index] = wire();
let output = |source: ProtoNodeIdentifier| {
let compiled = Compiled::new(network(source, proto_node(identifier.clone(), node_inputs.clone()), 0))?;
Some(compiled.evaluate(None).0)
};
let (Some(plain), Some(inverted)) = (output(plain_varied_image::IDENTIFIER), output(inverted_varied_image::IDENTIFIER)) else {
return;
};
let equal = outputs_equal(&plain, &inverted).unwrap_or_else(|| panic!("{} gives an output this test can't compare", identifier.as_str()));
assert!(!equal, "{} gives the same output for an image whether or not it's inverted by an effect", identifier.as_str());
}
}
/// A 96 by 96 image of gray noise, outlined so it reads back through a render, which Vectorize traces over several evaluations.
#[node_macro::node(category(""))]
fn outlined_noise(_: impl Ctx, _primary: ()) -> Item<Raster<CPU>> {
// Pseudo-random grays from an xorshift sequence, so the trace finds many small regions
let mut state = 0x2545_f491_u32;
let data = (0..96 * 96)
.map(|_| {
state ^= state << 13;
state ^= state >> 17;
state ^= state << 5;
let gray = (state % 256) as f32 / 255.;
Color::from_rgbaf32_unchecked(gray, gray, gray, 1.)
})
.collect();
let mut image = Item::new_from_element(Raster::new_cpu(Image { width: 96, height: 96, data })).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(96.)));
stamp_effect(&mut image, Effect::new(&outline()));
image
}
/// Each slice of a trace bumps the generation of Vectorize's source, which mustn't read the image back again and so restart the trace.
#[test]
fn a_trace_of_read_back_pixels_runs_to_its_end() {
let mut inputs = default_inputs(&graphene_std::vectorize_nodes::vectorize::IDENTIFIER);
inputs[0] = wire();
let Some(compiled) = Compiled::new(network(outlined_noise::IDENTIFIER, proto_node(graphene_std::vectorize_nodes::vectorize::IDENTIFIER, inputs), 0)) else {
return;
};
let (output, evaluations) = compiled.evaluate(None);
let traced = output.downcast::<List<Graphic>>().expect("Vectorize should output graphics");
assert!(evaluations > 1, "the trace should take several slices");
assert!(!traced.is_empty());
}
/// The node `identifier` with these `inputs`, its input fed a list of a black image and one inverted to white by an effect, giving its output.
fn evaluate_on_two_images<T: 'static>(identifier: ProtoNodeIdentifier, inputs: Vec<NodeInput>) -> Option<T> {
let compiled = Compiled::new(network(black_and_inverted_images::IDENTIFIER, proto_node(identifier.clone(), inputs), 0))?;
let (output, _) = compiled.evaluate(None);
Some(*output.downcast::<T>().unwrap_or_else(|_| panic!("{} should output a list of each image's result", identifier.as_str())))
}
#[test]
fn dehaze_reads_back_each_image_of_a_list() {
let inputs = vec![wire(), NodeInput::value(TaggedValue::Number(0.), false)];
let Some(images) = evaluate_on_two_images::<List<Raster<CPU>>>(graphene_std::raster_nodes::dehaze::dehaze::IDENTIFIER, inputs) else {
return;
};
let sizes: Vec<_> = images.iter_element_values().map(|image| (image.width, image.height)).collect();
assert_eq!(sizes, [(2, 2), (2, 2)]);
// Without any strength, the haze removal keeps each image's own read-back colors
let colors: Vec<_> = images
.iter_element_values()
.flat_map(|image| image.data.iter().map(|color| (color.r().round(), color.a().round())))
.collect();
assert_eq!(colors, [[(0., 1.); 4], [(1., 1.); 4]].concat(), "the black image stays black and the inverted one white");
}
#[test]
fn image_color_palette_finds_each_image_of_a_list_its_own_colors() {
let inputs = vec![wire(), NodeInput::value(TaggedValue::Integer(1), false)];
let Some(colors) = evaluate_on_two_images::<List<Color>>(graphene_std::raster_nodes::image_color_palette::image_color_palette::IDENTIFIER, inputs) else {
return;
};
let colors: Vec<_> = colors.iter_element_values().map(|color| (color.r().round(), color.a())).collect();
assert_eq!(colors, [(0., 1.), (1., 1.)], "one color for each image, in order");
}
#[test]
fn image_to_bytes_reads_back_each_image_of_a_list() {
let Some(resources) = evaluate_on_two_images::<List<Resource>>(graphene_std::platform_application_io::image_to_bytes::IDENTIFIER, vec![wire()]) else {
return;
};
let bytes: Vec<Vec<u8>> = resources.iter_element_values().map(|resource| resource.as_ref().to_vec()).collect();
assert_eq!(bytes, [[0, 0, 0, 255].repeat(4), [255, 255, 255, 255].repeat(4)]);
}