mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9de7e39431 | ||
|
|
198a352280 | ||
|
|
6843e3db89 | ||
|
|
547cbee448 | ||
|
|
9795704dce | ||
|
|
cc33aa6427 | ||
|
|
90fd674627 | ||
|
|
09017cdc6a | ||
|
|
683720a1ad | ||
|
|
c3589b6c89 | ||
|
|
35f4e0c43f | ||
|
|
fd41c925e6 | ||
|
|
adc1ec774a | ||
|
|
d4cb09d144 | ||
|
|
431aa27a66 | ||
|
|
e3ef519908 | ||
|
|
eb86348ed0 |
No files matched your search
Generated
+2
@@ -4209,6 +4209,7 @@ dependencies = [
|
||||
"graphene-std",
|
||||
"interpreted-executor",
|
||||
"log",
|
||||
"wgpu-executor",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6676,6 +6677,7 @@ dependencies = [
|
||||
"graphene-application-io",
|
||||
"graphene-core",
|
||||
"graphene-svg-renderer",
|
||||
"log",
|
||||
"node-macro",
|
||||
"vello",
|
||||
"web-sys",
|
||||
|
||||
@@ -253,7 +253,7 @@ impl NodeRuntime {
|
||||
assert_eq!(scoped_network.exports.len(), 1, "Graph with multiple outputs not yet handled");
|
||||
|
||||
let c = Compiler {};
|
||||
let proto_network = match c.compile_single(scoped_network) {
|
||||
let proto_network = match c.compile_single(scoped_network, Some(self.executor.typing_context_mut())) {
|
||||
Ok(network) => network,
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use graphene_core_shaders::Ctx;
|
||||
|
||||
use crate::Node;
|
||||
use crate::{ExtractFootprint, Node, transform::Footprint};
|
||||
use std::marker::PhantomData;
|
||||
|
||||
// TODO: Rename to "Passthrough"
|
||||
@@ -50,16 +50,16 @@ fn into<'i, T: 'i + Send + Into<O>, O: 'i + Send>(_: impl Ctx, value: T, _out_ty
|
||||
|
||||
/// The [`Convert`] trait allows for conversion between Rust primitive numeric types.
|
||||
/// Because number casting is lossy, we cannot use the normal [`Into`] trait like we do for other types.
|
||||
pub trait Convert<T>: Sized {
|
||||
pub trait Convert<T, C>: Sized {
|
||||
/// Converts this type into the (usually inferred) output type.
|
||||
#[must_use]
|
||||
fn convert(self) -> T;
|
||||
fn convert(self, footprint: Footprint, converter: C) -> impl Future<Output = T> + Send;
|
||||
}
|
||||
|
||||
impl<T: ToString> Convert<String> for T {
|
||||
impl<T: ToString + Send> Convert<String, ()> for T {
|
||||
/// Converts this type into a `String` using its `ToString` implementation.
|
||||
#[inline]
|
||||
fn convert(self) -> String {
|
||||
async fn convert(self, _: Footprint, _converter: ()) -> String {
|
||||
self.to_string()
|
||||
}
|
||||
}
|
||||
@@ -67,8 +67,8 @@ impl<T: ToString> Convert<String> for T {
|
||||
/// Implements the [`Convert`] trait for conversion between the cartesian product of Rust's primitive numeric types.
|
||||
macro_rules! impl_convert {
|
||||
($from:ty, $to:ty) => {
|
||||
impl Convert<$to> for $from {
|
||||
fn convert(self) -> $to {
|
||||
impl Convert<$to, ()> for $from {
|
||||
async fn convert(self, _: Footprint, _: ()) -> $to {
|
||||
self as $to
|
||||
}
|
||||
}
|
||||
@@ -106,8 +106,8 @@ impl_convert!(isize);
|
||||
impl_convert!(usize);
|
||||
|
||||
#[node_macro::node(skip_impl)]
|
||||
fn convert<'i, T: 'i + Send + Convert<O>, O: 'i + Send>(_: impl Ctx, value: T, _out_ty: PhantomData<O>) -> O {
|
||||
value.convert()
|
||||
async fn convert<'i, T: 'i + Send + Convert<O, C>, O: 'i + Send, C: 'i + Send>(ctx: impl Ctx + ExtractFootprint, value: T, converter: C, _out_ty: PhantomData<O>) -> O {
|
||||
value.convert(*ctx.try_footprint().unwrap_or(&Footprint::DEFAULT), converter).await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -9,7 +9,7 @@ use std::sync::{LazyLock, Mutex};
|
||||
pub use graphene_core_shaders::registry::types;
|
||||
|
||||
// Translation struct between macro and definition
|
||||
#[derive(Clone)]
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct NodeMetadata {
|
||||
pub display_name: &'static str,
|
||||
pub category: Option<&'static str>,
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
use criterion::{Criterion, black_box, criterion_group, criterion_main};
|
||||
use criterion::{Criterion, criterion_group, criterion_main};
|
||||
use graph_craft::util::DEMO_ART;
|
||||
use std::hint::black_box;
|
||||
fn compile_to_proto(c: &mut Criterion) {
|
||||
use graph_craft::util::{compile, load_from_name};
|
||||
let mut c = c.benchmark_group("Compile Network cold");
|
||||
|
||||
for name in DEMO_ART {
|
||||
let network = load_from_name(name);
|
||||
c.bench_function(name, |b| b.iter_batched(|| network.clone(), |network| compile(black_box(network)), criterion::BatchSize::SmallInput));
|
||||
c.bench_function(name, |b| {
|
||||
b.iter_batched(|| network.clone(), |network| compile(black_box(network), None), criterion::BatchSize::SmallInput)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ use iai_callgrind::{library_benchmark, library_benchmark_group, main};
|
||||
#[library_benchmark]
|
||||
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = load_from_name)]
|
||||
pub fn compile_to_proto(_input: NodeNetwork) {
|
||||
std::hint::black_box(compile(_input));
|
||||
std::hint::black_box(compile(_input, None));
|
||||
}
|
||||
|
||||
library_benchmark_group!(name = compile_group; benchmarks = compile_to_proto);
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
use crate::document::NodeNetwork;
|
||||
use crate::proto::{LocalFuture, ProtoNetwork};
|
||||
use crate::proto::{LocalFuture, ProtoNetwork, TypingContext};
|
||||
use std::error::Error;
|
||||
|
||||
pub struct Compiler {}
|
||||
|
||||
impl Compiler {
|
||||
pub fn compile(&self, mut network: NodeNetwork) -> impl Iterator<Item = Result<ProtoNetwork, String>> {
|
||||
pub fn compile(&self, mut network: NodeNetwork, mut ty: Option<&mut TypingContext>) -> impl Iterator<Item = Result<ProtoNetwork, String>> {
|
||||
let node_ids = network.nodes.keys().copied().collect::<Vec<_>>();
|
||||
network.populate_dependants();
|
||||
for id in node_ids {
|
||||
@@ -17,14 +17,14 @@ impl Compiler {
|
||||
let proto_networks = network.into_proto_networks();
|
||||
|
||||
proto_networks.map(move |mut proto_network| {
|
||||
proto_network.insert_context_nullification_nodes()?;
|
||||
proto_network.generate_stable_node_ids();
|
||||
proto_network.insert_context_nullification_nodes(ty.as_deref_mut())?;
|
||||
// proto_network.generate_stable_node_ids();
|
||||
Ok(proto_network)
|
||||
})
|
||||
}
|
||||
pub fn compile_single(&self, network: NodeNetwork) -> Result<ProtoNetwork, String> {
|
||||
pub fn compile_single(&self, network: NodeNetwork, ty: Option<&mut TypingContext>) -> Result<ProtoNetwork, String> {
|
||||
assert_eq!(network.exports.len(), 1, "Graph with multiple outputs not yet handled");
|
||||
let Some(proto_network) = self.compile(network).next() else {
|
||||
let Some(proto_network) = self.compile(network, ty).next() else {
|
||||
return Err("Failed to convert graph into proto graph".to_string());
|
||||
};
|
||||
proto_network
|
||||
|
||||
@@ -140,7 +140,7 @@ impl Default for ProtoNode {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
identifier: ProtoNodeIdentifier::new("graphene_core::ops::IdentityNode"),
|
||||
construction_args: ConstructionArgs::Value(value::TaggedValue::U32(0).into()),
|
||||
construction_args: ConstructionArgs::Nodes(Vec::new()),
|
||||
call_argument: concrete!(()),
|
||||
original_location: OriginalLocation::default(),
|
||||
skip_deduplication: false,
|
||||
@@ -211,6 +211,26 @@ enum NodeState {
|
||||
Visited,
|
||||
}
|
||||
|
||||
struct NodeList<'a> {
|
||||
vec: Vec<(NodeId, ProtoNode)>,
|
||||
ty: Option<&'a mut TypingContext>,
|
||||
id_mapping: Vec<usize>,
|
||||
}
|
||||
|
||||
impl<'a> NodeList<'a> {
|
||||
fn push_node(&mut self, node: ProtoNode, old_node_idx: Option<usize>) -> Result<(NodeId, Option<Type>), GraphErrors> {
|
||||
let node_id = node.stable_node_id().unwrap();
|
||||
let out_ty = if let Some(ty) = &mut self.ty { Some(ty.infer(node_id, &node)?.return_value) } else { None };
|
||||
// log::debug!("{old_node_idx:?}, {node_id:?}, {node:?}, {:?}", self.id_mapping);
|
||||
if let Some(old_node_idx) = old_node_idx {
|
||||
assert_eq!(old_node_idx, self.id_mapping.len());
|
||||
self.id_mapping.push(self.vec.len());
|
||||
}
|
||||
self.vec.push((node_id, node));
|
||||
Ok((node_id, out_ty))
|
||||
}
|
||||
}
|
||||
|
||||
impl ProtoNetwork {
|
||||
fn check_ref(&self, ref_id: &NodeId, id: &NodeId) {
|
||||
debug_assert!(
|
||||
@@ -296,33 +316,44 @@ impl ProtoNetwork {
|
||||
|
||||
/// Inserts context nullification nodes to optimize caching.
|
||||
/// This analysis is performed after topological sorting to ensure proper dependency tracking.
|
||||
pub fn insert_context_nullification_nodes(&mut self) -> Result<(), String> {
|
||||
pub fn insert_context_nullification_nodes(&mut self, ty: Option<&mut TypingContext>) -> Result<(), String> {
|
||||
// Perform topological sort once
|
||||
self.reorder_ids()?;
|
||||
|
||||
self.find_context_dependencies(self.output);
|
||||
let mut new_order = NodeList {
|
||||
vec: Vec::with_capacity(self.nodes.len() + 20),
|
||||
ty,
|
||||
id_mapping: Vec::with_capacity(self.nodes.len()),
|
||||
};
|
||||
let mut results = Vec::with_capacity(self.nodes.len());
|
||||
for node_id in 0..self.nodes.len() {
|
||||
self.find_context_dependencies(NodeId(node_id as u64), &mut new_order, &mut results).map_err(|e| format!("{e:?}"))?;
|
||||
}
|
||||
|
||||
// Perform topological sort a second time to integrate the new nodes
|
||||
self.reorder_ids()?;
|
||||
self.nodes = new_order.vec;
|
||||
self.output = results[self.output.0 as usize].1;
|
||||
// log::debug!("{:?}", self.nodes);
|
||||
// log::debug!("{:}", self);
|
||||
// // Perform topological sort a second time to integrate the new nodes
|
||||
// self.reorder_ids()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn insert_context_nullification_node(&mut self, node_id: NodeId, context_deps: ContextFeatures) -> NodeId {
|
||||
let (_, node) = &self.nodes[node_id.0 as usize];
|
||||
fn insert_context_nullification_node(&mut self, old_node_id: NodeId, new_node_id: NodeId, context_deps: ContextFeatures, new_nodes: &mut NodeList) -> Result<NodeId, GraphErrors> {
|
||||
let (_, node) = &self.nodes[old_node_id.0 as usize];
|
||||
let mut path = node.original_location.path.clone();
|
||||
|
||||
// log::debug!("Inserting context nullification after {:?} with context features: {:?}", node.identifier, context_deps);
|
||||
|
||||
// Add a path extension with a placeholder value which should not conflict with existing paths
|
||||
if let Some(p) = path.as_mut() {
|
||||
p.push(NodeId(10))
|
||||
}
|
||||
|
||||
let memo_node_id = NodeId(self.nodes.len() as u64);
|
||||
|
||||
self.nodes.push((
|
||||
memo_node_id,
|
||||
let (memo_node_id, _) = new_nodes.push_node(
|
||||
ProtoNode {
|
||||
construction_args: ConstructionArgs::Nodes(vec![node_id]),
|
||||
construction_args: ConstructionArgs::Nodes(vec![new_node_id]),
|
||||
call_argument: concrete!(Context),
|
||||
identifier: graphene_core::memo::memo::IDENTIFIER,
|
||||
original_location: OriginalLocation {
|
||||
@@ -331,12 +362,10 @@ impl ProtoNetwork {
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
));
|
||||
None,
|
||||
)?;
|
||||
|
||||
let nullification_value_node_id = NodeId(self.nodes.len() as u64);
|
||||
|
||||
self.nodes.push((
|
||||
nullification_value_node_id,
|
||||
let (nullification_value_node_id, _) = new_nodes.push_node(
|
||||
ProtoNode {
|
||||
construction_args: ConstructionArgs::Value(MemoHash::new(TaggedValue::ContextFeatures(context_deps))),
|
||||
call_argument: concrete!(Context),
|
||||
@@ -347,10 +376,9 @@ impl ProtoNetwork {
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
));
|
||||
let nullification_node_id = NodeId(self.nodes.len() as u64);
|
||||
self.nodes.push((
|
||||
nullification_node_id,
|
||||
None,
|
||||
)?;
|
||||
let (nullification_node_id, _) = new_nodes.push_node(
|
||||
ProtoNode {
|
||||
construction_args: ConstructionArgs::Nodes(vec![memo_node_id, nullification_value_node_id]),
|
||||
call_argument: concrete!(Context),
|
||||
@@ -361,11 +389,12 @@ impl ProtoNetwork {
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
));
|
||||
nullification_node_id
|
||||
None,
|
||||
)?;
|
||||
Ok(nullification_node_id)
|
||||
}
|
||||
|
||||
fn find_context_dependencies(&mut self, id: NodeId) -> (ContextFeatures, Option<NodeId>) {
|
||||
fn find_context_dependencies(&mut self, id: NodeId, new_order: &mut NodeList, results: &mut Vec<(ContextFeatures, NodeId, Option<Type>, bool)>) -> Result<(), GraphErrors> {
|
||||
let mut branch_dependencies = Vec::new();
|
||||
let mut combined_deps = ContextFeatures::default();
|
||||
let node_index = id.0 as usize;
|
||||
@@ -373,18 +402,32 @@ impl ProtoNetwork {
|
||||
let context_features = self.nodes[node_index].1.context_features;
|
||||
|
||||
let mut inputs = match &self.nodes[node_index].1.construction_args {
|
||||
// We pretend like we have already placed context modification nodes after ourselves because value nodes don't need to be cached
|
||||
ConstructionArgs::Value(_) => return (context_features.extract, Some(id)),
|
||||
ConstructionArgs::Nodes(items) => items.clone(),
|
||||
ConstructionArgs::Inline(_) => return (context_features.extract, Some(id)),
|
||||
// We pretend like we have already placed context modification nodes after ourselves because value nodes don't need to be cached
|
||||
_ => {
|
||||
let (stable_id, ty) = new_order.push_node(self.nodes[node_index].1.clone(), Some(node_index))?;
|
||||
results.push((context_features.extract, stable_id, ty, true));
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
|
||||
// Filter out identity nodes
|
||||
if self.nodes[node_index].1.identifier == ProtoNodeIdentifier::new("graphene_core::ops::IdentityNode") {
|
||||
// TODO: make cleaner
|
||||
let previous_id = new_order.id_mapping[inputs[0].0 as usize];
|
||||
new_order.id_mapping.push(previous_id);
|
||||
// Replicate the results from the input node
|
||||
results.push(results[inputs[0].0 as usize].clone());
|
||||
// new_order.push_node(previous.1, Some(node_index))?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Compute the dependencies for each branch and combine all of them
|
||||
for &node in &inputs {
|
||||
let branch = self.find_context_dependencies(node);
|
||||
let branch = &results[node.0 as usize];
|
||||
|
||||
branch_dependencies.push(branch);
|
||||
combined_deps |= branch.0;
|
||||
branch_dependencies.push(branch);
|
||||
}
|
||||
let mut new_deps = combined_deps;
|
||||
|
||||
@@ -393,15 +436,17 @@ impl ProtoNetwork {
|
||||
// Add requirements we have
|
||||
new_deps |= context_features.extract;
|
||||
|
||||
// If we either introduce new dependencies, we can cache all children which don't yet need that dependency
|
||||
let we_introduce_new_deps = !combined_deps.contains(new_deps);
|
||||
// If we introduce new dependencies, we can cache all children which don't yet need that dependency
|
||||
let we_introduce_new_deps = !combined_deps.contains(new_deps) && !new_deps.is_empty();
|
||||
// log::debug!("combined_deps: {combined_deps:?} new_deps: {new_deps:?}, context_features: {context_features:?}");
|
||||
|
||||
// For diverging branches, we can add a cache node for all branches which don't reqire all dependencies
|
||||
for (child_node, (deps, new_id)) in inputs.iter_mut().zip(branch_dependencies.into_iter()) {
|
||||
if let Some(new_id) = new_id {
|
||||
*child_node = new_id;
|
||||
} else if we_introduce_new_deps || deps != combined_deps {
|
||||
*child_node = self.insert_context_nullification_node(*child_node, deps);
|
||||
for (child_node, (deps, new_id, out_ty, already_placed_nullification)) in inputs.iter_mut().zip(branch_dependencies.into_iter()) {
|
||||
let old_child_id = *child_node;
|
||||
*child_node = *new_id;
|
||||
if !*already_placed_nullification && (we_introduce_new_deps || *deps != combined_deps) {
|
||||
// log::debug!("already_placed: {already_placed_nullification} we_introduce_new_deps {we_introduce_new_deps} deps: {deps:?} combined_deps: {combined_deps:?}");
|
||||
*child_node = self.insert_context_nullification_node(old_child_id, *new_id, *deps, new_order)?;
|
||||
}
|
||||
}
|
||||
self.nodes[node_index].1.construction_args = ConstructionArgs::Nodes(inputs);
|
||||
@@ -415,13 +460,18 @@ impl ProtoNetwork {
|
||||
// Do we satisfy any existing dependencies?
|
||||
let we_supply_existing_deps = !combined_deps.difference(remaining_deps_from_children).is_empty();
|
||||
|
||||
let mut new_id = None;
|
||||
if we_supply_existing_deps {
|
||||
// TODO: replace with mem take
|
||||
let (stable_id, out_ty) = new_order.push_node(self.nodes[node_index].1.clone(), Some(node_index))?;
|
||||
|
||||
let mut new_id = stable_id;
|
||||
if we_supply_existing_deps && node_index != self.nodes.len() - 1 {
|
||||
// log::debug!("we supply existing deps");
|
||||
// Our set of context dependencies has shrunk so we can add a cache node after the current node
|
||||
new_id = Some(self.insert_context_nullification_node(id, new_deps));
|
||||
new_id = self.insert_context_nullification_node(id, stable_id, new_deps, new_order)?;
|
||||
}
|
||||
|
||||
(new_deps, new_id)
|
||||
results.push((new_deps, new_id, out_ty, we_supply_existing_deps));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Update all of the references to a node ID in the graph with a new ID named `compose_node_id`.
|
||||
@@ -927,9 +977,7 @@ mod test {
|
||||
#[test]
|
||||
fn stable_node_id_generation() {
|
||||
let mut construction_network = test_network();
|
||||
construction_network
|
||||
.insert_context_nullification_nodes()
|
||||
.expect("Error when calling 'insert_context_nullification_nodes' on 'construction_network.");
|
||||
construction_network.reorder_ids().unwrap();
|
||||
construction_network.generate_stable_node_ids();
|
||||
assert_eq!(construction_network.nodes[0].1.identifier.name.as_ref(), "value");
|
||||
let ids: Vec<_> = construction_network.nodes.iter().map(|(id, _)| *id).collect();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::document::NodeNetwork;
|
||||
use crate::graphene_compiler::Compiler;
|
||||
use crate::proto::ProtoNetwork;
|
||||
use crate::proto::{ProtoNetwork, TypingContext};
|
||||
|
||||
pub fn load_network(document_string: &str) -> NodeNetwork {
|
||||
let document: serde_json::Value = serde_json::from_str(document_string).expect("Failed to parse document");
|
||||
@@ -8,9 +8,9 @@ pub fn load_network(document_string: &str) -> NodeNetwork {
|
||||
serde_json::from_str::<NodeNetwork>(&document).expect("Failed to parse document")
|
||||
}
|
||||
|
||||
pub fn compile(network: NodeNetwork) -> ProtoNetwork {
|
||||
pub fn compile(network: NodeNetwork, ty: Option<&mut TypingContext>) -> ProtoNetwork {
|
||||
let compiler = Compiler {};
|
||||
compiler.compile_single(network).unwrap()
|
||||
compiler.compile_single(network, ty).unwrap()
|
||||
}
|
||||
|
||||
pub fn load_from_name(name: &str) -> NodeNetwork {
|
||||
|
||||
@@ -3,7 +3,7 @@ use fern::colors::{Color, ColoredLevelConfig};
|
||||
use futures::executor::block_on;
|
||||
use graph_craft::document::*;
|
||||
use graph_craft::graphene_compiler::{Compiler, Executor};
|
||||
use graph_craft::proto::ProtoNetwork;
|
||||
use graph_craft::proto::{ProtoNetwork, TypingContext};
|
||||
use graph_craft::util::load_network;
|
||||
use graph_craft::wasm_application_io::EditorPreferences;
|
||||
use graphene_core::text::FontCache;
|
||||
@@ -187,7 +187,8 @@ fn compile_graph(document_string: String, editor_api: Arc<WasmEditorApi>) -> Res
|
||||
let wrapped_network = wrap_network_in_scope(network.clone(), editor_api);
|
||||
|
||||
let compiler = Compiler {};
|
||||
compiler.compile_single(wrapped_network).map_err(|x| x.into())
|
||||
let mut ty = TypingContext::new(&interpreted_executor::node_registry::NODE_REGISTRY);
|
||||
compiler.compile_single(wrapped_network, Some(&mut ty)).map_err(|x| x.into())
|
||||
}
|
||||
|
||||
fn create_executor(proto_network: ProtoNetwork) -> Result<DynamicExecutor, Box<dyn Error>> {
|
||||
|
||||
@@ -4,7 +4,7 @@ pub use graph_craft::wasm_application_io::*;
|
||||
use graphene_application_io::{ApplicationIo, ExportFormat, ImageTexture, RenderConfig, SurfaceFrame};
|
||||
use graphene_core::gradient::GradientStops;
|
||||
use graphene_core::raster::image::Image;
|
||||
use graphene_core::raster_types::{CPU, Raster};
|
||||
use graphene_core::raster_types::{CPU, GPU, Raster};
|
||||
use graphene_core::table::Table;
|
||||
use graphene_core::transform::Footprint;
|
||||
use graphene_core::vector::Vector;
|
||||
@@ -38,6 +38,7 @@ async fn render_intermediate<'a: 'n, T: 'static + Render + WasmNotSend + Send +
|
||||
Context -> Table<Graphic>,
|
||||
Context -> Table<Vector>,
|
||||
Context -> Table<Raster<CPU>>,
|
||||
Context -> Table<Raster<GPU>>,
|
||||
Context -> Table<Color>,
|
||||
Context -> Table<GradientStops>,
|
||||
)]
|
||||
|
||||
@@ -9,7 +9,7 @@ license = "MIT OR Apache-2.0"
|
||||
[dependencies]
|
||||
# Local dependencies
|
||||
dyn-any = { workspace = true }
|
||||
graphene-core = { workspace = true }
|
||||
graphene-core = { workspace = true, features = ["wgpu"] }
|
||||
|
||||
# Workspace dependencies
|
||||
glam = { workspace = true }
|
||||
@@ -21,4 +21,4 @@ usvg = { workspace = true }
|
||||
kurbo = { workspace = true }
|
||||
|
||||
# Optional workspace dependencies
|
||||
vello = { workspace = true, optional = true }
|
||||
vello = { workspace = true }
|
||||
@@ -28,7 +28,6 @@ use std::fmt::Write;
|
||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||
use std::ops::Deref;
|
||||
use std::sync::{Arc, LazyLock};
|
||||
#[cfg(feature = "vello")]
|
||||
use vello::*;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
@@ -152,7 +151,6 @@ impl Default for SvgRender {
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct RenderContext {
|
||||
#[cfg(feature = "vello")]
|
||||
pub resource_overrides: Vec<(peniko::Image, wgpu::Texture)>,
|
||||
}
|
||||
|
||||
@@ -261,7 +259,6 @@ impl RenderMetadata {
|
||||
pub trait Render: BoundingBox + RenderComplexity {
|
||||
fn render_svg(&self, render: &mut SvgRender, render_params: &RenderParams);
|
||||
|
||||
#[cfg(feature = "vello")]
|
||||
fn render_to_vello(&self, scene: &mut Scene, transform: DAffine2, context: &mut RenderContext, _render_params: &RenderParams);
|
||||
|
||||
/// The upstream click targets for each layer are collected during the render so that they do not have to be calculated for each click detection.
|
||||
@@ -292,7 +289,6 @@ impl Render for Graphic {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "vello")]
|
||||
fn render_to_vello(&self, scene: &mut Scene, transform: DAffine2, context: &mut RenderContext, render_params: &RenderParams) {
|
||||
match self {
|
||||
Graphic::Graphic(table) => table.render_to_vello(scene, transform, context, render_params),
|
||||
@@ -445,7 +441,6 @@ impl Render for Artboard {
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(feature = "vello")]
|
||||
fn render_to_vello(&self, scene: &mut Scene, transform: DAffine2, context: &mut RenderContext, render_params: &RenderParams) {
|
||||
use vello::peniko;
|
||||
|
||||
@@ -501,7 +496,6 @@ impl Render for Table<Artboard> {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "vello")]
|
||||
fn render_to_vello(&self, scene: &mut Scene, transform: DAffine2, context: &mut RenderContext, render_params: &RenderParams) {
|
||||
for row in self.iter() {
|
||||
row.element.render_to_vello(scene, transform, context, render_params);
|
||||
@@ -577,7 +571,6 @@ impl Render for Table<Graphic> {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "vello")]
|
||||
fn render_to_vello(&self, scene: &mut Scene, transform: DAffine2, context: &mut RenderContext, render_params: &RenderParams) {
|
||||
let mut iter = self.iter().peekable();
|
||||
let mut mask_element_and_transform = None;
|
||||
@@ -858,7 +851,6 @@ impl Render for Table<Vector> {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "vello")]
|
||||
fn render_to_vello(&self, scene: &mut Scene, parent_transform: DAffine2, _context: &mut RenderContext, render_params: &RenderParams) {
|
||||
use graphene_core::consts::{LAYER_OUTLINE_STROKE_COLOR, LAYER_OUTLINE_STROKE_WEIGHT};
|
||||
use graphene_core::vector::style::{GradientType, StrokeCap, StrokeJoin};
|
||||
@@ -1273,7 +1265,6 @@ impl Render for Table<Raster<CPU>> {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "vello")]
|
||||
fn render_to_vello(&self, scene: &mut Scene, transform: DAffine2, _: &mut RenderContext, render_params: &RenderParams) {
|
||||
use vello::peniko;
|
||||
|
||||
@@ -1334,7 +1325,6 @@ impl Render for Table<Raster<GPU>> {
|
||||
log::warn!("tried to render texture as an svg");
|
||||
}
|
||||
|
||||
#[cfg(feature = "vello")]
|
||||
fn render_to_vello(&self, scene: &mut Scene, transform: DAffine2, context: &mut RenderContext, _render_params: &RenderParams) {
|
||||
use vello::peniko;
|
||||
|
||||
@@ -1417,7 +1407,6 @@ impl Render for Table<Color> {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "vello")]
|
||||
fn render_to_vello(&self, scene: &mut Scene, _parent_transform: DAffine2, _context: &mut RenderContext, render_params: &RenderParams) {
|
||||
use vello::peniko;
|
||||
|
||||
@@ -1511,7 +1500,6 @@ impl Render for Table<GradientStops> {
|
||||
}
|
||||
|
||||
// TODO: Fix infinite gradient rendering
|
||||
#[cfg(feature = "vello")]
|
||||
fn render_to_vello(&self, scene: &mut Scene, _parent_transform: DAffine2, _context: &mut RenderContext, render_params: &RenderParams) {
|
||||
use vello::peniko;
|
||||
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
use graphene_core::BlendMode;
|
||||
use vello::peniko;
|
||||
|
||||
#[cfg(feature = "vello")]
|
||||
pub trait BlendModeExt {
|
||||
fn to_peniko(&self) -> peniko::Mix;
|
||||
}
|
||||
|
||||
#[cfg(feature = "vello")]
|
||||
impl BlendModeExt for BlendMode {
|
||||
fn to_peniko(&self) -> peniko::Mix {
|
||||
match self {
|
||||
|
||||
@@ -97,6 +97,10 @@ impl DynamicExecutor {
|
||||
self.typing_context.type_of(self.output).map(|node_io| node_io.call_argument.clone())
|
||||
}
|
||||
|
||||
pub fn typing_context_mut(&mut self) -> &mut TypingContext {
|
||||
&mut self.typing_context
|
||||
}
|
||||
|
||||
pub fn tree(&self) -> &BorrowTree {
|
||||
&self.tree
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ pub mod util;
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use futures::executor::block_on;
|
||||
use graph_craft::proto::TypingContext;
|
||||
use graphene_core::*;
|
||||
|
||||
#[test]
|
||||
@@ -44,7 +45,8 @@ mod tests {
|
||||
use graph_craft::graphene_compiler::Compiler;
|
||||
|
||||
let compiler = Compiler {};
|
||||
let protograph = compiler.compile_single(network).expect("Graph should be generated");
|
||||
let mut ty = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
|
||||
let protograph = compiler.compile_single(network, &mut ty).expect("Graph should be generated");
|
||||
|
||||
let _exec = block_on(DynamicExecutor::new(protograph)).map(|_e| panic!("The network should not type check ")).unwrap_err();
|
||||
}
|
||||
|
||||
@@ -12,7 +12,6 @@ use graphene_core::{Artboard, concrete};
|
||||
use graphene_core::{Cow, ProtoNodeIdentifier};
|
||||
use graphene_core::{NodeIO, NodeIOTypes};
|
||||
use graphene_core::{fn_type_fut, future};
|
||||
use graphene_std::Context;
|
||||
use graphene_std::Graphic;
|
||||
#[cfg(feature = "gpu")]
|
||||
use graphene_std::any::DowncastBothNode;
|
||||
@@ -29,6 +28,7 @@ use graphene_std::vector::Vector;
|
||||
use graphene_std::wasm_application_io::WasmEditorApi;
|
||||
#[cfg(feature = "gpu")]
|
||||
use graphene_std::wasm_application_io::WasmSurfaceHandle;
|
||||
use graphene_std::{Context, ContextFeatures};
|
||||
use node_registry_macros::{async_node, convert_node, into_node};
|
||||
use once_cell::sync::Lazy;
|
||||
use std::collections::HashMap;
|
||||
@@ -46,9 +46,9 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
// ==========
|
||||
into_node!(from: Table<Graphic>, to: Table<Graphic>),
|
||||
into_node!(from: Table<Vector>, to: Table<Vector>),
|
||||
into_node!(from: Table<Raster<CPU>>, to: Table<Raster<CPU>>),
|
||||
#[cfg(feature = "gpu")]
|
||||
into_node!(from: Table<Raster<GPU>>, to: Table<Raster<GPU>>),
|
||||
// into_node!(from: Table<Raster<CPU>>, to: Table<Raster<CPU>>),
|
||||
// #[cfg(feature = "gpu")]
|
||||
// into_node!(from: Table<Raster<GPU>>, to: Table<Raster<GPU>>),
|
||||
into_node!(from: Table<Vector>, to: Table<Graphic>),
|
||||
into_node!(from: Table<Raster<CPU>>, to: Table<Graphic>),
|
||||
#[cfg(feature = "gpu")]
|
||||
@@ -57,6 +57,22 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
#[cfg(feature = "gpu")]
|
||||
into_node!(from: &WasmEditorApi, to: &WgpuExecutor),
|
||||
convert_node!(from: String, to: String),
|
||||
#[cfg(feature = "gpu")]
|
||||
convert_node!(from: Table<Raster<CPU>>, to: Table<Raster<CPU>>, converter: &WgpuExecutor),
|
||||
#[cfg(feature = "gpu")]
|
||||
convert_node!(from: Table<Raster<CPU>>, to: Table<Raster<GPU>>, converter: &WgpuExecutor),
|
||||
#[cfg(feature = "gpu")]
|
||||
convert_node!(from: Table<Raster<GPU>>, to: Table<Raster<GPU>>, converter: &WgpuExecutor),
|
||||
#[cfg(feature = "gpu")]
|
||||
convert_node!(from: Table<Raster<GPU>>, to: Table<Raster<CPU>>, converter: &WgpuExecutor),
|
||||
#[cfg(feature = "gpu")]
|
||||
convert_node!(from: Table<Vector>, to: Table<Raster<GPU>>, converter: &WgpuExecutor),
|
||||
#[cfg(feature = "gpu")]
|
||||
convert_node!(from: Table<Graphic>, to: Table<Raster<GPU>>, converter: &WgpuExecutor),
|
||||
#[cfg(feature = "gpu")]
|
||||
convert_node!(from: Table<GradientStops>, to: Table<Raster<GPU>>, converter: &WgpuExecutor),
|
||||
#[cfg(feature = "gpu")]
|
||||
convert_node!(from: Table<Color>, to: Table<Raster<GPU>>, converter: &WgpuExecutor),
|
||||
// =============
|
||||
// MONITOR NODES
|
||||
// =============
|
||||
@@ -171,6 +187,8 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
#[cfg(feature = "gpu")]
|
||||
async_node!(graphene_core::memo::MemoNode<_, _>, input: Context, fn_params: [Context => WgpuSurface]),
|
||||
#[cfg(feature = "gpu")]
|
||||
async_node!(graphene_core::memo::MemoNode<_, _>, input: Context, fn_params: [Context => &WgpuExecutor]),
|
||||
#[cfg(feature = "gpu")]
|
||||
async_node!(graphene_core::memo::MemoNode<_, _>, input: Context, fn_params: [Context => Table<Raster<GPU>>]),
|
||||
async_node!(graphene_core::memo::MemoNode<_, _>, input: Context, fn_params: [Context => Option<f64>]),
|
||||
async_node!(graphene_core::memo::MemoNode<_, _>, input: Context, fn_params: [Context => Color]),
|
||||
@@ -219,6 +237,11 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
async_node!(graphene_core::memo::MemoNode<_, _>, input: Context, fn_params: [Context => graphene_core::text::TextAlign]),
|
||||
async_node!(graphene_core::memo::MemoNode<_, _>, input: Context, fn_params: [Context => RenderIntermediate]),
|
||||
// =================
|
||||
// CONTEXT MOD NODES
|
||||
// =================
|
||||
#[cfg(feature = "gpu")]
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => &WgpuExecutor, Context => ContextFeatures]),
|
||||
// =================
|
||||
// IMPURE MEMO NODES
|
||||
// =================
|
||||
async_node!(graphene_core::memo::ImpureMemoNode<_, _, _>, input: Context, fn_params: [Context => Table<Artboard>]),
|
||||
@@ -390,21 +413,30 @@ mod node_registry_macros {
|
||||
x
|
||||
}};
|
||||
(from: $from:ty, to: $to:ty) => {
|
||||
convert_node!(from: $from, to: $to, converter: ())
|
||||
};
|
||||
(from: $from:ty, to: $to:ty, converter: $convert:ty) => {
|
||||
(
|
||||
ProtoNodeIdentifier::new(concat!["graphene_core::ops::ConvertNode<", stringify!($to), ">"]),
|
||||
|mut args| {
|
||||
Box::pin(async move {
|
||||
let node = graphene_core::ops::ConvertNode::new(graphene_std::any::downcast_node::<Context, $from>(args.pop().unwrap()),
|
||||
graphene_std::any::FutureWrapperNode::new(graphene_std::value::ClonedNode::new(std::marker::PhantomData::<$to>)) );
|
||||
let mut args = args.drain(..);
|
||||
let node = graphene_core::ops::ConvertNode::new(
|
||||
graphene_std::any::downcast_node::<Context, $from>(args.next().expect("Convert node did not get first argument")),
|
||||
graphene_std::any::downcast_node::<Context, $convert>(args.next().expect("Convert node did not get converter argument")),
|
||||
graphene_std::any::FutureWrapperNode::new(graphene_std::value::ClonedNode::new(std::marker::PhantomData::<$to>))
|
||||
);
|
||||
let any: DynAnyNode<Context, $to, _> = graphene_std::any::DynAnyNode::new(node);
|
||||
Box::new(any) as TypeErasedBox
|
||||
})
|
||||
},
|
||||
{
|
||||
let node = graphene_core::ops::ConvertNode::new(graphene_std::any::PanicNode::<Context, core::pin::Pin<Box<dyn core::future::Future<Output = $from> + Send>>>::new(),
|
||||
|
||||
graphene_std::any::FutureWrapperNode::new(graphene_std::value::ClonedNode::new(std::marker::PhantomData::<$to>)) );
|
||||
let params = vec![fn_type_fut!(Context, $from)];
|
||||
let node = graphene_core::ops::ConvertNode::new(
|
||||
graphene_std::any::PanicNode::<Context, core::pin::Pin<Box<dyn core::future::Future<Output = $from> + Send>>>::new(),
|
||||
graphene_std::any::PanicNode::<Context, core::pin::Pin<Box<dyn core::future::Future<Output = $convert> + Send>>>::new(),
|
||||
graphene_std::any::FutureWrapperNode::new(graphene_std::value::ClonedNode::new(std::marker::PhantomData::<$to>))
|
||||
);
|
||||
let params = vec![fn_type_fut!(Context, $from), fn_type_fut!(Context, $convert)];
|
||||
let node_io = NodeIO::<'_, Context>::to_async_node_io(&node, params);
|
||||
node_io
|
||||
},
|
||||
|
||||
@@ -128,7 +128,7 @@ impl PerPixelAdjustCodegen<'_> {
|
||||
#(pub #uniform_members),*
|
||||
}
|
||||
};
|
||||
let uniform_struct_shader_struct_derive = crate::buffer_struct::derive_buffer_struct_struct(&self.crate_ident, &uniform_struct)?;
|
||||
let uniform_struct_shader_struct_derive = crate::buffer_struct::derive_buffer_struct_struct(self.crate_ident, &uniform_struct)?;
|
||||
|
||||
let image_params = self
|
||||
.params
|
||||
|
||||
@@ -11,5 +11,6 @@ log = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
graphene-std = { workspace = true, features = ["gpu"] }
|
||||
wgpu-executor = { workspace = true }
|
||||
graph-craft = { workspace = true }
|
||||
interpreted-executor = { workspace = true }
|
||||
@@ -8,6 +8,7 @@ use graph_craft::{ProtoNodeIdentifier, concrete};
|
||||
use graphene_std::registry::*;
|
||||
use graphene_std::*;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use wgpu_executor::WgpuExecutor;
|
||||
|
||||
pub fn expand_network(network: &mut NodeNetwork, substitutions: &HashMap<ProtoNodeIdentifier, DocumentNode>) {
|
||||
if network.generated {
|
||||
@@ -67,6 +68,7 @@ pub fn generate_node_substitutions() -> HashMap<ProtoNodeIdentifier, DocumentNod
|
||||
1 => {
|
||||
let input = inputs.iter().next().unwrap();
|
||||
let input_ty = input.nested_type();
|
||||
let mut inputs = vec![NodeInput::import(input.clone(), i)];
|
||||
|
||||
let into_node_identifier = ProtoNodeIdentifier {
|
||||
name: format!("graphene_core::ops::IntoNode<{}>", input_ty.clone()).into(),
|
||||
@@ -75,20 +77,30 @@ pub fn generate_node_substitutions() -> HashMap<ProtoNodeIdentifier, DocumentNod
|
||||
name: format!("graphene_core::ops::ConvertNode<{}>", input_ty.clone()).into(),
|
||||
};
|
||||
|
||||
let mut context_features = ContextDependencies::default();
|
||||
let proto_node = if into_node_registry.keys().any(|ident: &ProtoNodeIdentifier| ident.name.as_ref() == into_node_identifier.name.as_ref()) {
|
||||
generated_nodes += 1;
|
||||
into_node_identifier
|
||||
} else if into_node_registry.keys().any(|ident| ident.name.as_ref() == convert_node_identifier.name.as_ref()) {
|
||||
} else if let Some(impls) = into_node_registry.get(&convert_node_identifier) {
|
||||
generated_nodes += 1;
|
||||
let converter = match impls.keys().next() {
|
||||
Some(node_io) if node_io.inputs[1].nested_type() == &concrete!(&WgpuExecutor) => {
|
||||
context_features.extract |= ContextFeatures::FOOTPRINT;
|
||||
NodeInput::scope("wgpu-executor")
|
||||
}
|
||||
_ => NodeInput::value(TaggedValue::None, false),
|
||||
};
|
||||
inputs.push(converter);
|
||||
convert_node_identifier
|
||||
} else {
|
||||
identity_node.clone()
|
||||
};
|
||||
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::import(input.clone(), i)],
|
||||
inputs,
|
||||
implementation: DocumentNodeImplementation::ProtoNode(proto_node),
|
||||
visible: true,
|
||||
context_features,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ license = "MIT OR Apache-2.0"
|
||||
# Local dependencies
|
||||
graphene-core = { workspace = true, features = ["wgpu"] }
|
||||
graphene-application-io = { workspace = true, features = ["wgpu"] }
|
||||
graphene-svg-renderer = { workspace = true, features = ["vello"] }
|
||||
graphene-svg-renderer = { workspace = true }
|
||||
dyn-any = { workspace = true }
|
||||
node-macro = { workspace = true }
|
||||
|
||||
@@ -21,3 +21,4 @@ web-sys = { workspace = true }
|
||||
winit = { workspace = true }
|
||||
vello = { workspace = true }
|
||||
bytemuck = { workspace = true }
|
||||
log = { workspace = true }
|
||||
@@ -1,6 +1,7 @@
|
||||
mod context;
|
||||
pub mod shader_runtime;
|
||||
pub mod texture_upload;
|
||||
pub mod vector_to_raster;
|
||||
|
||||
use crate::shader_runtime::ShaderRuntime;
|
||||
use anyhow::Result;
|
||||
|
||||
@@ -1,52 +1,301 @@
|
||||
use crate::WgpuExecutor;
|
||||
use graphene_core::Color;
|
||||
use graphene_core::Ctx;
|
||||
use graphene_core::color::SRGBA8;
|
||||
use graphene_core::ops::Convert;
|
||||
use graphene_core::raster::Image;
|
||||
use graphene_core::raster_types::{CPU, GPU, Raster};
|
||||
use graphene_core::table::{Table, TableRow};
|
||||
use graphene_core::transform::Footprint;
|
||||
use wgpu::util::{DeviceExt, TextureDataOrder};
|
||||
use wgpu::{Extent3d, TextureDescriptor, TextureDimension, TextureFormat, TextureUsages};
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
pub async fn upload_texture<'a: 'n>(_: impl Ctx, input: Table<Raster<CPU>>, executor: &'a WgpuExecutor) -> Table<Raster<GPU>> {
|
||||
let device = &executor.context.device;
|
||||
let queue = &executor.context.queue;
|
||||
let table = input
|
||||
.iter()
|
||||
.map(|row| {
|
||||
let image = row.element;
|
||||
let rgba8_data: Vec<SRGBA8> = image.data.iter().map(|x| (*x).into()).collect();
|
||||
/// Uploads CPU image data to a GPU texture
|
||||
///
|
||||
/// Creates a new WGPU texture with RGBA8UnormSrgb format and uploads the provided
|
||||
/// image data. The texture is configured for binding, copying, and source operations.
|
||||
fn upload_to_texture(device: &std::sync::Arc<wgpu::Device>, queue: &std::sync::Arc<wgpu::Queue>, image: &Raster<CPU>) -> wgpu::Texture {
|
||||
let rgba8_data: Vec<SRGBA8> = image.data.iter().map(|x| (*x).into()).collect();
|
||||
|
||||
let texture = device.create_texture_with_data(
|
||||
queue,
|
||||
&TextureDescriptor {
|
||||
label: Some("upload_texture node texture"),
|
||||
size: Extent3d {
|
||||
width: image.width,
|
||||
height: image.height,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: TextureDimension::D2,
|
||||
format: TextureFormat::Rgba8UnormSrgb,
|
||||
// I don't know what usages are actually necessary
|
||||
usage: TextureUsages::TEXTURE_BINDING | TextureUsages::COPY_DST | TextureUsages::COPY_SRC,
|
||||
view_formats: &[],
|
||||
},
|
||||
TextureDataOrder::LayerMajor,
|
||||
bytemuck::cast_slice(rgba8_data.as_slice()),
|
||||
);
|
||||
|
||||
TableRow {
|
||||
element: Raster::new_gpu(texture),
|
||||
transform: *row.transform,
|
||||
alpha_blending: *row.alpha_blending,
|
||||
source_node_id: *row.source_node_id,
|
||||
device.create_texture_with_data(
|
||||
queue,
|
||||
&TextureDescriptor {
|
||||
label: Some("upload_texture node texture"),
|
||||
size: Extent3d {
|
||||
width: image.width,
|
||||
height: image.height,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: TextureDimension::D2,
|
||||
format: TextureFormat::Rgba8UnormSrgb,
|
||||
usage: TextureUsages::TEXTURE_BINDING | TextureUsages::COPY_DST | TextureUsages::COPY_SRC,
|
||||
view_formats: &[],
|
||||
},
|
||||
TextureDataOrder::LayerMajor,
|
||||
bytemuck::cast_slice(rgba8_data.as_slice()),
|
||||
)
|
||||
}
|
||||
|
||||
/// Downloads GPU texture data to a CPU buffer
|
||||
///
|
||||
/// Creates a buffer and adds a copy operation from the texture to the buffer
|
||||
/// using the provided command encoder. Returns dimensions and the buffer for
|
||||
/// later mapping and data extraction.
|
||||
fn download_to_buffer(device: &std::sync::Arc<wgpu::Device>, encoder: &mut wgpu::CommandEncoder, texture: &wgpu::Texture) -> (wgpu::Buffer, u32, u32, u32, u32) {
|
||||
let width = texture.width();
|
||||
let height = texture.height();
|
||||
let bytes_per_pixel = 4; // RGBA8
|
||||
let unpadded_bytes_per_row = width * bytes_per_pixel;
|
||||
let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
|
||||
let padded_bytes_per_row = unpadded_bytes_per_row.div_ceil(align) * align;
|
||||
let buffer_size = padded_bytes_per_row as u64 * height as u64;
|
||||
|
||||
let output_buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("texture_download_buffer"),
|
||||
size: buffer_size,
|
||||
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
encoder.copy_texture_to_buffer(
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
texture,
|
||||
mip_level: 0,
|
||||
origin: wgpu::Origin3d::ZERO,
|
||||
aspect: wgpu::TextureAspect::All,
|
||||
},
|
||||
wgpu::TexelCopyBufferInfo {
|
||||
buffer: &output_buffer,
|
||||
layout: wgpu::TexelCopyBufferLayout {
|
||||
offset: 0,
|
||||
bytes_per_row: Some(padded_bytes_per_row),
|
||||
rows_per_image: Some(height),
|
||||
},
|
||||
},
|
||||
Extent3d {
|
||||
width,
|
||||
height,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
);
|
||||
(output_buffer, width, height, unpadded_bytes_per_row, padded_bytes_per_row)
|
||||
}
|
||||
|
||||
/// Passthrough conversion for GPU tables - no conversion needed
|
||||
impl<'i> Convert<Table<Raster<GPU>>, &'i WgpuExecutor> for Table<Raster<GPU>> {
|
||||
async fn convert(self, _: Footprint, _converter: &'i WgpuExecutor) -> Table<Raster<GPU>> {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts CPU raster table to GPU by uploading each image to a texture
|
||||
impl<'i> Convert<Table<Raster<GPU>>, &'i WgpuExecutor> for Table<Raster<CPU>> {
|
||||
async fn convert(self, _: Footprint, executor: &'i WgpuExecutor) -> Table<Raster<GPU>> {
|
||||
let device = &executor.context.device;
|
||||
let queue = &executor.context.queue;
|
||||
let table = self
|
||||
.iter()
|
||||
.map(|row| {
|
||||
let image = row.element;
|
||||
let texture = upload_to_texture(device, queue, image);
|
||||
|
||||
TableRow {
|
||||
element: Raster::new_gpu(texture),
|
||||
transform: *row.transform,
|
||||
alpha_blending: *row.alpha_blending,
|
||||
source_node_id: *row.source_node_id,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
queue.submit([]);
|
||||
table
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts single CPU raster to GPU by uploading to texture
|
||||
impl<'i> Convert<Raster<GPU>, &'i WgpuExecutor> for Raster<CPU> {
|
||||
async fn convert(self, _: Footprint, executor: &'i WgpuExecutor) -> Raster<GPU> {
|
||||
let device = &executor.context.device;
|
||||
let queue = &executor.context.queue;
|
||||
let texture = upload_to_texture(device, queue, &self);
|
||||
|
||||
queue.submit([]);
|
||||
Raster::new_gpu(texture)
|
||||
}
|
||||
}
|
||||
|
||||
/// Passthrough conversion for CPU tables - no conversion needed
|
||||
impl<'i> Convert<Table<Raster<CPU>>, &'i WgpuExecutor> for Table<Raster<CPU>> {
|
||||
async fn convert(self, _: Footprint, _converter: &'i WgpuExecutor) -> Table<Raster<CPU>> {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts GPU raster table to CPU by downloading texture data in one go
|
||||
///
|
||||
/// then asynchronously maps all buffers and processes the results.
|
||||
impl<'i> Convert<Table<Raster<CPU>>, &'i WgpuExecutor> for Table<Raster<GPU>> {
|
||||
async fn convert(self, _: Footprint, executor: &'i WgpuExecutor) -> Table<Raster<CPU>> {
|
||||
let device = &executor.context.device;
|
||||
let queue = &executor.context.queue;
|
||||
|
||||
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||
label: Some("batch_texture_download_encoder"),
|
||||
});
|
||||
|
||||
let mut buffers_and_info = Vec::new();
|
||||
|
||||
for row in self.iter() {
|
||||
let gpu_raster = row.element;
|
||||
let texture = gpu_raster.data();
|
||||
|
||||
let (output_buffer, width, height, unpadded_bytes_per_row, padded_bytes_per_row) = download_to_buffer(device, &mut encoder, texture);
|
||||
|
||||
buffers_and_info.push((
|
||||
output_buffer,
|
||||
width,
|
||||
height,
|
||||
unpadded_bytes_per_row,
|
||||
padded_bytes_per_row,
|
||||
*row.transform,
|
||||
*row.alpha_blending,
|
||||
*row.source_node_id,
|
||||
));
|
||||
}
|
||||
|
||||
queue.submit([encoder.finish()]);
|
||||
|
||||
let mut map_futures = Vec::new();
|
||||
let mut buffer_sclices_and_info = Vec::new();
|
||||
for (buffer, width, height, unpadded_bytes_per_row, padded_bytes_per_row, transform, alpha_blending, source_node_id) in &buffers_and_info {
|
||||
let buffer_slice = buffer.slice(..);
|
||||
let (sender, receiver) = futures::channel::oneshot::channel();
|
||||
buffer_slice.map_async(wgpu::MapMode::Read, move |result| {
|
||||
let _ = sender.send(result);
|
||||
});
|
||||
map_futures.push(receiver);
|
||||
buffer_sclices_and_info.push((
|
||||
buffer,
|
||||
buffer_slice,
|
||||
width,
|
||||
height,
|
||||
unpadded_bytes_per_row,
|
||||
padded_bytes_per_row,
|
||||
transform,
|
||||
alpha_blending,
|
||||
source_node_id,
|
||||
));
|
||||
}
|
||||
|
||||
let map_results = futures::future::try_join_all(map_futures)
|
||||
.await
|
||||
.map_err(|_| "Failed to receive map result")
|
||||
.expect("Buffer mapping communication failed");
|
||||
|
||||
let mut table = Vec::new();
|
||||
for (i, (buffer, buffer_slice, width, height, unpadded_bytes_per_row, padded_bytes_per_row, transform, alpha_blending, source_node_id)) in buffer_sclices_and_info.into_iter().enumerate() {
|
||||
if let Err(e) = &map_results[i] {
|
||||
panic!("Buffer mapping failed: {e:?}");
|
||||
}
|
||||
|
||||
let view = buffer_slice.get_mapped_range();
|
||||
|
||||
let row_stride = *padded_bytes_per_row as usize;
|
||||
let row_bytes = *unpadded_bytes_per_row as usize;
|
||||
let mut cpu_data: Vec<Color> = Vec::with_capacity((width * height) as usize);
|
||||
for row in 0..*height as usize {
|
||||
let start = row * row_stride;
|
||||
let row_slice = &view[start..start + row_bytes];
|
||||
for px in row_slice.chunks_exact(4) {
|
||||
cpu_data.push(Color::from_rgba8_srgb(px[0], px[1], px[2], px[3]));
|
||||
}
|
||||
}
|
||||
|
||||
drop(view);
|
||||
buffer.unmap();
|
||||
let cpu_image = Image {
|
||||
data: cpu_data,
|
||||
width: *width,
|
||||
height: *height,
|
||||
base64_string: None,
|
||||
};
|
||||
let cpu_raster = Raster::new_cpu(cpu_image);
|
||||
|
||||
table.push(TableRow {
|
||||
element: cpu_raster,
|
||||
transform: *transform,
|
||||
alpha_blending: *alpha_blending,
|
||||
source_node_id: *source_node_id,
|
||||
});
|
||||
}
|
||||
|
||||
table.into_iter().collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts single GPU raster to CPU by downloading texture data
|
||||
impl<'i> Convert<Raster<CPU>, &'i WgpuExecutor> for Raster<GPU> {
|
||||
async fn convert(self, _: Footprint, executor: &'i WgpuExecutor) -> Raster<CPU> {
|
||||
let device = &executor.context.device;
|
||||
let queue = &executor.context.queue;
|
||||
|
||||
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||
label: Some("single_texture_download_encoder"),
|
||||
});
|
||||
|
||||
let gpu_raster = &self;
|
||||
let texture = gpu_raster.data();
|
||||
|
||||
let (buffer, width, height, unpadded_bytes_per_row, padded_bytes_per_row) = download_to_buffer(device, &mut encoder, texture);
|
||||
|
||||
queue.submit([encoder.finish()]);
|
||||
|
||||
let buffer_slice = buffer.slice(..);
|
||||
let (sender, receiver) = futures::channel::oneshot::channel();
|
||||
buffer_slice.map_async(wgpu::MapMode::Read, move |result| {
|
||||
let _ = sender.send(result);
|
||||
});
|
||||
receiver.await.expect("Failed to receive map result").expect("Buffer mapping failed");
|
||||
|
||||
let view = buffer_slice.get_mapped_range();
|
||||
|
||||
let row_stride = padded_bytes_per_row as usize;
|
||||
let row_bytes = unpadded_bytes_per_row as usize;
|
||||
let mut cpu_data: Vec<Color> = Vec::with_capacity((width * height) as usize);
|
||||
for row in 0..height as usize {
|
||||
let start = row * row_stride;
|
||||
let row_slice = &view[start..start + row_bytes];
|
||||
for px in row_slice.chunks_exact(4) {
|
||||
cpu_data.push(Color::from_rgba8_srgb(px[0], px[1], px[2], px[3]));
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
|
||||
drop(view);
|
||||
buffer.unmap();
|
||||
let cpu_image = Image {
|
||||
data: cpu_data,
|
||||
width,
|
||||
height,
|
||||
base64_string: None,
|
||||
};
|
||||
|
||||
queue.submit([]);
|
||||
Raster::new_cpu(cpu_image)
|
||||
}
|
||||
}
|
||||
|
||||
table
|
||||
/// Node for uploading textures from CPU to GPU. This Is now deprecated and
|
||||
/// we should use the Convert node in the future.
|
||||
///
|
||||
/// Accepts either individual rasters or tables of rasters and converts them
|
||||
/// to GPU format using the WgpuExecutor's device and queue.
|
||||
#[node_macro::node(category(""))]
|
||||
pub async fn upload_texture<'a: 'n, T: Convert<Table<Raster<GPU>>, &'a WgpuExecutor>>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Table<Raster<CPU>>, Table<Raster<GPU>>)] input: T,
|
||||
executor: &'a WgpuExecutor,
|
||||
) -> Table<Raster<GPU>> {
|
||||
input.convert(Footprint::DEFAULT, executor).await
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
use crate::WgpuExecutor;
|
||||
use glam::{DAffine2, DVec2, UVec2};
|
||||
use graphene_core::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use graphene_core::gradient::GradientStops;
|
||||
use graphene_core::ops::Convert;
|
||||
use graphene_core::raster_types::{GPU, Raster};
|
||||
use graphene_core::table::Table;
|
||||
use graphene_core::transform::Footprint;
|
||||
use graphene_core::vector::Vector;
|
||||
use graphene_core::{Artboard, Color, Graphic};
|
||||
use graphene_svg_renderer::{Render, RenderOutputType, RenderParams};
|
||||
use wgpu::{CommandEncoderDescriptor, TextureFormat, TextureViewDescriptor};
|
||||
|
||||
macro_rules! impl_convert {
|
||||
($ty:ty) => {
|
||||
/// Converts Table<Vector> to Table<Raster<GPU>> by rendering each vector to Vello scene and then to texture
|
||||
impl<'i> Convert<Table<Raster<GPU>>, &'i WgpuExecutor> for Table<$ty> {
|
||||
async fn convert(self, footprint: Footprint, executor: &'i WgpuExecutor) -> Table<Raster<GPU>> {
|
||||
// Create render parameters for Vello rendering
|
||||
let render_params = RenderParams {
|
||||
render_mode: graphene_core::vector::style::RenderMode::Normal,
|
||||
hide_artboards: false,
|
||||
for_export: false,
|
||||
render_output_type: RenderOutputType::Vello,
|
||||
footprint,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let vector = &self;
|
||||
let bounding_box = vector.bounding_box(DAffine2::IDENTITY, true);
|
||||
// TODO: Add cases for infinite bounding boxes
|
||||
let RenderBoundingBox::Rectangle(rect) = bounding_box else {
|
||||
panic!("did not find valid bounding box")
|
||||
};
|
||||
|
||||
// Create a Vello scene for this vector
|
||||
let mut scene = vello::Scene::new();
|
||||
let mut context = crate::RenderContext::default();
|
||||
|
||||
let viewport_bounds = footprint.viewport_bounds_in_local_space();
|
||||
|
||||
let image_bounds = graphene_core::math::bbox::AxisAlignedBbox { start: rect[0], end: rect[1] };
|
||||
let intersection = viewport_bounds.intersect(&image_bounds);
|
||||
|
||||
let size = intersection.size();
|
||||
|
||||
let offset = (intersection.start - image_bounds.start).max(DVec2::ZERO) + image_bounds.start;
|
||||
|
||||
// If the image would not be visible, return an empty image
|
||||
if size.x <= 0. || size.y <= 0. {
|
||||
return Table::new();
|
||||
}
|
||||
|
||||
let scale = footprint.scale();
|
||||
let width = (size.x * scale.x) as u32;
|
||||
let height = (size.y * scale.y) as u32;
|
||||
|
||||
// Render the scene to a GPU texture
|
||||
let resolution = UVec2::new(width, height);
|
||||
let background = graphene_core::Color::TRANSPARENT;
|
||||
|
||||
let render_transform = DAffine2::from_scale(scale) * DAffine2::from_translation(-offset);
|
||||
// Render the vector to the Vello scene with the row's transform
|
||||
vector.render_to_vello(&mut scene, render_transform, &mut context, &render_params);
|
||||
|
||||
// Use async rendering to get the texture
|
||||
let texture = executor
|
||||
.render_vello_scene_to_texture(&scene, resolution, &context, background)
|
||||
.await
|
||||
.expect("Failed to render Vello scene to texture");
|
||||
|
||||
let device = &executor.context.device;
|
||||
let queue = &executor.context.queue;
|
||||
let mut encoder = device.create_command_encoder(&CommandEncoderDescriptor::default());
|
||||
let blitter = wgpu::util::TextureBlitter::new(device, TextureFormat::Rgba8UnormSrgb);
|
||||
let view = texture.create_view(&TextureViewDescriptor::default());
|
||||
let new_texture = device.create_texture(&wgpu::wgt::TextureDescriptor {
|
||||
label: None,
|
||||
size: wgpu::Extent3d {
|
||||
width: texture.width(),
|
||||
height: texture.height(),
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
format: TextureFormat::Rgba8UnormSrgb,
|
||||
view_formats: &[],
|
||||
});
|
||||
let new_view = new_texture.create_view(&TextureViewDescriptor::default());
|
||||
|
||||
blitter.copy(device, &mut encoder, &view, &new_view);
|
||||
let command_buffer = encoder.finish();
|
||||
queue.submit([command_buffer]);
|
||||
|
||||
let mut table = Table::new_from_element(Raster::new_gpu(new_texture));
|
||||
*(table.get_mut(0).as_mut().unwrap().transform) = DAffine2::from_translation(offset) * DAffine2::from_scale(size);
|
||||
texture.destroy();
|
||||
table
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
impl_convert!(Vector);
|
||||
impl_convert!(Graphic);
|
||||
impl_convert!(Artboard);
|
||||
impl_convert!(GradientStops);
|
||||
impl_convert!(Color);
|
||||
Reference in new issue
Block a user