Compare commits

..
14 changed files with 302 additions and 295 deletions

No files matched your search

Generated
-1
View File
@@ -1900,7 +1900,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "928452f9c953e142b2f0973e4bd5f34445fcaa8069556ea97a3c9d34d15a4cf8"
dependencies = [
"bytemuck",
"libm",
"serde_core",
]
+2 -2
View File
@@ -194,7 +194,7 @@ color = "0.3"
rand = { version = "0.9", default-features = false, features = ["std_rng"] }
rand_chacha = "0.9"
glam = { version = "0.33", default-features = false, features = [
"nostd-libm",
"std",
"scalar-math",
"bytemuck",
"debug-glam-assert",
@@ -220,7 +220,7 @@ pretty_assertions = "1.4"
fern = { version = "0.7", features = ["colored"] }
num_enum = { version = "0.7", default-features = false }
num-derive = "0.4"
num-traits = { version = "0.2", default-features = false, features = ["libm"] }
num-traits = "0.2"
tsify = { version = "0.5", default-features = false, features = ["js"] }
syn = { version = "2.0", default-features = false, features = [
"full",
@@ -1857,56 +1857,6 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
}
}
// Noise Pattern and Mandelbrot once drew images cut off at a square, 100 units for a clipped Noise Pattern and 1 for Mandelbrot, where their
// patterns now fill the plane. An old Noise Pattern has a Clip toggle, after the primary input or first from before that input existed,
// and an old Mandelbrot lacks the primary input. Each takes the current inputs, with a square filled by its pattern where it was cut off.
const NOISE_SETTINGS: usize = 14;
let old_pattern_nodes = document
.network_interface
.document_network()
.recursive_nodes()
.filter_map(|(node_id, node, path)| {
let reference = document.network_interface.reference(node_id, &path)?;
let clipped = |clip_index: usize| !matches!(node.inputs.get(clip_index).and_then(|input| input.as_value()), Some(TaggedValue::Bool(false)));
let pipeline = NodeInput::scope(graphene_std::raster_nodes::raster_kernel::raster_kernel_pipeline::IDENTIFIER);
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER) {
let starts_with_clip = matches!(node.inputs.first().and_then(|input| input.as_value()), Some(TaggedValue::Bool(_)));
let clip_index = match node.inputs.len() {
// Also with the pipeline input these nodes took when they rendered on the GPU themselves
17 if node.inputs.last() == Some(&pipeline) => 1,
16 => 1,
15 if starts_with_clip => 0,
_ => return None,
};
return Some((*node_id, path, reference, Some(clip_index), clipped(clip_index).then_some(100.)));
}
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER) && (node.inputs.is_empty() || node.inputs == [pipeline]) {
return Some((*node_id, path, reference, None, Some(1.)));
}
None
})
.collect::<Vec<_>>();
for (node_id, network_path, reference, clip_index, clipped_size) in &old_pattern_nodes {
let Some(definition) = resolve_document_node_type(reference) else { continue };
let mut node_template = definition.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let Some(old_inputs) = document.network_interface.replace_inputs(node_id, network_path, &mut node_template) else {
continue;
};
// The noise settings follow the Clip toggle, in the same order as the current inputs after the primary one
if let Some(clip_index) = clip_index {
for (offset, input) in old_inputs.iter().skip(clip_index + 1).take(NOISE_SETTINGS).enumerate() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1 + offset), input.clone(), network_path);
}
}
if let Some(size) = clipped_size {
fill_square_with_pattern(document, node_id, network_path, *size);
}
}
// Parameters that historically accepted fractional numbers are now integers (the polygon and star "Sides", the index,
// shift amount, and slice bound parameters of the list, string, and regex nodes, the "Path is Closed" index, and the
// "Blend" count), so a stored F64 truncates as those slots' own casts and Floor node did, preserving what documents drew
@@ -1960,76 +1910,6 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
document.require_whole_document_stage();
}
/// Splices a rectangle filled with the pattern node's output onto the wires leaving it, covering the square from the origin of the pattern's space out to `size`.
/// The rectangle is centered on its origin, so a Transform moves it onto the square, and the paint is moved back by the same amount to stay in place.
fn fill_square_with_pattern(document: &mut DocumentMessageHandler, pattern_node_id: &NodeId, network_path: &[NodeId], size: f64) -> Option<()> {
let downstream_consumers: Vec<InputConnector> = document
.network_interface
.outward_wires(network_path)
.and_then(|wires| wires.get(&OutputConnector::node(*pattern_node_id, 0)))
.cloned()
.unwrap_or_default();
let was_in_chain = document.network_interface.is_chain(pattern_node_id, network_path);
let template = |identifier| resolve_document_node_type(&DefinitionIdentifier::ProtoNode(identifier)).map(|definition| definition.default_node_template());
let rectangle_template = template(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER)?;
let fill_template = template(graphene_std::vector_nodes::fill::IDENTIFIER)?;
let transform_template = template(graphene_std::transform_nodes::transform::IDENTIFIER)?;
let [rectangle_id, fill_id, paint_transform_id, placement_transform_id] = [(); 4].map(|_| NodeId::new());
document.network_interface.insert_node(rectangle_id, rectangle_template, network_path);
document.network_interface.insert_node(fill_id, fill_template, network_path);
document.network_interface.insert_node(paint_transform_id, transform_template.clone(), network_path);
document.network_interface.insert_node(placement_transform_id, transform_template, network_path);
let set_value = |document: &mut DocumentMessageHandler, node_id: NodeId, index: usize, value: TaggedValue| {
document
.network_interface
.set_input(&InputConnector::node_at_index(node_id, index), NodeInput::value(value, false), network_path);
};
let wire = |document: &mut DocumentMessageHandler, node_id: NodeId, index: usize, source: NodeId| {
document
.network_interface
.set_input(&InputConnector::node_at_index(node_id, index), NodeInput::node(source, 0), network_path);
};
// The rectangle's width and height, and the half-square translations of the paint and the filled rectangle
set_value(document, rectangle_id, 1, TaggedValue::Number(size));
set_value(document, rectangle_id, 2, TaggedValue::Number(size));
set_value(document, paint_transform_id, 1, TaggedValue::DVec2(DVec2::splat(-size / 2.)));
set_value(document, placement_transform_id, 1, TaggedValue::DVec2(DVec2::splat(size / 2.)));
wire(document, paint_transform_id, 0, *pattern_node_id);
wire(document, fill_id, 0, rectangle_id);
wire(document, fill_id, 1, paint_transform_id);
wire(document, placement_transform_id, 0, fill_id);
for consumer in &downstream_consumers {
document.network_interface.set_input(consumer, NodeInput::node(placement_transform_id, 0), network_path);
}
// A pattern in a layer chain gives way to the filled rectangle there, moving below to paint it, and otherwise the new nodes sit beside it
if was_in_chain {
document.network_interface.force_set_upstream_to_chain(&placement_transform_id, network_path);
if let Some(fill_position) = document.network_interface.position(&fill_id, network_path) {
document.network_interface.set_absolute_position(&paint_transform_id, fill_position + IVec2::new(-7, 3), network_path);
document.network_interface.set_absolute_position(pattern_node_id, fill_position + IVec2::new(-14, 3), network_path);
}
} else if let Some(position) = document.network_interface.position(pattern_node_id, network_path) {
let offsets = [
(paint_transform_id, IVec2::new(7, 0)),
(rectangle_id, IVec2::new(7, -3)),
(fill_id, IVec2::new(14, 0)),
(placement_transform_id, IVec2::new(21, 0)),
];
for (node_id, offset) in offsets {
document.network_interface.shift_absolute_node_position(&node_id, position + offset, network_path);
}
}
Some(())
}
/// 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> {
let NodeInput::Value { tagged_value, exposed } = input else { return None };
@@ -2880,6 +2760,20 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
}
}
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER) && inputs_count == 15 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 0), NodeInput::value(TaggedValue::None, false), network_path);
for (i, input) in old_inputs.iter().enumerate() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, i + 1), input.clone(), network_path);
}
}
// The Threshold node's luminance calculation input was retired
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::adjustments::threshold::IDENTIFIER) && inputs_count == 4 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
@@ -3689,6 +3583,8 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
graphene_std::raster_nodes::std_nodes::channels_to_image::IDENTIFIER,
graphene_std::raster_nodes::std_nodes::mask::IDENTIFIER,
graphene_std::raster_nodes::std_nodes::extend_image_to_bounds::IDENTIFIER,
graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER,
graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER,
graphene_std::raster_nodes::filter::median_filter::IDENTIFIER,
graphene_std::raster_nodes::effects::blur::IDENTIFIER,
graphene_std::raster_nodes::image_color_palette::image_color_palette::IDENTIFIER,
@@ -5420,81 +5316,4 @@ mod tests {
assert_eq!(interface.display_name(&node_id, &[]), "Image", "node {node_id}");
}
}
// Noise Pattern and Mandelbrot once drew a square of their patterns, which now fill the plane, so the square becomes a rectangle filled with the pattern
#[tokio::test]
async fn clipped_patterns_become_rectangles_filled_with_them() {
use crate::messages::portfolio::document_storage_io::load_legacy_document;
use crate::test_utils::test_prelude::*;
use graph_craft::application_io::resource::HashMapResourceStorage;
let proto = |identifier| DefinitionIdentifier::ProtoNode(identifier);
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let noise = editor.create_node_by_name(proto(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER)).await;
let mandelbrot = editor.create_node_by_name(proto(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER)).await;
let noise_reader = editor.create_node_by_name(proto(graphene_std::transform_nodes::transform::IDENTIFIER)).await;
let mandelbrot_reader = editor.create_node_by_name(proto(graphene_std::transform_nodes::transform::IDENTIFIER)).await;
let document = editor.active_document_mut();
for (reader, pattern) in [(noise_reader, noise), (mandelbrot_reader, mandelbrot)] {
document.network_interface.set_input(&InputConnector::node_at_index(reader, 0), NodeInput::node(pattern, 0), &[]);
}
// Save them as an older editor did, the Noise Pattern with its Clip toggle on and the Mandelbrot without a primary input
let mut noise_inputs = document.network_interface.document_node(&noise, &[]).unwrap().inputs.clone();
noise_inputs.insert(1, NodeInput::value(TaggedValue::Bool(true), false));
noise_inputs[2] = NodeInput::value(TaggedValue::Integer(7), false);
for (node_id, inputs) in [(noise, noise_inputs), (mandelbrot, Vec::new())] {
let mut legacy = NodeTemplate { inputs, ..Default::default() };
legacy.normalize_input_metadata();
document.network_interface.replace_inputs(&node_id, &[], &mut legacy);
}
let serialized = document.serialize_document();
let opened = load_legacy_document(serialized, &HashMapResourceStorage::new(), false).expect("the document should open");
let interface = &opened.network_interface;
let input = |node_id: NodeId, index: usize| interface.document_node(&node_id, &[]).and_then(|node| node.inputs.get(index)).cloned();
let upstream = |node_id: NodeId, index: usize| input(node_id, index).and_then(|input| input.as_node());
let value = |node_id: NodeId, index: usize| input(node_id, index).and_then(|input| input.as_value().cloned());
// Each reader now reads a rectangle of the square's size, moved onto the square, filled with the pattern moved back by the same amount
for (reader, pattern, size) in [(noise_reader, noise, 100.), (mandelbrot_reader, mandelbrot, 1.)] {
let placement = upstream(reader, 0).expect("the reader should read the placement transform");
assert_eq!(value(placement, 1), Some(TaggedValue::DVec2(DVec2::splat(size / 2.))));
let fill = upstream(placement, 0).expect("the placement should move the filled rectangle");
let rectangle = upstream(fill, 0).expect("the fill should paint a rectangle");
assert_eq!((value(rectangle, 1), value(rectangle, 2)), (Some(TaggedValue::Number(size)), Some(TaggedValue::Number(size))));
let paint = upstream(fill, 1).expect("the fill should paint with the moved pattern");
assert_eq!(value(paint, 1), Some(TaggedValue::DVec2(DVec2::splat(-size / 2.))));
assert_eq!(upstream(paint, 0), Some(pattern));
}
// The noise settings shift down past the removed Clip toggle, and the Mandelbrot gains its primary input
assert_eq!(interface.document_node(&noise, &[]).unwrap().inputs.len(), 15);
assert_eq!(value(noise, 1), Some(TaggedValue::Integer(7)));
assert_eq!(interface.document_node(&mandelbrot, &[]).unwrap().inputs.len(), 1);
}
// The demo draws its patterns through layers and adjustments, which must all take the generators the patterns now are
#[tokio::test]
async fn marbled_mandelbrot_renders_after_migration() {
use crate::messages::portfolio::ingest::utility_types::IngestAction;
use crate::messages::prelude::IngestMessage;
use crate::test_utils::test_prelude::*;
let mut editor = EditorTestUtils::create();
let content = std::fs::read_to_string("../demo-artwork/marbled-mandelbrot.graphite").unwrap();
editor.editor.handle_message(IngestMessage::Ingest {
data: content.into_bytes(),
action: IngestAction::Open,
mime_type: String::new(),
path: Some("marbled-mandelbrot.graphite".into()),
});
if let Err(error) = editor.eval_graph_until_finished().await {
panic!("The migrated demo failed to render: {error}");
}
}
}
@@ -17,7 +17,6 @@ workspace = true
[features]
default = ["serde"]
serde = ["dep:serde", "glam/serde", "half/serde"]
nightly = []
type_id_logging = []
dealloc_nodes = []
wasm = ["tsify", "wasm-bindgen"]
@@ -15,11 +15,9 @@ publish.workspace = true
workspace = true
[features]
default = ["std"]
std = ["dep:kurbo"]
derive = ["graphene-hash-derive"]
[dependencies]
graphene-hash-derive = { path = "derive", optional = true }
glam = { workspace = true }
kurbo = { workspace = true, optional = true }
kurbo = { workspace = true }
@@ -1,8 +1,3 @@
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(feature = "std")]
extern crate std;
#[cfg(feature = "derive")]
pub use graphene_hash_derive::CacheHash;
@@ -66,7 +61,6 @@ impl_via_hash! {
glam::BVec2, glam::BVec3, glam::BVec4,
}
#[cfg(feature = "std")]
impl_via_hash! {
String,
}
@@ -154,7 +148,6 @@ impl_glam_array! {
}
// kurbo path types: hash each element's verb and point coordinates via to_bits().
#[cfg(feature = "std")]
impl CacheHash for kurbo::Point {
#[inline]
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
@@ -163,7 +156,6 @@ impl CacheHash for kurbo::Point {
}
}
#[cfg(feature = "std")]
impl CacheHash for kurbo::PathEl {
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
core::hash::Hash::hash(&core::mem::discriminant(self), state);
@@ -183,7 +175,6 @@ impl CacheHash for kurbo::PathEl {
}
}
#[cfg(feature = "std")]
impl CacheHash for kurbo::BezPath {
#[inline]
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
@@ -224,7 +215,6 @@ impl<T: CacheHash, const N: usize> CacheHash for [T; N] {
}
}
#[cfg(feature = "std")]
impl<T: CacheHash> CacheHash for Vec<T> {
#[inline]
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
@@ -232,7 +222,6 @@ impl<T: CacheHash> CacheHash for Vec<T> {
}
}
#[cfg(feature = "std")]
impl<T: CacheHash> CacheHash for std::collections::BTreeSet<T> {
#[inline]
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
@@ -243,7 +232,6 @@ impl<T: CacheHash> CacheHash for std::collections::BTreeSet<T> {
}
}
#[cfg(feature = "std")]
impl<T: CacheHash + ?Sized> CacheHash for Box<T> {
#[inline]
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
@@ -251,7 +239,6 @@ impl<T: CacheHash + ?Sized> CacheHash for Box<T> {
}
}
#[cfg(feature = "std")]
impl<T: CacheHash + ?Sized> CacheHash for std::sync::Arc<T> {
#[inline]
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
+10 -2
View File
@@ -152,12 +152,20 @@ impl WgpuExecutor {
);
self.context().queue.lock().submit([encoder.finish()]);
let (sender, mut receiver) = futures::channel::oneshot::channel();
let (sender, receiver) = futures::channel::oneshot::channel();
buffer.slice(..).map_async(wgpu::MapMode::Read, move |result| {
let _ = sender.send(result);
});
let _ = device.poll(wgpu::wgt::PollType::wait_indefinitely());
let Ok(Some(mapping)) = receiver.try_recv() else {
// A poll on another thread can be the one running the callback, which may not have finished by the time this poll returns
#[cfg(not(target_family = "wasm"))]
let mapping = futures::executor::block_on(receiver).ok();
#[cfg(target_family = "wasm")]
let mapping = {
let mut receiver = receiver;
receiver.try_recv().ok().flatten()
};
let Some(mapping) = mapping else {
anyhow::bail!("The GPU didn't map the texture's pixels for reading");
};
mapping?;
@@ -48,12 +48,6 @@ impl PipelineCache {
pub fn executor(&self) -> Option<&WgpuExecutor> {
self.executor.get()
}
/// Runs the pipeline, or returns `None` when it was never initialized because no GPU is available.
pub fn try_run<P: Pipeline>(&self, args: &P::Args<'_>) -> Option<P::Out> {
self.executor.get()?;
self.run::<P>(args).ok()
}
}
impl std::fmt::Debug for PipelineCache {
@@ -12,7 +12,7 @@ use raster_kernels::adjustments::{AdjustmentVisitor, visit_kernel};
use raster_kernels::blur::{BlurHalve, BlurHorizontal, BlurPass, BlurSpace, BlurUpsample, BlurVertical, MAX_BLUR_REACH, blur_extent};
use raster_kernels::generators::visit_generator_kernel;
use raster_kernels::{GpuParams, MapColor, RasterKernel, RasterKernelVisitor, ToGpuParams, map_color_module, raster_kernel_module};
use raster_types::{GPU, Raster, Storage};
use raster_types::{GPU, ImageError, Raster, Storage};
use std::any::{TypeId, type_name};
/// The format of intermediate rasters a [`RasterKernel::FILTERED`] kernel reads, half-float precision but filterable on WebGL2 unlike [`RASTER_FORMAT`].
@@ -41,9 +41,17 @@ fn run<K: ToGpuParams + 'static>(
output_size,
output_format,
};
pipeline
.try_run::<RasterKernelRuntime>(&args)
.ok_or_else(|| NodeError::new("A GPU is required to process a GPU raster"))
if let Some(executor) = pipeline.executor() {
let limit = executor.context().device.limits().max_texture_dimension_2d;
if output_size.max_element() > limit {
return Err(ImageError::TooLarge {
width: output_size.x,
height: output_size.y,
}
.into());
}
}
Ok(pipeline.run::<RasterKernelRuntime>(&args)?)
}
fn raster_format(pipeline: &WgpuPipelineCache) -> WgpuTextureFormat {
@@ -12,7 +12,7 @@ fn executor() -> Option<&'static WgpuExecutor> {
EXECUTOR.get_or_init(|| futures::executor::block_on(WgpuExecutor::new())).as_ref()
}
/// Held while a test uses the shared GPU, since another test's work can delay or intercept a render's readback.
/// Held while a test uses the shared GPU, since another test's work can delay a render's readback.
fn take_turn() -> std::sync::MutexGuard<'static, ()> {
static TURN: std::sync::Mutex<()> = std::sync::Mutex::new(());
TURN.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
-1
View File
@@ -5,7 +5,6 @@ pub mod dehaze;
pub mod effects;
pub mod filter;
pub mod image_color_palette;
pub mod parallel_rows;
pub mod raster_kernel;
pub mod std_nodes;
@@ -1,60 +0,0 @@
//! Spreads per-row image work across threads on platforms that have them.
/// Below this many pixels, starting threads costs more than they save.
#[cfg(not(target_family = "wasm"))]
const MIN_PIXELS_FOR_THREADS: usize = 65_536;
/// Calls `fill_row` with the index and pixels of each row of `pixels`, an image `width` pixels wide.
/// On native platforms, bands of rows run on separate threads, so `fill_row` must not depend on the order rows are filled in.
pub fn fill_rows<P: Send>(pixels: &mut [P], width: usize, fill_row: impl Fn(usize, &mut [P]) + Sync) {
if width == 0 {
return;
}
#[cfg(not(target_family = "wasm"))]
if pixels.len() >= MIN_PIXELS_FOR_THREADS {
let threads = std::thread::available_parallelism().map_or(1, |threads| threads.get());
let rows_per_band = (pixels.len() / width).div_ceil(threads).max(1);
std::thread::scope(|scope| {
for (band_index, band) in pixels.chunks_mut(rows_per_band * width).enumerate() {
let fill_row = &fill_row;
let fill_band = move |band: &mut [P]| {
for (row_in_band, row) in band.chunks_mut(width).enumerate() {
fill_row(band_index * rows_per_band + row_in_band, row);
}
};
// The band is handed over only once its thread has started, so it can be filled here instead if the system won't start one
let (sender, receiver) = std::sync::mpsc::channel();
match std::thread::Builder::new().spawn_scoped(scope, move || receiver.recv().map(fill_band)) {
Ok(_) => {
let _ = sender.send(band);
}
Err(_) => fill_band(band),
}
}
});
return;
}
for (y, row) in pixels.chunks_mut(width).enumerate() {
fill_row(y, row);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_row_is_filled_with_its_own_index() {
// Large enough to run on threads where there are any, with a ragged count of rows per band
let (width, height) = (300, 301);
let mut pixels = vec![0_usize; width * height];
fill_rows(&mut pixels, width, |y, row| row.iter_mut().enumerate().for_each(|(x, pixel)| *pixel = y * width + x));
assert!(pixels.iter().enumerate().all(|(index, pixel)| *pixel == index));
}
}
+130 -4
View File
@@ -2,17 +2,18 @@ use crate::adjustments::{CellularDistanceFunction, CellularReturnType, DomainWar
use crate::gpu_params;
use crate::raster_kernel::{KernelFrame, RasterKernel, Wgsl, raster_kernel_pipeline, raster_placement, run_raster_kernel, union_frame};
use core_types::ATTR_TRANSFORM;
use core_types::context::Ctx;
use core_types::context::{Ctx, ExtractFootprint};
use core_types::list::Item;
use core_types::math::bbox::Bbox;
use core_types::transform::Transform;
use core_types::{Interrupt, NodeError};
use glam::{DAffine2, DVec2};
use glam::{DAffine2, DVec2, UVec2};
use graphene_resource::Resource;
use graphic_types::generator::{Generator, NoiseSettings};
use graphic_types::generator::{Generator, GeneratorPattern, NoiseSettings};
use raster_types::{CPU, GPU, Raster, Storage};
use raster_types::{Image, ImageError};
use wgpu_executor::WgpuPipelineCache;
use wgpu_executor::raster_kernel::render_generator;
#[node_macro::node(category("Raster"), icon("NodeChannelsToImage"), name("Channels to Image"), memoize)]
fn channels_to_image(
@@ -216,6 +217,102 @@ fn image(
#[node_macro::node(category("Raster"), icon("NodeNoisePattern"))]
#[allow(clippy::too_many_arguments)]
fn noise_pattern(
ctx: impl ExtractFootprint + Ctx,
_primary: (),
#[default(true)] clip: Item<bool>,
#[hard(0..)] seed: Item<i64>,
#[widget(ParsedWidgetOverride::Custom = "noise_inspector_scale")]
#[default(10.)]
scale: Item<f64>,
#[widget(ParsedWidgetOverride::Custom = "noise_inspector_noise_type")] noise_type: Item<NoiseType>,
#[widget(ParsedWidgetOverride::Custom = "noise_inspector_domain_warp_type")] domain_warp_type: Item<DomainWarpType>,
#[widget(ParsedWidgetOverride::Custom = "noise_inspector_domain_warp_amplitude")]
#[default(100.)]
domain_warp_amplitude: Item<f64>,
#[widget(ParsedWidgetOverride::Custom = "noise_inspector_fractal_type")] fractal_type: Item<FractalType>,
#[widget(ParsedWidgetOverride::Custom = "noise_inspector_fractal_octaves")]
#[default(3)]
#[hard(1..10)]
fractal_octaves: Item<i64>,
#[widget(ParsedWidgetOverride::Custom = "noise_inspector_fractal_lacunarity")]
#[default(2.)]
fractal_lacunarity: Item<f64>,
#[widget(ParsedWidgetOverride::Custom = "noise_inspector_fractal_gain")]
#[default(0.5)]
fractal_gain: Item<f64>,
#[widget(ParsedWidgetOverride::Custom = "noise_inspector_fractal_weighted_strength")] fractal_weighted_strength: Item<f64>,
#[widget(ParsedWidgetOverride::Custom = "noise_inspector_ping_pong_strength")]
#[default(2.)]
fractal_ping_pong_strength: Item<f64>,
#[widget(ParsedWidgetOverride::Custom = "noise_inspector_cellular_distance_function")] cellular_distance_function: Item<CellularDistanceFunction>,
#[widget(ParsedWidgetOverride::Custom = "noise_inspector_cellular_return_type")] cellular_return_type: Item<CellularReturnType>,
#[widget(ParsedWidgetOverride::Custom = "noise_inspector_cellular_jitter")]
#[default(1.)]
cellular_jitter: Item<f64>,
#[scope(raster_kernel_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>,
) -> Result<Item<Raster<GPU>>, Interrupt> {
let (clip, seed, scale, domain_warp_amplitude) = (*clip.element(), *seed.element(), *scale.element(), *domain_warp_amplitude.element());
let (fractal_octaves, fractal_lacunarity, fractal_gain) = (*fractal_octaves.element(), *fractal_lacunarity.element(), *fractal_gain.element());
let (fractal_weighted_strength, fractal_ping_pong_strength, cellular_jitter) = (*fractal_weighted_strength.element(), *fractal_ping_pong_strength.element(), *cellular_jitter.element());
let (noise_type, domain_warp_type, fractal_type) = (noise_type.into_element(), domain_warp_type.into_element(), fractal_type.into_element());
let (cellular_distance_function, cellular_return_type) = (cellular_distance_function.into_element(), cellular_return_type.into_element());
let footprint = ctx.footprint();
let viewport_bounds = footprint.viewport_bounds_in_local_space();
// TODO: Remove "clip" entirely (and its arbitrary 100x100 clipping square) once we have proper resolution-aware layer clipping
const CLIPPING_SQUARE_SIZE: f64 = 100.;
let logical_transform = if clip { DAffine2::from_scale(DVec2::splat(CLIPPING_SQUARE_SIZE)) } else { DAffine2::IDENTITY };
let mut size = viewport_bounds.size();
let mut offset = viewport_bounds.start;
if clip {
let image_bounds = Bbox::from_transform(logical_transform).to_axis_aligned_bbox();
let intersection = viewport_bounds.intersect(&image_bounds);
offset = (intersection.start - image_bounds.start).max(DVec2::ZERO);
size = intersection.size();
}
// If the image would not be visible, return an empty image
if size.x <= 0. || size.y <= 0. {
return Ok(Item::default().with_attribute(ATTR_TRANSFORM, logical_transform));
}
let transform = DAffine2::from_translation(offset) * DAffine2::from_scale(size);
let footprint_scale = footprint.scale();
let width = (size.x * footprint_scale.x) as u32;
let height = (size.y * footprint_scale.y) as u32;
if width == 0 || height == 0 {
return Ok(Item::default().with_attribute(ATTR_TRANSFORM, logical_transform));
}
let noise = GeneratorPattern::Noise(NoiseSettings {
seed,
scale,
noise_type,
domain_warp_type,
domain_warp_amplitude,
fractal_type,
fractal_octaves,
fractal_lacunarity,
fractal_gain,
fractal_weighted_strength,
fractal_ping_pong_strength,
cellular_distance_function,
cellular_return_type,
cellular_jitter,
});
let raster = render_generator(&noise, [offset, offset + size], UVec2::new(width, height), pipeline.element())?;
Ok(Item::new_from_element(raster.with_coverage(logical_transform.inverse() * transform)).with_attribute(ATTR_TRANSFORM, logical_transform))
}
/// Generates a procedural noise pattern which fills the plane, drawn at the resolution the render needs.
#[node_macro::node(category("Raster"), icon("NodeNoisePattern"))]
#[allow(clippy::too_many_arguments)]
fn noise_pattern_generator(
_: impl Ctx,
_primary: (),
#[hard(0..)] seed: Item<i64>,
@@ -270,7 +367,36 @@ fn noise_pattern(
generator
}
/// Generates the Mandelbrot set which fills the plane, drawn at the resolution the render needs.
#[node_macro::node(category("Raster"), icon("NodeMandelbrot"))]
fn mandelbrot(_: impl Ctx, _primary: ()) -> Item<Generator> {
fn mandelbrot_generator(_: impl Ctx, _primary: ()) -> Item<Generator> {
Item::new_from_element(Generator::Mandelbrot)
}
#[node_macro::node(category("Raster"), icon("NodeMandelbrot"))]
fn mandelbrot(ctx: impl ExtractFootprint + Send, #[scope(raster_kernel_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>) -> Result<Item<Raster<GPU>>, Interrupt> {
let footprint = ctx.footprint();
let viewport_bounds = footprint.viewport_bounds_in_local_space();
let image_bounds = Bbox::from_transform(DAffine2::IDENTITY).to_axis_aligned_bbox();
let intersection = viewport_bounds.intersect(&image_bounds);
let size = intersection.size();
let offset = (intersection.start - image_bounds.start).max(DVec2::ZERO);
// If the image would not be visible, return an empty image
if size.x <= 0. || size.y <= 0. {
return Ok(Item::default());
}
let scale = footprint.scale();
let width = (size.x * scale.x) as u32;
let height = (size.y * scale.y) as u32;
if width == 0 || height == 0 {
return Ok(Item::default());
}
let raster = render_generator(&GeneratorPattern::Mandelbrot, [offset, offset + size], UVec2::new(width, height), pipeline.element())?;
Ok(Item::new_from_element(raster.with_coverage(DAffine2::from_translation(offset) * DAffine2::from_scale(size))))
}
+130
View File
@@ -919,4 +919,134 @@ mod tests {
"neither the adapter nor what feeds it should read the footprint, leaving it unaffected by panning"
);
}
#[test]
fn a_footprint_dependent_raster_warns_at_a_footprint_invariant_node_and_feeds_others_unconverted() {
use graph_craft::application_io::PlatformEditorApi;
use graph_craft::document::value::TaggedValue;
use graph_craft::graphene_compiler::Compiler;
use graph_craft::proto::{GraphErrorType, TypingContext};
use graphene_std::raster_nodes::dehaze::dehaze;
use graphene_std::raster_nodes::filter::median_filter;
use graphene_std::raster_nodes::raster_kernel::raster_kernel_pipeline;
use graphene_std::raster_nodes::std_nodes::mandelbrot;
use graphene_std::runtime::{AsyncRuntime, Spawn, Task};
use interpreted_executor::util::wrap_network_in_scope;
use std::sync::Arc;
struct NoSpawner;
impl Spawn for NoSpawner {
fn spawn(&self, _: Task) {}
}
let compile = |consumer: ProtoNodeIdentifier| {
let network = NodeNetwork {
exports: vec![NodeInput::node(NodeId(1), 0)],
nodes: [
(
NodeId(0),
DocumentNode {
inputs: vec![NodeInput::scope(raster_kernel_pipeline::IDENTIFIER)],
implementation: DocumentNodeImplementation::ProtoNode(mandelbrot::IDENTIFIER),
..Default::default()
},
),
(
NodeId(1),
DocumentNode {
inputs: vec![
NodeInput::node(NodeId(0), 0),
NodeInput::value(TaggedValue::Number(10.), false),
NodeInput::scope(raster_kernel_pipeline::IDENTIFIER),
],
implementation: DocumentNodeImplementation::ProtoNode(consumer),
..Default::default()
},
),
]
.into_iter()
.collect(),
..Default::default()
};
let runtime = AsyncRuntime::new(Arc::new(NoSpawner), Arc::new(std::time::Instant::now()));
let mut network = wrap_network_in_scope(network, Arc::new(PlatformEditorApi::default()), runtime.handle());
Preprocessor::new().preprocess(&mut network, &|_| None).unwrap();
let compiled = Compiler {}.compile_single(network).unwrap();
let mut typing_context = TypingContext::new(&interpreted_executor::node_registry::NODE_REGISTRY);
typing_context.update(&compiled.network).expect("a GPU raster should reach the GPU-only input");
compiled.warnings
};
let warnings = compile(dehaze::IDENTIFIER);
assert_eq!(warnings.len(), 1, "Dehaze should warn about reading the footprint through its input: {warnings:?}");
assert!(warnings[0].error == GraphErrorType::FootprintDependentInput);
assert!(compile(median_filter::IDENTIFIER).is_empty(), "a node that isn't footprint invariant shouldn't warn");
}
#[test]
fn generator_nodes_compile_on_their_own_and_dont_reach_gpu_only_inputs() {
use graph_craft::application_io::PlatformEditorApi;
use graph_craft::document::value::TaggedValue;
use graph_craft::graphene_compiler::Compiler;
use graph_craft::proto::TypingContext;
use graphene_std::raster_nodes::filter::median_filter;
use graphene_std::raster_nodes::raster_kernel::raster_kernel_pipeline;
use graphene_std::raster_nodes::std_nodes::{mandelbrot_generator, noise_pattern_generator};
use graphene_std::runtime::{AsyncRuntime, Spawn, Task};
use interpreted_executor::util::wrap_network_in_scope;
use std::sync::Arc;
struct NoSpawner;
impl Spawn for NoSpawner {
fn spawn(&self, _: Task) {}
}
// Each generator's settings at their type's default, after the empty primary input
let generator_node = |identifier: &ProtoNodeIdentifier| {
let setting_types: Vec<Type> = {
let registry = core_types::registry::NODE_REGISTRY.lock().unwrap();
let (_, io) = registry[identifier].iter().next().unwrap();
io.inputs.iter().skip(1).map(|input| input.nested_type().clone()).collect()
};
let settings = setting_types.into_iter().map(|setting| NodeInput::value(TaggedValue::TypeDefault(setting), false));
DocumentNode {
inputs: std::iter::once(NodeInput::value(TaggedValue::None, false)).chain(settings).collect(),
implementation: DocumentNodeImplementation::ProtoNode(identifier.clone()),
..Default::default()
}
};
let compile = |nodes: Vec<(NodeId, DocumentNode)>, export: NodeId| {
let network = NodeNetwork {
exports: vec![NodeInput::node(export, 0)],
nodes: nodes.into_iter().collect(),
..Default::default()
};
let runtime = AsyncRuntime::new(Arc::new(NoSpawner), Arc::new(std::time::Instant::now()));
let mut network = wrap_network_in_scope(network, Arc::new(PlatformEditorApi::default()), runtime.handle());
Preprocessor::new().preprocess(&mut network, &|_| None).unwrap();
Compiler {}.compile_single(network).unwrap()
};
for identifier in [mandelbrot_generator::IDENTIFIER, noise_pattern_generator::IDENTIFIER] {
let compiled = compile(vec![(NodeId(0), generator_node(&identifier))], NodeId(0));
let mut typing_context = TypingContext::new(&interpreted_executor::node_registry::NODE_REGISTRY);
typing_context.update(&compiled.network).expect("a generator should compile on its own");
assert!(compiled.warnings.is_empty(), "{identifier:?} shouldn't warn: {:?}", compiled.warnings);
let median = DocumentNode {
inputs: vec![
NodeInput::node(NodeId(0), 0),
NodeInput::value(TaggedValue::Number(10.), false),
NodeInput::scope(raster_kernel_pipeline::IDENTIFIER),
],
implementation: DocumentNodeImplementation::ProtoNode(median_filter::IDENTIFIER),
..Default::default()
};
let compiled = compile(vec![(NodeId(0), generator_node(&identifier)), (NodeId(1), median)], NodeId(1));
let mut typing_context = TypingContext::new(&interpreted_executor::node_registry::NODE_REGISTRY);
assert!(typing_context.update(&compiled.network).is_err(), "{identifier:?} shouldn't reach a GPU-only input");
}
}
}