Read images back ahead of node inputs that take 'Pixels'

This commit is contained in:
Keavon Chambers committed 2026-12-05 07:59:54 -08:00
1 parent 6f4ef1fe3d
commit f3dafd9dc2
9 files changed
+485 -3

No files matched your search

Generated
+2
View File
@@ -5437,9 +5437,11 @@ dependencies = [
"glam",
"graph-craft",
"graphene-std",
"graphic-types",
"interpreted-executor",
"log",
"node-macro",
"wgpu-executor",
]
[[package]]
@@ -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,
}
+9 -1
View File
@@ -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<CPU>)));
}
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<CPU>)));
}
macro_rules! check {
($type_default:ty) => {
if **element == concrete!($type_default) { return Some(TaggedValue::TypeDefault(input.clone())); }
@@ -440,6 +440,8 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
node_types.extend(ranked_value_types!(cache_chain_nodes));
// The direct counterpart to `Box<VectorModification>`'s promotion adapter above (see that note)
node_types.extend(cache_chain_nodes!(Box<VectorModification>));
// 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<DashPattern>` dash connector by parsing each element into a dash pattern
@@ -496,6 +498,20 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
// Position and transform wires may feed a ranked `String` connector by formatting each element as text
node_types.extend(convert_adapter_node!(from_element: DVec2, element: String));
node_types.extend(convert_adapter_node!(from_element: DAffine2, element: String));
// An image wire feeds a `Pixels` connector through its GPU readback, an async node taking the executor, runtime, and source ID after the wire.
// These rows have no one-input passthrough siblings, which type resolution would match by their first input alone.
macro_rules! read_back_node {
($node:ty, wire: $wire:ty) => {
async_node!(
identifier: graphene_std::read_back::INPUT_ADAPTER,
$node,
input: Context,
fn_params: [Context => $wire, Context => Item<wgpu_executor::WgpuExecutor>, Context => Item<graphene_std::RuntimeHandle>, Context => Item<graphene_std::SourceId>]
)
};
}
node_types.push(read_back_node!(graphene_std::read_back::ReadBackNode<_, _, _, _>, wire: Item<Raster<CPU>>));
node_types.push(read_back_node!(graphene_std::read_back::ReadBackListNode<_, _, _, _>, wire: List<Raster<CPU>>));
// 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>) => {
+1
View File
@@ -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;
+32
View File
@@ -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<Pixels>");
/// 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<Raster<CPU>>,
#[scope(crate::platform_application_io::wgpu_executor::IDENTIFIER)] executor: Item<wgpu_executor::WgpuExecutor>,
) -> Result<Item<Pixels>, 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<Raster<CPU>>,
#[scope(crate::platform_application_io::wgpu_executor::IDENTIFIER)] executor: Item<wgpu_executor::WgpuExecutor>,
) -> Result<List<Pixels>, 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)
}
+2
View File
@@ -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 }
+21 -2
View File
@@ -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<NodeInput> = 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,
@@ -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<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::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<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}");
}