From f3dafd9dc2012db5604bb2f05466f5c1cf4426b0 Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Sat, 5 Dec 2026 06:08:48 -0800 Subject: [PATCH] Read images back ahead of node inputs that take 'Pixels' --- Cargo.lock | 2 + .../document/node_graph/utility_types.rs | 1 + node-graph/graph-craft/src/document/value.rs | 10 +- .../interpreted-executor/src/node_registry.rs | 16 + node-graph/nodes/gstd/src/lib.rs | 1 + node-graph/nodes/gstd/src/read_back.rs | 32 ++ node-graph/preprocessor/Cargo.toml | 2 + node-graph/preprocessor/src/lib.rs | 23 +- node-graph/preprocessor/src/readback_tests.rs | 401 ++++++++++++++++++ 9 files changed, 485 insertions(+), 3 deletions(-) create mode 100644 node-graph/nodes/gstd/src/read_back.rs create mode 100644 node-graph/preprocessor/src/readback_tests.rs diff --git a/Cargo.lock b/Cargo.lock index 041e9e6d7a..28b5f85218 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5437,9 +5437,11 @@ dependencies = [ "glam", "graph-craft", "graphene-std", + "graphic-types", "interpreted-executor", "log", "node-macro", + "wgpu-executor", ] [[package]] diff --git a/editor/src/messages/portfolio/document/node_graph/utility_types.rs b/editor/src/messages/portfolio/document/node_graph/utility_types.rs index efa78006c1..4ed0723ce9 100644 --- a/editor/src/messages/portfolio/document/node_graph/utility_types.rs +++ b/editor/src/messages/portfolio/document/node_graph/utility_types.rs @@ -37,6 +37,7 @@ impl FrontendGraphDataType { "f64" | "i64" | "bool" | "DVec2" | "DAffine2" => Self::Number, // A generator draws pixels like an image, at whatever resolution is needed "Generator" => Self::Raster, + "Pixels" => Self::Raster, raster if raster.starts_with("Raster") => Self::Raster, _ => Self::General, } diff --git a/node-graph/graph-craft/src/document/value.rs b/node-graph/graph-craft/src/document/value.rs index 408ea19bca..1e363a782c 100644 --- a/node-graph/graph-craft/src/document/value.rs +++ b/node-graph/graph-craft/src/document/value.rs @@ -12,7 +12,7 @@ pub use glam::{DAffine2, DVec2, IVec2, UVec2}; use graphene_animation::AnimationCurve; use graphene_application_io::resource::ResourceHash; use graphene_application_io::resource::ResourceId; -use graphic_types::raster_types::{CPU, Image, Raster}; +use graphic_types::raster_types::{CPU, Image, Pixels, Raster}; use graphic_types::vector_types::vector::misc::BoxCorners; use graphic_types::vector_types::vector::style::DashPattern; use graphic_types::vector_types::vector::style::{Gradient, GradientRamp}; @@ -400,6 +400,11 @@ macro_rules! tagged_value { Type::Fn(_, output) => TaggedValue::from_type(output), // Element types with a dedicated variant use it directly (the variant's value is a rank-0 cell); the rest store the structural type Type::Item(element) => TaggedValue::from_type(element).or_else(|| { + // Pixels are read back from an image, so a `Pixels` input holds the empty image + if **element == concrete!(Pixels) { + return Some(TaggedValue::TypeDefault(item!(Raster))); + } + macro_rules! check { ($type_default:ty) => { if **element == concrete!($type_default) { return Some(TaggedValue::TypeDefault(input.clone())); } @@ -416,6 +421,9 @@ macro_rules! tagged_value { if **element == concrete!(Stroke) { return Some(TaggedValue::Strokes(Vec::new())); } + if **element == concrete!(Pixels) { + return Some(TaggedValue::TypeDefault(list!(Raster))); + } macro_rules! check { ($type_default:ty) => { if **element == concrete!($type_default) { return Some(TaggedValue::TypeDefault(input.clone())); } diff --git a/node-graph/interpreted-executor/src/node_registry.rs b/node-graph/interpreted-executor/src/node_registry.rs index 81f77a5a1d..77856c61f5 100644 --- a/node-graph/interpreted-executor/src/node_registry.rs +++ b/node-graph/interpreted-executor/src/node_registry.rs @@ -440,6 +440,8 @@ fn node_registry() -> HashMap`'s promotion adapter above (see that note) node_types.extend(cache_chain_nodes!(Box)); + // Context nullification can wrap the read-back adapter's output + node_types.extend(cache_chain_nodes!(Pixels)); // A position wire may feed a ranked vector connector, each position becoming a single-anchor vector node_types.extend(input_adapter_row!(from_element: DVec2, element: Vector)); // A string wire may feed the ranked `Item` dash connector by parsing each element into a dash pattern @@ -496,6 +498,20 @@ fn node_registry() -> HashMap { + async_node!( + identifier: graphene_std::read_back::INPUT_ADAPTER, + $node, + input: Context, + fn_params: [Context => $wire, Context => Item, Context => Item, Context => Item] + ) + }; + } + node_types.push(read_back_node!(graphene_std::read_back::ReadBackNode<_, _, _, _>, wire: Item>)); + node_types.push(read_back_node!(graphene_std::read_back::ReadBackListNode<_, _, _, _>, wire: List>)); // The sanctioned attribute value conversions: an Item wire's elements box per cell, while a List wire boxes whole as one value macro_rules! attribute_value_node { (Item<$element:ty>) => { diff --git a/node-graph/nodes/gstd/src/lib.rs b/node-graph/nodes/gstd/src/lib.rs index b60dab158e..70717bdcc2 100644 --- a/node-graph/nodes/gstd/src/lib.rs +++ b/node-graph/nodes/gstd/src/lib.rs @@ -1,6 +1,7 @@ pub mod any; pub mod platform_application_io; pub mod poll_debug; +pub mod read_back; pub mod render_background; pub mod render_cache; pub mod render_node; diff --git a/node-graph/nodes/gstd/src/read_back.rs b/node-graph/nodes/gstd/src/read_back.rs new file mode 100644 index 0000000000..57b7369221 --- /dev/null +++ b/node-graph/nodes/gstd/src/read_back.rs @@ -0,0 +1,32 @@ +use core_types::list::{Item, List}; +use core_types::{Ctx, NodeError, ProtoNodeIdentifier}; +use graphic_types::raster_types::{CPU, Pixels, Raster}; + +/// The input adapter the compiler places ahead of each node input taking `Pixels`, with `read_back` and `read_back_list` as its rows. +pub const INPUT_ADAPTER: ProtoNodeIdentifier = ProtoNodeIdentifier::new("input_adapter"); + +/// Reads back the pixels of an image as the GPU draws it with its effects and fill, for a node input taking `Pixels`. It stays pending until the download lands, so the reader doesn't run on stand-in pixels. +#[node_macro::node(category("_Adapters"), skip_impl)] +async fn read_back( + _: impl Ctx, + image: Item>, + #[scope(crate::platform_application_io::wgpu_executor::IDENTIFIER)] executor: Item, +) -> Result, NodeError> { + executor.element().read_back(image).await.map_err(NodeError::new) +} + +/// The `List` counterpart of `read_back`, reading back each image in turn. +#[node_macro::node(category("_Adapters"), skip_impl)] +async fn read_back_list( + _: impl Ctx, + images: List>, + #[scope(crate::platform_application_io::wgpu_executor::IDENTIFIER)] executor: Item, +) -> Result, NodeError> { + let executor = executor.element(); + + let mut read_back = List::new(); + for image in images.into_iter() { + read_back.push(executor.read_back(image).await.map_err(NodeError::new)?); + } + Ok(read_back) +} diff --git a/node-graph/preprocessor/Cargo.toml b/node-graph/preprocessor/Cargo.toml index bae4d97946..cade1e05a3 100644 --- a/node-graph/preprocessor/Cargo.toml +++ b/node-graph/preprocessor/Cargo.toml @@ -31,3 +31,5 @@ futures = { workspace = true } glam = { workspace = true } node-macro = { workspace = true } document-loader = { workspace = true } +graphic-types = { workspace = true } +wgpu-executor = { workspace = true } diff --git a/node-graph/preprocessor/src/lib.rs b/node-graph/preprocessor/src/lib.rs index 3622d65394..d2b18ce151 100644 --- a/node-graph/preprocessor/src/lib.rs +++ b/node-graph/preprocessor/src/lib.rs @@ -1,6 +1,8 @@ #[macro_use] extern crate log; +#[cfg(test)] +mod readback_tests; mod value_types; use graph_craft::Type; @@ -195,7 +197,18 @@ impl Preprocessor { // We pre initialize the node registry here to avoid a deadlock let into_node_registry = &*interpreted_executor::node_registry::NODE_REGISTRY; let node_registry = core_types::registry::NODE_REGISTRY.lock().unwrap(); - for (id, metadata) in core_types::registry::NODE_METADATA.lock().unwrap().iter() { + let node_metadata = core_types::registry::NODE_METADATA.lock().unwrap(); + + // The read-back adapter is async, so it takes the executor, runtime, and source ID after the wire + let read_back_environment: Vec = match node_metadata.get(&read_back::read_back::IDENTIFIER) { + Some(metadata) => node_inputs(&metadata.fields, const { &NodeIOTypes::empty() }).into_iter().skip(1).collect(), + None => { + error!("The read-back adapter's node has no metadata, so it can't be given its executor, runtime, and source ID"); + Vec::new() + } + }; + + for (id, metadata) in node_metadata.iter() { let id = id.clone(); let NodeMetadata { @@ -254,8 +267,14 @@ impl Preprocessor { generated_nodes += 1; let mut original_location = OriginalLocation::default(); original_location.auto_convert_index = Some(i); + + let mut adapter_inputs = vec![NodeInput::import(generic!(X), i)]; + if input_adapter_identifier == read_back::INPUT_ADAPTER { + adapter_inputs.extend(read_back_environment.iter().cloned()); + } + let document_node = DocumentNode { - inputs: vec![NodeInput::import(generic!(X), i)], + inputs: adapter_inputs, implementation: DocumentNodeImplementation::ProtoNode(input_adapter_identifier), visible: true, compile_metadata: forwarding, diff --git a/node-graph/preprocessor/src/readback_tests.rs b/node-graph/preprocessor/src/readback_tests.rs new file mode 100644 index 0000000000..85f4b424ac --- /dev/null +++ b/node-graph/preprocessor/src/readback_tests.rs @@ -0,0 +1,401 @@ +//! 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::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> { + 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> { + [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> { + 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> { + 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) -> Item> { + 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> = 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) -> Item> { + 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>) -> Item> { + 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>); + +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, + editor_api: Arc, +} + +impl Compiled { + /// The `network` preprocessed and compiled with a GPU in scope, or `None` without a GPU. + fn new(network: NodeNetwork) -> Option { + let gpu = futures::executor::block_on(wgpu_executor::WgpuExecutor::new())?; + 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) -> Poll { + 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) -> (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) -> 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 { + 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>) -> 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::>>().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::>>().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))), + "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::>>().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::>>().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 { + (0..3) + .map(|index| match compiled.evaluate_once(output, Some(index)) { + Poll::Final(value) => value.downcast::>>().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::(), "the reader failed with {error}"); +}